greatstore 0.2.22 → 0.2.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,11 @@
3
3
  All notable changes to `@greatstore/cli` are recorded here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/).
5
5
 
6
+ ## 0.2.23 — 2026-11-10
7
+
8
+ ### Changed
9
+ - When a command brings `AGENTS.md` up to date, it says the update is routine and belongs in your next commit.
10
+
6
11
  ## 0.2.22 — 2026-11-10
7
12
 
8
13
  ### Changed
package/dist/cli.js CHANGED
@@ -22,7 +22,7 @@ h1{font-size:1.4rem;color:#a40000}code{background:#f4f4f4;padding:.1em .3em;bord
22
22
  <p>Return to your terminal for details.</p></body></html>`,se=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function Le(e){let t=(e.generateState??Yr)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>zr(s,e.browserCmdEnv)),o=Gt.createServer();try{await new Promise(c=>o.listen(0,"127.0.0.1",c));let s=o.address(),i=new URL(`${e.dashboardBaseUrl}/cli/authorize`);i.searchParams.set("port",String(s.port)),i.searchParams.set("state",t),e.requestedStore&&i.searchParams.set("store",e.requestedStore);let a=i.toString(),l=Wr(o,t,n);return r(a),process.stderr.write(`If your browser didn't open, visit:
23
23
  ${a}
24
24
  `),await l}finally{o.close()}}function Wr(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new se("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!==Vr){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,d=u.get("error"),b=u.get("error_description"),m=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(Mt),clearTimeout(a),i(()=>o(new se("Sign-in didn't complete. Please try again.")));return}if(d||!m){c.writeHead(400,{"content-type":"text/html"}),c.end(Mt),clearTimeout(a),i(()=>o(new se(b??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(Kr),clearTimeout(a);let Te=u.get("store")?.trim();i(()=>r(Te?{token:m,store:Te}:{token:m}))})})}function Yr(){return Ut.randomBytes(16).toString("hex")}function zr(e,t){let n=t?.trim();Vt(e,n?[n]:Xr(process.platform,process.env))}function Vt(e,t){let[n,...r]=t;if(n===void 0)return;let o=()=>Vt(e,r);try{let s;if(n==="start"){let l=`start "" "${e}"`;s=Ht("cmd.exe",["/d","/s","/c",l],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else s=Ht(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 Xr(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 fe from"os";import*as ct from"path";var Qr=".greatstore",Zr="credentials.json";function ie(e=fe.homedir()){return ct.join(e,Qr)}function lt(e=fe.homedir()){return ct.join(ie(e),Zr)}function N(e=fe.homedir()){let t=lt(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(eo(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function Oe(e,t=fe.homedir()){let n=ie(t);if(L.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{L.chmodSync(n,448)}catch{}let r=lt(t);L.writeFileSync(r,`${JSON.stringify(e,null,2)}
25
- `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function qt(e=fe.homedir()){L.rmSync(lt(e),{force:!0})}function Jt(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 Ie(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function eo(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var O="0.2.22";function me(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 H=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},U=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function to(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 no(e){let t=to(e)??N()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var ut=null;function zt(e){ut=e}async function f(e,t={}){if(ut!==null)return Kt(e,t,ut);let n=()=>`Run \`${no(e)}\`.`,r=N();if(!r)throw new U(`Sign in first. ${n()}`);if(Ie(r))throw new U(`Session expired. ${n()}`);try{return await Kt(e,t,r.access_token)}catch(o){throw o instanceof H&&o.status===401?new U(`Session expired. ${n()}`):o}}async function Kt(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":O,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:ro(i.status,c,l.detail);throw new H(i.status,p,l.code??l.error)}var Xt=`This version of the GreatStore CLI is no longer supported. Run the latest one:
25
+ `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function qt(e=fe.homedir()){L.rmSync(lt(e),{force:!0})}function Jt(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 Ie(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function eo(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var O="0.2.23";function me(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 H=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},U=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function to(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 no(e){let t=to(e)??N()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var ut=null;function zt(e){ut=e}async function f(e,t={}){if(ut!==null)return Kt(e,t,ut);let n=()=>`Run \`${no(e)}\`.`,r=N();if(!r)throw new U(`Sign in first. ${n()}`);if(Ie(r))throw new U(`Session expired. ${n()}`);try{return await Kt(e,t,r.access_token)}catch(o){throw o instanceof H&&o.status===401?new U(`Session expired. ${n()}`):o}}async function Kt(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":O,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:ro(i.status,c,l.detail);throw new H(i.status,p,l.code??l.error)}var Xt=`This version of the GreatStore CLI is no longer supported. Run the latest one:
26
26
 
27
27
  npx greatstore@latest <command>
28
28
 
@@ -83,44 +83,46 @@ Examples:
83
83
  npx greatstore configure set --theme.fontFamily Manrope --theme.radius sharp
84
84
  npx greatstore configure set --theme.brandColor "#1e1d66"
85
85
  npx greatstore configure set --theme '{"mode":"dark"}' --replace
86
- `}function fn(e){if(e===void 0||e==="show")return mo;if(e==="set")return yo()}import*as C from"fs";import*as j from"path";import{readdirSync as ii,readFileSync as ai}from"fs";import{fileURLToPath as li}from"url";var Me=null;function Ue(){return Me||(Me=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). See AGENTS.md.\\n generateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n // A hook for a voice call with the store\'s assistant: call it at the top\\n // of the component. See AGENTS.md.\\n useVoiceCall: () => {\\n status:\\n | \\"started\\"\\n | \\"connecting\\"\\n | \\"connected\\"\\n | \\"speaking\\"\\n | \\"listening\\"\\n | \\"working\\"\\n | \\"disconnected\\"\\n | \\"ended\\"\\n | \\"rejected\\"\\n | null;\\n available: boolean;\\n start: () => Promise<void>;\\n end: () => void;\\n };\\n store: { slug: string };\\n };\\n}\\n\\n// See AGENTS.md for how an app runs (the assistant picks it by the\\n// manifest\'s name and description, then calls it with these props), the\\n// design rules (style.css, em-based sizing, brand CSS variables), and how to\\n// write an async, backend-backed app.\\n//\\n// Take what you need from `$` at the top: `const { callTool, Image } = props.$;`\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div className=\\"app\\">\\n <strong>__GS_NAME__</strong> \u2014 hello from your app!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Use when <the shopper situation that should make the assistant open this app \u2014 say when to reach for it and what it reports back, never what it looks like; see AGENTS.md>.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","component/style.css":"/*\\n * Your app\'s styles. Plain CSS, applied inside the app alone: nothing here\\n * reaches the store\'s page, and nothing on the page reaches in.\\n *\\n * Style with the store\'s theme variables rather than fixed values \u2014 write\\n * `color: var(--color-foreground)`, never `color: #111827`. Each store sets\\n * its colours, fonts and corner style (and dark mode) in its GreatStore\\n * dashboard; an app built on these variables follows those settings, and\\n * changes with them.\\n *\\n * Fonts: --font-primary, --font-secondary\\n * Surfaces: --color-surface, --color-surface-secondary, --color-surface-accent,\\n * --color-surface-hover\\n * Text: --color-foreground, --color-foreground-secondary,\\n * --color-foreground-muted, --color-foreground-accent\\n * Borders: --color-border-default, --color-border-focus\\n * Brand: --color-primary, --color-primary-foreground, --color-primary-hover,\\n * --color-primary-muted, --color-primary-muted-foreground,\\n * --color-primary-tint, --color-link\\n * Status: --color-error, --color-error-surface, --color-error-border,\\n * --color-success\\n * Corners: --radius-xs, --radius-sm, --radius-md, --radius-lg, --radius-xl,\\n * --radius-2xl, --radius-3xl, --radius-4xl, --radius-pill\\n */\\n\\n/* Size in em, never rem: an app sits inside other people\'s pages. */\\n.app {\\n padding: 1em;\\n border: 1px solid var(--color-border-default);\\n border-radius: var(--radius-lg);\\n background: var(--color-surface);\\n color: var(--color-foreground);\\n font-family: var(--font-primary);\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/bundle.css\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> 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)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async app that builds its render from the generated payload \u2014 `await` it, then return the JSX. `fallback` is **required**: a schema-shaped object you supply that the app preview renders (so a generation-driven app previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `$.close()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `$.useVoiceCall()` | A hook \u2014 call it at the top of your component like any other \u2014 returning `{ status, available, start, end }` for a voice call with the store\'s assistant. `start()` starts the call without opening the chat \u2014 it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended` \u2014 or `rejected` instead of `ended` when the shopper refuses the microphone (calling `start()` again asks again, though a browser where they blocked it refuses without asking). Your app re-renders on every change. |\\n| `$.Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the app outside the store? Pass your own `$` with `Image: \\"img\\"` (or your own component) to render a plain image. |\\n| `$.store` | `{ slug }` \u2014 the store the app is running in. |\\n\\n## Async apps (backend-backed, render-blocking data)\\n\\nIf an app must load data from a backend/API before it can render\\ncorrectly, make it async \u2014 don\'t render an empty shell and fetch in a\\n`useEffect`. Set `\\"async\\": true` in `manifest.json` and export an async\\ndefault. GreatStore waits for your promise (showing a normal loading\\nstate, so you don\'t render your own placeholder), then renders what it\\nresolves to. Apps that render purely from their props stay synchronous.\\n\\nA thrown error is a **retry signal**: the in-store AI sees it and\\nusually re-calls the tool. So only throw when a *different* call could\\nhelp:\\n\\n1. `await` the backend call, then return the finished JSX.\\n2. Validate the AI-passed props first and throw on bad input \u2014 the AI\\n can fix the args and retry. (Don\'t validate the API\'s *output* and\\n throw: the AI can\'t fix the backend, it\'ll just loop.)\\n3. Broadcast a backend failure ONLY when retrying differently could\\n succeed, and say what to change (e.g. empty search \u2192 \\"try a broader\\n keyword\\"). For idempotent failures (500, timeout, missing record)\\n re-running the same call changes nothing \u2014 render a graceful fallback\\n instead of throwing.\\n\\n```tsx\\nexport default async function Example(props: Props) {\\n if (!props.query?.trim()) throw new Error(\\"missing required prop: query\\");\\n const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);\\n if (res.ok) {\\n const { results } = await res.json();\\n if (results.length === 0)\\n throw new Error(`no results for \\"${props.query}\\" \u2014 try a broader keyword`);\\n return <ul>{/* render results */}</ul>;\\n }\\n return <p>Couldn\'t load results right now.</p>; // idempotent: don\'t throw\\n}\\n```\\n","root/README.md":"# GreatStore apps\\n\\nCustom in-chat apps published to your GreatStore tenant. Each app is a\\nReact component living in its own folder under `components/`.\\n\\n```\\nnpm install\\nnpx greatstore apps init <app_name> # add a new app\\nnpx greatstore apps build # builds every components/<name>/bundle.js\\nnpx greatstore apps push # uploads every changed app as a draft\\nnpx greatstore apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `npx greatstore apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `npx greatstore apps pull` (no args) refreshes every live app into\\n `components/<name>/`. Apps with unsaved local edits are skipped with a\\n warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for how an app runs, how to write a manifest name and\\ndescription the assistant will actually pick, and the design rules every\\napp must follow (em-based sizing, brand CSS variables) \u2014 it doubles as\\nguidance for AI coding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"npx greatstore apps build\\",\\n \\"push\\": \\"npx greatstore apps build && npx greatstore apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `npx greatstore build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),Me)}var dn={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function Ge(e,t){let n=e;for(let o of Object.keys(dn)){let s=t[o];s!==void 0&&(n=n.split(dn[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 I from"fs";import*as Ve from"path";var Q="AGENTS.md",wo=["CLAUDE.md","GEMINI.md"];function So(){let e=Ue()[`root/${Q}`];if(e===void 0)throw new Error(`internal: template is missing root/${Q}`);return Ge(e,{version:O})}function gt(e,t={}){let n=[],r=So(),o=Ve.join(e,Q);(I.existsSync(o)?I.readFileSync(o,"utf8"):null)!==r&&(I.writeFileSync(o,r),n.push(Q));for(let i of wo){let a=Ve.join(e,i);t.force&&mn(a)&&I.rmSync(a),mn(a)||(I.symlinkSync(Q,a),n.push(i))}return n}function G(e){try{if(!I.existsSync(Ve.join(e,"components")))return;let t=gt(e);t.length>0&&process.stdout.write(`Updated the agent guide to CLI v${O}: ${t.join(", ")}
87
- `)}catch{}}function mn(e){try{return I.lstatSync(e),!0}catch{return!1}}var gn=/^[a-z][a-z0-9_]*$/;function hn(e){let t=e.positional[0];if(t!==void 0&&!gn.test(t))throw new Error(`Invalid component name: "${t}" (must match ${gn}).`);let n=g(e.flags,"force"),r=y(e.flags,"store"),o=y(e.flags,"out")??".",s=j.resolve(o),i=bo(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?ge(r):Ce()??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=xo(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 ${j.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
88
- `));return}let c=j.join(s,"components",t);vo(c,t,n);let p=j.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&l.length>0?["",`Also added to the project root: ${l.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," npx greatstore apps build"," npx greatstore apps push",""].join(`
89
- `))}function bo(e){return C.existsSync(j.join(e,"package.json"))&&C.existsSync(j.join(e,".gsrc"))}function xo(e,t,n,r){if(C.mkdirSync(e,{recursive:!0}),!t&&!n&&C.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?Eo():ko({store:r.store}),s=$o(e,o,n);return C.mkdirSync(j.join(e,"components"),{recursive:!0}),s}function $o(e,t,n){let r=[];for(let[o,s]of t){let i=j.join(e,o);C.mkdirSync(j.dirname(i),{recursive:!0}),!(!n&&C.existsSync(i))&&(C.writeFileSync(i,s),r.push(o))}return r.push(...gt(e,{force:n})),r}function vo(e,t,n){if(C.existsSync(e)&&!n&&C.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);C.mkdirSync(e,{recursive:!0});for(let[r,o]of Po(t))C.writeFileSync(j.join(e,r),o)}function ht(e,t,n=new Set){let r=Ue();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,Ge(s,t)])}function ko(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return ht("root/",{store:e.store},new Set([Q]))}function Eo(){return ht("root/",{},new Set([".gsrc",Q]))}function Po(e){return ht("component/",{name:e,displayName:Co(e)})}function Co(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 h from"path";import*as ye from"fs";import*as yt from"path";var x="style.css",_="bundle.css",qe=`./${x}`,yn=256*1024;function Ao(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 B(e){let t=yt.join(e,"component.tsx");if(!ye.existsSync(t))return{imported:!1,problems:[]};let n=Ao(ye.readFileSync(t,"utf8")),r=n.filter(i=>i!==qe).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${x}, imported as "${qe}"; move these rules there.`})),o=n.includes(qe);if(!o)return{imported:o,problems:r};let s=yt.join(e,x);if(!ye.existsSync(s))return r.push({file:"component.tsx",message:`imports "${qe}", but there's no ${x} beside it.`}),{imported:o,problems:r};for(let i of jo(ye.readFileSync(s,"utf8")))r.push({file:x,message:i});return{imported:o,problems:r}}function jo(e){let t=[],n=Buffer.byteLength(e,"utf8");n>yn&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${yn/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
90
- `).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 Mo}from"module";import{pathToFileURL as Dn}from"url";import*as An from"fs";import*as V from"path";import{createRequire as _o}from"module";import*as Je from"path";function Sn(e,t,n){let r=xn(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=To(r,o);return s?Io(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 ${Je.basename(t)} could not be parsed (${o.message})`}}}function bn(e,t,n){let r=xn(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(Ro(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function Ro(e,t){if(e.isPropertyAccessExpression(t))return wn(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return wn(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function wn(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function xn(e){let t=_o(Je.join(e,"package.json"));try{return t("typescript")}catch{return null}}function To(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&Lo(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=$n(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?Oo(e,t,r.text):null}function Lo(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function $n(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function Oo(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=$n(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function Io(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=wt(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:Fo(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 wt(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=>wt(e,t,s,r));return o.every(s=>s===null)?null:Pn(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 Pn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return wt(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=En(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function Fo(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=En(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function En(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Pn(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=V.join(t,"components",n),o=e.manifestPath??V.join(r,"manifest.json"),s=e.sourcePath??V.join(r,"component.tsx"),i=St(t,o),a=St(t,s),l=[],c=null,p=Cn(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let m=JSON.parse(p);!m||typeof m!="object"||Array.isArray(m)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=m}catch(m){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${m.message}`})}let u=Cn(s),d=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:Sn(t,s,u),b=u===null?!1:bn(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:d,usesWindowGreatStore:b,styleFile:St(t,V.join(r,"style.css")),stylesheet:B(r)},diagnostics:l}}function Cn(e){try{return An.readFileSync(e,"utf8")}catch{return null}}function St(e,t){let n=V.relative(e,t);return n.startsWith("..")?t:n.split(V.sep).join("/")}var _n=new Set(["$"]);var bt=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Rn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>bt.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 Tn=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function On(e){if(!e.manifest)return[];let t=Bo(e.manifest.inputSchema);if(t===null)return[];let n=[];if(t.includes("$")&&n.push({severity:"error",rule:"props/reserved",file:e.manifestFile,message:`${e.manifestFile} declares inputSchema field \`$\`, but GreatStore always passes its own \`$\` prop, so that field can never reach the component. Rename the field.`}),!e.props.ok)return[...n,{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return n;let r=new Set(e.props.props.names),o=new Set(t),s=[];for(let a of e.props.props.names){if(_n.has(a))continue;if(bt.has(a)){s.push(a);continue}let l=Tn.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:Rn(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:No(e.manifestFile,i)}),n}var Ln=8;function No(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,Ln).map(s=>`\`${s}\``).join(", "),r=t.length-Ln,o=r>0?`${n} (+${r} more)`:n;return`${e} declares ${t.length} inputSchema fields the component does not accept: ${o}. Add them to the component's props, or remove them from the schema.`}function Bo(e){if(!e||typeof e!="object")return null;let t=e.properties;return!t||typeof t!="object"||Array.isArray(t)?null:Object.keys(t)}var Do=["anyOf","oneOf","allOf","$ref","not"];function Ke(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>Ke(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of Do)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,Ke(i,`${t}.${s}`,n);"items"in r&&Ke(r.items,`${t}[]`,n)}function In(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};Ke(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("; ")}.
91
- 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 Fn(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 Nn(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 Bn(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 Ae(e){return e.filter(t=>t.severity==="error")}function xt(e){return e.filter(t=>t.severity==="warning")}function je(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var Ho=[Fn,In,On,Nn,Bn];function We(e){let{ctx:t,diagnostics:n}=jn(e);for(let r of Ho)n.push(...r(t));return{diagnostics:n,ok:Ae(n).length===0}}var q="components";async function Ye(e){let t=process.cwd();if(!v.existsSync(h.join(t,"package.json"))||!v.existsSync(h.join(t,q)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${q}/\`). Current dir: ${t}`);G(t);let n=Vo(t);if(n.length===0)return process.stdout.write(`(no components in ./${q} \u2014 run \`npx greatstore apps init <name>\` to add one)
86
+ `}function fn(e){if(e===void 0||e==="show")return mo;if(e==="set")return yo()}import*as C from"fs";import*as j from"path";import{readdirSync as ai,readFileSync as ci}from"fs";import{fileURLToPath as ui}from"url";var Me=null;function Ue(){return Me||(Me=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). See AGENTS.md.\\n generateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n // A hook for a voice call with the store\'s assistant: call it at the top\\n // of the component. See AGENTS.md.\\n useVoiceCall: () => {\\n status:\\n | \\"started\\"\\n | \\"connecting\\"\\n | \\"connected\\"\\n | \\"speaking\\"\\n | \\"listening\\"\\n | \\"working\\"\\n | \\"disconnected\\"\\n | \\"ended\\"\\n | \\"rejected\\"\\n | null;\\n available: boolean;\\n start: () => Promise<void>;\\n end: () => void;\\n };\\n store: { slug: string };\\n };\\n}\\n\\n// See AGENTS.md for how an app runs (the assistant picks it by the\\n// manifest\'s name and description, then calls it with these props), the\\n// design rules (style.css, em-based sizing, brand CSS variables), and how to\\n// write an async, backend-backed app.\\n//\\n// Take what you need from `$` at the top: `const { callTool, Image } = props.$;`\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div className=\\"app\\">\\n <strong>__GS_NAME__</strong> \u2014 hello from your app!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Use when <the shopper situation that should make the assistant open this app \u2014 say when to reach for it and what it reports back, never what it looks like; see AGENTS.md>.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","component/style.css":"/*\\n * Your app\'s styles. Plain CSS, applied inside the app alone: nothing here\\n * reaches the store\'s page, and nothing on the page reaches in.\\n *\\n * Style with the store\'s theme variables rather than fixed values \u2014 write\\n * `color: var(--color-foreground)`, never `color: #111827`. Each store sets\\n * its colours, fonts and corner style (and dark mode) in its GreatStore\\n * dashboard; an app built on these variables follows those settings, and\\n * changes with them.\\n *\\n * Fonts: --font-primary, --font-secondary\\n * Surfaces: --color-surface, --color-surface-secondary, --color-surface-accent,\\n * --color-surface-hover\\n * Text: --color-foreground, --color-foreground-secondary,\\n * --color-foreground-muted, --color-foreground-accent\\n * Borders: --color-border-default, --color-border-focus\\n * Brand: --color-primary, --color-primary-foreground, --color-primary-hover,\\n * --color-primary-muted, --color-primary-muted-foreground,\\n * --color-primary-tint, --color-link\\n * Status: --color-error, --color-error-surface, --color-error-border,\\n * --color-success\\n * Corners: --radius-xs, --radius-sm, --radius-md, --radius-lg, --radius-xl,\\n * --radius-2xl, --radius-3xl, --radius-4xl, --radius-pill\\n */\\n\\n/* Size in em, never rem: an app sits inside other people\'s pages. */\\n.app {\\n padding: 1em;\\n border: 1px solid var(--color-border-default);\\n border-radius: var(--radius-lg);\\n background: var(--color-surface);\\n color: var(--color-foreground);\\n font-family: var(--font-primary);\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/bundle.css\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> 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)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async app that builds its render from the generated payload \u2014 `await` it, then return the JSX. `fallback` is **required**: a schema-shaped object you supply that the app preview renders (so a generation-driven app previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `$.close()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `$.useVoiceCall()` | A hook \u2014 call it at the top of your component like any other \u2014 returning `{ status, available, start, end }` for a voice call with the store\'s assistant. `start()` starts the call without opening the chat \u2014 it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended` \u2014 or `rejected` instead of `ended` when the shopper refuses the microphone (calling `start()` again asks again, though a browser where they blocked it refuses without asking). Your app re-renders on every change. |\\n| `$.Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the app outside the store? Pass your own `$` with `Image: \\"img\\"` (or your own component) to render a plain image. |\\n| `$.store` | `{ slug }` \u2014 the store the app is running in. |\\n\\n## Async apps (backend-backed, render-blocking data)\\n\\nIf an app must load data from a backend/API before it can render\\ncorrectly, make it async \u2014 don\'t render an empty shell and fetch in a\\n`useEffect`. Set `\\"async\\": true` in `manifest.json` and export an async\\ndefault. GreatStore waits for your promise (showing a normal loading\\nstate, so you don\'t render your own placeholder), then renders what it\\nresolves to. Apps that render purely from their props stay synchronous.\\n\\nA thrown error is a **retry signal**: the in-store AI sees it and\\nusually re-calls the tool. So only throw when a *different* call could\\nhelp:\\n\\n1. `await` the backend call, then return the finished JSX.\\n2. Validate the AI-passed props first and throw on bad input \u2014 the AI\\n can fix the args and retry. (Don\'t validate the API\'s *output* and\\n throw: the AI can\'t fix the backend, it\'ll just loop.)\\n3. Broadcast a backend failure ONLY when retrying differently could\\n succeed, and say what to change (e.g. empty search \u2192 \\"try a broader\\n keyword\\"). For idempotent failures (500, timeout, missing record)\\n re-running the same call changes nothing \u2014 render a graceful fallback\\n instead of throwing.\\n\\n```tsx\\nexport default async function Example(props: Props) {\\n if (!props.query?.trim()) throw new Error(\\"missing required prop: query\\");\\n const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);\\n if (res.ok) {\\n const { results } = await res.json();\\n if (results.length === 0)\\n throw new Error(`no results for \\"${props.query}\\" \u2014 try a broader keyword`);\\n return <ul>{/* render results */}</ul>;\\n }\\n return <p>Couldn\'t load results right now.</p>; // idempotent: don\'t throw\\n}\\n```\\n","root/README.md":"# GreatStore apps\\n\\nCustom in-chat apps published to your GreatStore tenant. Each app is a\\nReact component living in its own folder under `components/`.\\n\\n```\\nnpm install\\nnpx greatstore apps init <app_name> # add a new app\\nnpx greatstore apps build # builds every components/<name>/bundle.js\\nnpx greatstore apps push # uploads every changed app as a draft\\nnpx greatstore apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `npx greatstore apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `npx greatstore apps pull` (no args) refreshes every live app into\\n `components/<name>/`. Apps with unsaved local edits are skipped with a\\n warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for how an app runs, how to write a manifest name and\\ndescription the assistant will actually pick, and the design rules every\\napp must follow (em-based sizing, brand CSS variables) \u2014 it doubles as\\nguidance for AI coding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"npx greatstore apps build\\",\\n \\"push\\": \\"npx greatstore apps build && npx greatstore apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `npx greatstore build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),Me)}var dn={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function Ge(e,t){let n=e;for(let o of Object.keys(dn)){let s=t[o];s!==void 0&&(n=n.split(dn[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 I from"fs";import*as Ve from"path";var Q="AGENTS.md",wo=["CLAUDE.md","GEMINI.md"];function So(){let e=Ue()[`root/${Q}`];if(e===void 0)throw new Error(`internal: template is missing root/${Q}`);return Ge(e,{version:O})}function gt(e,t={}){let n=[],r=So(),o=Ve.join(e,Q);(I.existsSync(o)?I.readFileSync(o,"utf8"):null)!==r&&(I.writeFileSync(o,r),n.push(Q));for(let i of wo){let a=Ve.join(e,i);t.force&&mn(a)&&I.rmSync(a),mn(a)||(I.symlinkSync(Q,a),n.push(i))}return n}function G(e){try{if(!I.existsSync(Ve.join(e,"components")))return;let t=gt(e);t.length>0&&process.stdout.write(bo(t))}catch{}}function bo(e){return`Refreshed ${e.join(", ")} to match GreatStore CLI v${O}.
87
+ This is a routine, expected update, like a lockfile. Commit it together with your
88
+ own changes, even though you didn't make it.
89
+ `}function mn(e){try{return I.lstatSync(e),!0}catch{return!1}}var gn=/^[a-z][a-z0-9_]*$/;function hn(e){let t=e.positional[0];if(t!==void 0&&!gn.test(t))throw new Error(`Invalid component name: "${t}" (must match ${gn}).`);let n=g(e.flags,"force"),r=y(e.flags,"store"),o=y(e.flags,"out")??".",s=j.resolve(o),i=xo(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?ge(r):Ce()??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=$o(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 ${j.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
90
+ `));return}let c=j.join(s,"components",t);ko(c,t,n);let p=j.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&l.length>0?["",`Also added to the project root: ${l.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," npx greatstore apps build"," npx greatstore apps push",""].join(`
91
+ `))}function xo(e){return C.existsSync(j.join(e,"package.json"))&&C.existsSync(j.join(e,".gsrc"))}function $o(e,t,n,r){if(C.mkdirSync(e,{recursive:!0}),!t&&!n&&C.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?Po():Eo({store:r.store}),s=vo(e,o,n);return C.mkdirSync(j.join(e,"components"),{recursive:!0}),s}function vo(e,t,n){let r=[];for(let[o,s]of t){let i=j.join(e,o);C.mkdirSync(j.dirname(i),{recursive:!0}),!(!n&&C.existsSync(i))&&(C.writeFileSync(i,s),r.push(o))}return r.push(...gt(e,{force:n})),r}function ko(e,t,n){if(C.existsSync(e)&&!n&&C.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);C.mkdirSync(e,{recursive:!0});for(let[r,o]of Co(t))C.writeFileSync(j.join(e,r),o)}function ht(e,t,n=new Set){let r=Ue();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,Ge(s,t)])}function Eo(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return ht("root/",{store:e.store},new Set([Q]))}function Po(){return ht("root/",{},new Set([".gsrc",Q]))}function Co(e){return ht("component/",{name:e,displayName:Ao(e)})}function Ao(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 h from"path";import*as ye from"fs";import*as yt from"path";var x="style.css",_="bundle.css",qe=`./${x}`,yn=256*1024;function jo(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 B(e){let t=yt.join(e,"component.tsx");if(!ye.existsSync(t))return{imported:!1,problems:[]};let n=jo(ye.readFileSync(t,"utf8")),r=n.filter(i=>i!==qe).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${x}, imported as "${qe}"; move these rules there.`})),o=n.includes(qe);if(!o)return{imported:o,problems:r};let s=yt.join(e,x);if(!ye.existsSync(s))return r.push({file:"component.tsx",message:`imports "${qe}", but there's no ${x} beside it.`}),{imported:o,problems:r};for(let i of _o(ye.readFileSync(s,"utf8")))r.push({file:x,message:i});return{imported:o,problems:r}}function _o(e){let t=[],n=Buffer.byteLength(e,"utf8");n>yn&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${yn/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
92
+ `).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 Uo}from"module";import{pathToFileURL as Dn}from"url";import*as An from"fs";import*as V from"path";import{createRequire as Ro}from"module";import*as Je from"path";function Sn(e,t,n){let r=xn(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=Lo(r,o);return s?Fo(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 ${Je.basename(t)} could not be parsed (${o.message})`}}}function bn(e,t,n){let r=xn(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(To(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function To(e,t){if(e.isPropertyAccessExpression(t))return wn(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return wn(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function wn(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function xn(e){let t=Ro(Je.join(e,"package.json"));try{return t("typescript")}catch{return null}}function Lo(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&Oo(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=$n(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?Io(e,t,r.text):null}function Oo(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function $n(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function Io(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=$n(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function Fo(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=wt(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:No(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 wt(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=>wt(e,t,s,r));return o.every(s=>s===null)?null:Pn(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 Pn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return wt(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=En(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function No(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=En(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function En(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Pn(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=V.join(t,"components",n),o=e.manifestPath??V.join(r,"manifest.json"),s=e.sourcePath??V.join(r,"component.tsx"),i=St(t,o),a=St(t,s),l=[],c=null,p=Cn(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let m=JSON.parse(p);!m||typeof m!="object"||Array.isArray(m)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=m}catch(m){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${m.message}`})}let u=Cn(s),d=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:Sn(t,s,u),b=u===null?!1:bn(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:d,usesWindowGreatStore:b,styleFile:St(t,V.join(r,"style.css")),stylesheet:B(r)},diagnostics:l}}function Cn(e){try{return An.readFileSync(e,"utf8")}catch{return null}}function St(e,t){let n=V.relative(e,t);return n.startsWith("..")?t:n.split(V.sep).join("/")}var _n=new Set(["$"]);var bt=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Rn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>bt.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 Tn=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function On(e){if(!e.manifest)return[];let t=Do(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(_n.has(a))continue;if(bt.has(a)){s.push(a);continue}let l=Tn.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:Rn(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:Bo(e.manifestFile,i)}),n}var Ln=8;function Bo(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,Ln).map(s=>`\`${s}\``).join(", "),r=t.length-Ln,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 Do(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 Ho=["anyOf","oneOf","allOf","$ref","not"];function Ke(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>Ke(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of Ho)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,Ke(i,`${t}.${s}`,n);"items"in r&&Ke(r.items,`${t}[]`,n)}function In(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};Ke(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("; ")}.
93
+ 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 Fn(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 Nn(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 Bn(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 Ae(e){return e.filter(t=>t.severity==="error")}function xt(e){return e.filter(t=>t.severity==="warning")}function je(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var Mo=[Fn,In,On,Nn,Bn];function We(e){let{ctx:t,diagnostics:n}=jn(e);for(let r of Mo)n.push(...r(t));return{diagnostics:n,ok:Ae(n).length===0}}var q="components";async function Ye(e){let t=process.cwd();if(!v.existsSync(h.join(t,"package.json"))||!v.existsSync(h.join(t,q)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${q}/\`). Current dir: ${t}`);G(t);let n=qo(t);if(n.length===0)return process.stdout.write(`(no components in ./${q} \u2014 run \`npx greatstore apps init <name>\` to add one)
92
94
  `),[];let r=e.positional,o=r.filter(c=>!n.includes(c));if(o.length>0)throw new Error(`No component named ${o.map(c=>`"${c}"`).join(", ")} in ./${q}`);let s=r.length>0?n.filter(c=>r.includes(c)):n,i=[],a=[];for(let c of s){let p=We({root:t,name:c});for(let u of p.diagnostics)process.stdout.write(` ${je(u)}
93
95
  `);(p.ok?a:i).push(c)}if(a.length===0)return process.stdout.write(`
94
96
  Nothing built \u2014 fix the errors above.
95
- `),process.exitCode=1,i;let l=await qo(t);for(let c of a)try{await Uo(t,c,l)}catch(p){process.stdout.write(` ${q}/${c}: ${p instanceof Error?p.message:String(p)}
97
+ `),process.exitCode=1,i;let l=await Jo(t);for(let c of a)try{await Go(t,c,l)}catch(p){process.stdout.write(` ${q}/${c}: ${p instanceof Error?p.message:String(p)}
96
98
  `),i.push(c)}return i.length>0?(process.stdout.write(`
97
99
  Not built (fix the errors above): ${i.join(", ")}
98
- `),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 Uo(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=h.join(e,q,t),i=h.join(s,"bundle.js");await n({plugins:[Go(s),r()],logLevel:"warn",build:{lib:{entry:h.join(s,"component.tsx"),formats:["es"],fileName:()=>"bundle.js"},outDir:s,emptyOutDir:!1,rollupOptions:{external:["react","react-dom","react/jsx-runtime"],output:{entryFileNames:"bundle.js",paths:{react:"/assets/remote-components/_runtime.js","react-dom":"/assets/remote-components/_runtime.js","react/jsx-runtime":"/assets/remote-components/_runtime.js"}}},minify:!0,sourcemap:!1}});let a=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 ${q}/${t}/bundle.js (${Hn(p)}, ${Mn(a,p)} smaller)
100
+ `),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 Go(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=h.join(e,q,t),i=h.join(s,"bundle.js");await n({plugins:[Vo(s),r()],logLevel:"warn",build:{lib:{entry:h.join(s,"component.tsx"),formats:["es"],fileName:()=>"bundle.js"},outDir:s,emptyOutDir:!1,rollupOptions:{external:["react","react-dom","react/jsx-runtime"],output:{entryFileNames:"bundle.js",paths:{react:"/assets/remote-components/_runtime.js","react-dom":"/assets/remote-components/_runtime.js","react/jsx-runtime":"/assets/remote-components/_runtime.js"}}},minify:!0,sourcemap:!1}});let a=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 ${q}/${t}/bundle.js (${Hn(p)}, ${Mn(a,p)} smaller)
99
101
  `);let u=h.join(s,_);if(!B(s).imported){v.rmSync(u,{force:!0});return}let d=v.readFileSync(h.join(s,x),"utf8"),b=await o(d,h.join(s,x),{minify:!0,legalComments:"none",loader:"css",sourcemap:!1});v.writeFileSync(u,b.code);let m=Buffer.byteLength(b.code,"utf8");process.stdout.write(`built ${q}/${t}/${_} (${Hn(m)}, ${Mn(Buffer.byteLength(d,"utf8"),m)} smaller)
100
- `)}function Go(e){let t=h.join(e,x),n=h.join(e,"component.tsx"),r="\0greatstore-stylesheet";return{name:"greatstore-stylesheet",enforce:"pre",resolveId(o,s){if(!/\.css(\?.*)?$/.test(o))return null;let i=h.resolve(s??n);if(h.resolve(h.dirname(i),o.replace(/\?.*$/,""))===t&&i===n)return r;throw new Error(`${h.relative(e,i)} imports "${o}". A component's styles go in its own ${x}, imported from component.tsx as "./${x}".`)},load(o){return o===r?"export {};":null}}}function Vo(e){let t=h.join(e,q);return v.readdirSync(t).filter(n=>{let r=h.join(t,n);return v.statSync(r).isDirectory()&&v.existsSync(h.join(r,"component.tsx"))}).sort()}function Hn(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Mn(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function qo(e){let t=Mo(h.join(e,"package.json")),n=Un(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=Un(t,"@vitejs/plugin-react");if(!r)throw new Error("Cannot find `@vitejs/plugin-react` in this project. Run `npm install` first.");let o=await import(Dn(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(Dn(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 Un(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Jo(n,t);if(!r)return null;let o=h.dirname(r),s;try{s=JSON.parse(v.readFileSync(r,"utf8"))}catch{return null}let a=Ko(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?h.resolve(o,a):null}function Jo(e,t){let n=h.dirname(e);for(;;){let r=h.join(n,"package.json");if(v.existsSync(r))try{if(JSON.parse(v.readFileSync(r,"utf8")).name===t)return r}catch{}let o=h.dirname(n);if(o===n)return null;n=o}}function Ko(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 Gn(e){let t=en(),n=`${A(t)}/api/apps/components`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
102
+ `)}function Vo(e){let t=h.join(e,x),n=h.join(e,"component.tsx"),r="\0greatstore-stylesheet";return{name:"greatstore-stylesheet",enforce:"pre",resolveId(o,s){if(!/\.css(\?.*)?$/.test(o))return null;let i=h.resolve(s??n);if(h.resolve(h.dirname(i),o.replace(/\?.*$/,""))===t&&i===n)return r;throw new Error(`${h.relative(e,i)} imports "${o}". A component's styles go in its own ${x}, imported from component.tsx as "./${x}".`)},load(o){return o===r?"export {};":null}}}function qo(e){let t=h.join(e,q);return v.readdirSync(t).filter(n=>{let r=h.join(t,n);return v.statSync(r).isDirectory()&&v.existsSync(h.join(r,"component.tsx"))}).sort()}function Hn(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Mn(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Jo(e){let t=Uo(h.join(e,"package.json")),n=Un(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=Un(t,"@vitejs/plugin-react");if(!r)throw new Error("Cannot find `@vitejs/plugin-react` in this project. Run `npm install` first.");let o=await import(Dn(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(Dn(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 Un(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Ko(n,t);if(!r)return null;let o=h.dirname(r),s;try{s=JSON.parse(v.readFileSync(r,"utf8"))}catch{return null}let a=Wo(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?h.resolve(o,a):null}function Ko(e,t){let n=h.dirname(e);for(;;){let r=h.join(n,"package.json");if(v.existsSync(r))try{if(JSON.parse(v.readFileSync(r,"utf8")).name===t)return r}catch{}let o=h.dirname(n);if(o===n)return null;n=o}}function Wo(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 Gn(e){let t=en(),n=`${A(t)}/api/apps/components`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
101
103
  `);return}if(r.components.length===0){process.stdout.write(`(no components in ${t})
102
104
  `);return}let o=r.components.map(a=>({name:a.name,draft:a.draft?`v${a.draft.version}`:"\u2014",live:a.live?`v${a.live.version}`:"\u2014",updated:a.live?.updatedAt??a.draft?.updatedAt??"",permalink:a.permalink??""})),s={name:Math.max(4,...o.map(a=>a.name.length)),draft:Math.max(5,...o.map(a=>a.draft.length)),live:Math.max(4,...o.map(a=>a.live.length)),updated:Math.max(7,...o.map(a=>a.updated.length))},i=`${Z("NAME",s.name)} ${Z("DRAFT",s.draft)} ${Z("LIVE",s.live)} ${Z("UPDATED",s.updated)} LINK`;process.stdout.write(i+`
103
105
  `);for(let a of o)process.stdout.write(`${Z(a.name,s.name)} ${Z(a.draft,s.draft)} ${Z(a.live,s.live)} ${Z(a.updated,s.updated)} ${a.permalink}
104
106
  `)}function Z(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as R from"fs";import*as K from"path";import*as Vn from"crypto";import*as ee from"fs";import*as J from"path";var qn=".gssync.json";function te(e){return Vn.createHash("sha256").update(e).digest("hex")}function we(e){return ee.existsSync(e)?te(ee.readFileSync(e,"utf8")):null}function Se(e){let t=we(J.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:we(J.join(e,"component.tsx")),bundleHash:we(J.join(e,"bundle.js")),...B(e).imported?{styleHash:we(J.join(e,x)),styleBundleHash:we(J.join(e,_))}:{styleHash:null,styleBundleHash:null}}}function be(e){let t=J.join(e,qn);if(!ee.existsSync(t))return null;try{let n=JSON.parse(ee.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 le(e,t){ee.writeFileSync(J.join(e,qn),JSON.stringify(t,null,2)+`
105
- `)}function Jn(e,t){let n=Wo(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:(we(J.join(e,x))??"")!==(t.styleHash??"")}function Wo(e){try{return Se(e)}catch{return null}}async function Kn(e){let t=E(),n=g(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return Yo({slug:t,root:o,args:e,force:n});if(r.length>1&&y(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `npx greatstore apps pull <name>`.");zn(o),G(o);let s=Xn(e),i=[];for(let a of r){let l=await Yn({slug:t,componentDir:K.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),Qn(l,n)}i.length>1&&Wn(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function Yo(e){let{slug:t,root:n,args:r,force:o}=e;if(y(r.flags,"version"))throw new Error("--version is per-component; pass it together with `npx greatstore apps pull <name>`.");zn(n),G(n);let s=Xn(r),i=`${A(t)}/api/apps/components`,a=await f(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
107
+ `)}function Jn(e,t){let n=Yo(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:(we(J.join(e,x))??"")!==(t.styleHash??"")}function Yo(e){try{return Se(e)}catch{return null}}async function Kn(e){let t=E(),n=g(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return zo({slug:t,root:o,args:e,force:n});if(r.length>1&&y(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `npx greatstore apps pull <name>`.");zn(o),G(o);let s=Xn(e),i=[];for(let a of r){let l=await Yn({slug:t,componentDir:K.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),Qn(l,n)}i.length>1&&Wn(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function zo(e){let{slug:t,root:n,args:r,force:o}=e;if(y(r.flags,"version"))throw new Error("--version is per-component; pass it together with `npx greatstore apps pull <name>`.");zn(n),G(n);let s=Xn(r),i=`${A(t)}/api/apps/components`,a=await f(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
106
108
  `);return}let l=[];for(let c of a.components){let p=K.join(n,"components",c.name),u=await Yn({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),Qn(u,o)}Wn(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function Wn(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(`
107
109
  ${s.join(", ")} (of ${e.length}) \u2190 ${t}
108
- `)}async function Yn(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&R.existsSync(n)){let m=be(n);if(Jn(n,m))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${A(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await f(`${i}${o}`)}catch(m){if(o===""&&zo(m))try{a=await f(`${i}?revision=draft`)}catch(ue){return{name:r,status:"failed",message:ue instanceof Error?ue.message:String(ue)}}else return{name:r,status:"failed",message:m instanceof Error?m.message:String(m)}}R.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
109
- `;R.writeFileSync(K.join(n,"manifest.json"),l),R.writeFileSync(K.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(R.writeFileSync(K.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=te(a.source));let u=K.join(n,x),d=K.join(n,_);typeof a.style=="string"?(R.writeFileSync(u,a.style),R.writeFileSync(d,a.style_bundle??a.style),c.push(x,_)):(R.rmSync(u,{force:!0}),R.rmSync(d,{force:!0})),le(n,{version:a.version,manifestHash:te(l),sourceHash:p,bundleHash:te(a.bundle)});let b=Se(n);return le(n,{version:a.version,manifestHash:b.manifestHash,sourceHash:b.sourceHash??"",bundleHash:b.bundleHash??"",styleHash:b.styleHash??"",styleBundleHash:b.styleBundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function zn(e){R.mkdirSync(K.join(e,"components"),{recursive:!0})}function zo(e){return e instanceof H&&e.status===404}function Xn(e){let t=y(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:g(e.flags,"draft")?"?revision=draft":g(e.flags,"live")?"?revision=live":""}function Qn(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
110
+ `)}async function Yn(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&R.existsSync(n)){let m=be(n);if(Jn(n,m))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${A(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await f(`${i}${o}`)}catch(m){if(o===""&&Xo(m))try{a=await f(`${i}?revision=draft`)}catch(ue){return{name:r,status:"failed",message:ue instanceof Error?ue.message:String(ue)}}else return{name:r,status:"failed",message:m instanceof Error?m.message:String(m)}}R.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
111
+ `;R.writeFileSync(K.join(n,"manifest.json"),l),R.writeFileSync(K.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(R.writeFileSync(K.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=te(a.source));let u=K.join(n,x),d=K.join(n,_);typeof a.style=="string"?(R.writeFileSync(u,a.style),R.writeFileSync(d,a.style_bundle??a.style),c.push(x,_)):(R.rmSync(u,{force:!0}),R.rmSync(d,{force:!0})),le(n,{version:a.version,manifestHash:te(l),sourceHash:p,bundleHash:te(a.bundle)});let b=Se(n);return le(n,{version:a.version,manifestHash:b.manifestHash,sourceHash:b.sourceHash??"",bundleHash:b.bundleHash??"",styleHash:b.styleHash??"",styleBundleHash:b.styleBundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function zn(e){R.mkdirSync(K.join(e,"components"),{recursive:!0})}function Xo(e){return e instanceof H&&e.status===404}function Xn(e){let t=y(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:g(e.flags,"draft")?"?revision=draft":g(e.flags,"live")?"?revision=live":""}function Qn(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
110
112
  `);return}case"skipped":process.stdout.write(` skipped ${e.name}: ${e.message}
111
113
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
112
- `);return}}import*as S from"fs";import*as k from"path";import*as Zn from"crypto";import*as ze from"fs";import*as er from"path";function Xe(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function Xo(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 tr(e){let t=Xo(e);return t?`${Zn.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function Qe(e,t){let n=er.join(e,t);return ze.existsSync(n)?ze.readFileSync(n):null}async function or(e){let t=E(),n=process.cwd();Qo(n);let r=k.join(n,"components");if(!S.existsSync(r))throw new Error("No components/ directory here. Run `npx greatstore apps init <name>` to scaffold the project root and your first component.");G(n);let o=e.positional,s=y(e.flags,"manifest"),i=y(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `npx greatstore apps push <name>`.");if(o.length>0){let c=g(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let d=await et({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(d),rr(d)}p.length>1&&nr(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=$t(r);if(a.length===0){process.stdout.write("(no components in ./components \u2014 run `npx greatstore apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await et({slug:t,root:n,name:c,force:!1});l.push(p),rr(p)}nr(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function nr(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(`
114
+ `);return}}import*as S from"fs";import*as k from"path";import*as Zn from"crypto";import*as ze from"fs";import*as er from"path";function Xe(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function Qo(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 tr(e){let t=Qo(e);return t?`${Zn.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function Qe(e,t){let n=er.join(e,t);return ze.existsSync(n)?ze.readFileSync(n):null}async function or(e){let t=E(),n=process.cwd();Zo(n);let r=k.join(n,"components");if(!S.existsSync(r))throw new Error("No components/ directory here. Run `npx greatstore apps init <name>` to scaffold the project root and your first component.");G(n);let o=e.positional,s=y(e.flags,"manifest"),i=y(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `npx greatstore apps push <name>`.");if(o.length>0){let c=g(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let d=await et({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(d),rr(d)}p.length>1&&nr(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=$t(r);if(a.length===0){process.stdout.write("(no components in ./components \u2014 run `npx greatstore apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await et({slug:t,root:n,name:c,force:!1});l.push(p),rr(p)}nr(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function nr(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(`
113
115
  ${s.join(", ")} (of ${e.length}) \u2192 ${t}
114
116
  `)}async function et(e){let{slug:t,root:n,name:r,force:o}=e,s=k.join(n,"components",r);if(!S.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(!S.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=We({root:n,name:r,manifestPath:i,sourcePath:l});for(let F of xt(c.diagnostics))process.stdout.write(` ${je(F)}
115
117
  `);if(!c.ok)return{name:r,status:"failed",message:Ae(c.diagnostics).map(F=>`${F.file}: ${F.message}`).join(`
116
- ${Ze}`)};let p=S.readFileSync(i,"utf8"),u=k.join(s,"listing.json"),d=Pe(t);if(d&&!S.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let b=Se(s),m=be(s),ue=e.bundlePath===void 0&&m?.bundleHash!==void 0&&m.sourceHash!==(b.sourceHash??"")&&m.bundleHash===(b.bundleHash??""),Te=m?.styleBundleHash!==void 0&&(m.styleHash??"")!==(b.styleHash??"")&&m.styleBundleHash===(b.styleBundleHash??""),Lt=B(s).imported,Ot=k.join(s,_);if(Lt&&!S.existsSync(Ot))return{name:r,status:"failed",message:`components/${r}/${_} is missing \u2014 run \`npx greatstore build ${r}\` first`};if(!o&&m!==null&&m.manifestHash===b.manifestHash&&m.sourceHash===(b.sourceHash??"")&&m.bundleHash!==void 0&&m.bundleHash===(b.bundleHash??"")&&(m.styleHash??"")===(b.styleHash??"")&&(m.styleBundleHash??"")===(b.styleBundleHash??""))return{name:r,status:"unchanged"};let Mr=S.readFileSync(a,"utf8"),It=S.existsSync(l)?S.readFileSync(l,"utf8"):null,D=new FormData;if(D.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),D.append("bundle",new Blob([Mr],{type:"text/javascript"}),"bundle.js"),It!==null&&D.append("source",new Blob([It],{type:"text/plain; charset=utf-8"}),"component.tsx"),Lt&&(D.append("style",new Blob([S.readFileSync(Ot,"utf8")],{type:"text/css; charset=utf-8"}),_),D.append("style_source",new Blob([S.readFileSync(k.join(s,x),"utf8")],{type:"text/css; charset=utf-8"}),x)),d){let F=S.readFileSync(u,"utf8");D.append("listing",new Blob([F],{type:"application/json"}),"listing.json");let Ft=k.join(s,"changelog.json");S.existsSync(Ft)&&D.append("changelog",new Blob([S.readFileSync(Ft,"utf8")],{type:"application/json"}),"changelog.json");let Nt=null;try{Nt=Xe(JSON.parse(F))}catch{}for(let at of Nt??[]){let Bt=Qe(s,at);if(!Bt)return{name:r,status:"failed",message:`components/${r}/${at} is named in listing.json but doesn't exist`};D.append("screenshot",new Blob([new Uint8Array(Bt)]),at)}}o||D.append("base_version",String(m?.version??0));let Ur=`${De(t)}/components/${encodeURIComponent(r)}`,pe;try{pe=await f(Ur,{method:"POST",multipart:D})}catch(F){return{name:r,status:"failed",message:F instanceof Error?F.message:String(F)}}let Ee=Se(s);return le(s,{version:pe.version,manifestHash:Ee.manifestHash,sourceHash:Ee.sourceHash??"",bundleHash:Ee.bundleHash??"",styleHash:Ee.styleHash??"",styleBundleHash:Ee.styleBundleHash??""}),{name:r,status:"pushed",version:pe.version,...pe.permalink!==void 0&&{permalink:pe.permalink},...pe.detached&&{detached:!0},...ue?{staleBundle:!0}:{},...Te?{staleStyle:!0}:{}}}function $t(e){return S.readdirSync(e).filter(t=>{let n=k.join(e,t);return S.statSync(n).isDirectory()&&S.existsSync(k.join(n,"manifest.json"))}).sort()}function Qo(e){let t=k.join(e,"manifest.json"),n=k.join(e,"components");if(S.existsSync(t)&&!S.existsSync(n))throw new Error(["Detected the old single-component layout (manifest.json at the project root).","The CLI now uses a multi-component layout: scaffold a fresh dir with","`npx greatstore apps init`, then move your component into `components/<name>/`. Re-run `npx greatstore apps push`","from the new project root."].join(" "))}var Ze=" ".repeat(12);function rr(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
118
+ ${Ze}`)};let p=S.readFileSync(i,"utf8"),u=k.join(s,"listing.json"),d=Pe(t);if(d&&!S.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let b=Se(s),m=be(s),ue=e.bundlePath===void 0&&m?.bundleHash!==void 0&&m.sourceHash!==(b.sourceHash??"")&&m.bundleHash===(b.bundleHash??""),Te=m?.styleBundleHash!==void 0&&(m.styleHash??"")!==(b.styleHash??"")&&m.styleBundleHash===(b.styleBundleHash??""),Lt=B(s).imported,Ot=k.join(s,_);if(Lt&&!S.existsSync(Ot))return{name:r,status:"failed",message:`components/${r}/${_} is missing \u2014 run \`npx greatstore build ${r}\` first`};if(!o&&m!==null&&m.manifestHash===b.manifestHash&&m.sourceHash===(b.sourceHash??"")&&m.bundleHash!==void 0&&m.bundleHash===(b.bundleHash??"")&&(m.styleHash??"")===(b.styleHash??"")&&(m.styleBundleHash??"")===(b.styleBundleHash??""))return{name:r,status:"unchanged"};let Mr=S.readFileSync(a,"utf8"),It=S.existsSync(l)?S.readFileSync(l,"utf8"):null,D=new FormData;if(D.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),D.append("bundle",new Blob([Mr],{type:"text/javascript"}),"bundle.js"),It!==null&&D.append("source",new Blob([It],{type:"text/plain; charset=utf-8"}),"component.tsx"),Lt&&(D.append("style",new Blob([S.readFileSync(Ot,"utf8")],{type:"text/css; charset=utf-8"}),_),D.append("style_source",new Blob([S.readFileSync(k.join(s,x),"utf8")],{type:"text/css; charset=utf-8"}),x)),d){let F=S.readFileSync(u,"utf8");D.append("listing",new Blob([F],{type:"application/json"}),"listing.json");let Ft=k.join(s,"changelog.json");S.existsSync(Ft)&&D.append("changelog",new Blob([S.readFileSync(Ft,"utf8")],{type:"application/json"}),"changelog.json");let Nt=null;try{Nt=Xe(JSON.parse(F))}catch{}for(let at of Nt??[]){let Bt=Qe(s,at);if(!Bt)return{name:r,status:"failed",message:`components/${r}/${at} is named in listing.json but doesn't exist`};D.append("screenshot",new Blob([new Uint8Array(Bt)]),at)}}o||D.append("base_version",String(m?.version??0));let Ur=`${De(t)}/components/${encodeURIComponent(r)}`,pe;try{pe=await f(Ur,{method:"POST",multipart:D})}catch(F){return{name:r,status:"failed",message:F instanceof Error?F.message:String(F)}}let Ee=Se(s);return le(s,{version:pe.version,manifestHash:Ee.manifestHash,sourceHash:Ee.sourceHash??"",bundleHash:Ee.bundleHash??"",styleHash:Ee.styleHash??"",styleBundleHash:Ee.styleBundleHash??""}),{name:r,status:"pushed",version:pe.version,...pe.permalink!==void 0&&{permalink:pe.permalink},...pe.detached&&{detached:!0},...ue?{staleBundle:!0}:{},...Te?{staleStyle:!0}:{}}}function $t(e){return S.readdirSync(e).filter(t=>{let n=k.join(e,t);return S.statSync(n).isDirectory()&&S.existsSync(k.join(n,"manifest.json"))}).sort()}function Zo(e){let t=k.join(e,"manifest.json"),n=k.join(e,"components");if(S.existsSync(t)&&!S.existsSync(n))throw new Error(["Detected the old single-component layout (manifest.json at the project root).","The CLI now uses a multi-component layout: scaffold a fresh dir with","`npx greatstore apps init`, then move your component into `components/<name>/`. Re-run `npx greatstore apps push`","from the new project root."].join(" "))}var Ze=" ".repeat(12);function rr(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
117
119
  `),e.detached&&process.stdout.write(`${Ze}This was a ready-made app GreatStore keeps up to date. It's now your own copy and won't get those updates.
118
120
  `),e.staleBundle&&process.stdout.write(`${Ze}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
119
121
  `),e.staleStyle&&process.stdout.write(`${Ze}style.css changed but bundle.css did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
120
122
  `);return;case"unchanged":process.stdout.write(` unchanged ${e.name}
121
123
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
122
124
  `);return}}async function ar(e){let t=e.positional;if(t.length===0)throw new Error("Usage: npx greatstore apps publish <name> [<name>...] [--version N]");let n=E(),r=y(e.flags,"version"),o;if(r!==void 0){if(t.length>1)throw new Error("--version is per-component; pass it together with a single `npx greatstore apps publish <name>`.");let c=Number.parseInt(r,10);if(!Number.isInteger(c)||c<1)throw new Error(`Invalid --version: ${r}`);o=c}if(t.length===1){let c=t[0],p=await sr(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
123
- `),p.embed_snippet&&ir(c,p.embed_snippet);return}let s=[];for(let c of t){let p;try{let u=await sr(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),Zo(p)}for(let c of s)c.snippet&&ir(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(`
125
+ `),p.embed_snippet&&ir(c,p.embed_snippet);return}let s=[];for(let c of t){let p;try{let u=await sr(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),es(p)}for(let c of s)c.snippet&&ir(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(`
124
126
  ${l.join(", ")} (of ${s.length}) \u2192 ${n}
125
127
  `),a>0&&(process.exitCode=1)}async function sr(e,t,n){let r=`${A(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return f(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function ir(e,t){process.stdout.write(`
126
128
  Put ${e} on your site by pasting this where you want it:
@@ -130,16 +132,16 @@ ${t.split(`
130
132
  `)}
131
133
 
132
134
  If the GreatStore script is already on the page, the second line is enough.
133
- `)}function Zo(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
135
+ `)}function es(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
134
136
  `);return}process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
135
137
  `)}async function cr(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=E(),r=`${A(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
136
- `)}import*as lr from"readline";async function ur(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=E();if(!g(e.flags,"yes")&&(await es(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
138
+ `)}import*as lr from"readline";async function ur(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=E();if(!g(e.flags,"yes")&&(await ts(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
137
139
  `);return}let r=`${A(n)}/api/apps/components/${encodeURIComponent(t)}`;await f(r,{method:"DELETE"}),process.stdout.write(`Deleted ${t}.
138
- `)}function es(e){return new Promise(t=>{let n=lr.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as M from"fs";import*as tt from"path";var ts=/^[a-z][a-z0-9_]*$/;async function pr(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(!ts.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=tt.join(process.cwd(),"components",t),s=tt.join(process.cwd(),"components",n),i=M.existsSync(o);if(M.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${A(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await f(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
139
- `);return}M.renameSync(o,s),ns(s,n),G(process.cwd()),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
140
- `)}function ns(e,t){let n=tt.join(e,"manifest.json");if(!M.existsSync(n))return;let r=M.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
141
- `;M.writeFileSync(n,o);let s=be(e);s&&s.manifestHash===te(r)&&le(e,{...s,manifestHash:te(o)})}import*as ne from"fs";import*as _e from"path";async function fr(e){let t=E();if(!Pe(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=ft();zt(await as(new URL(n).origin));let r=await Ye({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=De(t),i=_e.join(o,"components"),a=$t(i),l=ne.readdirSync(i).filter(u=>ne.statSync(_e.join(i,u)).isDirectory()),c=(await f(`${s}/components`)).components.filter(u=>u.live!==null).map(u=>u.name),p=[];for(let u of a)p.push(r.includes(u)?{name:u,status:"failed",message:"didn't build; see the errors above"}:await rs(s,o,t,u));for(let u of l.filter(d=>!a.includes(d)))p.push({name:u,status:"failed",message:`components/${u}/manifest.json is missing`});for(let u of c.filter(d=>!l.includes(d)))try{await f(`${s}/components/${encodeURIComponent(u)}/unpublish`,{method:"POST",body:{}}),p.push({name:u,status:"unpublished"})}catch(d){p.push({name:u,status:"failed",message:dr(d)})}for(let u of p){let d=u.status==="published"?` v${u.version}`:u.status==="failed"?`: ${u.message}`:"";process.stdout.write(` ${u.status.padEnd(11)} ${u.name}${d}
142
- `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function rs(e,t,n,r){try{let o=await os(e,r);if(o&&ss(o,_e.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await et({slug:n,root:t,name:r,force:!0});return s.status!=="pushed"||s.version===void 0?{name:r,status:"failed",message:s.message??"push failed"}:(await f(`${e}/components/${encodeURIComponent(r)}/publish`,{method:"POST",body:{version:s.version},validationDetail:!0}),{name:r,status:"published",version:s.version})}catch(o){return{name:r,status:"failed",message:dr(o)}}}async function os(e,t){try{return await f(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof H&&n.status===404)return null;throw n}}function ss(e,t){let n=i=>{let a=_e.join(t,i);return ne.existsSync(a)?ne.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)===(B(t).imported?n(x):null)&&(e.style_bundle??e.style??null)===(B(t).imported?n(_):null)&&xe(e.manifest)===xe(JSON.parse(r))&&xe(e.listing)===xe(is(JSON.parse(o),t))&&xe(e.changelog??null)===xe(s===null?null:nt(JSON.parse(s)))}catch{return!1}}function is(e,t){let n=nt(e),r=Xe(n);return r?{...n,screenshots:r.map(o=>{let s=Qe(t,o);return(s&&tr(s))??o})}:n}function nt(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(nt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,nt(n)])):e}function xe(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 as(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 dr(e){return e instanceof Error?e.message:String(e)}var mr=`npx greatstore apps \u2014 author and ship custom in-chat apps
140
+ `)}function ts(e){return new Promise(t=>{let n=lr.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as M from"fs";import*as tt from"path";var ns=/^[a-z][a-z0-9_]*$/;async function pr(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(!ns.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=tt.join(process.cwd(),"components",t),s=tt.join(process.cwd(),"components",n),i=M.existsSync(o);if(M.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${A(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await f(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
141
+ `);return}M.renameSync(o,s),rs(s,n),G(process.cwd()),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
142
+ `)}function rs(e,t){let n=tt.join(e,"manifest.json");if(!M.existsSync(n))return;let r=M.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
143
+ `;M.writeFileSync(n,o);let s=be(e);s&&s.manifestHash===te(r)&&le(e,{...s,manifestHash:te(o)})}import*as ne from"fs";import*as _e from"path";async function fr(e){let t=E();if(!Pe(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=ft();zt(await cs(new URL(n).origin));let r=await Ye({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=De(t),i=_e.join(o,"components"),a=$t(i),l=ne.readdirSync(i).filter(u=>ne.statSync(_e.join(i,u)).isDirectory()),c=(await f(`${s}/components`)).components.filter(u=>u.live!==null).map(u=>u.name),p=[];for(let u of a)p.push(r.includes(u)?{name:u,status:"failed",message:"didn't build; see the errors above"}:await os(s,o,t,u));for(let u of l.filter(d=>!a.includes(d)))p.push({name:u,status:"failed",message:`components/${u}/manifest.json is missing`});for(let u of c.filter(d=>!l.includes(d)))try{await f(`${s}/components/${encodeURIComponent(u)}/unpublish`,{method:"POST",body:{}}),p.push({name:u,status:"unpublished"})}catch(d){p.push({name:u,status:"failed",message:dr(d)})}for(let u of p){let d=u.status==="published"?` v${u.version}`:u.status==="failed"?`: ${u.message}`:"";process.stdout.write(` ${u.status.padEnd(11)} ${u.name}${d}
144
+ `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function os(e,t,n,r){try{let o=await ss(e,r);if(o&&is(o,_e.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await et({slug:n,root:t,name:r,force:!0});return s.status!=="pushed"||s.version===void 0?{name:r,status:"failed",message:s.message??"push failed"}:(await f(`${e}/components/${encodeURIComponent(r)}/publish`,{method:"POST",body:{version:s.version},validationDetail:!0}),{name:r,status:"published",version:s.version})}catch(o){return{name:r,status:"failed",message:dr(o)}}}async function ss(e,t){try{return await f(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof H&&n.status===404)return null;throw n}}function is(e,t){let n=i=>{let a=_e.join(t,i);return ne.existsSync(a)?ne.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)===(B(t).imported?n(x):null)&&(e.style_bundle??e.style??null)===(B(t).imported?n(_):null)&&xe(e.manifest)===xe(JSON.parse(r))&&xe(e.listing)===xe(as(JSON.parse(o),t))&&xe(e.changelog??null)===xe(s===null?null:nt(JSON.parse(s)))}catch{return!1}}function as(e,t){let n=nt(e),r=Xe(n);return r?{...n,screenshots:r.map(o=>{let s=Qe(t,o);return(s&&tr(s))??o})}:n}function nt(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(nt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,nt(n)])):e}function xe(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 cs(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 dr(e){return e instanceof Error?e.message:String(e)}var mr=`npx greatstore apps \u2014 author and ship custom in-chat apps
143
145
 
144
146
  Usage:
145
147
  npx greatstore apps <subcommand> [args] [flags]
@@ -157,13 +159,13 @@ Subcommands:
157
159
  `;async function vt(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(mr),0;case"init":return hn(n),0;case"build":return await Ye(n),0;case"list":return await Gn(n),0;case"pull":return await Kn(n),0;case"push":return await or(n),0;case"publish":return await ar(n),0;case"unpublish":return await cr(n),0;case"rename":return await pr(n),0;case"delete":return await ur(n),0;case"release":return await fr(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
158
160
 
159
161
  ${mr}`),1}}async function gr(e){let t=w(e),n=`${$(t)}/configure/config`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
160
- `);return}cs(t,r.brand)}function cs(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 ${kt(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 ${kt(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${kt(t.cspConnectHosts)}`),process.stdout.write(n.join(`
162
+ `);return}ls(t,r.brand)}function ls(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 ${kt(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 ${kt(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${kt(t.cspConnectHosts)}`),process.stdout.write(n.join(`
161
163
  `)+`
162
- `)}function kt(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as rt from"fs";import*as wr from"path";var hr="theme.",ls=["displayName","assistantName","storeLink"],us=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function Sr(e){let t=w(e),n={};for(let c of ls){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 us){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(d=>d.trim()).filter(d=>d.length>0);n[c]=u.length===0?null:u}let r=y(e.flags,"themeFile"),o=ds(e.flags),s=g(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:yr(c,"--theme")}else r!==void 0?i=yr(ps(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await fs(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=`${$(t)}/configure/save`,l=await f(a,{method:"POST",body:n,validationDetail:!0});if(g(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
164
+ `)}function kt(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as rt from"fs";import*as wr from"path";var hr="theme.",us=["displayName","assistantName","storeLink"],ps=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function Sr(e){let t=w(e),n={};for(let c of us){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 ps){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(d=>d.trim()).filter(d=>d.length>0);n[c]=u.length===0?null:u}let r=y(e.flags,"themeFile"),o=ms(e.flags),s=g(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:yr(c,"--theme")}else r!==void 0?i=yr(fs(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await ds(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=`${$(t)}/configure/save`,l=await f(a,{method:"POST",body:n,validationDetail:!0});if(g(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
163
165
  `);return}process.stdout.write(`Saved ${Object.keys(n).join(", ")} \u2192 ${t}
164
- `)}function ps(e,t){let n=wr.resolve(e);if(!rt.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return rt.readFileSync(n,"utf8")}function yr(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 fs(e){let t=`${$(e)}/configure/config`;return(await f(t)).brand.theme??{}}function ds(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(hr))continue;let o=n.slice(hr.length),s=X[o];if(!s){let i=pn(o);throw new Error(`Unknown theme field "${o}".
166
+ `)}function fs(e,t){let n=wr.resolve(e);if(!rt.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return rt.readFileSync(n,"utf8")}function yr(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 ds(e){let t=`${$(e)}/configure/config`;return(await f(t)).brand.theme??{}}function ms(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(hr))continue;let o=n.slice(hr.length),s=X[o];if(!s){let i=pn(o);throw new Error(`Unknown theme field "${o}".
165
167
  Valid fields: ${Object.keys(X).join(", ")}.`+(i.length>0?`
166
- 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]=ms(n,o,r)}return Object.keys(t).length>0?t:null}function ms(e,t,n){let r=X[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 it from"fs";import*as $e from"path";var ot=["icon","logoLight","logoDark"];function st(e){if(e&&ot.includes(e))return e;throw new Error(`Asset kind must be one of: ${ot.join(", ")}.`)}var gs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function br(e){let t=w(e),n=st(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${ot.join("|")}> <file>`);let o=$e.resolve(r);if(!it.existsSync(o))throw new Error(`File not found: ${o}`);let s=gs[$e.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=it.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),$e.basename(o));let l=`${$(t)}/configure/upload/${n}`,c=await f(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
168
+ 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]=gs(n,o,r)}return Object.keys(t).length>0?t:null}function gs(e,t,n){let r=X[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 it from"fs";import*as $e from"path";var ot=["icon","logoLight","logoDark"];function st(e){if(e&&ot.includes(e))return e;throw new Error(`Asset kind must be one of: ${ot.join(", ")}.`)}var hs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function br(e){let t=w(e),n=st(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${ot.join("|")}> <file>`);let o=$e.resolve(r);if(!it.existsSync(o))throw new Error(`File not found: ${o}`);let s=hs[$e.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=it.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),$e.basename(o));let l=`${$(t)}/configure/upload/${n}`,c=await f(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
167
169
  `)}async function xr(e){let t=w(e),n=st(e.positional[0]),r=`${$(t)}/configure/delete/${n}`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
168
170
  `)}async function $r(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await gr(n);return;case"set":await Sr(n);return;case"upload":await br(n);return;case"clear":await xr(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`npx greatstore configure [set|upload|clear]\`.`)}}async function T(e){let t=`${$(e)}/connectors/config`;return f(t)}function W(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 re(e,t,n,r=t.makerEnabled){let o=`${$(e)}/connectors/save`;return f(o,{method:"POST",body:{makerEnabled:r,makerPriority:Math.min(t.makerPriority,n.length),connectors:n}})}function oe(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=w(e),n=await T(t);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
169
171
  `);return}if(process.stdout.write(`Maker MCP: ${n.makerEnabled?"on":"off"} (position ${n.makerPriority+1})
@@ -179,32 +181,37 @@ Did you mean: ${i.join(", ")}?`:""))}if(typeof r!="string"){if(s.kind==="boolean
179
181
  `);return}let s=`${$(t)}/connectors/health`,i=await f(s,{method:"POST",body:r?{id:r}:{}});if(g(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
180
182
  `);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)
181
183
  `):(process.stdout.write(` failed ${c}: ${l.error??"discovery failed"}
182
- `),process.exitCode=1)}}var hs={readOnly:"read-only",write:"write",other:"other"};async function jr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors tools <name|id|maker|webmcp> [<tool>] [--json]");let r=n==="maker"||n==="webmcp"?n:oe(await T(t),n).id,o=await f(`${$(t)}/connectors/tools`,{method:"POST",body:{id:r}});if(!o.ok||!o.tools)throw new Error(`Couldn't list the tools of ${n}: ${o.error??"discovery failed"}`);let s=e.positional[1],i=s?o.tools.filter(a=>a.name===s):o.tools;if(s&&i.length===0)throw new Error(`${n} has no tool named "${s}". Run \`npx greatstore connectors tools ${n}\` to see them.`);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
184
+ `),process.exitCode=1)}}var ys={readOnly:"read-only",write:"write",other:"other"};async function jr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors tools <name|id|maker|webmcp> [<tool>] [--json]");let r=n==="maker"||n==="webmcp"?n:oe(await T(t),n).id,o=await f(`${$(t)}/connectors/tools`,{method:"POST",body:{id:r}});if(!o.ok||!o.tools)throw new Error(`Couldn't list the tools of ${n}: ${o.error??"discovery failed"}`);let s=e.positional[1],i=s?o.tools.filter(a=>a.name===s):o.tools;if(s&&i.length===0)throw new Error(`${n} has no tool named "${s}". Run \`npx greatstore connectors tools ${n}\` to see them.`);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
183
185
  `);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.
184
- `);return}process.stdout.write(i.map(ws).join(`
186
+ `);return}process.stdout.write(i.map(Ss).join(`
185
187
 
186
188
  `)+`
187
- `)}function ys(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 ws(e){let t=[`## ${e.name}`,`${hs[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${ys(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(`
189
+ `)}function ws(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 Ss(e){let t=[`## ${e.name}`,`${ys[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${ws(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(`
188
190
  `);t.push("","Input:");let n=Pt(e.inputSchema,1);return t.push(...n.length>0?n:[" (none)"]),t.join(`
189
- `)}function Pt(e,t){let n=Re(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=Re(i)??{};o.push(...Ct(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${At(t)}(no other fields accepted)`),o}function Ct(e,t,n,r){let o=[Ss(t),n?"required":"optional",...Ar(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${At(r)}${e} (${o.join(", ")})${s}`];i.push(...Pt(t,r+1));let a=Re(t.items);if(a){let l=Pt(a,r+2);l.length>0?i.push(`${At(r+1)}each item:`,...l):(Ar(a).length>0||a.description)&&i.push(...Ct("each item",a,!0,r+1))}for(let l of["anyOf","oneOf","allOf"])(Array.isArray(t[l])?t[l]:[]).forEach((p,u)=>{let d=Re(p);d&&i.push(...Ct(`${l}[${u}]`,d,!0,r+1))});return i}function Ss(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Re(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var bs=[["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 Ar(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 bs)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 Re(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function At(e){return" ".repeat(e)}var xs=7,_r=120,$s=864e5,vs={mcp:"connector",local:"custom app",browser:"browser"};async function Rr(e){let t=w(e),n=ks(y(e.flags,"days")),r=y(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*$s),i=await f(`${$(t)}/usage/report`,{method:"POST",body:{from:s.toISOString(),to:o.toISOString(),bucket:"day"}}),a=i.data.tools.toolFailures??[],l=r?a.filter(u=>u.tool_name===r):a,c=i.data.tools.toolFailuresTruncated===!0;if(g(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:l,truncated:c},null,2)+`
191
+ `)}function Pt(e,t){let n=Re(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=Re(i)??{};o.push(...Ct(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${At(t)}(no other fields accepted)`),o}function Ct(e,t,n,r){let o=[bs(t),n?"required":"optional",...Ar(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${At(r)}${e} (${o.join(", ")})${s}`];i.push(...Pt(t,r+1));let a=Re(t.items);if(a){let l=Pt(a,r+2);l.length>0?i.push(`${At(r+1)}each item:`,...l):(Ar(a).length>0||a.description)&&i.push(...Ct("each item",a,!0,r+1))}for(let l of["anyOf","oneOf","allOf"])(Array.isArray(t[l])?t[l]:[]).forEach((p,u)=>{let d=Re(p);d&&i.push(...Ct(`${l}[${u}]`,d,!0,r+1))});return i}function bs(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Re(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var xs=[["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 Ar(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 xs)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 Re(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function At(e){return" ".repeat(e)}var $s=7,_r=120,vs=864e5,ks={mcp:"connector",local:"custom app",browser:"browser"};async function Rr(e){let t=w(e),n=Es(y(e.flags,"days")),r=y(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*vs),i=await f(`${$(t)}/usage/report`,{method:"POST",body:{from:s.toISOString(),to:o.toISOString(),bucket:"day"}}),a=i.data.tools.toolFailures??[],l=r?a.filter(u=>u.tool_name===r):a,c=i.data.tools.toolFailuresTruncated===!0;if(g(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:l,truncated:c},null,2)+`
190
192
  `);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)
191
193
  `);return}process.stdout.write(`Tool errors in ${p}, last ${n} days (most frequent first):
192
194
 
193
- `);for(let u of l){let d=vs[u.tool_backend]??u.tool_backend;process.stdout.write(` ${String(u.occurrences).padStart(5)}\xD7 ${u.tool_name} (${d}), last ${u.last_at}
195
+ `);for(let u of l){let d=ks[u.tool_backend]??u.tool_backend;process.stdout.write(` ${String(u.occurrences).padStart(5)}\xD7 ${u.tool_name} (${d}), last ${u.last_at}
194
196
  ${u.error}
195
197
  `)}c&&process.stdout.write(`
196
198
  The rarest errors are left out of this list.
197
- `)}function ks(e){if(e===void 0)return xs;let t=Number(e);if(!Number.isInteger(t)||t<1||t>_r)throw new Error(`--days must be a whole number from 1 to ${_r}.`);return t}async function Tr(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 Er(n);return;case"enable":await Et(n,!0);return;case"disable":await Et(n,!1);return;case"maker":await Pr(n);return;case"health":await Cr(n);return;case"tools":await jr(n);return;case"errors":await Rr(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health|tools|errors]\`.`)}}function jt(e,t=15){if(!e.trim())return"";let n=e.split(`
199
+ `)}function Es(e){if(e===void 0)return $s;let t=Number(e);if(!Number.isInteger(t)||t<1||t>_r)throw new Error(`--days must be a whole number from 1 to ${_r}.`);return t}async function Tr(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 Er(n);return;case"enable":await Et(n,!0);return;case"disable":await Et(n,!1);return;case"maker":await Pr(n);return;case"health":await Cr(n);return;case"tools":await jr(n);return;case"errors":await Rr(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health|tools|errors]\`.`)}}function jt(e,t=15){if(!e.trim())return"";let n=e.split(`
198
200
  `),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(`
199
201
  `).trimEnd()}function Lr(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&&me(s,t)>0}r&&n.push(o)}return n.join(`
200
- `).trimEnd()}import*as ke from"fs";import*as _t from"os";import*as Fr from"path";var Es="version-check.json",Ps="0.0.0-dev";function Nr(e){return Fr.join(ie(e),Es)}function Rt(e=_t.homedir()){try{let t=JSON.parse(ke.readFileSync(Nr(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 Br(e,t=_t.homedir()){if(e===Ps)return!1;let n=Rt(t);if(n?.version===e)return!1;let r=n!==null&&me(e,n.version)>0;try{ke.mkdirSync(ie(t),{recursive:!0,mode:448});let o=n?{version:e,previous:n.version}:{version:e};ke.writeFileSync(Nr(t),JSON.stringify(o)+`
201
- `)}catch{return!1}return r}var Or="\x1B[34m",Cs="\x1B[30;42m",Ir="\x1B[0m";function Dr(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}`:""}
202
- `;let o=t?` ${Cs} Updated! ${Ir}${Or} ${r}`:"";return`${Or}greatstore v${e}${o}${Ir}
202
+ `).trimEnd()}import*as ke from"fs";import*as _t from"os";import*as Fr from"path";var Ps="version-check.json",Cs="0.0.0-dev";function Nr(e){return Fr.join(ie(e),Ps)}function Rt(e=_t.homedir()){try{let t=JSON.parse(ke.readFileSync(Nr(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 Br(e,t=_t.homedir()){if(e===Cs)return!1;let n=Rt(t);if(n?.version===e)return!1;let r=n!==null&&me(e,n.version)>0;try{ke.mkdirSync(ie(t),{recursive:!0,mode:448});let o=n?{version:e,previous:n.version}:{version:e};ke.writeFileSync(Nr(t),JSON.stringify(o)+`
203
+ `)}catch{return!1}return r}var Or="\x1B[34m",As="\x1B[30;42m",Ir="\x1B[0m";function Dr(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}`:""}
204
+ `;let o=t?` ${As} Updated! ${Ir}${Or} ${r}`:"";return`${Or}greatstore v${e}${o}${Ir}
203
205
  `}var Tt=`# Changelog
204
206
 
205
207
  All notable changes to \`@greatstore/cli\` are recorded here. The format
206
208
  follows [Keep a Changelog](https://keepachangelog.com/).
207
209
 
210
+ ## 0.2.23 \u2014 2026-11-10
211
+
212
+ ### Changed
213
+ - When a command brings \`AGENTS.md\` up to date, it says the update is routine and belongs in your next commit.
214
+
208
215
  ## 0.2.22 \u2014 2026-11-10
209
216
 
210
217
  ### Changed
@@ -943,13 +950,13 @@ Environment:
943
950
  GS_API_BASE Override API base (full URL, no trailing slash).
944
951
  GS_DASHBOARD_BASE Override the sign-in/store-picker base URL.
945
952
  GS_BROWSER_CMD Override the browser-open command.
946
- `,As=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function js(){let e=process.argv.slice(2),t=Dt(e);if(ln(O),g(t.flags,"version")){process.stdout.write(`greatstore v${O}
953
+ `,js=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function _s(){let e=process.argv.slice(2),t=Dt(e);if(ln(O),g(t.flags,"version")){process.stdout.write(`greatstore v${O}
947
954
 
948
955
  `);let n=jt(Tt);return n&&process.stdout.write(`${n}
949
- `),0}if(g(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?fn(t.positional[0]):void 0;return process.stdout.write(n??Hr),0}if(g(t.flags,"json")||process.stderr.write(Dr(O,Br(O))),t.command!==null&&As.has(t.command))return vt({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await nn(t),0;case"logout":return rn(),0;case"whoami":return on();case"switch":return sn(t.positional);case"apps":return vt(t);case"configure":return await $r(t),0;case"connectors":return await Tr(t),0;case"skill":return un(),0;case"whats-new":{let n=Rt()?.previous,r=n?Lr(Tt,n):jt(Tt);return process.stdout.write(`${r||"No release notes in this build."}
956
+ `),0}if(g(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?fn(t.positional[0]):void 0;return process.stdout.write(n??Hr),0}if(g(t.flags,"json")||process.stderr.write(Dr(O,Br(O))),t.command!==null&&js.has(t.command))return vt({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await nn(t),0;case"logout":return rn(),0;case"whoami":return on();case"switch":return sn(t.positional);case"apps":return vt(t);case"configure":return await $r(t),0;case"connectors":return await Tr(t),0;case"skill":return un(),0;case"whats-new":{let n=Rt()?.previous,r=n?Lr(Tt,n):jt(Tt);return process.stdout.write(`${r||"No release notes in this build."}
950
957
  `),0}default:return process.stderr.write(`Unknown command: ${t.command}
951
958
 
952
- ${Hr}`),1}}js().then(e=>process.exit(e||Number(process.exitCode??0))).catch(e=>{e instanceof U?process.stderr.write(`${e.message}
959
+ ${Hr}`),1}}_s().then(e=>process.exit(e||Number(process.exitCode??0))).catch(e=>{e instanceof U?process.stderr.write(`${e.message}
953
960
  `):e instanceof H?process.stderr.write(`Error: ${e.message}
954
961
  `):e instanceof Y||e instanceof se?process.stderr.write(`Error: ${e.message}
955
962
  `):e instanceof Error?process.stderr.write(`Error: ${e.message}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "greatstore",
3
- "version": "0.2.22",
3
+ "version": "0.2.23",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",