@greatstore/cli 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/cli.js +587 -2987
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,789 +1,41 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/cli.ts
4
- var SHORT_ALIASES = {
5
- h: "help",
6
- v: "version",
7
- o: "out"
8
- };
9
- function parseArgs(argv) {
10
- const out = { command: null, positional: [], flags: {} };
11
- if (argv.length === 0) return out;
12
- let i = 0;
13
- const first = argv[0];
14
- if (first && !first.startsWith("-")) {
15
- out.command = first;
16
- i = 1;
17
- }
18
- for (; i < argv.length; i++) {
19
- const token = argv[i] ?? "";
20
- if (token.startsWith("--")) {
21
- const eq = token.indexOf("=");
22
- let key;
23
- let value;
24
- if (eq !== -1) {
25
- key = token.slice(2, eq);
26
- value = token.slice(eq + 1);
27
- } else {
28
- key = token.slice(2);
29
- const next = argv[i + 1];
30
- if (next === void 0 || next.startsWith("--") || next.startsWith("-")) {
31
- value = true;
32
- } else {
33
- value = next;
34
- i++;
35
- }
36
- }
37
- if (key) out.flags[key] = value;
38
- } else if (token.startsWith("-") && token.length > 1) {
39
- const short = token.slice(1);
40
- const aliased = SHORT_ALIASES[short];
41
- if (!aliased) continue;
42
- const next = argv[i + 1];
43
- if (next === void 0 || next.startsWith("-")) {
44
- out.flags[aliased] = true;
45
- } else {
46
- out.flags[aliased] = next;
47
- i++;
48
- }
49
- } else {
50
- out.positional.push(token);
51
- }
52
- }
53
- return out;
54
- }
55
- function flagString(flags, key) {
56
- const v = flags[key];
57
- return typeof v === "string" ? v : void 0;
58
- }
59
- function flagBool(flags, key) {
60
- const v = flags[key];
61
- return v === true || v === "true";
62
- }
63
-
64
- // src/loopback.ts
65
- import * as crypto from "crypto";
66
- import * as http from "http";
67
- import { spawn } from "child_process";
68
- var CALLBACK_PATH = "/callback";
69
- var LOGO_SVG = `<svg width="40" height="40" viewBox="0 0 82 82" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path transform="scale(0.8) translate(7, 4)" d="M13 70.7522C13 70.7522 1.5 68.7522 1.5 57.7522C1.5 46.7522 23 48.2522 23 48.2522L80 47.2522C80 47.2522 91.5938 45.7522 91 36.2522C90.4062 26.7522 77 26.7522 77 26.7522H51C51 26.7522 44.5 27.6967 40.5 23.2522C36.5 18.8078 39 11.7522 44.5 7.25221C50 2.75222 52.5 0.752227 58 1.75223C63.5 2.75223 67.5 7.25221 65 14.2522C62.5 21.2522 32.5 74.7522 32.5 74.7522C32.5 74.7522 27.5 87.7522 36.5 90.7522C45.5 93.7522 49.5 86.2522 49.5 86.2522C49.5 86.2522 64 61.7522 66 58.7522C68 55.7522 72 52.4522 78 54.2522C84 56.0522 85.5 67.7522 85.5 69.7522C85.5 71.7522 85.5 82.2522 78 83.2522C70.5 84.2522 67.5 79.7522 66.5 78.7522C65.5 77.7522 31 20.7522 30 19.7522C29 18.7522 22 11.7522 16 15.7522C10 19.7522 12.5 27.2522 13 28.7522C13.5 30.2522 28 56.2522 29 58.7522C30 61.2522 31.5 66.7522 27 70.2522C22.5 73.7522 13 70.7522 13 70.7522Z" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
70
- var PAGE_STYLE = `:root{color-scheme:light}
2
+ var kn={h:"help",v:"version",o:"out"};function Be(e){let t={command:null,positional:[],flags:{}};if(e.length===0)return t;let n=0,r=e[0];for(r&&!r.startsWith("-")&&(t.command=r,n=1);n<e.length;n++){let o=e[n]??"";if(o.startsWith("--")){let s=o.indexOf("="),i,a;if(s!==-1)i=o.slice(2,s),a=o.slice(s+1);else{i=o.slice(2);let l=e[n+1];l===void 0||l.startsWith("--")||l.startsWith("-")?a=!0:(a=l,n++)}i&&(t.flags[i]=a)}else if(o.startsWith("-")&&o.length>1){let s=o.slice(1),i=kn[s];if(!i)continue;let a=e[n+1];a===void 0||a.startsWith("-")?t.flags[i]=!0:(t.flags[i]=a,n++)}else t.positional.push(o)}return t}function h(e,t){let n=e[t];return typeof n=="string"?n:void 0}function m(e,t){let n=e[t];return n===!0||n==="true"}import*as Ue from"crypto";import*as Ge from"http";import{spawn as He}from"child_process";var Pn="/callback",Cn='<svg width="40" height="40" viewBox="0 0 82 82" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path transform="scale(0.8) translate(7, 4)" d="M13 70.7522C13 70.7522 1.5 68.7522 1.5 57.7522C1.5 46.7522 23 48.2522 23 48.2522L80 47.2522C80 47.2522 91.5938 45.7522 91 36.2522C90.4062 26.7522 77 26.7522 77 26.7522H51C51 26.7522 44.5 27.6967 40.5 23.2522C36.5 18.8078 39 11.7522 44.5 7.25221C50 2.75222 52.5 0.752227 58 1.75223C63.5 2.75223 67.5 7.25221 65 14.2522C62.5 21.2522 32.5 74.7522 32.5 74.7522C32.5 74.7522 27.5 87.7522 36.5 90.7522C45.5 93.7522 49.5 86.2522 49.5 86.2522C49.5 86.2522 64 61.7522 66 58.7522C68 55.7522 72 52.4522 78 54.2522C84 56.0522 85.5 67.7522 85.5 69.7522C85.5 71.7522 85.5 82.2522 78 83.2522C70.5 84.2522 67.5 79.7522 66.5 78.7522C65.5 77.7522 31 20.7522 30 19.7522C29 18.7522 22 11.7522 16 15.7522C10 19.7522 12.5 27.2522 13 28.7522C13.5 30.2522 28 56.2522 29 58.7522C30 61.2522 31.5 66.7522 27 70.2522C22.5 73.7522 13 70.7522 13 70.7522Z" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>',$n=`:root{color-scheme:light}
71
3
  body{font-family:"Instrument Sans",ui-sans-serif,system-ui,sans-serif;font-size:15px;line-height:1.6;margin:0;padding:4rem 1.5rem;max-width:26rem;margin-inline:auto;color:#091717;background:#fcfaf6;text-align:center}
72
4
  .logo{color:#091717;margin-bottom:1.5rem}
73
5
  h1{font-family:"Instrument Serif",ui-serif,Georgia,serif;font-style:italic;font-weight:400;font-size:1.75rem;margin:0 0 .5rem}
74
- p{color:#2c3a38}`;
75
- var SUCCESS_HTML = `<!doctype html>
6
+ p{color:#2c3a38}`,En=`<!doctype html>
76
7
  <html lang="en"><head><meta charset="utf-8"><title>GreatStore CLI</title>
77
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
78
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
79
10
  <link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=Instrument+Serif:ital@1&display=swap" rel="stylesheet">
80
- <style>${PAGE_STYLE}</style></head>
11
+ <style>${$n}</style></head>
81
12
  <body>
82
- <div class="logo">${LOGO_SVG}</div>
13
+ <div class="logo">${Cn}</div>
83
14
  <h1>You're signed in.</h1>
84
15
  <p>This window will close automatically. If it doesn't, you can close it and return to your terminal.</p>
85
16
  <script>setTimeout(function(){window.close();},250);</script>
86
- </body></html>`;
87
- var FAILURE_HTML = `<!doctype html>
17
+ </body></html>`,Me=`<!doctype html>
88
18
  <html lang="en"><head><meta charset="utf-8"><title>GreatStore CLI</title>
89
19
  <style>body{font:14px/1.5 system-ui;margin:4rem auto;max-width:32rem;color:#222;text-align:center}
90
20
  h1{font-size:1.4rem;color:#a40000}code{background:#f4f4f4;padding:.1em .3em;border-radius:.2em}</style></head>
91
21
  <body><h1>Sign-in failed.</h1>
92
- <p>Return to your terminal for details.</p></body></html>`;
93
- var LoopbackError = class extends Error {
94
- constructor(message) {
95
- super(message);
96
- this.name = "LoopbackError";
97
- }
98
- };
99
- async function captureLoopbackToken(options) {
100
- const state = (options.generateState ?? defaultState)();
101
- const timeoutMs = options.timeoutMs ?? 5 * 60 * 1e3;
102
- const open = options.openBrowser ?? ((url) => openInBrowser(url, options.browserCmdEnv));
103
- const server = http.createServer();
104
- try {
105
- await new Promise((resolve8) => server.listen(0, "127.0.0.1", resolve8));
106
- const address = server.address();
107
- const authTarget = new URL(`${options.dashboardBaseUrl}/cli/authorize`);
108
- authTarget.searchParams.set("port", String(address.port));
109
- authTarget.searchParams.set("state", state);
110
- if (options.requestedStore) {
111
- authTarget.searchParams.set("store", options.requestedStore);
112
- }
113
- const authUrl = authTarget.toString();
114
- const tokenPromise = waitForCallback(server, state, timeoutMs);
115
- open(authUrl);
116
- return await tokenPromise;
117
- } finally {
118
- server.close();
119
- }
120
- }
121
- function waitForCallback(server, expectedState, timeoutMs) {
122
- return new Promise((resolve8, reject) => {
123
- let settled = false;
124
- const settle = (fn) => {
125
- if (settled) return;
126
- settled = true;
127
- fn();
128
- };
129
- const timer = setTimeout(() => {
130
- settle(() => reject(new LoopbackError("Sign-in timed out. Re-run `gs login`.")));
131
- }, timeoutMs);
132
- if (typeof timer.unref === "function") timer.unref();
133
- server.on("request", (req, res) => {
134
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
135
- if (url.pathname !== CALLBACK_PATH) {
136
- res.writeHead(404, { "content-type": "text/plain" });
137
- res.end("Not found");
138
- return;
139
- }
140
- const params = url.searchParams;
141
- const error = params.get("error");
142
- const errorDescription = params.get("error_description");
143
- const token = params.get("code");
144
- const returnedState = params.get("state");
145
- if (returnedState !== expectedState) {
146
- res.writeHead(400, { "content-type": "text/html" });
147
- res.end(FAILURE_HTML);
148
- clearTimeout(timer);
149
- settle(() => reject(new LoopbackError("Sign-in didn't complete. Please try again.")));
150
- return;
151
- }
152
- if (error || !token) {
153
- res.writeHead(400, { "content-type": "text/html" });
154
- res.end(FAILURE_HTML);
155
- clearTimeout(timer);
156
- settle(
157
- () => reject(new LoopbackError(errorDescription ?? "Sign-in failed. Please try again."))
158
- );
159
- return;
160
- }
161
- res.writeHead(200, { "content-type": "text/html" });
162
- res.end(SUCCESS_HTML);
163
- clearTimeout(timer);
164
- const store = params.get("store")?.trim();
165
- settle(() => resolve8(store ? { token, store } : { token }));
166
- });
167
- });
168
- }
169
- function defaultState() {
170
- return crypto.randomBytes(16).toString("hex");
171
- }
172
- function openInBrowser(url, overrideCmd) {
173
- const override = overrideCmd?.trim();
174
- const cmd = override ?? defaultBrowserCommand();
175
- if (!cmd) {
176
- return;
177
- }
178
- try {
179
- let child;
180
- if (cmd === "start") {
181
- const command = `start "" "${url}"`;
182
- child = spawn("cmd.exe", ["/d", "/s", "/c", command], {
183
- stdio: "ignore",
184
- detached: true,
185
- windowsVerbatimArguments: true
186
- });
187
- } else {
188
- child = spawn(cmd, [url], { stdio: "ignore", detached: true });
189
- }
190
- child.on("error", () => {
191
- });
192
- child.unref();
193
- } catch {
194
- }
195
- }
196
- function defaultBrowserCommand() {
197
- switch (process.platform) {
198
- case "darwin":
199
- return "open";
200
- case "win32":
201
- return "start";
202
- case "linux":
203
- return "xdg-open";
204
- default:
205
- return null;
206
- }
207
- }
208
-
209
- // src/credentials.ts
210
- import * as fs from "fs";
211
- import * as os from "os";
212
- import * as path from "path";
213
- var DIR_NAME = ".greatstore";
214
- var FILE_NAME = "credentials.json";
215
- function credentialsDir(home = os.homedir()) {
216
- return path.join(home, DIR_NAME);
217
- }
218
- function credentialsPath(home = os.homedir()) {
219
- return path.join(credentialsDir(home), FILE_NAME);
220
- }
221
- function read(home = os.homedir()) {
222
- const file = credentialsPath(home);
223
- let raw;
224
- try {
225
- const stat = fs.statSync(file);
226
- if (process.platform !== "win32") {
227
- const mode = stat.mode & 511;
228
- if (mode & 63) {
229
- throw new Error(
230
- `Refusing to read ${file}: permissions are ${mode.toString(8)} (should be 600). Run \`chmod 600 ${file}\`.`
231
- );
232
- }
233
- }
234
- raw = fs.readFileSync(file, "utf8");
235
- } catch (err) {
236
- if (isENOENT(err)) return null;
237
- throw err;
238
- }
239
- try {
240
- const parsed = JSON.parse(raw);
241
- if (typeof parsed.access_token !== "string") return null;
242
- return parsed;
243
- } catch {
244
- return null;
245
- }
246
- }
247
- function write(creds, home = os.homedir()) {
248
- const dir = credentialsDir(home);
249
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
250
- if (process.platform !== "win32") {
251
- try {
252
- fs.chmodSync(dir, 448);
253
- } catch {
254
- }
255
- }
256
- const file = credentialsPath(home);
257
- fs.writeFileSync(file, `${JSON.stringify(creds, null, 2)}
258
- `, {
259
- mode: 384
260
- });
261
- if (process.platform !== "win32") {
262
- fs.chmodSync(file, 384);
263
- }
264
- }
265
- function clear(home = os.homedir()) {
266
- fs.rmSync(credentialsPath(home), { force: true });
267
- }
268
- function decodeJwtPayload(token) {
269
- const parts = token.split(".");
270
- if (parts.length !== 3) {
271
- throw new Error("Invalid JWT: expected three dot-separated segments");
272
- }
273
- const segment = parts[1];
274
- if (!segment) throw new Error("Invalid JWT: empty payload segment");
275
- const padded = segment + "=".repeat((4 - segment.length % 4) % 4);
276
- const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
277
- const json = Buffer.from(base64, "base64").toString("utf8");
278
- return JSON.parse(json);
279
- }
280
- function isExpired(creds, nowSeconds = Math.floor(Date.now() / 1e3)) {
281
- return creds.expires_at <= nowSeconds;
282
- }
283
- function isENOENT(err) {
284
- return typeof err === "object" && err !== null && err.code === "ENOENT";
285
- }
286
-
287
- // src/version.ts
288
- var CLI_VERSION = true ? "0.1.8" : "0.0.0-dev";
289
-
290
- // src/http.ts
291
- var HttpError = class extends Error {
292
- constructor(status, message, code) {
293
- super(message);
294
- this.status = status;
295
- this.code = code;
296
- this.name = "HttpError";
297
- }
298
- };
299
- var AuthRequiredError = class extends Error {
300
- constructor(message = "Sign in first. Run `gs login`.") {
301
- super(message);
302
- this.name = "AuthRequiredError";
303
- }
304
- };
305
- var SESSION_EXPIRED = "Session expired. Run `gs login` to sign in again.";
306
- async function request(url, options = {}) {
307
- const stored = read();
308
- if (!stored) throw new AuthRequiredError();
309
- if (isExpired(stored)) throw new AuthRequiredError(SESSION_EXPIRED);
310
- try {
311
- return await sendOnce(url, options, stored.access_token);
312
- } catch (err) {
313
- if (err instanceof HttpError && err.status === 401) {
314
- throw new AuthRequiredError(SESSION_EXPIRED);
315
- }
316
- throw err;
317
- }
318
- }
319
- async function sendOnce(url, options, accessToken) {
320
- const headers = {
321
- accept: "application/json",
322
- authorization: `Bearer ${accessToken}`,
323
- // The server decides whether this version may be served; stating it on
324
- // every request is what lets it refuse an incompatible CLI.
325
- "x-gs-cli-version": CLI_VERSION,
326
- ...options.headers ?? {}
327
- };
328
- let body;
329
- if (options.multipart && options.body !== void 0) {
330
- throw new Error("request(): pass either `body` or `multipart`, not both");
331
- }
332
- if (options.multipart) {
333
- body = options.multipart;
334
- delete headers["content-type"];
335
- } else if (options.body !== void 0) {
336
- body = JSON.stringify(options.body);
337
- headers["content-type"] = "application/json";
338
- }
339
- const init = {
340
- method: options.method ?? "GET",
341
- headers
342
- };
343
- if (body !== void 0) init.body = body;
344
- const res = await fetch(url, init);
345
- if (res.status >= 200 && res.status < 300) {
346
- if (res.status === 204) return void 0;
347
- const ct = res.headers.get("content-type") ?? "";
348
- if (ct.includes("application/json")) {
349
- return await res.json();
350
- }
351
- return await res.text();
352
- }
353
- const text = await res.text();
354
- let parsed = {};
355
- try {
356
- parsed = JSON.parse(text);
357
- } catch {
358
- }
359
- const identifier = parsed.code ?? parsed.error;
360
- const message = options.validationDetail && res.status === 400 && parsed.error ? parsed.error : buildErrorMessage(res.status, identifier, parsed.detail);
361
- throw new HttpError(res.status, message, parsed.code ?? parsed.error);
362
- }
363
- var UPGRADE_MESSAGE = "This version of the GreatStore CLI is no longer supported.\n\n npm install -g @greatstore/cli@latest\n";
364
- var KNOWN_ERROR_MESSAGES = {
365
- cli_upgrade_required: { message: UPGRADE_MESSAGE },
366
- // /api/apps/components/:name — parseName()
367
- INVALID_NAME: {
368
- message: "Invalid component name. Use lowercase letters, digits, and underscores, starting with a letter."
369
- },
370
- // commitDraft() / promote() / unpublish() — StoreComponentFailure
371
- not_found: { message: "Component not found on the server." },
372
- concurrent_write: {
373
- message: "Another change landed before this one. Run `gs apps pull` and try again."
374
- },
375
- name_mismatch: {
376
- message: "Manifest `name` does not match the component folder name.",
377
- includeDetail: true
378
- },
379
- manifest_invalid: {
380
- message: "manifest.json is invalid.",
381
- includeDetail: true
382
- },
383
- bundle_too_large: {
384
- message: "bundle.js is too large."
385
- },
386
- bundle_not_module: {
387
- message: "bundle.js is not a valid ES module."
388
- },
389
- source_too_large: {
390
- message: "component.tsx is too large."
391
- }
392
- };
393
- function buildErrorMessage(status, identifier, detail) {
394
- if (identifier && identifier in KNOWN_ERROR_MESSAGES) {
395
- const entry = KNOWN_ERROR_MESSAGES[identifier];
396
- if (!entry) return genericMessage(status);
397
- if (entry.includeDetail && detail) {
398
- return `${entry.message} (${detail})`;
399
- }
400
- return entry.message;
401
- }
402
- return genericMessage(status);
403
- }
404
- function genericMessage(status) {
405
- if (status === 401) return "Sign-in needed. Run `gs login`.";
406
- if (status === 426) return UPGRADE_MESSAGE;
407
- if (status === 403) return "Not authorized for this component or store.";
408
- if (status === 404) return "Not found.";
409
- if (status === 409) return "Conflict \u2014 refresh and try again.";
410
- if (status === 413) return "Upload too large.";
411
- if (status === 429) return "Too many requests \u2014 wait a moment and retry.";
412
- if (status >= 500) return "Server error \u2014 try again shortly.";
413
- if (status >= 400) return "Request rejected.";
414
- return "Unexpected response.";
415
- }
416
- function buildCredentials(token, store) {
417
- const claims = decodeJwtPayload(token);
418
- const sub = readString(claims, "sub");
419
- if (!sub) throw new Error("Token is missing a `sub` claim.");
420
- const exp = readNumber(claims, "exp");
421
- return {
422
- access_token: token,
423
- expires_at: exp ?? Math.floor(Date.now() / 1e3) + 60 * 60,
424
- sub,
425
- ...maybeString(claims, "email", "email"),
426
- ...maybeString(claims, "accountId", "accountId"),
427
- ...maybeString(claims, "name", "name"),
428
- ...maybeString(claims, "surname", "surname"),
429
- ...maybeBool(claims, "superUser", "superUser"),
430
- ...store ? { store } : {}
431
- };
432
- }
433
- function readString(obj, key) {
434
- const v = obj[key];
435
- return typeof v === "string" ? v : void 0;
436
- }
437
- function readNumber(obj, key) {
438
- const v = obj[key];
439
- return typeof v === "number" && Number.isFinite(v) ? v : void 0;
440
- }
441
- function maybeString(obj, src, dst) {
442
- const v = readString(obj, src);
443
- return v ? { [dst]: v } : {};
444
- }
445
- function maybeBool(obj, src, dst) {
446
- const v = obj[src];
447
- if (v === true) return { [dst]: true };
448
- if (typeof v === "string" && v.toLowerCase() === "true") return { [dst]: true };
449
- return {};
450
- }
451
-
452
- // src/config.ts
453
- import * as fs2 from "fs";
454
- import * as path2 from "path";
455
- var DASHBOARD_BASE_DEFAULT = "https://my.greatstore.ai";
456
- var StoreResolutionError = class extends Error {
457
- constructor(message) {
458
- super(message);
459
- this.name = "StoreResolutionError";
460
- }
461
- };
462
- function requireProjectStore(input = {}) {
463
- const fromRc = findGsrc(input.cwd ?? process.cwd());
464
- if (fromRc) return assertMatchesSignedInStore(fromRc);
465
- throw new StoreResolutionError(
466
- "No .gsrc found in this directory or any ancestor. Run `gs apps init --store <slug>` first to scaffold a GreatStore project."
467
- );
468
- }
469
- function resolveReadStore(cwd = process.cwd()) {
470
- const fromRc = findGsrc(cwd);
471
- if (fromRc) return assertMatchesSignedInStore(fromRc);
472
- const pinned = signedInStore();
473
- if (pinned) return pinned;
474
- throw new StoreResolutionError(
475
- "No store selected. Run `gs login`, or run from a project with a .gsrc."
476
- );
477
- }
478
- function signedInStore() {
479
- try {
480
- return read()?.store ?? null;
481
- } catch {
482
- return null;
483
- }
484
- }
485
- function assertMatchesSignedInStore(slug) {
486
- const pinned = signedInStore();
487
- if (pinned && pinned !== slug) {
488
- throw new StoreResolutionError(
489
- `This targets store "${slug}" but you're signed in to "${pinned}". Run \`gs switch ${slug}\` to change stores.`
490
- );
491
- }
492
- return slug;
493
- }
494
- function findGsrc(cwd) {
495
- let dir = path2.resolve(cwd);
496
- const root = path2.parse(dir).root;
497
- while (true) {
498
- const candidate = path2.join(dir, ".gsrc");
499
- if (fs2.existsSync(candidate)) {
500
- try {
501
- const raw = fs2.readFileSync(candidate, "utf8");
502
- const parsed = JSON.parse(raw);
503
- if (typeof parsed.store === "string" && parsed.store.trim()) {
504
- return parsed.store.trim();
505
- }
506
- } catch {
507
- }
508
- }
509
- if (dir === root) return null;
510
- const parent = path2.dirname(dir);
511
- if (parent === dir) return null;
512
- dir = parent;
513
- }
514
- }
515
- function resolveAdminStore(args) {
516
- const explicit = flagString(args.flags, "store")?.trim();
517
- if (explicit) return assertMatchesSignedInStore(explicit);
518
- const fromRc = findGsrc(process.cwd());
519
- if (fromRc) return assertMatchesSignedInStore(fromRc);
520
- const pinned = signedInStore();
521
- if (pinned) return pinned;
522
- throw new StoreResolutionError(
523
- "No store selected. Pass --store <slug>, or run from a project with a .gsrc."
524
- );
525
- }
526
- function apiBaseFor(slug, env = process.env) {
527
- const override = env.GS_API_BASE?.trim();
528
- if (override) return stripTrailingSlash(override);
529
- return `https://${slug}.greatstore.ai`;
530
- }
531
- function dashboardBase(env = process.env) {
532
- const override = env.GS_DASHBOARD_BASE?.trim();
533
- if (override) return stripTrailingSlash(override);
534
- return DASHBOARD_BASE_DEFAULT;
535
- }
536
- function adminApiBase(slug, env = process.env) {
537
- return `${dashboardBase(env)}/${slug}/admin`;
538
- }
539
- function stripTrailingSlash(s) {
540
- return s.endsWith("/") ? s.slice(0, -1) : s;
541
- }
542
-
543
- // src/commands/login.ts
544
- async function loginCommand(args) {
545
- const requestedStore = flagString(args.flags, "store")?.trim();
546
- process.stdout.write("Opening browser for sign-in\u2026\n");
547
- const { token, store } = await captureLoopbackToken({
548
- dashboardBaseUrl: dashboardBase(),
549
- ...requestedStore ? { requestedStore } : {}
550
- });
551
- const next = buildCredentials(token, store);
552
- write(next);
553
- const who = next.email ?? next.sub;
554
- if (next.store) {
555
- process.stdout.write(`Logged in as ${who}, working on store "${next.store}".
556
- `);
557
- } else {
558
- process.stdout.write(`Logged in as ${who}.
559
- `);
560
- }
561
- }
562
-
563
- // src/commands/logout.ts
564
- function logoutCommand() {
565
- const existed = read() !== null;
566
- clear();
567
- process.stdout.write(existed ? "Logged out.\n" : "Not logged in.\n");
568
- }
569
-
570
- // src/commands/whoami.ts
571
- function whoamiCommand() {
572
- const stored = read();
573
- if (!stored) {
574
- process.stderr.write("Not logged in. Run `gs login`.\n");
575
- return 1;
576
- }
577
- const expired = isExpired(stored);
578
- const lines = [
579
- `sub: ${stored.sub}`,
580
- `email: ${stored.email ?? "(none)"}`,
581
- `accountId: ${stored.accountId ?? "(none)"}`,
582
- `superUser: ${stored.superUser ?? false}`,
583
- `store: ${stored.store ?? "(none \u2014 run `gs switch`)"}`,
584
- `name: ${[stored.name, stored.surname].filter(Boolean).join(" ") || "(none)"}`,
585
- `expires: ${new Date(stored.expires_at * 1e3).toISOString()}${expired ? " (EXPIRED)" : ""}`
586
- ];
587
- process.stdout.write(lines.join("\n") + "\n");
588
- return expired ? 1 : 0;
589
- }
590
-
591
- // src/commands/switch.ts
592
- async function switchCommand(positional) {
593
- const stored = read();
594
- if (!stored) throw new AuthRequiredError();
595
- const requested = positional[0]?.trim();
596
- process.stdout.write("Opening browser to switch stores\u2026\n");
597
- const { token, store } = await captureLoopbackToken({
598
- dashboardBaseUrl: dashboardBase(),
599
- ...requested ? { requestedStore: requested } : {}
600
- });
601
- const next = buildCredentials(token, store);
602
- write(next);
603
- if (next.store) {
604
- process.stdout.write(`Now working on store "${next.store}".
605
- `);
606
- } else {
607
- process.stdout.write("Switched.\n");
608
- }
609
- return 0;
610
- }
611
-
612
- // src/commands/skill.ts
613
- import * as fs3 from "fs";
614
- import * as os2 from "os";
615
- import * as path4 from "path";
616
-
617
- // src/skill.ts
618
- import { existsSync as existsSync2 } from "fs";
619
- import * as path3 from "path";
620
- import { fileURLToPath } from "url";
621
- var SKILL_DIR_NAME = "greatstore";
622
- function skillSourceDir() {
623
- for (const candidate of ["./gs-skill/", "../../gs-skill/"]) {
624
- const dir = path3.resolve(fileURLToPath(new URL(candidate, import.meta.url)));
625
- if (existsSync2(path3.join(dir, "SKILL.md"))) return dir;
626
- }
627
- throw new Error(
628
- "internal: this install of the CLI is missing the agent skill files"
629
- );
630
- }
631
-
632
- // src/commands/skill.ts
633
- function skillCommand() {
634
- process.stdout.write(installInstructions(skillSourceDir()));
635
- }
636
- function installInstructions(source) {
637
- if (looksEphemeral(source)) {
638
- throw new Error(
639
- [
640
- "This copy of the CLI is running from a temporary cache, so the agent",
641
- "skill has no stable location to install from. Install the CLI first,",
642
- "then ask again:",
643
- "",
644
- " npm install -g @greatstore/cli",
645
- " gs skill"
646
- ].join("\n")
647
- );
648
- }
649
- return [
650
- "GreatStore agent skill \u2014 installation instructions for an AI coding agent.",
651
- "",
652
- "Skill source on this machine:",
653
- ` ${source}`,
654
- "",
655
- `Symlink that folder into your skills directory as "${SKILL_DIR_NAME}":`,
656
- "",
657
- " mkdir -p <SKILLS_DIR>",
658
- ` ln -sfn "${source}" "<SKILLS_DIR>/${SKILL_DIR_NAME}"`,
659
- "",
660
- "Symlink it, do not copy it: the link keeps the skill current every",
661
- "time @greatstore/cli is upgraded, with nothing to re-run.",
662
- "",
663
- "<SKILLS_DIR> is wherever you load skills from \u2014 for Claude Code that",
664
- "is ~/.claude/skills for every project, or ./.claude/skills for this",
665
- "one. Use your own location if it differs, and create it if missing.",
666
- `Then read <SKILLS_DIR>/${SKILL_DIR_NAME}/SKILL.md to confirm the install.`,
667
- "",
668
- `On Windows: mklink /D "<SKILLS_DIR>\\${SKILL_DIR_NAME}" "${source}"`,
669
- ""
670
- ].join("\n");
671
- }
672
- function looksEphemeral(dir) {
673
- const posix = dir.split(path4.sep).join("/");
674
- if (/\/(?:_npx|_cacache|\.bun\/install\/cache)\//.test(posix)) return true;
675
- if (/\/(?:dlx-|bunx-|\.npx-)/.test(posix)) return true;
676
- const tmp = os2.tmpdir();
677
- return isInside(dir, tmp) || isInside(dir, realPath(tmp));
678
- }
679
- function isInside(child, parent) {
680
- const rel = path4.relative(parent, child);
681
- return rel !== "" && !rel.startsWith("..") && !path4.isAbsolute(rel);
682
- }
683
- function realPath(p) {
684
- try {
685
- return fs3.realpathSync(p);
686
- } catch {
687
- return p;
688
- }
689
- }
690
-
691
- // src/commands/configure/theme-fields.ts
692
- var THEME_FIELDS = {
693
- mode: {
694
- kind: "string",
695
- values: ["auto", "light", "dark", "custom"],
696
- help: "Color scheme. `auto` follows the shopper's system preference.",
697
- brandVisible: true
698
- },
699
- radius: {
700
- kind: "string",
701
- values: ["sharp", "default", "rounded"],
702
- help: "Corner rounding preset applied to every surface.",
703
- brandVisible: true
704
- },
705
- panelPosition: {
706
- kind: "string",
707
- values: ["left", "right", "middle"],
708
- help: "Where the chat panel sits on desktop.",
709
- brandVisible: true
710
- },
711
- fontFamily: {
712
- kind: "string",
713
- help: "Primary font family name.",
714
- brandVisible: true
715
- },
716
- secondaryFontFamily: {
717
- kind: "string",
718
- help: "Font family for the assistant's chat bubbles.",
719
- brandVisible: true
720
- },
721
- mobileBottomBar: {
722
- kind: "boolean",
723
- help: "Show the compact bottom bar on mobile.",
724
- brandVisible: true
725
- },
726
- zIndex: {
727
- kind: "integer",
728
- help: "Stacking order of the chat panel on the host page."
729
- },
730
- brandColor: { kind: "color", help: "Accent color.", brandVisible: true },
731
- surfaceColor: { kind: "color", help: "Background color.", brandVisible: true },
732
- textColor: { kind: "color", help: "Text color.", brandVisible: true },
733
- surface: { kind: "color", help: "Panel background." },
734
- surfaceSecondary: { kind: "color", help: "Secondary background." },
735
- surfaceAccent: { kind: "color", help: "Accented background." },
736
- surfaceHover: { kind: "color", help: "Hovered background." },
737
- foreground: { kind: "color", help: "Body text." },
738
- foregroundSecondary: { kind: "color", help: "Secondary text." },
739
- foregroundMuted: { kind: "color", help: "Muted text." },
740
- foregroundAccent: { kind: "color", help: "Accented text." },
741
- border: { kind: "color", help: "Border color." },
742
- borderFocus: { kind: "color", help: "Focus-ring color." },
743
- primary: { kind: "color", help: "Primary button background." },
744
- primaryForeground: { kind: "color", help: "Primary button text." },
745
- primaryHover: { kind: "color", help: "Primary button hover." },
746
- primaryMuted: { kind: "color", help: "Muted primary background." },
747
- primaryMutedForeground: { kind: "color", help: "Muted primary text." },
748
- primaryTint: { kind: "color", help: "Primary tint wash." },
749
- link: { kind: "color", help: "Link color." }
750
- };
751
- function suggestThemeFields(input) {
752
- const target = input.toLowerCase();
753
- return Object.keys(THEME_FIELDS).map((name) => {
754
- const lower = name.toLowerCase();
755
- return {
756
- name,
757
- distance: editDistance(target, lower),
758
- prefix: commonPrefixLength(target, lower)
759
- };
760
- }).filter(
761
- ({ name, distance, prefix }) => distance <= Math.max(2, name.length / 3) || prefix >= 4
762
- ).sort((a, b) => b.prefix - a.prefix || a.distance - b.distance).slice(0, 3).map(({ name }) => name);
763
- }
764
- function commonPrefixLength(a, b) {
765
- let i = 0;
766
- while (i < a.length && i < b.length && a[i] === b[i]) i++;
767
- return i;
768
- }
769
- function editDistance(a, b) {
770
- let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
771
- for (let i = 1; i <= a.length; i++) {
772
- const row = [i];
773
- for (let j = 1; j <= b.length; j++) {
774
- row[j] = Math.min(
775
- (prev[j] ?? 0) + 1,
776
- (row[j - 1] ?? 0) + 1,
777
- (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1)
778
- );
779
- }
780
- prev = row;
781
- }
782
- return prev[b.length] ?? 0;
783
- }
784
-
785
- // src/commands/configure/help.ts
786
- var CONFIGURE_HELP = `gs configure \u2014 view and edit a store's configuration.
22
+ <p>Return to your terminal for details.</p></body></html>`,V=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function fe(e){let t=(e.generateState??jn)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Rn(s,e.browserCmdEnv)),o=Ge.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=An(o,t,n);return r(a),await l}finally{o.close()}}function An(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new V("Sign-in timed out. Re-run `gs 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!==Pn){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,f=u.get("error"),j=u.get("error_description"),k=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(Me),clearTimeout(a),i(()=>o(new V("Sign-in didn't complete. Please try again.")));return}if(f||!k){c.writeHead(400,{"content-type":"text/html"}),c.end(Me),clearTimeout(a),i(()=>o(new V(j??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(En),clearTimeout(a);let R=u.get("store")?.trim();i(()=>r(R?{token:k,store:R}:{token:k}))})})}function jn(){return Ue.randomBytes(16).toString("hex")}function Rn(e,t){let r=t?.trim()??_n();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=He("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=He(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function _n(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as P from"fs";import*as z from"os";import*as je from"path";var Tn=".greatstore",Ln="credentials.json";function qe(e=z.homedir()){return je.join(e,Tn)}function Re(e=z.homedir()){return je.join(qe(e),Ln)}function _(e=z.homedir()){let t=Re(e),n;try{let r=P.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=P.readFileSync(t,"utf8")}catch(r){if(On(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function de(e,t=z.homedir()){let n=qe(t);if(P.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{P.chmodSync(n,448)}catch{}let r=Re(t);P.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
+ `,{mode:384}),process.platform!=="win32"&&P.chmodSync(r,384)}function Ve(e=z.homedir()){P.rmSync(Re(e),{force:!0})}function Ke(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 me(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function On(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var F="0.1.10";var N=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},L=class extends Error{constructor(t="Sign in first. Run `gs login`."){super(t),this.name="AuthRequiredError"}};function In(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 Fn(e){let t=In(e)??_()?.store;return t?`gs login --store ${t}`:"gs login"}async function d(e,t={}){let n=()=>`Run \`${Fn(e)}\`.`,r=_();if(!r)throw new L(`Sign in first. ${n()}`);if(me(r))throw new L(`Session expired. ${n()}`);try{return await Nn(e,t,r.access_token)}catch(o){throw o instanceof N&&o.status===401?new L(`Session expired. ${n()}`):o}}async function Nn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":F,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:Dn(i.status,c,l.detail);throw new N(i.status,p,l.code??l.error)}var ze=`This version of the GreatStore CLI is no longer supported.
24
+
25
+ npm install -g @greatstore/cli@latest
26
+ `,We={cli_upgrade_required:{message:ze},INVALID_NAME:{message:"Invalid component name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"Component not found on the server."},concurrent_write:{message:"Another change landed before this one. Run `gs apps pull` and try again."},stale_base:{message:"The store has moved past the version this copy was taken from. Run `gs apps pull` first, or push again with --force to overwrite it.",includeDetail:!0},name_mismatch:{message:"Manifest `name` does not match the component folder name.",includeDetail:!0},manifest_invalid:{message:"manifest.json is invalid.",includeDetail:!0},bundle_too_large:{message:"bundle.js is too large."},bundle_not_module:{message:"bundle.js is not a valid ES module."},source_too_large:{message:"component.tsx is too large."}};function Dn(e,t,n){if(t&&t in We){let r=We[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:Je(e)}return Je(e)}function Je(e){return e===401?"Sign-in needed. Run `gs login`.":e===426?ze:e===403?"Not authorized for this component or store.":e===404?"Not found.":e===409?"Conflict \u2014 refresh and try again.":e===413?"Upload too large.":e===429?"Too many requests \u2014 wait a moment and retry.":e>=500?"Server error \u2014 try again shortly.":e>=400?"Request rejected.":"Unexpected response."}function he(e,t){let n=Ke(e),r=Xe(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=Bn(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...ge(n,"email","email"),...ge(n,"accountId","accountId"),...ge(n,"name","name"),...ge(n,"surname","surname"),...Hn(n,"superUser","superUser"),...t?{store:t}:{}}}function Xe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Bn(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ge(e,t,n){let r=Xe(e,t);return r?{[n]:r}:{}}function Hn(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as ye from"fs";import*as B from"path";var Mn="https://my.greatstore.ai",D=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function E(e={}){let t=_e(e.cwd??process.cwd());if(t)return Y(t);throw new D("No .gsrc found in this directory or any ancestor. Run `gs apps init --store <slug>` first to scaffold a GreatStore project.")}function Ye(e=process.cwd()){let t=_e(e);if(t)return Y(t);let n=oe();if(n)return n;throw new D("No store selected. Run `gs login`, or run from a project with a .gsrc.")}function oe(){try{return _()?.store??null}catch{return null}}function Y(e){let t=oe();if(t&&t!==e)throw new D(`This targets store "${e}" but you're signed in to "${t}". Run \`gs switch ${e}\` to change stores.`);return e}function _e(e){let t=B.resolve(e),n=B.parse(t).root;for(;;){let r=B.join(t,".gsrc");if(ye.existsSync(r))try{let s=ye.readFileSync(r,"utf8"),i=JSON.parse(s);if(typeof i.store=="string"&&i.store.trim())return i.store.trim()}catch{}if(t===n)return null;let o=B.dirname(t);if(o===t)return null;t=o}}function y(e){let t=h(e.flags,"store")?.trim();if(t)return Y(t);let n=_e(process.cwd());if(n)return Y(n);let r=oe();if(r)return r;throw new D("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function C(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?Qe(n):`https://${e}.greatstore.ai`}function se(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?Qe(t):Mn}function b(e,t=process.env){return`${se(t)}/${e}/admin`}function Qe(e){return e.endsWith("/")?e.slice(0,-1):e}async function Ze(e){let t=h(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
27
+ `);let{token:n,store:r}=await fe({dashboardBaseUrl:se(),...t?{requestedStore:t}:{}}),o=he(n,r);de(o);let s=o.email??o.sub;o.store?process.stdout.write(`Logged in as ${s}, working on store "${o.store}".
28
+ `):process.stdout.write(`Logged in as ${s}.
29
+ `)}function et(){let e=_()!==null;Ve(),process.stdout.write(e?`Logged out.
30
+ `:`Not logged in.
31
+ `)}function tt(){let e=_();if(!e)return process.stderr.write("Not logged in. Run `gs login`.\n"),1;let t=me(e),n=[`sub: ${e.sub}`,`email: ${e.email??"(none)"}`,`accountId: ${e.accountId??"(none)"}`,`superUser: ${e.superUser??!1}`,`store: ${e.store??"(none \u2014 run `gs switch`)"}`,`name: ${[e.name,e.surname].filter(Boolean).join(" ")||"(none)"}`,`expires: ${new Date(e.expires_at*1e3).toISOString()}${t?" (EXPIRED)":""}`];return process.stdout.write(n.join(`
32
+ `)+`
33
+ `),t?1:0}async function nt(e){if(!_())throw new L;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
34
+ `);let{token:r,store:o}=await fe({dashboardBaseUrl:se(),...n?{requestedStore:n}:{}}),s=he(r,o);return de(s),s.store?process.stdout.write(`Now working on store "${s.store}".
35
+ `):process.stdout.write(`Switched.
36
+ `),0}import*as st from"fs";import*as it from"os";import*as Q from"path";import{existsSync as Un}from"fs";import*as we from"path";import{fileURLToPath as Gn}from"url";var ie="greatstore";function rt(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=we.resolve(Gn(new URL(e,import.meta.url)));if(Un(we.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function at(){process.stdout.write(qn(rt()))}function qn(e){if(Vn(e))throw new Error(["This copy of the CLI is running from a temporary cache, so the agent","skill has no stable location to install from. Install the CLI first,","then ask again:",""," npm install -g @greatstore/cli"," gs skill"].join(`
37
+ `));return["GreatStore agent skill \u2014 installation instructions for an AI coding agent.","","Skill source on this machine:",` ${e}`,"",`Symlink that folder into your skills directory as "${ie}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${ie}"`,"","Symlink it, do not copy it: the link keeps the skill current every","time @greatstore/cli is upgraded, with nothing to re-run.","","<SKILLS_DIR> is wherever you load skills from \u2014 for Claude Code that","is ~/.claude/skills for every project, or ./.claude/skills for this","one. Use your own location if it differs, and create it if missing.",`Then read <SKILLS_DIR>/${ie}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${ie}" "${e}"`,""].join(`
38
+ `)}function Vn(e){let t=e.split(Q.sep).join("/");if(/\/(?:_npx|_cacache|\.bun\/install\/cache)\//.test(t)||/\/(?:dlx-|bunx-|\.npx-)/.test(t))return!0;let n=it.tmpdir();return ot(e,n)||ot(e,Kn(n))}function ot(e,t){let n=Q.relative(t,e);return n!==""&&!n.startsWith("..")&&!Q.isAbsolute(n)}function Kn(e){try{return st.realpathSync(e)}catch{return e}}var H={mode:{kind:"string",values:["auto","light","dark","custom"],help:"Color scheme. `auto` follows the shopper's system preference.",brandVisible:!0},radius:{kind:"string",values:["sharp","default","rounded"],help:"Corner rounding preset applied to every surface.",brandVisible:!0},panelPosition:{kind:"string",values:["left","right","middle"],help:"Where the chat panel sits on desktop.",brandVisible:!0},fontFamily:{kind:"string",help:"Primary font family name.",brandVisible:!0},secondaryFontFamily:{kind:"string",help:"Font family for the assistant's chat bubbles.",brandVisible:!0},mobileBottomBar:{kind:"boolean",help:"Show the compact bottom bar on mobile.",brandVisible:!0},zIndex:{kind:"integer",help:"Stacking order of the chat panel on the host page."},brandColor:{kind:"color",help:"Accent color.",brandVisible:!0},surfaceColor:{kind:"color",help:"Background color.",brandVisible:!0},textColor:{kind:"color",help:"Text color.",brandVisible:!0},surface:{kind:"color",help:"Panel background."},surfaceSecondary:{kind:"color",help:"Secondary background."},surfaceAccent:{kind:"color",help:"Accented background."},surfaceHover:{kind:"color",help:"Hovered background."},foreground:{kind:"color",help:"Body text."},foregroundSecondary:{kind:"color",help:"Secondary text."},foregroundMuted:{kind:"color",help:"Muted text."},foregroundAccent:{kind:"color",help:"Accented text."},border:{kind:"color",help:"Border color."},borderFocus:{kind:"color",help:"Focus-ring color."},primary:{kind:"color",help:"Primary button background."},primaryForeground:{kind:"color",help:"Primary button text."},primaryHover:{kind:"color",help:"Primary button hover."},primaryMuted:{kind:"color",help:"Muted primary background."},primaryMutedForeground:{kind:"color",help:"Muted primary text."},primaryTint:{kind:"color",help:"Primary tint wash."},link:{kind:"color",help:"Link color."}};function ct(e){let t=e.toLowerCase();return Object.keys(H).map(n=>{let r=n.toLowerCase();return{name:n,distance:Jn(t,r),prefix:Wn(t,r)}}).filter(({name:n,distance:r,prefix:o})=>r<=Math.max(2,n.length/3)||o>=4).sort((n,r)=>r.prefix-n.prefix||n.distance-r.distance).slice(0,3).map(({name:n})=>n)}function Wn(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function Jn(e,t){let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r++){let o=[r];for(let s=1;s<=t.length;s++)o[s]=Math.min((n[s]??0)+1,(o[s-1]??0)+1,(n[s-1]??0)+(e[r-1]===t[s-1]?0:1));n=o}return n[t.length]??0}var zn=`gs configure \u2014 view and edit a store's configuration.
787
39
 
788
40
  Usage:
789
41
  gs configure Show the current configuration.
@@ -796,20 +48,8 @@ Run \`gs configure set --help\` for the full field list.
796
48
  Flags:
797
49
  --store <slug> Which store to act on (default: nearest .gsrc).
798
50
  --json Machine-readable output.
799
- `;
800
- function themeFieldLines() {
801
- const rows = Object.entries(THEME_FIELDS).map(([name, field]) => {
802
- const type = field.values ? field.values.join(" | ") : field.kind === "color" ? "<css color>" : field.kind === "boolean" ? "true | false" : field.kind === "integer" ? "<integer>" : "<name>";
803
- return { flag: ` --theme.${name} ${type}`, help: field.help };
804
- });
805
- const width = Math.max(...rows.map((r) => r.flag.length)) + 2;
806
- return rows.map((r) => `${r.flag.padEnd(width)}${r.help}`).join("\n");
807
- }
808
- function brandVisibleNames() {
809
- return Object.entries(THEME_FIELDS).filter(([, field]) => field.brandVisible).map(([name]) => name).join(", ");
810
- }
811
- function configureSetHelp() {
812
- return `gs configure set \u2014 save configuration fields.
51
+ `;function Xn(){let e=Object.entries(H).map(([n,r])=>{let o=r.values?r.values.join(" | "):r.kind==="color"?"<css color>":r.kind==="boolean"?"true | false":r.kind==="integer"?"<integer>":"<name>";return{flag:` --theme.${n} ${o}`,help:r.help}}),t=Math.max(...e.map(n=>n.flag.length))+2;return e.map(n=>`${n.flag.padEnd(t)}${n.help}`).join(`
52
+ `)}function Yn(){return Object.entries(H).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function Qn(){return`gs configure set \u2014 save configuration fields.
813
53
 
814
54
  Only the fields you pass are written; everything else is left alone. Pass an
815
55
  empty value to clear a field (e.g. --displayName "").
@@ -823,7 +63,7 @@ Store fields:
823
63
  --cspConnectHosts <a,b,c> Extra connect hosts to allow.
824
64
 
825
65
  Theme fields (merge into the stored theme):
826
- ${themeFieldLines()}
66
+ ${Xn()}
827
67
 
828
68
  Whole-object theme writes:
829
69
  --theme '<json>' Merge this JSON object into the stored theme.
@@ -832,1544 +72,51 @@ Whole-object theme writes:
832
72
  --theme "" Clear the theme entirely.
833
73
 
834
74
  These are shopper-visible, so confirm them with the merchant before writing:
835
- ${brandVisibleNames()}
75
+ ${Yn()}
836
76
 
837
77
  Examples:
838
78
  gs configure set --theme.fontFamily Manrope --theme.radius sharp
839
79
  gs configure set --theme.brandColor "#1e1d66"
840
80
  gs configure set --theme '{"mode":"dark"}' --replace
841
- `;
842
- }
843
- function configureHelp(sub) {
844
- if (sub === void 0 || sub === "show") return CONFIGURE_HELP;
845
- if (sub === "set") return configureSetHelp();
846
- return void 0;
847
- }
848
-
849
- // src/commands/apps/init.ts
850
- import * as fs4 from "fs";
851
- import * as path5 from "path";
852
-
853
- // src/template.ts
854
- import { readdirSync, readFileSync as readFileSync3 } from "fs";
855
- import { fileURLToPath as fileURLToPath2 } from "url";
856
- var cache = null;
857
- function loadTemplate() {
858
- if (cache) return cache;
859
- cache = true ? JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onCallTool: (name: string, args: Record<string, unknown>) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema). Resolves to the generated object. `fallback` is a required,\\n // schema-shaped stand-in rendered in the component preview (and validated\\n // against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for the design rules (em-based sizing, brand CSS\\n// variables), the lifecycle props, and how to write an async,\\n// backend-backed component.\\nexport default function __GS_PASCAL__(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your component!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Renders the __GS_NAME__ widget.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `gs apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `gs apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the components in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nThese components render inside arbitrary publisher websites (the embed\\nwidget mounts on a host page) as well as the GreatStore storefront. You\\ncontrol neither the host page\'s base font size nor its color scheme, and\\nthe store owner controls the look from GreatStore theme settings. The\\nrules below keep components portable across both.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the component\'s own font size, so it stays\\nself-consistent wherever the component is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### 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 component clash with the rest of the\\nstore. Read from the CSS variables GreatStore injects on the surface\\ninstead, so the component 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\\ncomponent reflects the store\'s full type system instead of a single\\nface.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## Component props\\n\\nEach component receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onCallTool(name, args)` | Chain into another remote-component tool by name. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-component state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your component can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async component 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 component preview renders (so a generation-driven component previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the component outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async components (backend-backed, render-blocking data)\\n\\nIf a component 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. Components that render purely from their props stay\\nsynchronous.\\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 components\\n\\nCustom React components published to your GreatStore tenant. Each\\ncomponent lives in its own folder under `components/`.\\n\\n```\\nnpm install\\ngs apps init <component_name> # add a new component\\ngs apps build # builds every components/<name>/bundle.js\\ngs apps push # uploads every changed component as a draft\\ngs apps publish <component_name> # promote a specific component to live\\n```\\n\\n- `gs apps push` (no args) hashes each component and only uploads the ones\\n that have changed since the last sync.\\n- `gs apps pull` (no args) refreshes every remote component into\\n `components/<name>/`. Components with unsaved local edits are skipped\\n with a warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for the design rules every component must follow\\n(em-based sizing, brand CSS variables) \u2014 it doubles as guidance for AI\\ncoding 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\\": \\"gs apps build\\",\\n \\"push\\": \\"gs apps build && gs 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 `gs 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"}') : readTreeFromDisk(new URL("../template/", import.meta.url));
860
- return cache;
861
- }
862
- var TOKENS = {
863
- name: "__GS_NAME__",
864
- pascalName: "__GS_PASCAL__",
865
- displayName: "__GS_DISPLAY_NAME__",
866
- store: "__GS_STORE__",
867
- version: "__GS_VERSION__"
868
- };
869
- function applyTemplate(content, vars) {
870
- let out = content;
871
- for (const key of Object.keys(TOKENS)) {
872
- const value = vars[key];
873
- if (value !== void 0) out = out.split(TOKENS[key]).join(value);
874
- }
875
- const leftover = out.match(/__GS_[A-Z_]+__/);
876
- if (leftover) {
877
- throw new Error(
878
- `internal: template placeholder ${leftover[0]} was not provided`
879
- );
880
- }
881
- return out;
882
- }
883
-
884
- // src/commands/apps/init.ts
885
- var NAME_REGEX = /^[a-z][a-z0-9_]*$/;
886
- function initCommand(args) {
887
- const name = args.positional[0];
888
- if (name !== void 0 && !NAME_REGEX.test(name)) {
889
- throw new Error(`Invalid component name: "${name}" (must match ${NAME_REGEX}).`);
890
- }
891
- const force = flagBool(args.flags, "force");
892
- const storeFlag = flagString(args.flags, "store");
893
- const outRel = flagString(args.flags, "out") ?? ".";
894
- const root = path5.resolve(outRel);
895
- const rootExisted = hasRootScaffold(root);
896
- let store;
897
- if (rootExisted) {
898
- if (storeFlag !== void 0) {
899
- throw new Error(
900
- `Project at ${root} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`
901
- );
902
- }
903
- requireProjectStore({ cwd: root });
904
- } else {
905
- store = storeFlag !== void 0 ? assertMatchesSignedInStore(storeFlag) : signedInStore() ?? void 0;
906
- if (store === void 0) {
907
- const example = name ? `gs apps init ${name} --store <slug>` : `gs apps init --store <slug>`;
908
- throw new Error(
909
- `--store <slug> is required when scaffolding a new project root. Run \`${example}\`.`
910
- );
911
- }
912
- }
913
- const writtenRootFiles = ensureRoot(root, rootExisted, force, { store });
914
- if (!name) {
915
- const lines = [];
916
- if (rootExisted) {
917
- lines.push(`Updated GreatStore project root in ${root}.`);
918
- if (writtenRootFiles.length > 0) {
919
- lines.push("", `Added: ${writtenRootFiles.join(", ")}`);
920
- } else {
921
- lines.push("", "Already up to date \u2014 nothing to add.");
922
- }
923
- } else {
924
- lines.push(`Scaffolded GreatStore project root in ${root}.`);
925
- }
926
- lines.push(
927
- "",
928
- "Next steps:",
929
- ` cd ${path5.relative(process.cwd(), root) || "."}`,
930
- " npm install",
931
- " gs apps init <component_name> # add your first component",
932
- ""
933
- );
934
- process.stdout.write(lines.join("\n"));
935
- return;
936
- }
937
- const componentDir = path5.join(root, "components", name);
938
- ensureComponent(componentDir, name, force);
939
- const projectLabel = path5.relative(process.cwd(), root) || ".";
940
- process.stdout.write(
941
- [
942
- `Added component "${name}" at components/${name}/.`,
943
- ...rootExisted && writtenRootFiles.length > 0 ? ["", `Also added to the project root: ${writtenRootFiles.join(", ")}`] : [],
944
- "",
945
- "Next steps:",
946
- ...rootExisted ? [] : [` cd ${projectLabel}`, " npm install"],
947
- ` # edit components/${name}/component.tsx and manifest.json`,
948
- " gs apps build",
949
- " gs apps push",
950
- ""
951
- ].join("\n")
952
- );
953
- }
954
- function hasRootScaffold(dir) {
955
- return fs4.existsSync(path5.join(dir, "package.json")) && fs4.existsSync(path5.join(dir, ".gsrc"));
956
- }
957
- function ensureRoot(root, rootExisted, force, opts) {
958
- fs4.mkdirSync(root, { recursive: true });
959
- if (!rootExisted && !force) {
960
- const entries = fs4.readdirSync(root).filter((e) => e !== ".gsrc");
961
- if (entries.length > 0) {
962
- throw new Error(
963
- `Refusing to scaffold project root into non-empty directory ${root}. Pass --force to override.`
964
- );
965
- }
966
- }
967
- const files = rootExisted ? existingRootFiles() : rootFiles({ store: opts.store });
968
- const written = writeRootFiles(root, files, force);
969
- fs4.mkdirSync(path5.join(root, "components"), { recursive: true });
970
- return written;
971
- }
972
- var CLI_OWNED_ROOT_FILES = /* @__PURE__ */ new Set(["AGENTS.md"]);
973
- function writeRootFiles(root, files, force) {
974
- const written = [];
975
- for (const [relPath, content] of files) {
976
- const full = path5.join(root, relPath);
977
- fs4.mkdirSync(path5.dirname(full), { recursive: true });
978
- const exists = fs4.existsSync(full);
979
- if (!force && exists && !CLI_OWNED_ROOT_FILES.has(relPath)) continue;
980
- const changed = !exists || fs4.readFileSync(full, "utf8") !== content;
981
- fs4.writeFileSync(full, content);
982
- if (changed) written.push(relPath);
983
- }
984
- for (const link of ["CLAUDE.md", "GEMINI.md"]) {
985
- const linkPath = path5.join(root, link);
986
- if (force && pathExists(linkPath)) fs4.rmSync(linkPath);
987
- if (!pathExists(linkPath)) {
988
- fs4.symlinkSync("AGENTS.md", linkPath);
989
- written.push(link);
990
- }
991
- }
992
- return written;
993
- }
994
- function pathExists(p) {
995
- try {
996
- fs4.lstatSync(p);
997
- return true;
998
- } catch {
999
- return false;
1000
- }
1001
- }
1002
- function ensureComponent(componentDir, name, force) {
1003
- if (fs4.existsSync(componentDir) && !force) {
1004
- const entries = fs4.readdirSync(componentDir);
1005
- if (entries.length > 0) {
1006
- throw new Error(
1007
- `Refusing to overwrite existing components/${name}/. Pass --force to override.`
1008
- );
1009
- }
1010
- }
1011
- fs4.mkdirSync(componentDir, { recursive: true });
1012
- for (const [relPath, content] of componentFiles(name)) {
1013
- fs4.writeFileSync(path5.join(componentDir, relPath), content);
1014
- }
1015
- }
1016
- function templateFiles(prefix, vars, exclude = /* @__PURE__ */ new Set()) {
1017
- const tree = loadTemplate();
1018
- return Object.entries(tree).filter(([rel]) => rel.startsWith(prefix)).map(([rel, content]) => [rel.slice(prefix.length), content]).filter(([dest]) => !exclude.has(dest)).map(([dest, content]) => [dest, applyTemplate(content, vars)]);
1019
- }
1020
- function rootFiles(opts) {
1021
- if (!opts.store) {
1022
- throw new Error("internal: rootFiles called without a store slug");
1023
- }
1024
- return templateFiles("root/", { store: opts.store, version: CLI_VERSION });
1025
- }
1026
- function existingRootFiles() {
1027
- return templateFiles("root/", { version: CLI_VERSION }, /* @__PURE__ */ new Set([".gsrc"]));
1028
- }
1029
- function componentFiles(name) {
1030
- return templateFiles("component/", {
1031
- name,
1032
- pascalName: pascal(name),
1033
- displayName: defaultDisplayName(name)
1034
- });
1035
- }
1036
- function defaultDisplayName(name) {
1037
- const words = name.split("_").filter(Boolean);
1038
- if (words.length === 0) return name;
1039
- const first = words[0];
1040
- return first.charAt(0).toUpperCase() + first.slice(1) + (words.length > 1 ? " " + words.slice(1).join(" ") : "");
1041
- }
1042
- function pascal(name) {
1043
- return name.split(/[_-]/).filter(Boolean).map((part) => part[0]?.toUpperCase() + part.slice(1)).join("");
1044
- }
1045
-
1046
- // src/commands/apps/build.ts
1047
- import * as fs6 from "fs";
1048
- import * as path8 from "path";
1049
- import { createRequire as createRequire2 } from "module";
1050
-
1051
- // src/validation/context.ts
1052
- import * as fs5 from "fs";
1053
- import * as path7 from "path";
1054
-
1055
- // src/validation/ast.ts
1056
- import { createRequire } from "module";
1057
- import * as path6 from "path";
1058
- function analyzeComponentProps(root, sourcePath, sourceText) {
1059
- const ts = loadTypeScript(root);
1060
- if (!ts) {
1061
- return {
1062
- ok: false,
1063
- reason: "couldn't check props against the manifest \u2014 `typescript` isn't installed in this project (run `npm install`)"
1064
- };
1065
- }
1066
- try {
1067
- const sourceFile = ts.createSourceFile(
1068
- sourcePath,
1069
- sourceText,
1070
- ts.ScriptTarget.Latest,
1071
- true,
1072
- ts.ScriptKind.TSX
1073
- );
1074
- const fn = findDefaultExport(ts, sourceFile);
1075
- if (!fn) {
1076
- return {
1077
- ok: false,
1078
- reason: "couldn't find a default-exported component function to check props against \u2014 export the component as `export default function \u2026`"
1079
- };
1080
- }
1081
- return propsOfParameter(ts, sourceFile, fn);
1082
- } catch (err) {
1083
- return {
1084
- ok: false,
1085
- reason: `couldn't check props against the manifest \u2014 ${path6.basename(sourcePath)} could not be parsed (${err.message})`
1086
- };
1087
- }
1088
- }
1089
- function usesWindowGreatStore(root, sourcePath, sourceText) {
1090
- const ts = loadTypeScript(root);
1091
- if (!ts) return false;
1092
- try {
1093
- const sourceFile = ts.createSourceFile(
1094
- sourcePath,
1095
- sourceText,
1096
- ts.ScriptTarget.Latest,
1097
- true,
1098
- ts.ScriptKind.TSX
1099
- );
1100
- let found = false;
1101
- const visit = (node) => {
1102
- if (found) return;
1103
- if (isGreatStoreOnGlobal(ts, node)) {
1104
- found = true;
1105
- return;
1106
- }
1107
- ts.forEachChild(node, visit);
1108
- };
1109
- visit(sourceFile);
1110
- return found;
1111
- } catch {
1112
- return false;
1113
- }
1114
- }
1115
- function isGreatStoreOnGlobal(ts, node) {
1116
- if (ts.isPropertyAccessExpression(node)) {
1117
- return isGlobalObject(ts, node.expression) && node.name.text === "GreatStore";
1118
- }
1119
- if (ts.isElementAccessExpression(node)) {
1120
- const arg = node.argumentExpression;
1121
- return isGlobalObject(ts, node.expression) && ts.isStringLiteralLike(arg) && arg.text === "GreatStore";
1122
- }
1123
- return false;
1124
- }
1125
- function isGlobalObject(ts, node) {
1126
- return ts.isIdentifier(node) && (node.text === "window" || node.text === "globalThis");
1127
- }
1128
- function loadTypeScript(root) {
1129
- const localRequire = createRequire(path6.join(root, "package.json"));
1130
- try {
1131
- return localRequire("typescript");
1132
- } catch {
1133
- return null;
1134
- }
1135
- }
1136
- function findDefaultExport(ts, sourceFile) {
1137
- let assigned = null;
1138
- for (const statement of sourceFile.statements) {
1139
- if (ts.isFunctionDeclaration(statement) && hasDefaultModifier(ts, statement)) {
1140
- return statement;
1141
- }
1142
- if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
1143
- assigned = statement.expression;
1144
- }
1145
- }
1146
- if (!assigned) return null;
1147
- const expression = unwrap(ts, assigned);
1148
- if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression)) {
1149
- return expression;
1150
- }
1151
- if (ts.isIdentifier(expression)) {
1152
- return findLocalFunction(ts, sourceFile, expression.text);
1153
- }
1154
- return null;
1155
- }
1156
- function hasDefaultModifier(ts, node) {
1157
- return node.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) ?? false;
1158
- }
1159
- function unwrap(ts, node) {
1160
- let current = node;
1161
- while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current)) {
1162
- current = current.expression;
1163
- }
1164
- return current;
1165
- }
1166
- function findLocalFunction(ts, sourceFile, name) {
1167
- for (const statement of sourceFile.statements) {
1168
- if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) {
1169
- return statement;
1170
- }
1171
- if (!ts.isVariableStatement(statement)) continue;
1172
- for (const declaration of statement.declarationList.declarations) {
1173
- if (!ts.isIdentifier(declaration.name) || declaration.name.text !== name) continue;
1174
- if (!declaration.initializer) continue;
1175
- const initializer = unwrap(ts, declaration.initializer);
1176
- if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) {
1177
- return initializer;
1178
- }
1179
- }
1180
- }
1181
- return null;
1182
- }
1183
- function propsOfParameter(ts, sourceFile, fn) {
1184
- const parameter = fn.parameters[0];
1185
- if (!parameter) return { ok: true, props: { names: [], open: false } };
1186
- if (parameter.type) {
1187
- const fromType = namesFromTypeNode(ts, sourceFile, parameter.type, /* @__PURE__ */ new Set());
1188
- if (fromType) return { ok: true, props: fromType };
1189
- }
1190
- if (ts.isObjectBindingPattern(parameter.name)) {
1191
- return { ok: true, props: namesFromBindingPattern(ts, parameter.name) };
1192
- }
1193
- return {
1194
- ok: false,
1195
- 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"
1196
- };
1197
- }
1198
- function namesFromTypeNode(ts, sourceFile, node, seen) {
1199
- if (ts.isTypeLiteralNode(node)) {
1200
- return propsFromMembers(ts, node.members);
1201
- }
1202
- if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
1203
- return namesFromTypeName(ts, sourceFile, node.typeName.text, seen);
1204
- }
1205
- if (ts.isIntersectionTypeNode(node)) {
1206
- const parts = node.types.map((t) => namesFromTypeNode(ts, sourceFile, t, seen));
1207
- if (parts.every((p) => p === null)) return null;
1208
- return mergeProps(parts.map((p) => p ?? { names: [], open: true }));
1209
- }
1210
- return null;
1211
- }
1212
- function namesFromTypeName(ts, sourceFile, name, seen) {
1213
- if (seen.has(name)) return { names: [], open: false };
1214
- seen.add(name);
1215
- for (const statement of sourceFile.statements) {
1216
- if (ts.isInterfaceDeclaration(statement) && statement.name.text === name) {
1217
- const own = propsFromMembers(ts, statement.members);
1218
- const bases = (statement.heritageClauses ?? []).flatMap(
1219
- (clause) => clause.types.map(
1220
- (base) => ts.isIdentifier(base.expression) ? namesFromTypeName(ts, sourceFile, base.expression.text, seen) ?? {
1221
- names: [],
1222
- open: true
1223
- } : { names: [], open: true }
1224
- )
1225
- );
1226
- return mergeProps([own, ...bases]);
1227
- }
1228
- if (ts.isTypeAliasDeclaration(statement) && statement.name.text === name) {
1229
- return namesFromTypeNode(ts, sourceFile, statement.type, seen);
1230
- }
1231
- }
1232
- return null;
1233
- }
1234
- function propsFromMembers(ts, members) {
1235
- const names = [];
1236
- let open = false;
1237
- for (const member of members) {
1238
- if (ts.isIndexSignatureDeclaration(member)) {
1239
- open = true;
1240
- continue;
1241
- }
1242
- if (!ts.isPropertySignature(member) && !ts.isMethodSignature(member)) continue;
1243
- const memberName = staticMemberName(ts, member.name);
1244
- if (memberName === null) {
1245
- open = true;
1246
- continue;
1247
- }
1248
- names.push(memberName);
1249
- }
1250
- return { names, open };
1251
- }
1252
- function namesFromBindingPattern(ts, pattern) {
1253
- const names = [];
1254
- let open = false;
1255
- for (const element of pattern.elements) {
1256
- if (element.dotDotDotToken) {
1257
- open = true;
1258
- continue;
1259
- }
1260
- const key = element.propertyName ?? element.name;
1261
- const name = staticMemberName(ts, key);
1262
- if (name === null) open = true;
1263
- else names.push(name);
1264
- }
1265
- return { names, open };
1266
- }
1267
- function staticMemberName(ts, name) {
1268
- if (ts.isIdentifier(name)) return name.text;
1269
- if (ts.isStringLiteral(name)) return name.text;
1270
- return null;
1271
- }
1272
- function mergeProps(parts) {
1273
- const names = [];
1274
- let open = false;
1275
- for (const part of parts) {
1276
- for (const name of part.names) {
1277
- if (!names.includes(name)) names.push(name);
1278
- }
1279
- open ||= part.open;
1280
- }
1281
- return { names, open };
1282
- }
1283
-
1284
- // src/validation/context.ts
1285
- function buildContext(paths) {
1286
- const { root, name } = paths;
1287
- const componentDir = path7.join(root, "components", name);
1288
- const manifestPath = paths.manifestPath ?? path7.join(componentDir, "manifest.json");
1289
- const sourcePath = paths.sourcePath ?? path7.join(componentDir, "component.tsx");
1290
- const manifestFile = relative4(root, manifestPath);
1291
- const sourceFile = relative4(root, sourcePath);
1292
- const diagnostics = [];
1293
- let manifest = null;
1294
- const manifestText = readIfPresent(manifestPath);
1295
- if (manifestText === null) {
1296
- diagnostics.push({
1297
- severity: "error",
1298
- rule: "manifest/missing",
1299
- file: manifestFile,
1300
- message: "manifest not found."
1301
- });
1302
- } else {
1303
- try {
1304
- const parsed = JSON.parse(manifestText);
1305
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1306
- diagnostics.push({
1307
- severity: "error",
1308
- rule: "manifest/invalid",
1309
- file: manifestFile,
1310
- message: "manifest must be a JSON object."
1311
- });
1312
- } else {
1313
- manifest = parsed;
1314
- }
1315
- } catch (err) {
1316
- diagnostics.push({
1317
- severity: "error",
1318
- rule: "manifest/invalid",
1319
- file: manifestFile,
1320
- message: `manifest is not valid JSON: ${err.message}`
1321
- });
1322
- }
1323
- }
1324
- const sourceText = readIfPresent(sourcePath);
1325
- const props = sourceText === null ? { ok: false, reason: `couldn't check props against the manifest \u2014 ${sourceFile} not found` } : analyzeComponentProps(root, sourcePath, sourceText);
1326
- const usesGlobal = sourceText === null ? false : usesWindowGreatStore(root, sourcePath, sourceText);
1327
- return {
1328
- ctx: {
1329
- name,
1330
- manifestFile,
1331
- sourceFile,
1332
- manifest,
1333
- props,
1334
- usesWindowGreatStore: usesGlobal
1335
- },
1336
- diagnostics
1337
- };
1338
- }
1339
- function readIfPresent(file) {
1340
- try {
1341
- return fs5.readFileSync(file, "utf8");
1342
- } catch {
1343
- return null;
1344
- }
1345
- }
1346
- function relative4(root, target) {
1347
- const rel = path7.relative(root, target);
1348
- return rel.startsWith("..") ? target : rel.split(path7.sep).join("/");
1349
- }
1350
-
1351
- // src/validation/injected-props.ts
1352
- var INJECTED_PROPS = /* @__PURE__ */ new Set([
1353
- "onSendMessage",
1354
- "onCallTool",
1355
- "onClose",
1356
- "onUpdateModelContext",
1357
- "onShowLightbox",
1358
- "onGenerateStructuredContent",
1359
- "storeData",
1360
- "Image"
1361
- ]);
1362
-
1363
- // src/validation/retired-props.ts
1364
- var RETIRED_LIFECYCLE_PROPS = /* @__PURE__ */ new Map([
1365
- [
1366
- "onError",
1367
- '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.'
1368
- ]
1369
- ]);
1370
-
1371
- // src/validation/rules/component-props.ts
1372
- function componentPropsRule(ctx) {
1373
- if (!ctx.manifest) return [];
1374
- const schemaFields = schemaFieldNames(ctx.manifest.inputSchema);
1375
- if (schemaFields === null) return [];
1376
- if (!ctx.props.ok) {
1377
- return [
1378
- {
1379
- severity: "warning",
1380
- rule: "props/not-analyzable",
1381
- file: ctx.sourceFile,
1382
- message: `${ctx.props.reason}.`
1383
- }
1384
- ];
1385
- }
1386
- if (ctx.props.props.open) return [];
1387
- const declared = new Set(ctx.props.props.names);
1388
- const schema = new Set(schemaFields);
1389
- const diagnostics = [];
1390
- for (const prop of ctx.props.props.names) {
1391
- if (INJECTED_PROPS.has(prop)) continue;
1392
- const retirement = RETIRED_LIFECYCLE_PROPS.get(prop);
1393
- if (retirement) {
1394
- diagnostics.push({
1395
- severity: "warning",
1396
- rule: "props/retired-lifecycle",
1397
- file: ctx.sourceFile,
1398
- message: retirement
1399
- });
1400
- continue;
1401
- }
1402
- if (schema.has(prop)) continue;
1403
- diagnostics.push({
1404
- severity: "warning",
1405
- rule: "props/undeclared",
1406
- file: ctx.sourceFile,
1407
- message: `prop \`${prop}\` is not declared in ${ctx.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`
1408
- });
1409
- }
1410
- const missing = schemaFields.filter((field) => !declared.has(field));
1411
- if (missing.length > 0) {
1412
- diagnostics.push({
1413
- severity: "error",
1414
- rule: "props/missing",
1415
- file: ctx.sourceFile,
1416
- message: missingFieldsMessage(ctx.manifestFile, missing)
1417
- });
1418
- }
1419
- return diagnostics;
1420
- }
1421
- var MAX_LISTED_FIELDS = 8;
1422
- function missingFieldsMessage(manifestFile, fields) {
1423
- if (fields.length === 1) {
1424
- const [field] = fields;
1425
- return `${manifestFile} declares inputSchema field \`${field}\`, but the component does not accept a \`${field}\` prop. Add it to the component's props, or remove it from the schema.`;
1426
- }
1427
- const listed = fields.slice(0, MAX_LISTED_FIELDS).map((f) => `\`${f}\``).join(", ");
1428
- const overflow = fields.length - MAX_LISTED_FIELDS;
1429
- const names = overflow > 0 ? `${listed} (+${overflow} more)` : listed;
1430
- return `${manifestFile} declares ${fields.length} inputSchema fields the component does not accept: ${names}. Add them to the component's props, or remove them from the schema.`;
1431
- }
1432
- function schemaFieldNames(inputSchema) {
1433
- if (!inputSchema || typeof inputSchema !== "object") return null;
1434
- const properties = inputSchema["properties"];
1435
- if (!properties || typeof properties !== "object" || Array.isArray(properties)) {
1436
- return null;
1437
- }
1438
- return Object.keys(properties);
1439
- }
1440
-
1441
- // src/validation/rules/input-schema-complexity.ts
1442
- var MAX_SCHEMA_BYTES = 8 * 1024;
1443
- var MAX_SCHEMA_FIELDS = 50;
1444
- var UNION_KEYWORDS = ["anyOf", "oneOf", "allOf", "$ref", "not"];
1445
- function measure(node, path14, acc) {
1446
- if (Array.isArray(node)) {
1447
- node.forEach((entry, i) => measure(entry, `${path14}[${i}]`, acc));
1448
- return;
1449
- }
1450
- if (!node || typeof node !== "object") return;
1451
- const record = node;
1452
- for (const keyword of UNION_KEYWORDS) {
1453
- if (keyword in record) acc.unionPaths.push(`${path14}.${keyword}`);
1454
- }
1455
- const properties = record["properties"];
1456
- if (properties && typeof properties === "object" && !Array.isArray(properties)) {
1457
- for (const [name, sub] of Object.entries(properties)) {
1458
- acc.fields += 1;
1459
- measure(sub, `${path14}.${name}`, acc);
1460
- }
1461
- }
1462
- if ("items" in record) measure(record["items"], `${path14}[]`, acc);
1463
- }
1464
- function inputSchemaComplexityRule(ctx) {
1465
- const inputSchema = ctx.manifest?.inputSchema;
1466
- if (!inputSchema || typeof inputSchema !== "object") return [];
1467
- const acc = {
1468
- bytes: Buffer.byteLength(JSON.stringify(inputSchema), "utf8"),
1469
- fields: 0,
1470
- unionPaths: []
1471
- };
1472
- measure(inputSchema, "inputSchema", acc);
1473
- const problems = [];
1474
- if (acc.unionPaths.length > 0) {
1475
- const shown = acc.unionPaths.slice(0, 3).join(", ");
1476
- const more = acc.unionPaths.length > 3 ? ` (+${acc.unionPaths.length - 3} more)` : "";
1477
- problems.push(
1478
- `uses ${shown}${more} \u2014 declare exactly one type per field; accept alternate shapes in component code instead`
1479
- );
1480
- }
1481
- if (acc.bytes > MAX_SCHEMA_BYTES) {
1482
- problems.push(
1483
- `is ${(acc.bytes / 1024).toFixed(1)} KB serialized (limit ${MAX_SCHEMA_BYTES / 1024} KB)`
1484
- );
1485
- }
1486
- if (acc.fields > MAX_SCHEMA_FIELDS) {
1487
- problems.push(`declares ${acc.fields} fields (limit ${MAX_SCHEMA_FIELDS})`);
1488
- }
1489
- if (problems.length === 0) return [];
1490
- return [
1491
- {
1492
- severity: "error",
1493
- rule: "manifest/input-schema-too-complex",
1494
- file: ctx.manifestFile,
1495
- message: `inputSchema ${problems.join("; ")}.
1496
- A schema this complex is usually a sign the component is overengineered, and the assistant 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.`
1497
- }
1498
- ];
1499
- }
1500
-
1501
- // src/validation/rules/manifest-name.ts
1502
- function manifestNameRule(ctx) {
1503
- const declared = ctx.manifest?.name;
1504
- if (typeof declared !== "string" || declared === ctx.name) return [];
1505
- return [
1506
- {
1507
- severity: "error",
1508
- rule: "manifest/name-mismatch",
1509
- file: ctx.manifestFile,
1510
- message: `manifest name "${declared}" does not match folder name "${ctx.name}".`
1511
- }
1512
- ];
1513
- }
1514
-
1515
- // src/validation/rules/prefer-lifecycle-props.ts
1516
- function preferLifecyclePropsRule(ctx) {
1517
- if (!ctx.usesWindowGreatStore) return [];
1518
- return [
1519
- {
1520
- severity: "warning",
1521
- rule: "globals/window-greatstore",
1522
- file: ctx.sourceFile,
1523
- message: "this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onCallTool`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."
1524
- }
1525
- ];
1526
- }
1527
-
1528
- // src/validation/types.ts
1529
- function errorsIn(diagnostics) {
1530
- return diagnostics.filter((d) => d.severity === "error");
1531
- }
1532
- function warningsIn(diagnostics) {
1533
- return diagnostics.filter((d) => d.severity === "warning");
1534
- }
1535
- function formatDiagnostic(d) {
1536
- return `${d.severity === "error" ? "error" : "warning"} ${d.file}: ${d.message}`;
1537
- }
1538
-
1539
- // src/validation/index.ts
1540
- var RULES = [
1541
- manifestNameRule,
1542
- inputSchemaComplexityRule,
1543
- componentPropsRule,
1544
- preferLifecyclePropsRule
1545
- ];
1546
- function validateComponent(paths) {
1547
- const { ctx, diagnostics } = buildContext(paths);
1548
- for (const rule of RULES) diagnostics.push(...rule(ctx));
1549
- return { diagnostics, ok: errorsIn(diagnostics).length === 0 };
1550
- }
1551
-
1552
- // src/commands/apps/build.ts
1553
- var COMPONENTS_DIR = "components";
1554
- async function buildCommand(args) {
1555
- const root = process.cwd();
1556
- if (!fs6.existsSync(path8.join(root, "package.json")) || !fs6.existsSync(path8.join(root, COMPONENTS_DIR))) {
1557
- throw new Error(
1558
- `\`gs apps build\` must run from a project root (contains \`package.json\` and \`${COMPONENTS_DIR}/\`). Current dir: ${root}`
1559
- );
1560
- }
1561
- const components = listComponents(root);
1562
- if (components.length === 0) {
1563
- process.stdout.write(
1564
- `(no components in ./${COMPONENTS_DIR} \u2014 run \`gs apps init <name>\` to add one)
1565
- `
1566
- );
1567
- return;
1568
- }
1569
- const target = args.positional[0];
1570
- const queue = target ? components.filter((c) => c === target) : components;
1571
- if (target && queue.length === 0) {
1572
- throw new Error(`No component named "${target}" in ./${COMPONENTS_DIR}`);
1573
- }
1574
- const invalid = [];
1575
- const buildable = [];
1576
- for (const name of queue) {
1577
- const report = validateComponent({ root, name });
1578
- for (const diagnostic of report.diagnostics) {
1579
- process.stdout.write(` ${formatDiagnostic(diagnostic)}
1580
- `);
1581
- }
1582
- (report.ok ? buildable : invalid).push(name);
1583
- }
1584
- if (buildable.length === 0) {
1585
- process.stdout.write(`
81
+ `}function lt(e){if(e===void 0||e==="show")return zn;if(e==="set")return Qn()}import*as g from"fs";import*as x from"path";import{readdirSync as So,readFileSync as vo}from"fs";import{fileURLToPath as ko}from"url";var be=null;function pt(){return be||(be=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onCallTool: (name: string, args: Record<string, unknown>) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema). Resolves to the generated object. `fallback` is a required,\\n // schema-shaped stand-in rendered in the component preview (and validated\\n // against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for the design rules (em-based sizing, brand CSS\\n// variables), the lifecycle props, and how to write an async,\\n// backend-backed component.\\nexport default function __GS_PASCAL__(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your component!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Renders the __GS_NAME__ widget.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `gs apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `gs apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the components in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nThese components render inside arbitrary publisher websites (the embed\\nwidget mounts on a host page) as well as the GreatStore storefront. You\\ncontrol neither the host page\'s base font size nor its color scheme, and\\nthe store owner controls the look from GreatStore theme settings. The\\nrules below keep components portable across both.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the component\'s own font size, so it stays\\nself-consistent wherever the component is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### 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 component clash with the rest of the\\nstore. Read from the CSS variables GreatStore injects on the surface\\ninstead, so the component 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\\ncomponent reflects the store\'s full type system instead of a single\\nface.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## Component props\\n\\nEach component receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onCallTool(name, args)` | Chain into another remote-component tool by name. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-component state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your component can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async component 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 component preview renders (so a generation-driven component previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the component outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async components (backend-backed, render-blocking data)\\n\\nIf a component 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. Components that render purely from their props stay\\nsynchronous.\\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 components\\n\\nCustom React components published to your GreatStore tenant. Each\\ncomponent lives in its own folder under `components/`.\\n\\n```\\nnpm install\\ngs apps init <component_name> # add a new component\\ngs apps build # builds every components/<name>/bundle.js\\ngs apps push # uploads every changed component as a draft\\ngs apps publish <component_name> # promote a specific component to live\\n```\\n\\n- `gs apps push` (no args) hashes each component and only uploads the ones\\n that have changed since the last sync.\\n- `gs apps pull` (no args) refreshes every remote component into\\n `components/<name>/`. Components with unsaved local edits are skipped\\n with a warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for the design rules every component must follow\\n(em-based sizing, brand CSS variables) \u2014 it doubles as guidance for AI\\ncoding 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\\": \\"gs apps build\\",\\n \\"push\\": \\"gs apps build && gs 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 `gs build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),be)}var ut={name:"__GS_NAME__",pascalName:"__GS_PASCAL__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function ft(e,t){let n=e;for(let o of Object.keys(ut)){let s=t[o];s!==void 0&&(n=n.split(ut[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var dt=/^[a-z][a-z0-9_]*$/;function gt(e){let t=e.positional[0];if(t!==void 0&&!dt.test(t))throw new Error(`Invalid component name: "${t}" (must match ${dt}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=x.resolve(o),i=Zn(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?Y(r):oe()??void 0,a===void 0){let u=t?`gs apps init ${t} --store <slug>`:"gs apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=er(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 ${x.relative(process.cwd(),s)||"."}`," npm install"," gs apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
82
+ `));return}let c=x.join(s,"components",t);rr(c,t,n);let p=x.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`," gs apps build"," gs apps push",""].join(`
83
+ `))}function Zn(e){return g.existsSync(x.join(e,"package.json"))&&g.existsSync(x.join(e,".gsrc"))}function er(e,t,n,r){if(g.mkdirSync(e,{recursive:!0}),!t&&!n&&g.readdirSync(e).filter(a=>a!==".gsrc").length>0)throw new Error(`Refusing to scaffold project root into non-empty directory ${e}. Pass --force to override.`);let o=t?sr():or({store:r.store}),s=nr(e,o,n);return g.mkdirSync(x.join(e,"components"),{recursive:!0}),s}var tr=new Set(["AGENTS.md"]);function nr(e,t,n){let r=[];for(let[o,s]of t){let i=x.join(e,o);g.mkdirSync(x.dirname(i),{recursive:!0});let a=g.existsSync(i);if(!n&&a&&!tr.has(o))continue;let l=!a||g.readFileSync(i,"utf8")!==s;g.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=x.join(e,o);n&&mt(s)&&g.rmSync(s),mt(s)||(g.symlinkSync("AGENTS.md",s),r.push(o))}return r}function mt(e){try{return g.lstatSync(e),!0}catch{return!1}}function rr(e,t,n){if(g.existsSync(e)&&!n&&g.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);g.mkdirSync(e,{recursive:!0});for(let[r,o]of ir(t))g.writeFileSync(x.join(e,r),o)}function Te(e,t,n=new Set){let r=pt();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,ft(s,t)])}function or(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return Te("root/",{store:e.store,version:F})}function sr(){return Te("root/",{version:F},new Set([".gsrc"]))}function ir(e){return Te("component/",{name:e,pascalName:cr(e),displayName:ar(e)})}function ar(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(" "):"")}function cr(e){return e.split(/[_-]/).filter(Boolean).map(t=>t[0]?.toUpperCase()+t.slice(1)).join("")}import*as S from"fs";import*as w from"path";import{createRequire as Sr}from"module";import*as Et from"fs";import*as M from"path";import{createRequire as lr}from"module";import*as Se from"path";function yt(e,t,n){let r=bt(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=pr(r,o);return s?mr(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 ${Se.basename(t)} could not be parsed (${o.message})`}}}function wt(e,t,n){let r=bt(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(ur(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function ur(e,t){if(e.isPropertyAccessExpression(t))return ht(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return ht(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function ht(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function bt(e){let t=lr(Se.join(e,"package.json"));try{return t("typescript")}catch{return null}}function pr(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&fr(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=St(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?dr(e,t,r.text):null}function fr(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function St(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function dr(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=St(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function mr(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=Le(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:gr(e,r.name)}:{ok:!1,reason:"couldn't check props against the manifest \u2014 declare the component's props as a local `interface`/`type` or destructure them in the signature"}}function Le(e,t,n,r){if(e.isTypeLiteralNode(n))return xt(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return vt(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>Le(e,t,s,r));return o.every(s=>s===null)?null:Pt(o.map(s=>s??{names:[],open:!0}))}return null}function vt(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=xt(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?vt(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Pt([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return Le(e,t,o.type,r)}return null}function xt(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=kt(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function gr(e,t){let n=[],r=!1;for(let o of t.elements){if(o.dotDotDotToken){r=!0;continue}let s=o.propertyName??o.name,i=kt(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function kt(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Pt(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 At(e){let{root:t,name:n}=e,r=M.join(t,"components",n),o=e.manifestPath??M.join(r,"manifest.json"),s=e.sourcePath??M.join(r,"component.tsx"),i=$t(t,o),a=$t(t,s),l=[],c=null,p=Ct(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let k=JSON.parse(p);!k||typeof k!="object"||Array.isArray(k)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=k}catch(k){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${k.message}`})}let u=Ct(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:yt(t,s,u),j=u===null?!1:wt(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:j},diagnostics:l}}function Ct(e){try{return Et.readFileSync(e,"utf8")}catch{return null}}function $t(e,t){let n=M.relative(e,t);return n.startsWith("..")?t:n.split(M.sep).join("/")}var jt=new Set(["onSendMessage","onCallTool","onClose","onUpdateModelContext","onShowLightbox","onGenerateStructuredContent","storeData","Image"]);var Rt=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 Tt(e){if(!e.manifest)return[];let t=yr(e.manifest.inputSchema);if(t===null)return[];if(!e.props.ok)return[{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return[];let n=new Set(e.props.props.names),r=new Set(t),o=[];for(let i of e.props.props.names){if(jt.has(i))continue;let a=Rt.get(i);if(a){o.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:a});continue}r.has(i)||o.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${i}\` is not declared in ${e.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`})}let s=t.filter(i=>!n.has(i));return s.length>0&&o.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:hr(e.manifestFile,s)}),o}var _t=8;function hr(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,_t).map(s=>`\`${s}\``).join(", "),r=t.length-_t,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 yr(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 wr=["anyOf","oneOf","allOf","$ref","not"];function ve(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>ve(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of wr)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,ve(i,`${t}.${s}`,n);"items"in r&&ve(r.items,`${t}[]`,n)}function Lt(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};ve(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("; ")}.
84
+ A schema this complex is usually a sign the component is overengineered, and the assistant 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 Ot(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 It(e){return e.usesWindowGreatStore?[{severity:"warning",rule:"globals/window-greatstore",file:e.sourceFile,message:"this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onCallTool`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function ae(e){return e.filter(t=>t.severity==="error")}function Oe(e){return e.filter(t=>t.severity==="warning")}function ce(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var br=[Ot,Lt,Tt,It];function xe(e){let{ctx:t,diagnostics:n}=At(e);for(let r of br)n.push(...r(t));return{diagnostics:n,ok:ae(n).length===0}}var K="components";async function Nt(e){let t=process.cwd();if(!S.existsSync(w.join(t,"package.json"))||!S.existsSync(w.join(t,K)))throw new Error(`\`gs apps build\` must run from a project root (contains \`package.json\` and \`${K}/\`). Current dir: ${t}`);let n=vr(t);if(n.length===0){process.stdout.write(`(no components in ./${K} \u2014 run \`gs apps init <name>\` to add one)
85
+ `);return}let r=e.positional[0],o=r?n.filter(p=>p===r):n;if(r&&o.length===0)throw new Error(`No component named "${r}" in ./${K}`);let s=[],i=[];for(let p of o){let u=xe({root:t,name:p});for(let f of u.diagnostics)process.stdout.write(` ${ce(f)}
86
+ `);(u.ok?i:s).push(p)}if(i.length===0){process.stdout.write(`
1586
87
  Nothing built \u2014 fix the errors above.
1587
- `);
1588
- process.exitCode = 1;
1589
- return;
1590
- }
1591
- const { build, reactPlugin, transformWithEsbuild } = await loadVite(root);
1592
- for (const name of buildable) {
1593
- const dir = path8.join(root, COMPONENTS_DIR, name);
1594
- const bundlePath = path8.join(dir, "bundle.js");
1595
- await build({
1596
- plugins: [reactPlugin()],
1597
- logLevel: "warn",
1598
- build: {
1599
- lib: {
1600
- entry: path8.join(dir, "component.tsx"),
1601
- formats: ["es"],
1602
- fileName: () => "bundle.js"
1603
- },
1604
- outDir: dir,
1605
- emptyOutDir: false,
1606
- rollupOptions: {
1607
- external: ["react", "react-dom", "react/jsx-runtime"],
1608
- output: {
1609
- entryFileNames: "bundle.js",
1610
- paths: {
1611
- react: "/assets/remote-components/_runtime.js",
1612
- "react-dom": "/assets/remote-components/_runtime.js",
1613
- "react/jsx-runtime": "/assets/remote-components/_runtime.js"
1614
- }
1615
- }
1616
- },
1617
- minify: true,
1618
- sourcemap: false
1619
- }
1620
- });
1621
- const beforeBytes = fs6.statSync(bundlePath).size;
1622
- const src = fs6.readFileSync(bundlePath, "utf8");
1623
- const { code } = await transformWithEsbuild(src, bundlePath, {
1624
- minify: true,
1625
- legalComments: "none",
1626
- target: "esnext",
1627
- loader: "js",
1628
- sourcemap: false
1629
- });
1630
- fs6.writeFileSync(bundlePath, code);
1631
- const afterBytes = Buffer.byteLength(code, "utf8");
1632
- process.stdout.write(
1633
- `built ${COMPONENTS_DIR}/${name}/bundle.js (${formatBytes(afterBytes)}, ${pctSmaller(beforeBytes, afterBytes)} smaller)
1634
- `
1635
- );
1636
- }
1637
- if (invalid.length > 0) {
1638
- process.stdout.write(
1639
- `
1640
- Not built (fix the errors above): ${invalid.join(", ")}
1641
- `
1642
- );
1643
- process.exitCode = 1;
1644
- return;
1645
- }
1646
- process.stdout.write(
1647
- `
1648
- Built locally \u2014 nothing uploaded yet. Next: \`gs apps push\` to upload, then \`gs 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).
1649
- `
1650
- );
1651
- }
1652
- function listComponents(root) {
1653
- const dir = path8.join(root, COMPONENTS_DIR);
1654
- return fs6.readdirSync(dir).filter((entry) => {
1655
- const candidate = path8.join(dir, entry);
1656
- return fs6.statSync(candidate).isDirectory() && fs6.existsSync(path8.join(candidate, "component.tsx"));
1657
- }).sort();
1658
- }
1659
- function formatBytes(n) {
1660
- if (n < 1024) return `${n} B`;
1661
- return `${(n / 1024).toFixed(1)} KB`;
1662
- }
1663
- function pctSmaller(before, after) {
1664
- if (before === 0) return "0%";
1665
- return `${Math.round((1 - after / before) * 100)}%`;
1666
- }
1667
- async function loadVite(root) {
1668
- const localRequire = createRequire2(path8.join(root, "package.json"));
1669
- const vitePath = resolveEsmEntry(localRequire, "vite");
1670
- if (!vitePath) {
1671
- throw new Error(
1672
- "Cannot find `vite` in this project. Run `npm install` first."
1673
- );
1674
- }
1675
- const reactPath = resolveEsmEntry(localRequire, "@vitejs/plugin-react");
1676
- if (!reactPath) {
1677
- throw new Error(
1678
- "Cannot find `@vitejs/plugin-react` in this project. Run `npm install` first."
1679
- );
1680
- }
1681
- const viteMod = await import(vitePath);
1682
- const build = viteMod.build ?? viteMod.default?.build;
1683
- if (typeof build !== "function") {
1684
- throw new Error(
1685
- `Loaded \`vite\` from ${vitePath} but couldn't find its \`build()\` export. Reinstall vite (>= 5) and retry.`
1686
- );
1687
- }
1688
- const transformWithEsbuild = viteMod.transformWithEsbuild ?? viteMod.default?.transformWithEsbuild;
1689
- if (typeof transformWithEsbuild !== "function") {
1690
- throw new Error(
1691
- `Loaded \`vite\` from ${vitePath} but couldn't find its \`transformWithEsbuild()\` export. Reinstall vite (>= 5) and retry.`
1692
- );
1693
- }
1694
- const reactMod = await import(reactPath);
1695
- const reactPlugin = reactMod.default ?? reactMod;
1696
- if (typeof reactPlugin !== "function") {
1697
- throw new Error(
1698
- `Loaded \`@vitejs/plugin-react\` from ${reactPath} but couldn't find its default export.`
1699
- );
1700
- }
1701
- return {
1702
- build,
1703
- reactPlugin,
1704
- transformWithEsbuild
1705
- };
1706
- }
1707
- function resolveEsmEntry(req, specifier) {
1708
- let anchor;
1709
- try {
1710
- anchor = req.resolve(specifier);
1711
- } catch {
1712
- return null;
1713
- }
1714
- const pkgJsonPath = findOwningPackageJson(anchor, specifier);
1715
- if (!pkgJsonPath) return null;
1716
- const pkgDir = path8.dirname(pkgJsonPath);
1717
- let pkg;
1718
- try {
1719
- pkg = JSON.parse(fs6.readFileSync(pkgJsonPath, "utf8"));
1720
- } catch {
1721
- return null;
1722
- }
1723
- const fromExports = pickImportEntry(pkg.exports);
1724
- const entry = fromExports ?? (typeof pkg.module === "string" ? pkg.module : null) ?? (typeof pkg.main === "string" ? pkg.main : null);
1725
- if (!entry) return null;
1726
- return path8.resolve(pkgDir, entry);
1727
- }
1728
- function findOwningPackageJson(start, specifier) {
1729
- let dir = path8.dirname(start);
1730
- while (true) {
1731
- const candidate = path8.join(dir, "package.json");
1732
- if (fs6.existsSync(candidate)) {
1733
- try {
1734
- const parsed = JSON.parse(fs6.readFileSync(candidate, "utf8"));
1735
- if (parsed.name === specifier) return candidate;
1736
- } catch {
1737
- }
1738
- }
1739
- const parent = path8.dirname(dir);
1740
- if (parent === dir) return null;
1741
- dir = parent;
1742
- }
1743
- }
1744
- function pickImportEntry(exports) {
1745
- if (typeof exports !== "object" || exports === null) return null;
1746
- const map = exports;
1747
- const dot = map["."] ?? exports;
1748
- if (typeof dot !== "object" || dot === null) return null;
1749
- const imp = dot.import;
1750
- if (typeof imp === "string") return imp;
1751
- if (typeof imp === "object" && imp !== null) {
1752
- const def = imp.default;
1753
- if (typeof def === "string") return def;
1754
- }
1755
- return null;
1756
- }
1757
-
1758
- // src/commands/apps/list.ts
1759
- async function listCommand(args) {
1760
- const slug = resolveReadStore();
1761
- const url = `${apiBaseFor(slug)}/api/apps/components`;
1762
- const data = await request(url);
1763
- if (flagBool(args.flags, "json")) {
1764
- process.stdout.write(JSON.stringify(data, null, 2) + "\n");
1765
- return;
1766
- }
1767
- if (data.components.length === 0) {
1768
- process.stdout.write(`(no components in ${slug})
1769
- `);
1770
- return;
1771
- }
1772
- const rows = data.components.map((c) => ({
1773
- name: c.name,
1774
- draft: c.draft ? `v${c.draft.version}` : "\u2014",
1775
- live: c.live ? `v${c.live.version}` : "\u2014",
1776
- updated: c.live?.updatedAt ?? c.draft?.updatedAt ?? "",
1777
- permalink: c.permalink ?? ""
1778
- }));
1779
- const widths = {
1780
- name: Math.max(4, ...rows.map((r) => r.name.length)),
1781
- draft: Math.max(5, ...rows.map((r) => r.draft.length)),
1782
- live: Math.max(4, ...rows.map((r) => r.live.length)),
1783
- updated: Math.max(7, ...rows.map((r) => r.updated.length))
1784
- };
1785
- const header = `${pad("NAME", widths.name)} ${pad("DRAFT", widths.draft)} ${pad("LIVE", widths.live)} ${pad("UPDATED", widths.updated)} LINK`;
1786
- process.stdout.write(header + "\n");
1787
- for (const r of rows) {
1788
- process.stdout.write(
1789
- `${pad(r.name, widths.name)} ${pad(r.draft, widths.draft)} ${pad(r.live, widths.live)} ${pad(r.updated, widths.updated)} ${r.permalink}
1790
- `
1791
- );
1792
- }
1793
- }
1794
- function pad(s, width) {
1795
- return s.length >= width ? s : s + " ".repeat(width - s.length);
1796
- }
1797
-
1798
- // src/commands/apps/pull.ts
1799
- import * as fs8 from "fs";
1800
- import * as path10 from "path";
1801
-
1802
- // src/sync.ts
1803
- import * as crypto2 from "crypto";
1804
- import * as fs7 from "fs";
1805
- import * as path9 from "path";
1806
- var SYNC_FILE = ".gssync.json";
1807
- function hashString(text) {
1808
- return crypto2.createHash("sha256").update(text).digest("hex");
1809
- }
1810
- function hashFile(filePath) {
1811
- if (!fs7.existsSync(filePath)) return null;
1812
- return hashString(fs7.readFileSync(filePath, "utf8"));
1813
- }
1814
- function computeComponentHashes(componentDir) {
1815
- const manifestHash = hashFile(path9.join(componentDir, "manifest.json"));
1816
- if (manifestHash === null) {
1817
- throw new Error(`Missing manifest.json in ${componentDir}`);
1818
- }
1819
- return {
1820
- manifestHash,
1821
- sourceHash: hashFile(path9.join(componentDir, "component.tsx")),
1822
- bundleHash: hashFile(path9.join(componentDir, "bundle.js"))
1823
- };
1824
- }
1825
- function readSyncState(componentDir) {
1826
- const file = path9.join(componentDir, SYNC_FILE);
1827
- if (!fs7.existsSync(file)) return null;
1828
- try {
1829
- const parsed = JSON.parse(fs7.readFileSync(file, "utf8"));
1830
- if (typeof parsed.version === "number" && typeof parsed.manifestHash === "string" && typeof parsed.sourceHash === "string") {
1831
- return {
1832
- version: parsed.version,
1833
- manifestHash: parsed.manifestHash,
1834
- sourceHash: parsed.sourceHash,
1835
- ...typeof parsed.bundleHash === "string" ? { bundleHash: parsed.bundleHash } : {}
1836
- };
1837
- }
1838
- return null;
1839
- } catch {
1840
- return null;
1841
- }
1842
- }
1843
- function writeSyncState(componentDir, state) {
1844
- fs7.writeFileSync(
1845
- path9.join(componentDir, SYNC_FILE),
1846
- JSON.stringify(state, null, 2) + "\n"
1847
- );
1848
- }
1849
- function hasLocalChanges(componentDir, state) {
1850
- const hashes = safeComputeHashes(componentDir);
1851
- if (!hashes) return false;
1852
- if (state === null) return true;
1853
- if (hashes.manifestHash !== state.manifestHash) return true;
1854
- const localSource = hashes.sourceHash ?? "";
1855
- const storedSource = state.sourceHash ?? "";
1856
- return localSource !== storedSource;
1857
- }
1858
- function safeComputeHashes(componentDir) {
1859
- try {
1860
- return computeComponentHashes(componentDir);
1861
- } catch {
1862
- return null;
1863
- }
1864
- }
1865
-
1866
- // src/commands/apps/pull.ts
1867
- async function pullCommand(args) {
1868
- const slug = requireProjectStore();
1869
- const force = flagBool(args.flags, "force");
1870
- const targets = args.positional;
1871
- const root = process.cwd();
1872
- if (targets.length === 0 || targets.length === 1 && targets[0] === "*") {
1873
- return pullAll({ slug, root, args, force });
1874
- }
1875
- if (targets.length > 1 && flagString(args.flags, "version")) {
1876
- throw new Error(
1877
- "--version is per-component; pass it together with a single `gs apps pull <name>`."
1878
- );
1879
- }
1880
- ensureComponentsDir(root);
1881
- const revisionQuery = buildRevisionQuery(args);
1882
- const outcomes = [];
1883
- for (const name of targets) {
1884
- const outcome = await pullOne({
1885
- slug,
1886
- componentDir: path10.join(root, "components", name),
1887
- name,
1888
- revisionQuery,
1889
- force
1890
- });
1891
- outcomes.push(outcome);
1892
- printOutcome(outcome, force);
1893
- }
1894
- if (outcomes.length > 1) printPullSummary(outcomes, slug);
1895
- if (outcomes.some((o) => o.status === "failed")) process.exitCode = 1;
1896
- }
1897
- async function pullAll(opts) {
1898
- const { slug, root, args, force } = opts;
1899
- if (flagString(args.flags, "version")) {
1900
- throw new Error(
1901
- "--version is per-component; pass it together with `gs apps pull <name>`."
1902
- );
1903
- }
1904
- ensureComponentsDir(root);
1905
- const revisionQuery = buildRevisionQuery(args);
1906
- const listUrl = `${apiBaseFor(slug)}/api/apps/components`;
1907
- const list = await request(listUrl);
1908
- if (list.components.length === 0) {
1909
- process.stdout.write(`(no components in ${slug})
1910
- `);
1911
- return;
1912
- }
1913
- const outcomes = [];
1914
- for (const entry of list.components) {
1915
- const componentDir = path10.join(root, "components", entry.name);
1916
- const outcome = await pullOne({
1917
- slug,
1918
- componentDir,
1919
- name: entry.name,
1920
- revisionQuery: revisionQuery === "" && entry.live === null ? "?revision=draft" : revisionQuery,
1921
- force
1922
- });
1923
- outcomes.push(outcome);
1924
- printOutcome(outcome, force);
1925
- }
1926
- printPullSummary(outcomes, slug);
1927
- if (outcomes.some((o) => o.status === "failed")) process.exitCode = 1;
1928
- }
1929
- function printPullSummary(outcomes, slug) {
1930
- const pulled = outcomes.filter((o) => o.status === "pulled").length;
1931
- const skipped = outcomes.filter((o) => o.status === "skipped").length;
1932
- const failed = outcomes.filter((o) => o.status === "failed").length;
1933
- const summary = [`${pulled} pulled`, `${skipped} skipped`];
1934
- if (failed > 0) summary.push(`${failed} failed`);
1935
- process.stdout.write(
1936
- `
1937
- ${summary.join(", ")} (of ${outcomes.length}) \u2190 ${slug}
1938
- `
1939
- );
1940
- }
1941
- async function pullOne(opts) {
1942
- const { slug, componentDir, name, revisionQuery, force } = opts;
1943
- if (!force && fs8.existsSync(componentDir)) {
1944
- const sync = readSyncState(componentDir);
1945
- if (hasLocalChanges(componentDir, sync)) {
1946
- return {
1947
- name,
1948
- status: "skipped",
1949
- message: "local has uncommitted changes; pass --force to overwrite"
1950
- };
1951
- }
1952
- }
1953
- const base = `${apiBaseFor(slug)}/api/apps/components/${encodeURIComponent(name)}`;
1954
- let data;
1955
- try {
1956
- data = await request(`${base}${revisionQuery}`);
1957
- } catch (err) {
1958
- if (revisionQuery === "" && isNotFound(err)) {
1959
- try {
1960
- data = await request(`${base}?revision=draft`);
1961
- } catch (draftErr) {
1962
- return {
1963
- name,
1964
- status: "failed",
1965
- message: draftErr instanceof Error ? draftErr.message : String(draftErr)
1966
- };
1967
- }
1968
- } else {
1969
- return {
1970
- name,
1971
- status: "failed",
1972
- message: err instanceof Error ? err.message : String(err)
1973
- };
1974
- }
1975
- }
1976
- fs8.mkdirSync(componentDir, { recursive: true });
1977
- const manifestText = JSON.stringify(data.manifest, null, 2) + "\n";
1978
- fs8.writeFileSync(path10.join(componentDir, "manifest.json"), manifestText);
1979
- fs8.writeFileSync(path10.join(componentDir, "bundle.js"), data.bundle);
1980
- const wrote = ["manifest.json", "bundle.js"];
1981
- let sourceHash = "";
1982
- if (data.source !== null) {
1983
- fs8.writeFileSync(path10.join(componentDir, "component.tsx"), data.source);
1984
- wrote.push("component.tsx");
1985
- sourceHash = hashString(data.source);
1986
- }
1987
- writeSyncState(componentDir, {
1988
- version: data.version,
1989
- manifestHash: hashString(manifestText),
1990
- sourceHash,
1991
- bundleHash: hashString(data.bundle)
1992
- });
1993
- const onDisk = computeComponentHashes(componentDir);
1994
- writeSyncState(componentDir, {
1995
- version: data.version,
1996
- manifestHash: onDisk.manifestHash,
1997
- sourceHash: onDisk.sourceHash ?? "",
1998
- bundleHash: onDisk.bundleHash ?? ""
1999
- });
2000
- return { name, status: "pulled", version: data.version, wrote };
2001
- }
2002
- function ensureComponentsDir(root) {
2003
- fs8.mkdirSync(path10.join(root, "components"), { recursive: true });
2004
- }
2005
- function isNotFound(err) {
2006
- return err instanceof HttpError && err.status === 404;
2007
- }
2008
- function buildRevisionQuery(args) {
2009
- const version = flagString(args.flags, "version");
2010
- if (version) return `?version=${encodeURIComponent(version)}`;
2011
- if (flagBool(args.flags, "draft")) return `?revision=draft`;
2012
- if (flagBool(args.flags, "live")) return `?revision=live`;
2013
- return "";
2014
- }
2015
- function printOutcome(outcome, force) {
2016
- switch (outcome.status) {
2017
- case "pulled": {
2018
- const files = outcome.wrote ? `{${outcome.wrote.join(", ")}}` : "";
2019
- process.stdout.write(
2020
- ` pulled ${outcome.name} v${outcome.version} ${files}
2021
- `
2022
- );
2023
- return;
2024
- }
2025
- case "skipped":
2026
- process.stdout.write(` skipped ${outcome.name}: ${outcome.message}
2027
- `);
2028
- return;
2029
- case "failed":
2030
- process.stdout.write(
2031
- ` failed ${outcome.name}: ${outcome.message ?? "unknown error"}
2032
- `
2033
- );
2034
- return;
2035
- }
2036
- void force;
2037
- }
2038
-
2039
- // src/commands/apps/push.ts
2040
- import * as fs9 from "fs";
2041
- import * as path11 from "path";
2042
- async function pushCommand(args) {
2043
- const slug = requireProjectStore();
2044
- const root = process.cwd();
2045
- rejectLegacyLayout(root);
2046
- const componentsDir = path11.join(root, "components");
2047
- if (!fs9.existsSync(componentsDir)) {
2048
- throw new Error(
2049
- "No components/ directory here. Run `gs apps init <name>` to scaffold the project root and your first component."
2050
- );
2051
- }
2052
- const named = args.positional;
2053
- const manifestOverride = flagString(args.flags, "manifest");
2054
- const bundleOverride = flagString(args.flags, "bundle");
2055
- if (named.length !== 1 && (manifestOverride || bundleOverride)) {
2056
- throw new Error(
2057
- "--manifest / --bundle can only be used together with a single `gs apps push <name>`."
2058
- );
2059
- }
2060
- if (named.length > 0) {
2061
- const force = flagBool(args.flags, "force") || manifestOverride !== void 0 || bundleOverride !== void 0;
2062
- const outcomes2 = [];
2063
- for (const name of named) {
2064
- const outcome = await pushOne({
2065
- slug,
2066
- root,
2067
- name,
2068
- ...manifestOverride !== void 0 ? { manifestPath: manifestOverride } : {},
2069
- ...bundleOverride !== void 0 ? { bundlePath: bundleOverride } : {},
2070
- force
2071
- });
2072
- outcomes2.push(outcome);
2073
- printOutcome2(outcome);
2074
- }
2075
- if (outcomes2.length > 1) printPushSummary(outcomes2, slug);
2076
- if (outcomes2.some((o) => o.status === "failed")) process.exitCode = 1;
2077
- return;
2078
- }
2079
- const names = listLocalComponents(componentsDir);
2080
- if (names.length === 0) {
2081
- process.stdout.write(
2082
- "(no components in ./components \u2014 run `gs apps init <name>` to add one)\n"
2083
- );
2084
- return;
2085
- }
2086
- const outcomes = [];
2087
- for (const name of names) {
2088
- const outcome = await pushOne({ slug, root, name, force: false });
2089
- outcomes.push(outcome);
2090
- printOutcome2(outcome);
2091
- }
2092
- printPushSummary(outcomes, slug);
2093
- if (outcomes.some((o) => o.status === "failed")) process.exitCode = 1;
2094
- }
2095
- function printPushSummary(outcomes, slug) {
2096
- const pushed = outcomes.filter((o) => o.status === "pushed").length;
2097
- const unchanged = outcomes.filter((o) => o.status === "unchanged").length;
2098
- const failed = outcomes.filter((o) => o.status === "failed").length;
2099
- const summary = [`${pushed} pushed`, `${unchanged} unchanged`];
2100
- if (failed > 0) summary.push(`${failed} failed`);
2101
- process.stdout.write(`
2102
- ${summary.join(", ")} (of ${outcomes.length}) \u2192 ${slug}
2103
- `);
2104
- }
2105
- async function pushOne(opts) {
2106
- const { slug, root, name, force } = opts;
2107
- const componentDir = path11.join(root, "components", name);
2108
- if (!fs9.existsSync(componentDir)) {
2109
- return {
2110
- name,
2111
- status: "failed",
2112
- message: `components/${name}/ does not exist`
2113
- };
2114
- }
2115
- const manifestPath = opts.manifestPath ? path11.resolve(opts.manifestPath) : path11.join(componentDir, "manifest.json");
2116
- const bundlePath = opts.bundlePath ? path11.resolve(opts.bundlePath) : path11.join(componentDir, "bundle.js");
2117
- const sourcePath = path11.join(componentDir, "component.tsx");
2118
- if (!fs9.existsSync(bundlePath)) {
2119
- return {
2120
- name,
2121
- status: "failed",
2122
- message: `bundle not found: ${bundlePath} (did you run \`npm run build\`?)`
2123
- };
2124
- }
2125
- const report = validateComponent({
2126
- root,
2127
- name,
2128
- manifestPath,
2129
- sourcePath
2130
- });
2131
- for (const diagnostic of warningsIn(report.diagnostics)) {
2132
- process.stdout.write(` ${formatDiagnostic(diagnostic)}
2133
- `);
2134
- }
2135
- if (!report.ok) {
2136
- return {
2137
- name,
2138
- status: "failed",
2139
- message: errorsIn(report.diagnostics).map((d) => `${d.file}: ${d.message}`).join(`
2140
- ${OUTCOME_INDENT}`)
2141
- };
2142
- }
2143
- const manifestText = fs9.readFileSync(manifestPath, "utf8");
2144
- const before = computeComponentHashes(componentDir);
2145
- const sync = readSyncState(componentDir);
2146
- const staleBundle = opts.bundlePath === void 0 && sync?.bundleHash !== void 0 && sync.sourceHash !== (before.sourceHash ?? "") && sync.bundleHash === (before.bundleHash ?? "");
2147
- if (!force) {
2148
- const unchanged = sync !== null && sync.manifestHash === before.manifestHash && sync.sourceHash === (before.sourceHash ?? "") && // An older sync file has no bundle hash; treat that as "unknown" and
2149
- // push, rather than assume a bundle we never recorded is current.
2150
- sync.bundleHash !== void 0 && sync.bundleHash === (before.bundleHash ?? "");
2151
- if (unchanged) {
2152
- return { name, status: "unchanged" };
2153
- }
2154
- }
2155
- const bundleText = fs9.readFileSync(bundlePath, "utf8");
2156
- const sourceText = fs9.existsSync(sourcePath) ? fs9.readFileSync(sourcePath, "utf8") : null;
2157
- const form = new FormData();
2158
- form.append(
2159
- "manifest",
2160
- new Blob([manifestText], { type: "application/json" }),
2161
- "manifest.json"
2162
- );
2163
- form.append(
2164
- "bundle",
2165
- new Blob([bundleText], { type: "text/javascript" }),
2166
- "bundle.js"
2167
- );
2168
- if (sourceText !== null) {
2169
- form.append(
2170
- "source",
2171
- new Blob([sourceText], { type: "text/plain; charset=utf-8" }),
2172
- "component.tsx"
2173
- );
2174
- }
2175
- const url = `${apiBaseFor(slug)}/api/apps/components/${encodeURIComponent(name)}`;
2176
- let data;
2177
- try {
2178
- data = await request(url, { method: "POST", multipart: form });
2179
- } catch (err) {
2180
- return {
2181
- name,
2182
- status: "failed",
2183
- message: err instanceof Error ? err.message : String(err)
2184
- };
2185
- }
2186
- const hashes = computeComponentHashes(componentDir);
2187
- writeSyncState(componentDir, {
2188
- version: data.version,
2189
- manifestHash: hashes.manifestHash,
2190
- sourceHash: hashes.sourceHash ?? "",
2191
- bundleHash: hashes.bundleHash ?? ""
2192
- });
2193
- return {
2194
- name,
2195
- status: "pushed",
2196
- version: data.version,
2197
- permalink: data.permalink,
2198
- ...staleBundle ? { staleBundle: true } : {}
2199
- };
2200
- }
2201
- function listLocalComponents(componentsDir) {
2202
- return fs9.readdirSync(componentsDir).filter((entry) => {
2203
- const dir = path11.join(componentsDir, entry);
2204
- return fs9.statSync(dir).isDirectory() && fs9.existsSync(path11.join(dir, "manifest.json"));
2205
- }).sort();
2206
- }
2207
- function rejectLegacyLayout(root) {
2208
- const rootManifest = path11.join(root, "manifest.json");
2209
- const componentsDir = path11.join(root, "components");
2210
- if (fs9.existsSync(rootManifest) && !fs9.existsSync(componentsDir)) {
2211
- throw new Error(
2212
- [
2213
- "Detected the old single-component layout (manifest.json at the project root).",
2214
- "The CLI now uses a multi-component layout: scaffold a fresh dir with",
2215
- "`gs apps init`, then move your component into `components/<name>/`. Re-run `gs apps push`",
2216
- "from the new project root."
2217
- ].join(" ")
2218
- );
2219
- }
2220
- }
2221
- var OUTCOME_INDENT = " ".repeat(" failed ".length);
2222
- function printOutcome2(outcome) {
2223
- switch (outcome.status) {
2224
- case "pushed":
2225
- process.stdout.write(
2226
- ` pushed ${outcome.name} v${outcome.version} \u2192 ${outcome.permalink ?? ""}
2227
- `
2228
- );
2229
- if (outcome.staleBundle) {
2230
- process.stdout.write(
2231
- `${OUTCOME_INDENT}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`gs build ${outcome.name}\` and push again.
2232
- `
2233
- );
2234
- }
2235
- return;
2236
- case "unchanged":
2237
- process.stdout.write(` unchanged ${outcome.name}
2238
- `);
2239
- return;
2240
- case "failed":
2241
- process.stdout.write(
2242
- ` failed ${outcome.name}: ${outcome.message ?? "unknown error"}
2243
- `
2244
- );
2245
- return;
2246
- }
2247
- }
2248
-
2249
- // src/commands/apps/publish.ts
2250
- async function publishCommand(args) {
2251
- const names = args.positional;
2252
- if (names.length === 0) {
2253
- throw new Error("Usage: gs apps publish <name> [<name>...] [--version N]");
2254
- }
2255
- const slug = requireProjectStore();
2256
- const versionFlag = flagString(args.flags, "version");
2257
- let version;
2258
- if (versionFlag !== void 0) {
2259
- if (names.length > 1) {
2260
- throw new Error(
2261
- "--version is per-component; pass it together with a single `gs apps publish <name>`."
2262
- );
2263
- }
2264
- const n = Number.parseInt(versionFlag, 10);
2265
- if (!Number.isInteger(n) || n < 1) {
2266
- throw new Error(`Invalid --version: ${versionFlag}`);
2267
- }
2268
- version = n;
2269
- }
2270
- if (names.length === 1) {
2271
- const name = names[0];
2272
- const data = await publish(slug, name, version);
2273
- process.stdout.write(
2274
- `Published ${name} (v${data.live_version}). ${data.permalink}
2275
- `
2276
- );
2277
- return;
2278
- }
2279
- const outcomes = [];
2280
- for (const name of names) {
2281
- let outcome;
2282
- try {
2283
- const data = await publish(slug, name, version);
2284
- outcome = {
2285
- name,
2286
- status: "published",
2287
- version: data.live_version,
2288
- permalink: data.permalink
2289
- };
2290
- } catch (err) {
2291
- outcome = {
2292
- name,
2293
- status: "failed",
2294
- message: err instanceof Error ? err.message : String(err)
2295
- };
2296
- }
2297
- outcomes.push(outcome);
2298
- printOutcome3(outcome);
2299
- }
2300
- const published = outcomes.filter((o) => o.status === "published").length;
2301
- const failed = outcomes.filter((o) => o.status === "failed").length;
2302
- const summary = [`${published} published`];
2303
- if (failed > 0) summary.push(`${failed} failed`);
2304
- process.stdout.write(
2305
- `
2306
- ${summary.join(", ")} (of ${outcomes.length}) \u2192 ${slug}
2307
- `
2308
- );
2309
- if (failed > 0) process.exitCode = 1;
2310
- }
2311
- async function publish(slug, name, version) {
2312
- const url = `${apiBaseFor(slug)}/api/apps/components/${encodeURIComponent(name)}/publish`;
2313
- const body = version !== void 0 ? { version } : {};
2314
- return request(url, { method: "POST", body });
2315
- }
2316
- function printOutcome3(outcome) {
2317
- if (outcome.status === "published") {
2318
- process.stdout.write(
2319
- ` published ${outcome.name} v${outcome.version} \u2192 ${outcome.permalink ?? ""}
2320
- `
2321
- );
2322
- return;
2323
- }
2324
- process.stdout.write(
2325
- ` failed ${outcome.name}: ${outcome.message ?? "unknown error"}
2326
- `
2327
- );
2328
- }
2329
-
2330
- // src/commands/apps/unpublish.ts
2331
- async function unpublishCommand(args) {
2332
- const name = args.positional[0];
2333
- if (!name) throw new Error("Usage: gs apps unpublish <name>");
2334
- const slug = requireProjectStore();
2335
- const url = `${apiBaseFor(slug)}/api/apps/components/${encodeURIComponent(name)}/unpublish`;
2336
- await request(url, { method: "POST", body: {} });
2337
- process.stdout.write(`Unpublished ${name}.
2338
- `);
2339
- }
2340
-
2341
- // src/commands/apps/delete.ts
2342
- import * as readline from "readline";
2343
- async function deleteCommand(args) {
2344
- const name = args.positional[0];
2345
- if (!name) throw new Error("Usage: gs apps delete <name> [--yes]");
2346
- const slug = requireProjectStore();
2347
- if (!flagBool(args.flags, "yes")) {
2348
- const confirmed = await prompt(
2349
- `Soft-delete component "${name}" in store "${slug}"? Type "yes" to confirm: `
2350
- );
2351
- if (confirmed.trim() !== "yes") {
2352
- process.stdout.write("Aborted.\n");
2353
- return;
2354
- }
2355
- }
2356
- const url = `${apiBaseFor(slug)}/api/apps/components/${encodeURIComponent(name)}`;
2357
- await request(url, { method: "DELETE" });
2358
- process.stdout.write(`Deleted ${name}.
2359
- `);
2360
- }
2361
- function prompt(question) {
2362
- return new Promise((resolve8) => {
2363
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2364
- rl.question(question, (answer) => {
2365
- rl.close();
2366
- resolve8(answer);
2367
- });
2368
- });
2369
- }
2370
-
2371
- // src/commands/apps/index.ts
2372
- var APPS_HELP = `gs apps \u2014 author and ship custom in-chat apps
88
+ `),process.exitCode=1;return}let{build:a,reactPlugin:l,transformWithEsbuild:c}=await Pr(t);for(let p of i){let u=w.join(t,K,p),f=w.join(u,"bundle.js");await a({plugins:[l()],logLevel:"warn",build:{lib:{entry:w.join(u,"component.tsx"),formats:["es"],fileName:()=>"bundle.js"},outDir:u,emptyOutDir:!1,rollupOptions:{external:["react","react-dom","react/jsx-runtime"],output:{entryFileNames:"bundle.js",paths:{react:"/assets/remote-components/_runtime.js","react-dom":"/assets/remote-components/_runtime.js","react/jsx-runtime":"/assets/remote-components/_runtime.js"}}},minify:!0,sourcemap:!1}});let j=S.statSync(f).size,k=S.readFileSync(f,"utf8"),{code:J}=await c(k,f,{minify:!0,legalComments:"none",target:"esnext",loader:"js",sourcemap:!1});S.writeFileSync(f,J);let R=Buffer.byteLength(J,"utf8");process.stdout.write(`built ${K}/${p}/bundle.js (${xr(R)}, ${kr(j,R)} smaller)
89
+ `)}if(s.length>0){process.stdout.write(`
90
+ Not built (fix the errors above): ${s.join(", ")}
91
+ `),process.exitCode=1;return}process.stdout.write("\nBuilt locally \u2014 nothing uploaded yet. Next: `gs apps push` to upload, then `gs apps publish <name>` to ship. If you're an AI assistant: confirm with the user before running these (or just run them if they already asked you to ship end-to-end).\n")}function vr(e){let t=w.join(e,K);return S.readdirSync(t).filter(n=>{let r=w.join(t,n);return S.statSync(r).isDirectory()&&S.existsSync(w.join(r,"component.tsx"))}).sort()}function xr(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function kr(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Pr(e){let t=Sr(w.join(e,"package.json")),n=Ft(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=Ft(t,"@vitejs/plugin-react");if(!r)throw new Error("Cannot find `@vitejs/plugin-react` in this project. Run `npm install` first.");let o=await import(n),s=o.build??o.default?.build;if(typeof s!="function")throw new Error(`Loaded \`vite\` from ${n} but couldn't find its \`build()\` export. Reinstall vite (>= 5) and retry.`);let i=o.transformWithEsbuild??o.default?.transformWithEsbuild;if(typeof i!="function")throw new Error(`Loaded \`vite\` from ${n} but couldn't find its \`transformWithEsbuild()\` export. Reinstall vite (>= 5) and retry.`);let a=await import(r),l=a.default??a;if(typeof l!="function")throw new Error(`Loaded \`@vitejs/plugin-react\` from ${r} but couldn't find its default export.`);return{build:s,reactPlugin:l,transformWithEsbuild:i}}function Ft(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Cr(n,t);if(!r)return null;let o=w.dirname(r),s;try{s=JSON.parse(S.readFileSync(r,"utf8"))}catch{return null}let a=$r(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?w.resolve(o,a):null}function Cr(e,t){let n=w.dirname(e);for(;;){let r=w.join(n,"package.json");if(S.existsSync(r))try{if(JSON.parse(S.readFileSync(r,"utf8")).name===t)return r}catch{}let o=w.dirname(n);if(o===n)return null;n=o}}function $r(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 Dt(e){let t=Ye(),n=`${C(t)}/api/apps/components`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
92
+ `);return}if(r.components.length===0){process.stdout.write(`(no components in ${t})
93
+ `);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=`${U("NAME",s.name)} ${U("DRAFT",s.draft)} ${U("LIVE",s.live)} ${U("UPDATED",s.updated)} LINK`;process.stdout.write(i+`
94
+ `);for(let a of o)process.stdout.write(`${U(a.name,s.name)} ${U(a.draft,s.draft)} ${U(a.live,s.live)} ${U(a.updated,s.updated)} ${a.permalink}
95
+ `)}function U(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as O from"fs";import*as W from"path";import*as Bt from"crypto";import*as G from"fs";import*as Z from"path";var Ht=".gssync.json";function le(e){return Bt.createHash("sha256").update(e).digest("hex")}function Ie(e){return G.existsSync(e)?le(G.readFileSync(e,"utf8")):null}function ee(e){let t=Ie(Z.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:Ie(Z.join(e,"component.tsx")),bundleHash:Ie(Z.join(e,"bundle.js"))}}function ke(e){let t=Z.join(e,Ht);if(!G.existsSync(t))return null;try{let n=JSON.parse(G.readFileSync(t,"utf8"));return typeof n.version=="number"&&typeof n.manifestHash=="string"&&typeof n.sourceHash=="string"?{version:n.version,manifestHash:n.manifestHash,sourceHash:n.sourceHash,...typeof n.bundleHash=="string"?{bundleHash:n.bundleHash}:{}}:null}catch{return null}}function ue(e,t){G.writeFileSync(Z.join(e,Ht),JSON.stringify(t,null,2)+`
96
+ `)}function Mt(e,t){let n=Er(e);if(!n)return!1;if(t===null||n.manifestHash!==t.manifestHash)return!0;let r=n.sourceHash??"",o=t.sourceHash??"";return r!==o}function Er(e){try{return ee(e)}catch{return null}}async function Ut(e){let t=E(),n=m(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return Ar({slug:t,root:o,args:e,force:n});if(r.length>1&&h(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `gs apps pull <name>`.");Vt(o);let s=Kt(e),i=[];for(let a of r){let l=await qt({slug:t,componentDir:W.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),Wt(l,n)}i.length>1&&Gt(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function Ar(e){let{slug:t,root:n,args:r,force:o}=e;if(h(r.flags,"version"))throw new Error("--version is per-component; pass it together with `gs apps pull <name>`.");Vt(n);let s=Kt(r),i=`${C(t)}/api/apps/components`,a=await d(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
97
+ `);return}let l=[];for(let c of a.components){let p=W.join(n,"components",c.name),u=await qt({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),Wt(u,o)}Gt(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function Gt(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(`
98
+ ${s.join(", ")} (of ${e.length}) \u2190 ${t}
99
+ `)}async function qt(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&O.existsSync(n)){let f=ke(n);if(Mt(n,f))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${C(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await d(`${i}${o}`)}catch(f){if(o===""&&jr(f))try{a=await d(`${i}?revision=draft`)}catch(j){return{name:r,status:"failed",message:j instanceof Error?j.message:String(j)}}else return{name:r,status:"failed",message:f instanceof Error?f.message:String(f)}}O.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
100
+ `;O.writeFileSync(W.join(n,"manifest.json"),l),O.writeFileSync(W.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(O.writeFileSync(W.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=le(a.source)),ue(n,{version:a.version,manifestHash:le(l),sourceHash:p,bundleHash:le(a.bundle)});let u=ee(n);return ue(n,{version:a.version,manifestHash:u.manifestHash,sourceHash:u.sourceHash??"",bundleHash:u.bundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function Vt(e){O.mkdirSync(W.join(e,"components"),{recursive:!0})}function jr(e){return e instanceof N&&e.status===404}function Kt(e){let t=h(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:m(e.flags,"draft")?"?revision=draft":m(e.flags,"live")?"?revision=live":""}function Wt(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
101
+ `);return}case"skipped":process.stdout.write(` skipped ${e.name}: ${e.message}
102
+ `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
103
+ `);return}}import*as v from"fs";import*as $ from"path";async function Yt(e){let t=E(),n=process.cwd();_r(n);let r=$.join(n,"components");if(!v.existsSync(r))throw new Error("No components/ directory here. Run `gs apps init <name>` to scaffold the project root and your first component.");let o=e.positional,s=h(e.flags,"manifest"),i=h(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `gs apps push <name>`.");if(o.length>0){let c=m(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let f=await zt({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(f),Xt(f)}p.length>1&&Jt(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=Rr(r);if(a.length===0){process.stdout.write("(no components in ./components \u2014 run `gs apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await zt({slug:t,root:n,name:c,force:!1});l.push(p),Xt(p)}Jt(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function Jt(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(`
104
+ ${s.join(", ")} (of ${e.length}) \u2192 ${t}
105
+ `)}async function zt(e){let{slug:t,root:n,name:r,force:o}=e,s=$.join(n,"components",r);if(!v.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?$.resolve(e.manifestPath):$.join(s,"manifest.json"),a=e.bundlePath?$.resolve(e.bundlePath):$.join(s,"bundle.js"),l=$.join(s,"component.tsx");if(!v.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=xe({root:n,name:r,manifestPath:i,sourcePath:l});for(let T of Oe(c.diagnostics))process.stdout.write(` ${ce(T)}
106
+ `);if(!c.ok)return{name:r,status:"failed",message:ae(c.diagnostics).map(T=>`${T.file}: ${T.message}`).join(`
107
+ ${Qt}`)};let p=v.readFileSync(i,"utf8"),u=ee(s),f=ke(s),j=e.bundlePath===void 0&&f?.bundleHash!==void 0&&f.sourceHash!==(u.sourceHash??"")&&f.bundleHash===(u.bundleHash??"");if(!o&&f!==null&&f.manifestHash===u.manifestHash&&f.sourceHash===(u.sourceHash??"")&&f.bundleHash!==void 0&&f.bundleHash===(u.bundleHash??""))return{name:r,status:"unchanged"};let k=v.readFileSync(a,"utf8"),J=v.existsSync(l)?v.readFileSync(l,"utf8"):null,R=new FormData;R.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),R.append("bundle",new Blob([k],{type:"text/javascript"}),"bundle.js"),J!==null&&R.append("source",new Blob([J],{type:"text/plain; charset=utf-8"}),"component.tsx"),o||R.append("base_version",String(f?.version??0));let xn=`${C(t)}/api/apps/components/${encodeURIComponent(r)}`,pe;try{pe=await d(xn,{method:"POST",multipart:R})}catch(T){return{name:r,status:"failed",message:T instanceof Error?T.message:String(T)}}let Ae=ee(s);return ue(s,{version:pe.version,manifestHash:Ae.manifestHash,sourceHash:Ae.sourceHash??"",bundleHash:Ae.bundleHash??""}),{name:r,status:"pushed",version:pe.version,permalink:pe.permalink,...j?{staleBundle:!0}:{}}}function Rr(e){return v.readdirSync(e).filter(t=>{let n=$.join(e,t);return v.statSync(n).isDirectory()&&v.existsSync($.join(n,"manifest.json"))}).sort()}function _r(e){let t=$.join(e,"manifest.json"),n=$.join(e,"components");if(v.existsSync(t)&&!v.existsSync(n))throw new Error(["Detected the old single-component layout (manifest.json at the project root).","The CLI now uses a multi-component layout: scaffold a fresh dir with","`gs apps init`, then move your component into `components/<name>/`. Re-run `gs apps push`","from the new project root."].join(" "))}var Qt=" ".repeat(12);function Xt(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version} \u2192 ${e.permalink??""}
108
+ `),e.staleBundle&&process.stdout.write(`${Qt}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`gs build ${e.name}\` and push again.
109
+ `);return;case"unchanged":process.stdout.write(` unchanged ${e.name}
110
+ `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
111
+ `);return}}async function en(e){let t=e.positional;if(t.length===0)throw new Error("Usage: gs apps publish <name> [<name>...] [--version N]");let n=E(),r=h(e.flags,"version"),o;if(r!==void 0){if(t.length>1)throw new Error("--version is per-component; pass it together with a single `gs 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 Zt(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
112
+ `);return}let s=[];for(let c of t){let p;try{let u=await Zt(n,c,o);p={name:c,status:"published",version:u.live_version,permalink:u.permalink}}catch(u){p={name:c,status:"failed",message:u instanceof Error?u.message:String(u)}}s.push(p),Tr(p)}let i=s.filter(c=>c.status==="published").length,a=s.filter(c=>c.status==="failed").length,l=[`${i} published`];a>0&&l.push(`${a} failed`),process.stdout.write(`
113
+ ${l.join(", ")} (of ${s.length}) \u2192 ${n}
114
+ `),a>0&&(process.exitCode=1)}async function Zt(e,t,n){let r=`${C(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return d(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function Tr(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
115
+ `);return}process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
116
+ `)}async function tn(e){let t=e.positional[0];if(!t)throw new Error("Usage: gs apps unpublish <name>");let n=E(),r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
117
+ `)}import*as nn from"readline";async function rn(e){let t=e.positional[0];if(!t)throw new Error("Usage: gs apps delete <name> [--yes]");let n=E();if(!m(e.flags,"yes")&&(await Lr(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
118
+ `);return}let r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}`;await d(r,{method:"DELETE"}),process.stdout.write(`Deleted ${t}.
119
+ `)}function Lr(e){return new Promise(t=>{let n=nn.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}var on=`gs apps \u2014 author and ship custom in-chat apps
2373
120
 
2374
121
  Usage:
2375
122
  gs apps <subcommand> [args] [flags]
@@ -2383,594 +130,518 @@ Subcommands:
2383
130
  publish <name>... Promote the draft(s) (or --version N) to live.
2384
131
  unpublish <name> Clear the live pointer.
2385
132
  delete <name> Soft-delete the component.
2386
- `;
2387
- async function appsCommand(args) {
2388
- const sub = args.positional[0];
2389
- const rest = { ...args, positional: args.positional.slice(1) };
2390
- switch (sub) {
2391
- case void 0:
2392
- case "help":
2393
- process.stdout.write(APPS_HELP);
2394
- return 0;
2395
- case "init":
2396
- initCommand(rest);
2397
- return 0;
2398
- case "build":
2399
- await buildCommand(rest);
2400
- return 0;
2401
- case "list":
2402
- await listCommand(rest);
2403
- return 0;
2404
- case "pull":
2405
- await pullCommand(rest);
2406
- return 0;
2407
- case "push":
2408
- await pushCommand(rest);
2409
- return 0;
2410
- case "publish":
2411
- await publishCommand(rest);
2412
- return 0;
2413
- case "unpublish":
2414
- await unpublishCommand(rest);
2415
- return 0;
2416
- case "delete":
2417
- await deleteCommand(rest);
2418
- return 0;
2419
- default:
2420
- process.stderr.write(`Unknown apps subcommand: ${sub}
2421
-
2422
- ${APPS_HELP}`);
2423
- return 1;
2424
- }
2425
- }
2426
-
2427
- // src/commands/configure/show.ts
2428
- async function showConfig(args) {
2429
- const slug = resolveAdminStore(args);
2430
- const url = `${adminApiBase(slug)}/configure/config`;
2431
- const data = await request(url);
2432
- if (flagBool(args.flags, "json")) {
2433
- process.stdout.write(JSON.stringify(data.brand, null, 2) + "\n");
2434
- return;
2435
- }
2436
- printBrand(slug, data.brand);
2437
- }
2438
- function printBrand(slug, brand) {
2439
- const lines = [`Configuration for ${slug}:`, ""];
2440
- lines.push(` displayName ${brand.displayName ?? "\u2014"}`);
2441
- lines.push(` assistantName ${brand.assistantName ?? "\u2014"}`);
2442
- lines.push(` storeLink ${brand.storeLink ?? "\u2014"}`);
2443
- lines.push(` extraOrigins ${formatList(brand.extraOrigins)}`);
2444
- lines.push(` icon ${brand.icon?.url ?? "\u2014"}`);
2445
- lines.push(` logoLight ${brand.logo?.light?.url ?? "\u2014"}`);
2446
- lines.push(` logoDark ${brand.logo?.dark?.url ?? "\u2014"}`);
2447
- lines.push(` theme ${brand.theme ? JSON.stringify(brand.theme) : "\u2014"}`);
2448
- lines.push(` cspScriptHosts ${formatList(brand.cspScriptHosts)}`);
2449
- lines.push(` cspConnectHosts ${formatList(brand.cspConnectHosts)}`);
2450
- process.stdout.write(lines.join("\n") + "\n");
2451
- }
2452
- function formatList(list) {
2453
- if (!list || list.length === 0) return "\u2014";
2454
- return list.join(", ");
2455
- }
2456
-
2457
- // src/commands/configure/set.ts
2458
- import * as fs10 from "fs";
2459
- import * as path12 from "path";
2460
- var THEME_FLAG_PREFIX = "theme.";
2461
- var TEXT_FIELDS = [
2462
- "displayName",
2463
- "assistantName",
2464
- "storeLink"
2465
- ];
2466
- var LIST_FIELDS = ["extraOrigins", "cspScriptHosts", "cspConnectHosts"];
2467
- async function setConfig(args) {
2468
- const slug = resolveAdminStore(args);
2469
- const body = {};
2470
- for (const field of TEXT_FIELDS) {
2471
- if (!(field in args.flags)) continue;
2472
- const v = args.flags[field];
2473
- if (typeof v !== "string") {
2474
- throw new Error(`--${field} requires a value (use --${field} "" to clear).`);
2475
- }
2476
- body[field] = v === "" ? null : v;
2477
- }
2478
- for (const field of LIST_FIELDS) {
2479
- if (!(field in args.flags)) continue;
2480
- const v = args.flags[field];
2481
- if (typeof v !== "string") {
2482
- throw new Error(
2483
- `--${field} requires a comma-separated value (use --${field} "" to clear).`
2484
- );
2485
- }
2486
- const entries = v.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
2487
- body[field] = entries.length === 0 ? null : entries;
2488
- }
2489
- const themeFile = flagString(args.flags, "themeFile");
2490
- const perField = collectThemeFieldFlags(args.flags);
2491
- const replace = flagBool(args.flags, "replace");
2492
- if ("theme" in args.flags && themeFile !== void 0) {
2493
- throw new Error("Pass either --theme or --themeFile, not both.");
2494
- }
2495
- if (perField !== null && ("theme" in args.flags || themeFile !== void 0)) {
2496
- throw new Error(
2497
- "Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both."
2498
- );
2499
- }
2500
- let themePatch;
2501
- if ("theme" in args.flags) {
2502
- const v = args.flags["theme"];
2503
- if (typeof v !== "string") {
2504
- throw new Error('--theme requires a JSON value (use --theme "" to clear).');
2505
- }
2506
- themePatch = v === "" ? null : parseThemeJson(v, "--theme");
2507
- } else if (themeFile !== void 0) {
2508
- themePatch = parseThemeJson(readTextFile(themeFile, "--themeFile"), "--themeFile");
2509
- } else if (perField !== null) {
2510
- themePatch = perField;
2511
- }
2512
- if (themePatch !== void 0) {
2513
- body["theme"] = themePatch === null || replace ? themePatch : { ...await readStoredTheme(slug), ...themePatch };
2514
- if (body["theme"] !== null) {
2515
- const merged = body["theme"];
2516
- for (const [key, value] of Object.entries(merged)) {
2517
- if (value === "") delete merged[key];
2518
- }
2519
- }
2520
- }
2521
- if (Object.keys(body).length === 0) {
2522
- throw new Error(
2523
- 'Nothing to save. Pass at least one field flag, e.g. `gs configure set --displayName "Acme"`.'
2524
- );
2525
- }
2526
- const url = `${adminApiBase(slug)}/configure/save`;
2527
- const data = await request(url, {
2528
- method: "POST",
2529
- body,
2530
- // Every 400 from this endpoint names the offending field and the values
2531
- // it accepts — worth far more to the caller than "Request rejected."
2532
- validationDetail: true
2533
- });
2534
- if (flagBool(args.flags, "json")) {
2535
- process.stdout.write(JSON.stringify(data.config, null, 2) + "\n");
2536
- return;
2537
- }
2538
- process.stdout.write(`Saved ${Object.keys(body).join(", ")} \u2192 ${slug}
2539
- `);
2540
- }
2541
- function readTextFile(filePath, flag) {
2542
- const resolved = path12.resolve(filePath);
2543
- if (!fs10.existsSync(resolved)) {
2544
- throw new Error(`${flag}: file not found: ${resolved}`);
2545
- }
2546
- return fs10.readFileSync(resolved, "utf8");
2547
- }
2548
- function parseThemeJson(raw, flag) {
2549
- let parsed;
2550
- try {
2551
- parsed = JSON.parse(raw);
2552
- } catch (err) {
2553
- throw new Error(`${flag}: not valid JSON: ${err.message}`);
2554
- }
2555
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2556
- throw new Error(`${flag}: theme must be a JSON object.`);
2557
- }
2558
- return parsed;
2559
- }
2560
- async function readStoredTheme(slug) {
2561
- const url = `${adminApiBase(slug)}/configure/config`;
2562
- const data = await request(url);
2563
- return data.brand.theme ?? {};
2564
- }
2565
- function collectThemeFieldFlags(flags) {
2566
- const patch = {};
2567
- for (const [flag, raw] of Object.entries(flags)) {
2568
- if (!flag.startsWith(THEME_FLAG_PREFIX)) continue;
2569
- const name = flag.slice(THEME_FLAG_PREFIX.length);
2570
- const field = THEME_FIELDS[name];
2571
- if (!field) {
2572
- const suggestions = suggestThemeFields(name);
2573
- throw new Error(
2574
- `Unknown theme field "${name}".
2575
- Valid fields: ${Object.keys(THEME_FIELDS).join(", ")}.` + (suggestions.length > 0 ? `
2576
- Did you mean: ${suggestions.join(", ")}?` : "")
2577
- );
2578
- }
2579
- if (typeof raw !== "string") {
2580
- if (field.kind === "boolean") {
2581
- patch[name] = true;
2582
- continue;
2583
- }
2584
- throw new Error(`--${flag} requires a value (use --${flag} "" to clear).`);
2585
- }
2586
- patch[name] = coerceThemeValue(flag, name, raw);
2587
- }
2588
- return Object.keys(patch).length > 0 ? patch : null;
2589
- }
2590
- function coerceThemeValue(flag, name, raw) {
2591
- const field = THEME_FIELDS[name];
2592
- if (!field || raw === "") return raw;
2593
- if (field.values && !field.values.includes(raw)) {
2594
- throw new Error(
2595
- `--${flag} must be one of: ${field.values.join(", ")} (got "${raw}").`
2596
- );
2597
- }
2598
- if (field.kind === "boolean") {
2599
- if (raw !== "true" && raw !== "false") {
2600
- throw new Error(`--${flag} must be true or false (got "${raw}").`);
2601
- }
2602
- return raw === "true";
2603
- }
2604
- if (field.kind === "integer") {
2605
- const n = Number.parseInt(raw, 10);
2606
- if (!Number.isInteger(n) || String(n) !== raw.trim()) {
2607
- throw new Error(`--${flag} must be an integer (got "${raw}").`);
2608
- }
2609
- return n;
2610
- }
2611
- return raw;
2612
- }
2613
-
2614
- // src/commands/configure/upload.ts
2615
- import * as fs11 from "fs";
2616
- import * as path13 from "path";
2617
-
2618
- // src/commands/configure/shared.ts
2619
- var ASSET_KINDS = ["icon", "logoLight", "logoDark"];
2620
- function parseAssetKind(raw) {
2621
- if (raw && ASSET_KINDS.includes(raw)) {
2622
- return raw;
2623
- }
2624
- throw new Error(`Asset kind must be one of: ${ASSET_KINDS.join(", ")}.`);
2625
- }
2626
-
2627
- // src/commands/configure/upload.ts
2628
- var MIME_BY_EXT = {
2629
- ".png": "image/png",
2630
- ".jpg": "image/jpeg",
2631
- ".jpeg": "image/jpeg",
2632
- ".webp": "image/webp"
2633
- };
2634
- async function uploadAsset(args) {
2635
- const slug = resolveAdminStore(args);
2636
- const kind = parseAssetKind(args.positional[0]);
2637
- const filePath = args.positional[1];
2638
- if (!filePath) {
2639
- throw new Error(`Usage: gs configure upload <${ASSET_KINDS.join("|")}> <file>`);
2640
- }
2641
- const resolved = path13.resolve(filePath);
2642
- if (!fs11.existsSync(resolved)) {
2643
- throw new Error(`File not found: ${resolved}`);
2644
- }
2645
- const mime = MIME_BY_EXT[path13.extname(resolved).toLowerCase()];
2646
- if (!mime) {
2647
- throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");
2648
- }
2649
- const bytes = fs11.readFileSync(resolved);
2650
- const form = new FormData();
2651
- form.append(
2652
- "file",
2653
- new Blob([new Uint8Array(bytes)], { type: mime }),
2654
- path13.basename(resolved)
2655
- );
2656
- const url = `${adminApiBase(slug)}/configure/upload/${kind}`;
2657
- const data = await request(url, {
2658
- method: "POST",
2659
- multipart: form
2660
- });
2661
- process.stdout.write(`Uploaded ${kind} \u2192 ${data.url}
2662
- `);
2663
- }
2664
-
2665
- // src/commands/configure/clear.ts
2666
- async function clearAsset(args) {
2667
- const slug = resolveAdminStore(args);
2668
- const kind = parseAssetKind(args.positional[0]);
2669
- const url = `${adminApiBase(slug)}/configure/delete/${kind}`;
2670
- await request(url, { method: "POST", body: {} });
2671
- process.stdout.write(`Cleared ${kind} for ${slug}
2672
- `);
2673
- }
2674
-
2675
- // src/commands/configure/index.ts
2676
- async function configureCommand(args) {
2677
- const sub = args.positional[0] ?? "show";
2678
- const rest = { ...args, positional: args.positional.slice(1) };
2679
- switch (sub) {
2680
- case "show":
2681
- await showConfig(rest);
2682
- return;
2683
- case "set":
2684
- await setConfig(rest);
2685
- return;
2686
- case "upload":
2687
- await uploadAsset(rest);
2688
- return;
2689
- case "clear":
2690
- await clearAsset(rest);
2691
- return;
2692
- default:
2693
- throw new Error(
2694
- `Unknown configure subcommand: ${sub}. Use \`gs configure [set|upload|clear]\`.`
2695
- );
2696
- }
2697
- }
2698
-
2699
- // src/commands/connectors/shared.ts
2700
- async function fetchConfig(slug) {
2701
- const url = `${adminApiBase(slug)}/connectors/config`;
2702
- return request(url);
2703
- }
2704
- function echoConnector(row) {
2705
- return {
2706
- id: row.id,
2707
- name: row.name,
2708
- url: row.url,
2709
- transport: row.transport,
2710
- authKind: row.authKind,
2711
- enabled: row.enabled,
2712
- profileUrl: row.profileUrl
2713
- };
2714
- }
2715
- async function saveConfig(slug, config, connectors, makerEnabled = config.makerEnabled) {
2716
- const url = `${adminApiBase(slug)}/connectors/save`;
2717
- return request(url, {
2718
- method: "POST",
2719
- body: {
2720
- makerEnabled,
2721
- // Maker's slot is only valid in [0, N]; removing a connector can
2722
- // shrink the list below the stored priority.
2723
- makerPriority: Math.min(config.makerPriority, connectors.length),
2724
- connectors
2725
- }
2726
- });
2727
- }
2728
- function findConnector(config, ref) {
2729
- const byId = config.connectors.find((r) => r.id === ref);
2730
- if (byId) return byId;
2731
- const byName = config.connectors.filter((r) => r.name === ref);
2732
- if (byName.length === 1) return byName[0];
2733
- if (byName.length > 1) {
2734
- const ids = byName.map((r) => r.id).join(", ");
2735
- throw new Error(
2736
- `Multiple connectors are named "${ref}". Use an id instead: ${ids}`
2737
- );
2738
- }
2739
- throw new Error(`No connector named "${ref}". Run \`gs connectors\` to see them.`);
2740
- }
2741
-
2742
- // src/commands/connectors/list.ts
2743
- async function listConnectors(args) {
2744
- const slug = resolveAdminStore(args);
2745
- const config = await fetchConfig(slug);
2746
- if (flagBool(args.flags, "json")) {
2747
- process.stdout.write(JSON.stringify(config, null, 2) + "\n");
2748
- return;
2749
- }
2750
- process.stdout.write(
2751
- `Maker MCP: ${config.makerEnabled ? "on" : "off"} (position ${config.makerPriority + 1})
2752
- `
2753
- );
2754
- if (config.connectors.length === 0) {
2755
- process.stdout.write(`(no custom connectors in ${slug})
2756
- `);
2757
- return;
2758
- }
2759
- const rows = config.connectors.map((r) => ({
2760
- name: r.name,
2761
- enabled: r.enabled ? "on" : "off",
2762
- auth: r.authKind === "bearer" ? r.hasToken ? "bearer" : "bearer (no token)" : "none",
2763
- url: r.url
2764
- }));
2765
- const widths = {
2766
- name: Math.max(4, ...rows.map((r) => r.name.length)),
2767
- enabled: Math.max(7, ...rows.map((r) => r.enabled.length)),
2768
- auth: Math.max(4, ...rows.map((r) => r.auth.length))
2769
- };
2770
- process.stdout.write(
2771
- `${pad2("NAME", widths.name)} ${pad2("ENABLED", widths.enabled)} ${pad2("AUTH", widths.auth)} URL
2772
- `
2773
- );
2774
- for (const r of rows) {
2775
- process.stdout.write(
2776
- `${pad2(r.name, widths.name)} ${pad2(r.enabled, widths.enabled)} ${pad2(r.auth, widths.auth)} ${r.url}
2777
- `
2778
- );
2779
- }
2780
- }
2781
- function pad2(s, width) {
2782
- return s.length >= width ? s : s + " ".repeat(width - s.length);
2783
- }
2784
-
2785
- // src/commands/connectors/add.ts
2786
- async function addConnector(args) {
2787
- const slug = resolveAdminStore(args);
2788
- const name = args.positional[0];
2789
- if (!name) {
2790
- throw new Error("Usage: gs connectors add <name> --url <url> [--token <token>]");
2791
- }
2792
- const url = flagString(args.flags, "url");
2793
- if (!url) {
2794
- throw new Error("--url is required for `gs connectors add`.");
2795
- }
2796
- const token = flagString(args.flags, "token");
2797
- const profileUrl = flagString(args.flags, "profileUrl") ?? null;
2798
- const enabled = !flagBool(args.flags, "disabled");
2799
- if (!flagBool(args.flags, "force")) {
2800
- const probeUrl = `${adminApiBase(slug)}/connectors/probe`;
2801
- const probe = await request(
2802
- probeUrl,
2803
- {
2804
- method: "POST",
2805
- body: {
2806
- url,
2807
- ...token !== void 0 ? { token } : {},
2808
- ...profileUrl !== null ? { profileUrl } : {}
2809
- }
2810
- }
2811
- );
2812
- if (!probe.ok) {
2813
- throw new Error(
2814
- `Connector did not answer tool discovery${probe.error ? `: ${probe.error}` : ""}. Fix the URL/token or pass --force to save it anyway.`
2815
- );
2816
- }
2817
- process.stdout.write(`Probe ok \u2014 ${probe.toolCount ?? 0} tool(s) discovered.
2818
- `);
2819
- }
2820
- const config = await fetchConfig(slug);
2821
- const next = {
2822
- // The server treats an id it doesn't recognize as "mint a fresh one".
2823
- id: "",
2824
- name,
2825
- url,
2826
- transport: "http",
2827
- authKind: token ? "bearer" : "none",
2828
- enabled,
2829
- profileUrl,
2830
- ...token !== void 0 ? { token } : {}
2831
- };
2832
- const saved = await saveConfig(slug, config, [
2833
- ...config.connectors.map(echoConnector),
2834
- next
2835
- ]);
2836
- const row = saved.connectors.find((r) => r.name === name);
2837
- process.stdout.write(
2838
- `Added connector "${name}"${row ? ` (${row.id})` : ""} \u2192 ${slug}
2839
- `
2840
- );
2841
- }
2842
-
2843
- // src/commands/connectors/remove.ts
2844
- async function removeConnector(args) {
2845
- const slug = resolveAdminStore(args);
2846
- const ref = args.positional[0];
2847
- if (!ref) throw new Error("Usage: gs connectors remove <name|id>");
2848
- const config = await fetchConfig(slug);
2849
- const target = findConnector(config, ref);
2850
- const kept = config.connectors.filter((r) => r.id !== target.id).map(echoConnector);
2851
- await saveConfig(slug, config, kept);
2852
- process.stdout.write(`Removed connector "${target.name}" from ${slug}
2853
- `);
2854
- }
2855
-
2856
- // src/commands/connectors/enable.ts
2857
- async function setConnectorEnabled(args, enabled) {
2858
- const slug = resolveAdminStore(args);
2859
- const ref = args.positional[0];
2860
- if (!ref) {
2861
- throw new Error(`Usage: gs connectors ${enabled ? "enable" : "disable"} <name|id>`);
2862
- }
2863
- const config = await fetchConfig(slug);
2864
- const target = findConnector(config, ref);
2865
- const next = config.connectors.map(
2866
- (r) => r.id === target.id ? { ...echoConnector(r), enabled } : echoConnector(r)
2867
- );
2868
- await saveConfig(slug, config, next);
2869
- process.stdout.write(
2870
- `Connector "${target.name}" is now ${enabled ? "enabled" : "disabled"}
2871
- `
2872
- );
2873
- }
2874
-
2875
- // src/commands/connectors/maker.ts
2876
- async function setMaker(args) {
2877
- const slug = resolveAdminStore(args);
2878
- const state = args.positional[0];
2879
- if (state !== "on" && state !== "off") {
2880
- throw new Error("Usage: gs connectors maker on|off");
2881
- }
2882
- const config = await fetchConfig(slug);
2883
- await saveConfig(slug, config, config.connectors.map(echoConnector), state === "on");
2884
- process.stdout.write(`Maker MCP is now ${state}
2885
- `);
2886
- }
2887
-
2888
- // src/commands/connectors/health.ts
2889
- async function healthCheck(args) {
2890
- const slug = resolveAdminStore(args);
2891
- const config = await fetchConfig(slug);
2892
- let onlyId = null;
2893
- const ref = args.positional[0];
2894
- if (ref) onlyId = findConnector(config, ref).id;
2895
- if (config.connectors.length === 0) {
2896
- process.stdout.write(`(no custom connectors in ${slug})
2897
- `);
2898
- return;
2899
- }
2900
- const url = `${adminApiBase(slug)}/connectors/health`;
2901
- const data = await request(url, { method: "POST", body: onlyId ? { id: onlyId } : {} });
2902
- if (flagBool(args.flags, "json")) {
2903
- process.stdout.write(JSON.stringify(data.health, null, 2) + "\n");
2904
- return;
2905
- }
2906
- const nameById = new Map(config.connectors.map((r) => [r.id, r.name]));
2907
- for (const result of data.health) {
2908
- const name = nameById.get(result.id) ?? result.id;
2909
- if (result.ok) {
2910
- process.stdout.write(` ok ${name} (${result.toolCount ?? 0} tools)
2911
- `);
2912
- } else {
2913
- process.stdout.write(` failed ${name}: ${result.error ?? "discovery failed"}
2914
- `);
2915
- process.exitCode = 1;
2916
- }
2917
- }
2918
- }
2919
-
2920
- // src/commands/connectors/index.ts
2921
- async function connectorsCommand(args) {
2922
- const sub = args.positional[0] ?? "list";
2923
- const rest = { ...args, positional: args.positional.slice(1) };
2924
- switch (sub) {
2925
- case "list":
2926
- await listConnectors(rest);
2927
- return;
2928
- case "add":
2929
- await addConnector(rest);
2930
- return;
2931
- case "remove":
2932
- await removeConnector(rest);
2933
- return;
2934
- case "enable":
2935
- await setConnectorEnabled(rest, true);
2936
- return;
2937
- case "disable":
2938
- await setConnectorEnabled(rest, false);
2939
- return;
2940
- case "maker":
2941
- await setMaker(rest);
2942
- return;
2943
- case "health":
2944
- await healthCheck(rest);
2945
- return;
2946
- default:
2947
- throw new Error(
2948
- `Unknown connectors subcommand: ${sub}. Use \`gs connectors [add|remove|enable|disable|maker|health]\`.`
2949
- );
2950
- }
2951
- }
2952
-
2953
- // src/changelog.ts
2954
- function recentChangelog(text, minItems = 15) {
2955
- if (!text.trim()) return "";
2956
- const lines = text.split("\n");
2957
- const out = [];
2958
- let bullets = 0;
2959
- let inSection = false;
2960
- for (const line of lines) {
2961
- if (line.startsWith("## ")) {
2962
- if (inSection && bullets >= minItems) break;
2963
- inSection = true;
2964
- }
2965
- out.push(line);
2966
- if (inSection && /^\s*[-*+]\s/.test(line)) bullets++;
2967
- }
2968
- return out.join("\n").trimEnd();
2969
- }
2970
-
2971
- // src/index.ts
2972
- var CHANGELOG = true ? "# Changelog\n\nAll notable changes to `@greatstore/cli` are recorded here. The format\nfollows [Keep a Changelog](https://keepachangelog.com/).\n\n## 0.1.8 \u2014 2026-09-12\n\n### Changed\n- When your session has expired, commands now say so and stop, instead of\n opening a browser to sign you back in. Run `gs login` when you're ready.\n\n## 0.1.7 \u2014 2026-09-12\n\n### Changed\n- Commands no longer check for a new release before running, so they start\n without waiting on the network. Running a supported version is still\n required: the server says so when it isn't, and this release is the minimum\n it accepts \u2014 earlier ones stop working. Run\n `npm install -g @greatstore/cli@latest` to upgrade.\n\n## 0.1.6 \u2014 2026-09-12\n\n### Fixed\n- `gs apps push <name>` skips a component nothing changed in, like a push with\n no arguments does. Naming a component used to upload it regardless, burning\n a version number on identical code. Pass `--force` to upload anyway.\n\n## 0.1.5 \u2014 2026-09-12\n\n### Fixed\n- `gs apps push` says when a component's source changed but its bundle did\n not \u2014 \"did you forget to build?\" \u2014 instead of reporting a successful push\n of code that was never built.\n- A rebuilt bundle is now pushed even when the source is untouched. Such a\n change was reported as \"unchanged\" and never uploaded.\n\n## 0.1.4 \u2014 2026-09-12\n\n### Added\n- Edit one theme field at a time: `gs configure set --theme.fontFamily Manrope\n --theme.radius sharp`. Theme writes merge into the stored theme, so a\n one-field change no longer means retyping the whole object (and no longer\n drops the keys you left out). `--replace` writes a theme outright.\n- `gs configure set --help` prints every field it accepts with its type and\n legal values, and a mistyped field name or value is now rejected with the\n valid list before anything is sent.\n\n### Changed\n- Rejected configuration writes say what was wrong with them \u2014 the field and\n the values it accepts \u2014 instead of \"Request rejected.\"\n- Commands no longer wait on a version check every run, which takes about half\n a second off each one.\n\n## 0.1.3 \u2014 2026-09-12\n\n### Changed\n- `gs skill` prints the steps for installing the GreatStore agent skill\n instead of installing it itself, so any AI coding agent can set it up in\n whichever skills directory it uses \u2014 no `--global` or `--dir` to pick.\n- The installed skill is a link to the copy that ships with the CLI, so\n upgrading `@greatstore/cli` keeps it current with nothing to re-run.\n\n## 0.1.2 \u2014 2026-09-04\n\n### Fixed\n- `gs apps pull` now downloads components that aren't published yet. Pulling\n one used to report that it wasn't found on the server.\n\n## 0.1.1 \u2014 2026-08-20\n\n### Changed\n- Signing in now asks you to authorize the store you picked before the CLI\n gets access to it, and that access can be ended anytime from **Team \u2192 CLI\n access** in the dashboard. Ending it there signs this computer out on its\n next command.\n- For each store, you're signed in on one computer at a time. Signing in to\n that store again from another machine replaces the previous one, which then\n has to sign in again; your other stores are unaffected.\n- This release is required: earlier versions no longer work. Run\n `npm install -g @greatstore/cli` to upgrade.\n\n## 0.1.0 \u2014 2026-08-19\n\n### Changed\n- When a component's `inputSchema` declares fields the component doesn't\n accept, validation now reports them on a single line \u2014 naming the fields\n (capped, with a `(+N more)` count past that) \u2014 instead of one error per\n field. A schema/component mismatch stays readable instead of burying the\n other diagnostics.\n\n## 0.0.48 \u2014 2026-08-19\n\n### Changed\n- Component validation now warns when a component reaches for the page-level\n `window.GreatStore` API. Components should interact with GreatStore through\n the lifecycle props passed into them (`onSendMessage`, `onCallTool`,\n `onGenerateStructuredContent`, \u2026), which are wired to the surface the\n component is mounted in; the warning points you there. It's a nudge, not a\n build failure.\n\n## 0.0.47 \u2014 2026-08-18\n\n### Changed\n- `onGenerateStructuredContent` now takes a required third argument,\n `fallback` \u2014 a schema-shaped object you supply. The component preview\n renders it (there's no live store to generate against there), so a\n generation-driven component previews as it would live. It's validated\n against the schema and throws if the two don't line up.\n\n## 0.0.46 \u2014 2026-08-18\n\n### Added\n- Components now receive an `onGenerateStructuredContent(schema, prompt)`\n prop: ask the store's assistant for content matching a JSON Schema (or a\n Zod schema) and render what it returns, personalized to the shopper. It\n works the same in the conversation on the storefront and every embed.\n Added to the component template, the scaffolded `AGENTS.md` reference, and\n prop validation.\n\n## 0.0.45 \u2014 2026-08-18\n\n### Changed\n- The auto-generated `AGENTS.md` banner now records the CLI version that\n wrote it, so you can tell at a glance when it trails your installed CLI\n and a `gs apps init` refresh is due.\n\n## 0.0.44 \u2014 2026-08-18\n\n### Added\n- New check: a component that still declares `onError` gets a warning\n pointing at the async-component pattern that replaced it, with the\n throw-vs-fallback caveat (a throw asks the assistant to retry, so\n permanent failures should render a fallback rather than throw). Earlier\n this surfaced as the generic \"prop isn't declared in the schema\"\n warning, whose suggested fix was wrong for a former lifecycle callback.\n\n### Changed\n- `gs apps init` now always refreshes `AGENTS.md` (the agent guidance\n file) so it tracks the installed CLI version instead of going stale.\n The file carries a \"do not edit \u2014 auto-generated\" banner; your own\n project files are still left untouched.\n\n## 0.0.43 \u2014 2026-08-18\n\n### Added\n- `gs apps build` and `gs apps push` now check each component before\n building or uploading it. Findings are reported as **errors** (a\n blocker \u2014 the component isn't built or uploaded) or **warnings** (it\n builds and is ready to publish, but something is worth improving),\n and a single run reports everything it found rather than stopping at\n the first problem.\n- New check: a component's props and its `inputSchema.properties` must\n agree. A schema field the component doesn't accept is an error; a prop\n the schema doesn't declare is a warning, since nothing will ever pass\n it. The props GreatStore injects (`onSendMessage`, `onCallTool`,\n `onUpdateModelContext`, `onShowLightbox`, `onClose`, `storeData`,\n `Image`) are exempt.\n\n## 0.0.42 \u2014 2026-08-15\n\n### Changed\n- `gs apps list` now works outside a project. With no `.gsrc` it lists the\n components of the store you're signed in to, instead of erroring. The\n commands that write files or change the store \u2014 `push`, `pull`, `publish`,\n `unpublish`, `delete` \u2014 still require a project.\n\n## 0.0.41 \u2014 2026-08-14\n\n### Changed\n- Internal authentication rework. Re-run `gs login` after updating.\n\n## 0.0.40 \u2014 2026-07-24\n\n### Removed\n- `gs configure set` no longer accepts `--salesGuide` or\n `--salesGuideFile`, and `gs configure show` no longer lists the field.\n\n## 0.0.39 \u2014 2026-07-21\n\n### Added\n- Components now receive an `Image` prop \u2014 a drop-in for `<img>` that\n serves images at the size they're displayed. Render `<Image src=\u2026 />`\n instead of `<img>`; pass `Image={\"img\"}` to preview a component\n outside a store. Scaffolded into `gs apps init` and documented in\n `AGENTS.md`.\n\n## 0.0.38 \u2014 2026-07-13\n\n### Added\n- `gs login --store <slug>` skips the store picker and signs in\n directly to that store \u2014 fails immediately if your account doesn't\n have access to it, instead of falling back to the picker.\n\n## 0.0.37 \u2014 2026-07-10\n\n### Added\n- Signing in now ends by choosing which store to work on \u2014 skipped\n automatically when your account has exactly one. Commands default to\n that store, so `--store` is rarely needed anymore.\n- `gs switch [<slug>]` changes the working store without signing in\n again.\n- `gs apps init` no longer requires `--store` when your sign-in already\n selected a store.\n\n### Changed\n- A `--store` flag or project `.gsrc` that names a different store than\n the one you signed in to is now an error, so work can't accidentally\n target the wrong store. Run `gs switch` to change stores.\n\n## 0.0.33 \u2014 2026-07-10\n\n### Changed\n- `gs apps push` now rejects a component whose `inputSchema` is too\n complex for the assistant to call reliably: union keywords\n (`anyOf`/`oneOf`/`allOf`/`$ref`/`not`), more than 8 KB serialized, or\n more than 50 declared fields. Keep schemas to a small set of flat,\n single-type fields \u2014 one canonical name per concept \u2014 and handle\n aliases or edge cases in component code instead.\n\n## 0.0.32 \u2014 2026-06-18\n\n### Added\n- Chat components can expand an image into a full-screen, on-brand\n lightbox via a new `onShowLightbox({ src, originRect })` prop. Wire it\n to an image's `onClick` \u2014 pass the image URL and, for a smooth zoom,\n the clicked element's `getBoundingClientRect()`. Use it for product\n photos, swatches, or size charts the shopper may want to inspect up\n close, instead of building your own overlay.\n\n## 0.0.31 \u2014 2026-06-18\n\n### Added\n- Components can read a secondary brand font from `--font-secondary`,\n for a second layer of typography. Falls back to the primary font.\n\n### Changed\n- The brand font variable is now `--font-primary` (was `--font-sans`).\n\n## 0.0.30 \u2014 2026-06-17\n\n### Added\n- The agent skill documents a new way to give the assistant background\n context without sending a visible message:\n `window.GreatStore.updateModelContext(text)` on the page, and the\n matching `onUpdateModelContext(text)` prop inside a chat component. Use\n it to keep the assistant aware of what the shopper is doing \u2014 the\n product they're viewing, what's in their cart, the variant they just\n selected \u2014 so its replies stay on point. Each call replaces the previous\n value, and nothing renders in the chat.\n\n## 0.0.29 \u2014 2026-06-12\n\n### Fixed\n- The \"update available\" notice actually fires now. It previously raced\n a 1-second timeout against the npm registry and usually lost, so most\n installs never saw it. The notice is now served instantly from a local\n cache, refreshed in the background after each day's first invocation \u2014\n it can lag one run behind a release, but it no longer adds latency or\n goes silent on slow networks.\n\n## 0.0.28 \u2014 2026-06-12\n\n### Added\n- `gs configure` \u2014 view and edit the store configuration from the CLI:\n display name, assistant name, sales guide, store link, extra origins,\n theme, CSP host lists, and icon/logo uploads. Same fields and\n behaviour as the dashboard's Configure panel.\n- `gs connectors` \u2014 manage the store's MCP connectors: list, add (with\n a discovery probe before saving), remove, enable/disable, toggle the\n Maker MCP, and health-check. Same behaviour as the dashboard's\n Connectors panel.\n- `--store <slug>` on the new admin commands, so they work outside a\n scaffolded component project (a `.gsrc` is still used when present).\n- The agent skill gains a store-administration reference: coding agents\n can read the store's configuration and connectors to ground their\n work, self-serve additive changes like origin allowlists and CSP\n hosts (read-merge-write), and are told which changes need the\n merchant's go-ahead first.\n\n### Changed\n- Component commands now live under `gs apps` (`gs apps push`,\n `gs apps build`, \u2026), matching the dashboard's Apps panel. The old\n top-level forms keep working as aliases, so existing scripts and\n scaffolded projects are unaffected.\n- The skill's structured-content guide now teaches \"point, don't\n paste\": name the SKU/product/collection and let GreatStore research\n the catalog itself instead of inlining fetched specs; validate with\n `gs connectors` that a connector exists for the data a prompt or\n schema depends on (research can't exceed the wired-up connectors);\n and never put shopper data in prompts \u2014 GreatStore already knows the\n shopper, and identified shoppers get per-shopper cached responses.\n\n## 0.0.27 \u2014 2026-06-11\n\n### Changed\n- Skill code samples now carry an explicit reference-only disclaimer:\n coding agents are told to re-express the logic in the host repo's\n framework (React, Vue, Shopify Liquid, Svelte, \u2026) instead of\n retrofitting the framework-free samples as-is.\n\n## 0.0.26 \u2014 2026-06-11\n\n### Added\n- The agent skill gains a \"GreatStore launchers\" recipe: a horizontally\n scrollable row of AI-generated chips, each an engaging first-person\n question about the current page that's sent to the assistant on tap.\n\n### Changed\n- Skill recipes are now one file each under `recipes/`, indexed from\n SKILL.md by a table with description and use-case columns.\n\n## 0.0.25 \u2014 2026-06-11\n\n### Added\n- `gs skill` installs the GreatStore agent skill \u2014 a guide AI coding\n agents use to build with GreatStore: AI content for your own UI, chat\n entry points, page tools, custom in-chat components, push\n notifications, and the store's MCP endpoints. Installs into\n `./.claude/skills/`; use `--global` for `~/.claude/skills/`, or\n `--dir <path>` for agents that read skills from somewhere else. Run\n it again any time to update an installed copy.\n\n## 0.0.24 \u2014 2026-06-03\n\n### Changed\n- `gs init` in an existing project now fills in any scaffold files that\n are missing (for example, the `AGENTS.md` design guide added in\n 0.0.23) and leaves your own files alone. Pass `--force` to refresh\n every scaffold file to the latest version. Your pinned store\n (`.gsrc`) is never rewritten either way.\n\n## 0.0.23 \u2014 2026-06-03\n\n### Added\n- `gs init` now scaffolds an `AGENTS.md` (with `CLAUDE.md` and\n `GEMINI.md` symlinked to it) documenting the design rules every\n component should follow \u2014 use `em` rather than `rem` for sizing, and\n style from the provided brand CSS variables so components match the\n store's theme. It doubles as guidance for AI coding agents.\n\n## 0.0.22 \u2014 2026-06-02\n\n### Added\n- `gs list` now shows a link to each component's page in the dashboard,\n so you can jump straight to a component to preview or publish it. The\n link is also included in `gs list --json`.\n\n## 0.0.21 \u2014 2026-05-31\n\n### Changed\n- The `gs init` component scaffold now shows how to write **async**\n components that load data before they render \u2014 including validating\n inputs up front and signalling a failure by throwing. The scaffolded\n component no longer includes an `onError` prop; throw from an async\n component to report a failure instead.\n\n## 0.0.20 \u2014 2026-05-29\n\n### Added\n- `gs pull`, `gs push`, and `gs publish` now accept several component\n names at once (e.g. `gs publish header footer cart`). Each component\n is reported on its own line and one failure no longer stops the rest.\n\n## 0.0.19 \u2014 2026-05-28\n\n### Fixed\n- `gs login` on Windows no longer opens a sign-in URL with parameters\n stripped, which surfaced as a \"Missing redirect_uri or state\n parameter\" page in the browser.\n\n## 0.0.18 \u2014 2026-05-28\n\n### Changed\n- Push and publish errors now name the specific reason \u2014 including\n every failing field in `manifest.json` \u2014 instead of the previous\n generic message.\n\n## 0.0.17 \u2014 2026-05-28\n\n### Added\n- Each command now prints a one-line upgrade notice when a newer\n `@greatstore/cli` is available on npm.\n\n## 0.0.16 \u2014 2026-05-28\n\n### Changed\n- Simplified error messages.\n\n## 0.0.15 \u2014 2026-05-24\n\n### Added\n- Scaffolded `component.tsx` now declares the four injected lifecycle\n props (`onSendMessage`, `onCallTool`, `onClose`, `onError`) on\n `Props`. Use `onError(message)` to report expected failures (failed\n fetch, host action rejected, invalid host state) so the AI can\n recover on its next turn. Render-time crashes are reported for you.\n\n## 0.0.14 \u2014 2026-05-24\n\n### Changed\n- `gs build` output is now whitespace-minified \u2014 typically ~50% smaller.\n\n## 0.0.13 \u2014 2026-05-24\n\n### Changed\n- `gs build` prints the next-step hint (`gs push`, then `gs publish`).\n\n## 0.0.12 \u2014 2026-05-24\n\n### Fixed\n- `gs build` failing to load Vite in some setups.\n\n## 0.0.11 \u2014 2026-05-24\n\n### Added\n- Multi-component projects. `gs init` (no args) scaffolds the project\n root; `gs init <name>` adds a component under `components/<name>/`.\n- `gs build [<name>]` \u2014 compiles every `components/<name>/bundle.js`.\n- `gs push` (no args) uploads only the components that changed.\n- `gs pull` (no args, or `*`) downloads every component. Locally\n edited components are skipped; pass `--force` to overwrite.\n- Public `CHANGELOG.md`; `gs --version` prints recent entries.\n\n### Changed\n- A project folder ships to exactly one store. Only `gs init` accepts\n `--store`; every other command reads the slug from `.gsrc`. The old\n single-component layout is rejected with a migration hint.\n- `gs init` requires `--store <slug>` for a fresh root, and rejects\n `--store` on an existing root.\n- `gs init` no longer writes `build.mjs` \u2014 scripts call `gs build`.\n\n## 0.0.10 \u2014 2026-05-23\n\n### Changed\n- The sign-in browser tab auto-closes once `gs login` finishes.\n\n## 0.0.9 \u2014 2026-05-23\n\n### Changed\n- Scaffolded manifests include a `displayName` so the admin UI has a\n friendlier label.\n\n## 0.0.8 \u2014 2026-05-23\n\n### Changed\n- `gs push` and `gs publish` print a link to view the component.\n\n## 0.0.6 \u2014 2026-05-23\n\n### Changed\n- `gs --version` reads from the published package version.\n\n## 0.0.4 \u2014 2026-05-23\n\n### Changed\n- Scaffolded projects produce browser-ready bundles out of the box.\n\n## 0.0.3 \u2014 2026-05-23\n\n### Changed\n- Trimmed public README to the essentials.\n\n## 0.0.2 \u2014 2026-05-23\n\n### Fixed\n- Sign-in callback parameter handling.\n" : "";
2973
- var HELP = `gs \u2014 GreatStore CLI (v${CLI_VERSION})
133
+ `;async function Fe(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(on),0;case"init":return gt(n),0;case"build":return await Nt(n),0;case"list":return await Dt(n),0;case"pull":return await Ut(n),0;case"push":return await Yt(n),0;case"publish":return await en(n),0;case"unpublish":return await tn(n),0;case"delete":return await rn(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
134
+
135
+ ${on}`),1}}async function sn(e){let t=y(e),n=`${b(t)}/configure/config`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
136
+ `);return}Or(t,r.brand)}function Or(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 ${Ne(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 ${Ne(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${Ne(t.cspConnectHosts)}`),process.stdout.write(n.join(`
137
+ `)+`
138
+ `)}function Ne(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as Pe from"fs";import*as ln from"path";var an="theme.",Ir=["displayName","assistantName","storeLink"],Fr=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function un(e){let t=y(e),n={};for(let c of Ir){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 Fr){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(f=>f.trim()).filter(f=>f.length>0);n[c]=u.length===0?null:u}let r=h(e.flags,"themeFile"),o=Br(e.flags),s=m(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:cn(c,"--theme")}else r!==void 0?i=cn(Nr(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await Dr(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. `gs configure set --displayName "Acme"`.');let a=`${b(t)}/configure/save`,l=await d(a,{method:"POST",body:n,validationDetail:!0});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
139
+ `);return}process.stdout.write(`Saved ${Object.keys(n).join(", ")} \u2192 ${t}
140
+ `)}function Nr(e,t){let n=ln.resolve(e);if(!Pe.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return Pe.readFileSync(n,"utf8")}function cn(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 Dr(e){let t=`${b(e)}/configure/config`;return(await d(t)).brand.theme??{}}function Br(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(an))continue;let o=n.slice(an.length),s=H[o];if(!s){let i=ct(o);throw new Error(`Unknown theme field "${o}".
141
+ Valid fields: ${Object.keys(H).join(", ")}.`+(i.length>0?`
142
+ 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]=Hr(n,o,r)}return Object.keys(t).length>0?t:null}function Hr(e,t,n){let r=H[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 Ee from"fs";import*as te from"path";var Ce=["icon","logoLight","logoDark"];function $e(e){if(e&&Ce.includes(e))return e;throw new Error(`Asset kind must be one of: ${Ce.join(", ")}.`)}var Mr={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function pn(e){let t=y(e),n=$e(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: gs configure upload <${Ce.join("|")}> <file>`);let o=te.resolve(r);if(!Ee.existsSync(o))throw new Error(`File not found: ${o}`);let s=Mr[te.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=Ee.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),te.basename(o));let l=`${b(t)}/configure/upload/${n}`,c=await d(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
143
+ `)}async function fn(e){let t=y(e),n=$e(e.positional[0]),r=`${b(t)}/configure/delete/${n}`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
144
+ `)}async function dn(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await sn(n);return;case"set":await un(n);return;case"upload":await pn(n);return;case"clear":await fn(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`gs configure [set|upload|clear]\`.`)}}async function A(e){let t=`${b(e)}/connectors/config`;return d(t)}function I(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 q(e,t,n,r=t.makerEnabled){let o=`${b(e)}/connectors/save`;return d(o,{method:"POST",body:{makerEnabled:r,makerPriority:Math.min(t.makerPriority,n.length),connectors:n}})}function ne(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 \`gs connectors\` to see them.`)}async function mn(e){let t=y(e),n=await A(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
145
+ `);return}if(process.stdout.write(`Maker MCP: ${n.makerEnabled?"on":"off"} (position ${n.makerPriority+1})
146
+ `),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
147
+ `);return}let r=n.connectors.map(s=>({name:s.name,enabled:s.enabled?"on":"off",auth:s.authKind==="bearer"?s.hasToken?"bearer":"bearer (no token)":"none",url:s.url})),o={name:Math.max(4,...r.map(s=>s.name.length)),enabled:Math.max(7,...r.map(s=>s.enabled.length)),auth:Math.max(4,...r.map(s=>s.auth.length))};process.stdout.write(`${re("NAME",o.name)} ${re("ENABLED",o.enabled)} ${re("AUTH",o.auth)} URL
148
+ `);for(let s of r)process.stdout.write(`${re(s.name,o.name)} ${re(s.enabled,o.enabled)} ${re(s.auth,o.auth)} ${s.url}
149
+ `)}function re(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function gn(e){let t=y(e),n=e.positional[0];if(!n)throw new Error("Usage: gs connectors add <name> --url <url> [--token <token>]");let r=h(e.flags,"url");if(!r)throw new Error("--url is required for `gs connectors add`.");let o=h(e.flags,"token"),s=h(e.flags,"profileUrl")??null,i=!m(e.flags,"disabled");if(!m(e.flags,"force")){let u=`${b(t)}/connectors/probe`,f=await d(u,{method:"POST",body:{url:r,...o!==void 0?{token:o}:{},...s!==null?{profileUrl:s}:{}}});if(!f.ok)throw new Error(`Connector did not answer tool discovery${f.error?`: ${f.error}`:""}. Fix the URL/token or pass --force to save it anyway.`);process.stdout.write(`Probe ok \u2014 ${f.toolCount??0} tool(s) discovered.
150
+ `)}let a=await A(t),l={id:"",name:n,url:r,transport:"http",authKind:o?"bearer":"none",enabled:i,profileUrl:s,...o!==void 0?{token:o}:{}},p=(await q(t,a,[...a.connectors.map(I),l])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
151
+ `)}async function hn(e){let t=y(e),n=e.positional[0];if(!n)throw new Error("Usage: gs connectors remove <name|id>");let r=await A(t),o=ne(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(I);await q(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
152
+ `)}async function De(e,t){let n=y(e),r=e.positional[0];if(!r)throw new Error(`Usage: gs connectors ${t?"enable":"disable"} <name|id>`);let o=await A(n),s=ne(o,r),i=o.connectors.map(a=>a.id===s.id?{...I(a),enabled:t}:I(a));await q(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
153
+ `)}async function yn(e){let t=y(e),n=e.positional[0];if(n!=="on"&&n!=="off")throw new Error("Usage: gs connectors maker on|off");let r=await A(t);await q(t,r,r.connectors.map(I),n==="on"),process.stdout.write(`Maker MCP is now ${n}
154
+ `)}async function wn(e){let t=y(e),n=await A(t),r=null,o=e.positional[0];if(o&&(r=ne(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
155
+ `);return}let s=`${b(t)}/connectors/health`,i=await d(s,{method:"POST",body:r?{id:r}:{}});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
156
+ `);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)
157
+ `):(process.stdout.write(` failed ${c}: ${l.error??"discovery failed"}
158
+ `),process.exitCode=1)}}async function bn(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await mn(n);return;case"add":await gn(n);return;case"remove":await hn(n);return;case"enable":await De(n,!0);return;case"disable":await De(n,!1);return;case"maker":await yn(n);return;case"health":await wn(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`gs connectors [add|remove|enable|disable|maker|health]\`.`)}}function Sn(e,t=15){if(!e.trim())return"";let n=e.split(`
159
+ `),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(`
160
+ `).trimEnd()}var Ur=`# Changelog
161
+
162
+ All notable changes to \`@greatstore/cli\` are recorded here. The format
163
+ follows [Keep a Changelog](https://keepachangelog.com/).
164
+
165
+ ## 0.1.10 \u2014 2026-09-13
166
+
167
+ ### Changed
168
+ - This release is the minimum version the server accepts \u2014 earlier ones stop
169
+ working. Run \`npm install -g @greatstore/cli@latest\` to upgrade.
170
+ - The published package is around a third smaller to download.
171
+
172
+ ## 0.1.9 \u2014 2026-09-12
173
+
174
+ ### Added
175
+ - \`gs apps push\` stops and asks you to \`gs apps pull\` first when the store has
176
+ a newer version of a component than the copy you are pushing, instead of
177
+ replacing work you have never seen. Pass \`--force\` to push over it anyway.
178
+
179
+ ### Fixed
180
+ - \`gs apps pull\` downloads a pre-installed app you have unpublished, instead of
181
+ reporting it as not found.
182
+
183
+ ## 0.1.8 \u2014 2026-09-12
184
+
185
+ ### Changed
186
+ - When your session has expired, commands now say so and stop, instead of
187
+ opening a browser to sign you back in. Run \`gs login\` when you're ready.
188
+
189
+ ## 0.1.7 \u2014 2026-09-12
190
+
191
+ ### Changed
192
+ - Commands no longer check for a new release before running, so they start
193
+ without waiting on the network. Running a supported version is still
194
+ required: the server says so when it isn't, and this release is the minimum
195
+ it accepts \u2014 earlier ones stop working. Run
196
+ \`npm install -g @greatstore/cli@latest\` to upgrade.
197
+
198
+ ## 0.1.6 \u2014 2026-09-12
199
+
200
+ ### Fixed
201
+ - \`gs apps push <name>\` skips a component nothing changed in, like a push with
202
+ no arguments does. Naming a component used to upload it regardless, burning
203
+ a version number on identical code. Pass \`--force\` to upload anyway.
204
+
205
+ ## 0.1.5 \u2014 2026-09-12
206
+
207
+ ### Fixed
208
+ - \`gs apps push\` says when a component's source changed but its bundle did
209
+ not \u2014 "did you forget to build?" \u2014 instead of reporting a successful push
210
+ of code that was never built.
211
+ - A rebuilt bundle is now pushed even when the source is untouched. Such a
212
+ change was reported as "unchanged" and never uploaded.
213
+
214
+ ## 0.1.4 \u2014 2026-09-12
215
+
216
+ ### Added
217
+ - Edit one theme field at a time: \`gs configure set --theme.fontFamily Manrope
218
+ --theme.radius sharp\`. Theme writes merge into the stored theme, so a
219
+ one-field change no longer means retyping the whole object (and no longer
220
+ drops the keys you left out). \`--replace\` writes a theme outright.
221
+ - \`gs configure set --help\` prints every field it accepts with its type and
222
+ legal values, and a mistyped field name or value is now rejected with the
223
+ valid list before anything is sent.
224
+
225
+ ### Changed
226
+ - Rejected configuration writes say what was wrong with them \u2014 the field and
227
+ the values it accepts \u2014 instead of "Request rejected."
228
+ - Commands no longer wait on a version check every run, which takes about half
229
+ a second off each one.
230
+
231
+ ## 0.1.3 \u2014 2026-09-12
232
+
233
+ ### Changed
234
+ - \`gs skill\` prints the steps for installing the GreatStore agent skill
235
+ instead of installing it itself, so any AI coding agent can set it up in
236
+ whichever skills directory it uses \u2014 no \`--global\` or \`--dir\` to pick.
237
+ - The installed skill is a link to the copy that ships with the CLI, so
238
+ upgrading \`@greatstore/cli\` keeps it current with nothing to re-run.
239
+
240
+ ## 0.1.2 \u2014 2026-09-04
241
+
242
+ ### Fixed
243
+ - \`gs apps pull\` now downloads components that aren't published yet. Pulling
244
+ one used to report that it wasn't found on the server.
245
+
246
+ ## 0.1.1 \u2014 2026-08-20
247
+
248
+ ### Changed
249
+ - Signing in now asks you to authorize the store you picked before the CLI
250
+ gets access to it, and that access can be ended anytime from **Team \u2192 CLI
251
+ access** in the dashboard. Ending it there signs this computer out on its
252
+ next command.
253
+ - For each store, you're signed in on one computer at a time. Signing in to
254
+ that store again from another machine replaces the previous one, which then
255
+ has to sign in again; your other stores are unaffected.
256
+ - This release is required: earlier versions no longer work. Run
257
+ \`npm install -g @greatstore/cli\` to upgrade.
258
+
259
+ ## 0.1.0 \u2014 2026-08-19
260
+
261
+ ### Changed
262
+ - When a component's \`inputSchema\` declares fields the component doesn't
263
+ accept, validation now reports them on a single line \u2014 naming the fields
264
+ (capped, with a \`(+N more)\` count past that) \u2014 instead of one error per
265
+ field. A schema/component mismatch stays readable instead of burying the
266
+ other diagnostics.
267
+
268
+ ## 0.0.48 \u2014 2026-08-19
269
+
270
+ ### Changed
271
+ - Component validation now warns when a component reaches for the page-level
272
+ \`window.GreatStore\` API. Components should interact with GreatStore through
273
+ the lifecycle props passed into them (\`onSendMessage\`, \`onCallTool\`,
274
+ \`onGenerateStructuredContent\`, \u2026), which are wired to the surface the
275
+ component is mounted in; the warning points you there. It's a nudge, not a
276
+ build failure.
277
+
278
+ ## 0.0.47 \u2014 2026-08-18
279
+
280
+ ### Changed
281
+ - \`onGenerateStructuredContent\` now takes a required third argument,
282
+ \`fallback\` \u2014 a schema-shaped object you supply. The component preview
283
+ renders it (there's no live store to generate against there), so a
284
+ generation-driven component previews as it would live. It's validated
285
+ against the schema and throws if the two don't line up.
286
+
287
+ ## 0.0.46 \u2014 2026-08-18
288
+
289
+ ### Added
290
+ - Components now receive an \`onGenerateStructuredContent(schema, prompt)\`
291
+ prop: ask the store's assistant for content matching a JSON Schema (or a
292
+ Zod schema) and render what it returns, personalized to the shopper. It
293
+ works the same in the conversation on the storefront and every embed.
294
+ Added to the component template, the scaffolded \`AGENTS.md\` reference, and
295
+ prop validation.
296
+
297
+ ## 0.0.45 \u2014 2026-08-18
298
+
299
+ ### Changed
300
+ - The auto-generated \`AGENTS.md\` banner now records the CLI version that
301
+ wrote it, so you can tell at a glance when it trails your installed CLI
302
+ and a \`gs apps init\` refresh is due.
303
+
304
+ ## 0.0.44 \u2014 2026-08-18
305
+
306
+ ### Added
307
+ - New check: a component that still declares \`onError\` gets a warning
308
+ pointing at the async-component pattern that replaced it, with the
309
+ throw-vs-fallback caveat (a throw asks the assistant to retry, so
310
+ permanent failures should render a fallback rather than throw). Earlier
311
+ this surfaced as the generic "prop isn't declared in the schema"
312
+ warning, whose suggested fix was wrong for a former lifecycle callback.
313
+
314
+ ### Changed
315
+ - \`gs apps init\` now always refreshes \`AGENTS.md\` (the agent guidance
316
+ file) so it tracks the installed CLI version instead of going stale.
317
+ The file carries a "do not edit \u2014 auto-generated" banner; your own
318
+ project files are still left untouched.
319
+
320
+ ## 0.0.43 \u2014 2026-08-18
321
+
322
+ ### Added
323
+ - \`gs apps build\` and \`gs apps push\` now check each component before
324
+ building or uploading it. Findings are reported as **errors** (a
325
+ blocker \u2014 the component isn't built or uploaded) or **warnings** (it
326
+ builds and is ready to publish, but something is worth improving),
327
+ and a single run reports everything it found rather than stopping at
328
+ the first problem.
329
+ - New check: a component's props and its \`inputSchema.properties\` must
330
+ agree. A schema field the component doesn't accept is an error; a prop
331
+ the schema doesn't declare is a warning, since nothing will ever pass
332
+ it. The props GreatStore injects (\`onSendMessage\`, \`onCallTool\`,
333
+ \`onUpdateModelContext\`, \`onShowLightbox\`, \`onClose\`, \`storeData\`,
334
+ \`Image\`) are exempt.
335
+
336
+ ## 0.0.42 \u2014 2026-08-15
337
+
338
+ ### Changed
339
+ - \`gs apps list\` now works outside a project. With no \`.gsrc\` it lists the
340
+ components of the store you're signed in to, instead of erroring. The
341
+ commands that write files or change the store \u2014 \`push\`, \`pull\`, \`publish\`,
342
+ \`unpublish\`, \`delete\` \u2014 still require a project.
343
+
344
+ ## 0.0.41 \u2014 2026-08-14
345
+
346
+ ### Changed
347
+ - Internal authentication rework. Re-run \`gs login\` after updating.
348
+
349
+ ## 0.0.40 \u2014 2026-07-24
350
+
351
+ ### Removed
352
+ - \`gs configure set\` no longer accepts \`--salesGuide\` or
353
+ \`--salesGuideFile\`, and \`gs configure show\` no longer lists the field.
354
+
355
+ ## 0.0.39 \u2014 2026-07-21
356
+
357
+ ### Added
358
+ - Components now receive an \`Image\` prop \u2014 a drop-in for \`<img>\` that
359
+ serves images at the size they're displayed. Render \`<Image src=\u2026 />\`
360
+ instead of \`<img>\`; pass \`Image={"img"}\` to preview a component
361
+ outside a store. Scaffolded into \`gs apps init\` and documented in
362
+ \`AGENTS.md\`.
363
+
364
+ ## 0.0.38 \u2014 2026-07-13
365
+
366
+ ### Added
367
+ - \`gs login --store <slug>\` skips the store picker and signs in
368
+ directly to that store \u2014 fails immediately if your account doesn't
369
+ have access to it, instead of falling back to the picker.
370
+
371
+ ## 0.0.37 \u2014 2026-07-10
372
+
373
+ ### Added
374
+ - Signing in now ends by choosing which store to work on \u2014 skipped
375
+ automatically when your account has exactly one. Commands default to
376
+ that store, so \`--store\` is rarely needed anymore.
377
+ - \`gs switch [<slug>]\` changes the working store without signing in
378
+ again.
379
+ - \`gs apps init\` no longer requires \`--store\` when your sign-in already
380
+ selected a store.
381
+
382
+ ### Changed
383
+ - A \`--store\` flag or project \`.gsrc\` that names a different store than
384
+ the one you signed in to is now an error, so work can't accidentally
385
+ target the wrong store. Run \`gs switch\` to change stores.
386
+
387
+ ## 0.0.33 \u2014 2026-07-10
388
+
389
+ ### Changed
390
+ - \`gs apps push\` now rejects a component whose \`inputSchema\` is too
391
+ complex for the assistant to call reliably: union keywords
392
+ (\`anyOf\`/\`oneOf\`/\`allOf\`/\`$ref\`/\`not\`), more than 8 KB serialized, or
393
+ more than 50 declared fields. Keep schemas to a small set of flat,
394
+ single-type fields \u2014 one canonical name per concept \u2014 and handle
395
+ aliases or edge cases in component code instead.
396
+
397
+ ## 0.0.32 \u2014 2026-06-18
398
+
399
+ ### Added
400
+ - Chat components can expand an image into a full-screen, on-brand
401
+ lightbox via a new \`onShowLightbox({ src, originRect })\` prop. Wire it
402
+ to an image's \`onClick\` \u2014 pass the image URL and, for a smooth zoom,
403
+ the clicked element's \`getBoundingClientRect()\`. Use it for product
404
+ photos, swatches, or size charts the shopper may want to inspect up
405
+ close, instead of building your own overlay.
406
+
407
+ ## 0.0.31 \u2014 2026-06-18
408
+
409
+ ### Added
410
+ - Components can read a secondary brand font from \`--font-secondary\`,
411
+ for a second layer of typography. Falls back to the primary font.
412
+
413
+ ### Changed
414
+ - The brand font variable is now \`--font-primary\` (was \`--font-sans\`).
415
+
416
+ ## 0.0.30 \u2014 2026-06-17
417
+
418
+ ### Added
419
+ - The agent skill documents a new way to give the assistant background
420
+ context without sending a visible message:
421
+ \`window.GreatStore.updateModelContext(text)\` on the page, and the
422
+ matching \`onUpdateModelContext(text)\` prop inside a chat component. Use
423
+ it to keep the assistant aware of what the shopper is doing \u2014 the
424
+ product they're viewing, what's in their cart, the variant they just
425
+ selected \u2014 so its replies stay on point. Each call replaces the previous
426
+ value, and nothing renders in the chat.
427
+
428
+ ## 0.0.29 \u2014 2026-06-12
429
+
430
+ ### Fixed
431
+ - The "update available" notice actually fires now. It previously raced
432
+ a 1-second timeout against the npm registry and usually lost, so most
433
+ installs never saw it. The notice is now served instantly from a local
434
+ cache, refreshed in the background after each day's first invocation \u2014
435
+ it can lag one run behind a release, but it no longer adds latency or
436
+ goes silent on slow networks.
437
+
438
+ ## 0.0.28 \u2014 2026-06-12
439
+
440
+ ### Added
441
+ - \`gs configure\` \u2014 view and edit the store configuration from the CLI:
442
+ display name, assistant name, sales guide, store link, extra origins,
443
+ theme, CSP host lists, and icon/logo uploads. Same fields and
444
+ behaviour as the dashboard's Configure panel.
445
+ - \`gs connectors\` \u2014 manage the store's MCP connectors: list, add (with
446
+ a discovery probe before saving), remove, enable/disable, toggle the
447
+ Maker MCP, and health-check. Same behaviour as the dashboard's
448
+ Connectors panel.
449
+ - \`--store <slug>\` on the new admin commands, so they work outside a
450
+ scaffolded component project (a \`.gsrc\` is still used when present).
451
+ - The agent skill gains a store-administration reference: coding agents
452
+ can read the store's configuration and connectors to ground their
453
+ work, self-serve additive changes like origin allowlists and CSP
454
+ hosts (read-merge-write), and are told which changes need the
455
+ merchant's go-ahead first.
456
+
457
+ ### Changed
458
+ - Component commands now live under \`gs apps\` (\`gs apps push\`,
459
+ \`gs apps build\`, \u2026), matching the dashboard's Apps panel. The old
460
+ top-level forms keep working as aliases, so existing scripts and
461
+ scaffolded projects are unaffected.
462
+ - The skill's structured-content guide now teaches "point, don't
463
+ paste": name the SKU/product/collection and let GreatStore research
464
+ the catalog itself instead of inlining fetched specs; validate with
465
+ \`gs connectors\` that a connector exists for the data a prompt or
466
+ schema depends on (research can't exceed the wired-up connectors);
467
+ and never put shopper data in prompts \u2014 GreatStore already knows the
468
+ shopper, and identified shoppers get per-shopper cached responses.
469
+
470
+ ## 0.0.27 \u2014 2026-06-11
471
+
472
+ ### Changed
473
+ - Skill code samples now carry an explicit reference-only disclaimer:
474
+ coding agents are told to re-express the logic in the host repo's
475
+ framework (React, Vue, Shopify Liquid, Svelte, \u2026) instead of
476
+ retrofitting the framework-free samples as-is.
477
+
478
+ ## 0.0.26 \u2014 2026-06-11
479
+
480
+ ### Added
481
+ - The agent skill gains a "GreatStore launchers" recipe: a horizontally
482
+ scrollable row of AI-generated chips, each an engaging first-person
483
+ question about the current page that's sent to the assistant on tap.
484
+
485
+ ### Changed
486
+ - Skill recipes are now one file each under \`recipes/\`, indexed from
487
+ SKILL.md by a table with description and use-case columns.
488
+
489
+ ## 0.0.25 \u2014 2026-06-11
490
+
491
+ ### Added
492
+ - \`gs skill\` installs the GreatStore agent skill \u2014 a guide AI coding
493
+ agents use to build with GreatStore: AI content for your own UI, chat
494
+ entry points, page tools, custom in-chat components, push
495
+ notifications, and the store's MCP endpoints. Installs into
496
+ \`./.claude/skills/\`; use \`--global\` for \`~/.claude/skills/\`, or
497
+ \`--dir <path>\` for agents that read skills from somewhere else. Run
498
+ it again any time to update an installed copy.
499
+
500
+ ## 0.0.24 \u2014 2026-06-03
501
+
502
+ ### Changed
503
+ - \`gs init\` in an existing project now fills in any scaffold files that
504
+ are missing (for example, the \`AGENTS.md\` design guide added in
505
+ 0.0.23) and leaves your own files alone. Pass \`--force\` to refresh
506
+ every scaffold file to the latest version. Your pinned store
507
+ (\`.gsrc\`) is never rewritten either way.
508
+
509
+ ## 0.0.23 \u2014 2026-06-03
510
+
511
+ ### Added
512
+ - \`gs init\` now scaffolds an \`AGENTS.md\` (with \`CLAUDE.md\` and
513
+ \`GEMINI.md\` symlinked to it) documenting the design rules every
514
+ component should follow \u2014 use \`em\` rather than \`rem\` for sizing, and
515
+ style from the provided brand CSS variables so components match the
516
+ store's theme. It doubles as guidance for AI coding agents.
517
+
518
+ ## 0.0.22 \u2014 2026-06-02
519
+
520
+ ### Added
521
+ - \`gs list\` now shows a link to each component's page in the dashboard,
522
+ so you can jump straight to a component to preview or publish it. The
523
+ link is also included in \`gs list --json\`.
524
+
525
+ ## 0.0.21 \u2014 2026-05-31
526
+
527
+ ### Changed
528
+ - The \`gs init\` component scaffold now shows how to write **async**
529
+ components that load data before they render \u2014 including validating
530
+ inputs up front and signalling a failure by throwing. The scaffolded
531
+ component no longer includes an \`onError\` prop; throw from an async
532
+ component to report a failure instead.
533
+
534
+ ## 0.0.20 \u2014 2026-05-29
535
+
536
+ ### Added
537
+ - \`gs pull\`, \`gs push\`, and \`gs publish\` now accept several component
538
+ names at once (e.g. \`gs publish header footer cart\`). Each component
539
+ is reported on its own line and one failure no longer stops the rest.
540
+
541
+ ## 0.0.19 \u2014 2026-05-28
542
+
543
+ ### Fixed
544
+ - \`gs login\` on Windows no longer opens a sign-in URL with parameters
545
+ stripped, which surfaced as a "Missing redirect_uri or state
546
+ parameter" page in the browser.
547
+
548
+ ## 0.0.18 \u2014 2026-05-28
549
+
550
+ ### Changed
551
+ - Push and publish errors now name the specific reason \u2014 including
552
+ every failing field in \`manifest.json\` \u2014 instead of the previous
553
+ generic message.
554
+
555
+ ## 0.0.17 \u2014 2026-05-28
556
+
557
+ ### Added
558
+ - Each command now prints a one-line upgrade notice when a newer
559
+ \`@greatstore/cli\` is available on npm.
560
+
561
+ ## 0.0.16 \u2014 2026-05-28
562
+
563
+ ### Changed
564
+ - Simplified error messages.
565
+
566
+ ## 0.0.15 \u2014 2026-05-24
567
+
568
+ ### Added
569
+ - Scaffolded \`component.tsx\` now declares the four injected lifecycle
570
+ props (\`onSendMessage\`, \`onCallTool\`, \`onClose\`, \`onError\`) on
571
+ \`Props\`. Use \`onError(message)\` to report expected failures (failed
572
+ fetch, host action rejected, invalid host state) so the AI can
573
+ recover on its next turn. Render-time crashes are reported for you.
574
+
575
+ ## 0.0.14 \u2014 2026-05-24
576
+
577
+ ### Changed
578
+ - \`gs build\` output is now whitespace-minified \u2014 typically ~50% smaller.
579
+
580
+ ## 0.0.13 \u2014 2026-05-24
581
+
582
+ ### Changed
583
+ - \`gs build\` prints the next-step hint (\`gs push\`, then \`gs publish\`).
584
+
585
+ ## 0.0.12 \u2014 2026-05-24
586
+
587
+ ### Fixed
588
+ - \`gs build\` failing to load Vite in some setups.
589
+
590
+ ## 0.0.11 \u2014 2026-05-24
591
+
592
+ ### Added
593
+ - Multi-component projects. \`gs init\` (no args) scaffolds the project
594
+ root; \`gs init <name>\` adds a component under \`components/<name>/\`.
595
+ - \`gs build [<name>]\` \u2014 compiles every \`components/<name>/bundle.js\`.
596
+ - \`gs push\` (no args) uploads only the components that changed.
597
+ - \`gs pull\` (no args, or \`*\`) downloads every component. Locally
598
+ edited components are skipped; pass \`--force\` to overwrite.
599
+ - Public \`CHANGELOG.md\`; \`gs --version\` prints recent entries.
600
+
601
+ ### Changed
602
+ - A project folder ships to exactly one store. Only \`gs init\` accepts
603
+ \`--store\`; every other command reads the slug from \`.gsrc\`. The old
604
+ single-component layout is rejected with a migration hint.
605
+ - \`gs init\` requires \`--store <slug>\` for a fresh root, and rejects
606
+ \`--store\` on an existing root.
607
+ - \`gs init\` no longer writes \`build.mjs\` \u2014 scripts call \`gs build\`.
608
+
609
+ ## 0.0.10 \u2014 2026-05-23
610
+
611
+ ### Changed
612
+ - The sign-in browser tab auto-closes once \`gs login\` finishes.
613
+
614
+ ## 0.0.9 \u2014 2026-05-23
615
+
616
+ ### Changed
617
+ - Scaffolded manifests include a \`displayName\` so the admin UI has a
618
+ friendlier label.
619
+
620
+ ## 0.0.8 \u2014 2026-05-23
621
+
622
+ ### Changed
623
+ - \`gs push\` and \`gs publish\` print a link to view the component.
624
+
625
+ ## 0.0.6 \u2014 2026-05-23
626
+
627
+ ### Changed
628
+ - \`gs --version\` reads from the published package version.
629
+
630
+ ## 0.0.4 \u2014 2026-05-23
631
+
632
+ ### Changed
633
+ - Scaffolded projects produce browser-ready bundles out of the box.
634
+
635
+ ## 0.0.3 \u2014 2026-05-23
636
+
637
+ ### Changed
638
+ - Trimmed public README to the essentials.
639
+
640
+ ## 0.0.2 \u2014 2026-05-23
641
+
642
+ ### Fixed
643
+ - Sign-in callback parameter handling.
644
+ `,vn=`gs \u2014 GreatStore CLI (v${F})
2974
645
 
2975
646
  Usage:
2976
647
  gs <command> [args] [flags]
@@ -3024,85 +695,14 @@ Environment:
3024
695
  GS_API_BASE Override API base (full URL, no trailing slash).
3025
696
  GS_DASHBOARD_BASE Override the sign-in/store-picker base URL.
3026
697
  GS_BROWSER_CMD Override the browser-open command.
3027
- `;
3028
- var APPS_ALIASES = /* @__PURE__ */ new Set([
3029
- "init",
3030
- "build",
3031
- "list",
3032
- "pull",
3033
- "push",
3034
- "publish",
3035
- "unpublish",
3036
- "delete"
3037
- ]);
3038
- async function main() {
3039
- const argv = process.argv.slice(2);
3040
- const parsed = parseArgs(argv);
3041
- if (flagBool(parsed.flags, "version")) {
3042
- process.stdout.write(`gs v${CLI_VERSION}
3043
-
3044
- `);
3045
- const changelog = recentChangelog(CHANGELOG);
3046
- if (changelog) process.stdout.write(`${changelog}
3047
- `);
3048
- return 0;
3049
- }
3050
- if (flagBool(parsed.flags, "help") || parsed.command === "help" || parsed.command === null) {
3051
- const specific = parsed.command === "configure" ? configureHelp(parsed.positional[0]) : void 0;
3052
- process.stdout.write(specific ?? HELP);
3053
- return 0;
3054
- }
3055
- if (parsed.command !== null && APPS_ALIASES.has(parsed.command)) {
3056
- return appsCommand({
3057
- ...parsed,
3058
- positional: [parsed.command, ...parsed.positional]
3059
- });
3060
- }
3061
- switch (parsed.command) {
3062
- case "login":
3063
- await loginCommand(parsed);
3064
- return 0;
3065
- case "logout":
3066
- logoutCommand();
3067
- return 0;
3068
- case "whoami":
3069
- return whoamiCommand();
3070
- case "switch":
3071
- return switchCommand(parsed.positional);
3072
- case "apps":
3073
- return appsCommand(parsed);
3074
- case "configure":
3075
- await configureCommand(parsed);
3076
- return 0;
3077
- case "connectors":
3078
- await connectorsCommand(parsed);
3079
- return 0;
3080
- case "skill":
3081
- skillCommand();
3082
- return 0;
3083
- default:
3084
- process.stderr.write(`Unknown command: ${parsed.command}
3085
-
3086
- ${HELP}`);
3087
- return 1;
3088
- }
3089
- }
3090
- main().then((code) => process.exit(code)).catch((err) => {
3091
- if (err instanceof AuthRequiredError) {
3092
- process.stderr.write(`${err.message}
3093
- `);
3094
- } else if (err instanceof HttpError) {
3095
- process.stderr.write(`Error: ${err.message}
3096
- `);
3097
- } else if (err instanceof StoreResolutionError || err instanceof LoopbackError) {
3098
- process.stderr.write(`Error: ${err.message}
3099
- `);
3100
- } else if (err instanceof Error) {
3101
- process.stderr.write(`Error: ${err.message}
3102
- `);
3103
- } else {
3104
- process.stderr.write(`Error: ${String(err)}
3105
- `);
3106
- }
3107
- process.exit(1);
3108
- });
698
+ `,Gr=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function qr(){let e=process.argv.slice(2),t=Be(e);if(m(t.flags,"version")){process.stdout.write(`gs v${F}
699
+
700
+ `);let n=Sn(Ur);return n&&process.stdout.write(`${n}
701
+ `),0}if(m(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?lt(t.positional[0]):void 0;return process.stdout.write(n??vn),0}if(t.command!==null&&Gr.has(t.command))return Fe({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await Ze(t),0;case"logout":return et(),0;case"whoami":return tt();case"switch":return nt(t.positional);case"apps":return Fe(t);case"configure":return await dn(t),0;case"connectors":return await bn(t),0;case"skill":return at(),0;default:return process.stderr.write(`Unknown command: ${t.command}
702
+
703
+ ${vn}`),1}}qr().then(e=>process.exit(e)).catch(e=>{e instanceof L?process.stderr.write(`${e.message}
704
+ `):e instanceof N?process.stderr.write(`Error: ${e.message}
705
+ `):e instanceof D||e instanceof V?process.stderr.write(`Error: ${e.message}
706
+ `):e instanceof Error?process.stderr.write(`Error: ${e.message}
707
+ `):process.stderr.write(`Error: ${String(e)}
708
+ `),process.exit(1)});