@githumbi/grabby 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +223 -135
- package/dist/angular/index.js +6 -5
- package/dist/angular/index.js.map +1 -1
- package/dist/cli/index.js +494 -20
- package/dist/cli/index.js.map +1 -1
- package/dist/core/index.cjs +6 -5
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.js +6 -5
- package/dist/core/index.js.map +1 -1
- package/dist/grabby.global.js +10 -10
- package/dist/react/index.js +6 -5
- package/dist/react/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/cli/index.ts
|
|
4
|
-
import { spawn } from "child_process";
|
|
5
4
|
import { parseArgs } from "util";
|
|
6
5
|
|
|
7
6
|
// src/cli/commands/init.ts
|
|
@@ -130,10 +129,60 @@ function patchAngularAppConfig(code) {
|
|
|
130
129
|
const withProvider = `${code.slice(0, at)}provideGrabby(), ${code.slice(at)}`;
|
|
131
130
|
return { status: "patched", code: insertImport(withProvider, "import { provideGrabby } from '@githumbi/grabby/angular';") };
|
|
132
131
|
}
|
|
132
|
+
function tagAttrs(tag, style) {
|
|
133
|
+
const jsx = style !== "html";
|
|
134
|
+
const q = (v) => JSON.stringify(v);
|
|
135
|
+
return [
|
|
136
|
+
`src=${q(tag.src)}`,
|
|
137
|
+
...tag.integrity ? [`integrity=${q(tag.integrity)}`, jsx ? 'crossOrigin="anonymous"' : 'crossorigin="anonymous"'] : [],
|
|
138
|
+
...tag.dataIntegrity ? [`data-integrity=${q(tag.dataIntegrity)}`] : [],
|
|
139
|
+
'data-mode="live"',
|
|
140
|
+
`data-server=${q(tag.server)}`,
|
|
141
|
+
`data-project-key=${q(tag.projectKey)}`,
|
|
142
|
+
style === "next-script" ? 'strategy="afterInteractive"' : "defer"
|
|
143
|
+
];
|
|
144
|
+
}
|
|
145
|
+
function renderTag(tag, style, indent = "", name = style === "next-script" ? "Script" : "script") {
|
|
146
|
+
const attrs = tagAttrs(tag, style).map((a) => `${indent} ${a}`).join("\n");
|
|
147
|
+
return style === "next-script" ? `<${name}
|
|
148
|
+
${attrs}
|
|
149
|
+
${indent}/>` : `<${name}
|
|
150
|
+
${attrs}
|
|
151
|
+
${indent}></${name}>`;
|
|
152
|
+
}
|
|
153
|
+
var EXISTING_TAG = /<(script|Script)\b(?=[^>]*@githumbi\/grabby@[^"'\s>]*\/dist\/loader\.global\.js)[^>]*?(?:\/>|>\s*<\/\1>)/;
|
|
154
|
+
function indentAt(code, index) {
|
|
155
|
+
const lineStart = code.lastIndexOf("\n", index - 1) + 1;
|
|
156
|
+
return /^[ \t]*/.exec(code.slice(lineStart, index))?.[0] ?? "";
|
|
157
|
+
}
|
|
158
|
+
function patchLoaderTag(code, tag, kind) {
|
|
159
|
+
const existing = EXISTING_TAG.exec(code);
|
|
160
|
+
if (existing) {
|
|
161
|
+
const name2 = existing[1];
|
|
162
|
+
const style = name2 === "Script" ? "next-script" : kind === "html" ? "html" : "jsx";
|
|
163
|
+
const next = renderTag(tag, style, indentAt(code, existing.index), name2);
|
|
164
|
+
if (next === existing[0]) return { status: "already" };
|
|
165
|
+
return { status: "patched", code: code.slice(0, existing.index) + next + code.slice(existing.index + existing[0].length) };
|
|
166
|
+
}
|
|
167
|
+
const bodies = code.split("</body>").length - 1;
|
|
168
|
+
if (bodies !== 1) return { status: "unrecognised", reason: bodies ? "more than one </body>" : "no </body> found" };
|
|
169
|
+
const at = code.indexOf("</body>");
|
|
170
|
+
const indent = `${indentAt(code, at)} `;
|
|
171
|
+
if (kind !== "next-app") {
|
|
172
|
+
const withTag2 = `${code.slice(0, at)} ${renderTag(tag, kind, indent)}
|
|
173
|
+
${indentAt(code, at)}${code.slice(at)}`;
|
|
174
|
+
return { status: "patched", code: withTag2 };
|
|
175
|
+
}
|
|
176
|
+
const imported = /import\s+(\w+)\s+from\s+['"]next\/script['"]/.exec(code);
|
|
177
|
+
const name = imported?.[1] ?? "Script";
|
|
178
|
+
const withTag = `${code.slice(0, at)} ${renderTag(tag, "next-script", indent, name)}
|
|
179
|
+
${indentAt(code, at)}${code.slice(at)}`;
|
|
180
|
+
return { status: "patched", code: imported ? withTag : insertImport(withTag, 'import Script from "next/script";') };
|
|
181
|
+
}
|
|
133
182
|
|
|
134
183
|
// src/cli/versions.ts
|
|
135
|
-
var GRABBY_VERSION = "0.
|
|
136
|
-
var SERVER_PACKAGE = `@githumbi/grabby-server@${"0.
|
|
184
|
+
var GRABBY_VERSION = "0.2.0";
|
|
185
|
+
var SERVER_PACKAGE = `@githumbi/grabby-server@${"0.2.0"}`;
|
|
137
186
|
|
|
138
187
|
// src/cli/commands/init.ts
|
|
139
188
|
var PKG = "@githumbi/grabby";
|
|
@@ -152,6 +201,16 @@ function sri(file) {
|
|
|
152
201
|
return null;
|
|
153
202
|
}
|
|
154
203
|
}
|
|
204
|
+
function liveTag(server, projectKey) {
|
|
205
|
+
return {
|
|
206
|
+
src: `https://cdn.jsdelivr.net/npm/${PKG}@${GRABBY_VERSION}/dist/loader.global.js`,
|
|
207
|
+
integrity: sri("loader.global.js"),
|
|
208
|
+
// The loader fetches the full build itself; data-integrity covers that file.
|
|
209
|
+
dataIntegrity: sri("grabby.global.js"),
|
|
210
|
+
server,
|
|
211
|
+
projectKey
|
|
212
|
+
};
|
|
213
|
+
}
|
|
155
214
|
function cdnScriptTag(live) {
|
|
156
215
|
const file = live ? "loader.global.js" : "grabby.global.js";
|
|
157
216
|
const own = sri(file);
|
|
@@ -340,9 +399,9 @@ function getMcpServerEntry() {
|
|
|
340
399
|
args: ["-y", SERVER_PACKAGE, "mcp"]
|
|
341
400
|
};
|
|
342
401
|
}
|
|
343
|
-
async function addMcp() {
|
|
344
|
-
log2("Adding grabby MCP server...\n");
|
|
345
|
-
const mcpJsonPath = join3(process.cwd(), ".mcp.json");
|
|
402
|
+
async function addMcp(options = {}) {
|
|
403
|
+
if (!options.quiet) log2("Adding grabby MCP server...\n");
|
|
404
|
+
const mcpJsonPath = join3(options.cwd ?? process.cwd(), ".mcp.json");
|
|
346
405
|
let config = {};
|
|
347
406
|
if (existsSync3(mcpJsonPath)) {
|
|
348
407
|
try {
|
|
@@ -357,28 +416,413 @@ async function addMcp() {
|
|
|
357
416
|
servers[MCP_SERVER_NAME] = getMcpServerEntry();
|
|
358
417
|
config.mcpServers = servers;
|
|
359
418
|
writeFileSync2(mcpJsonPath, JSON.stringify(config, null, 2) + "\n");
|
|
360
|
-
success("Added grabby MCP server to .mcp.json");
|
|
419
|
+
success(options.quiet ? "\x1B[32m\u2713\x1B[0m .mcp.json (grabby MCP server)" : "Added grabby MCP server to .mcp.json");
|
|
420
|
+
if (options.quiet) return;
|
|
361
421
|
console.log("");
|
|
362
|
-
console.log("
|
|
363
|
-
console.log("
|
|
422
|
+
console.log(" After `npx @githumbi/grabby share`, it reads your live site's feedback.");
|
|
423
|
+
console.log(" Otherwise it collects comments from your app on http://localhost:3456;");
|
|
424
|
+
console.log(" point Grabby at it: initGrabby({ server: 'http://localhost:3456' })");
|
|
364
425
|
console.log("");
|
|
365
426
|
console.log(" \x1B[1mRestart your editor\x1B[0m to activate the MCP connection.");
|
|
366
427
|
console.log(" When prompted, \x1B[1mapprove the MCP server\x1B[0m in your editor.");
|
|
367
428
|
console.log("");
|
|
368
429
|
}
|
|
369
430
|
|
|
431
|
+
// src/cli/commands/share.ts
|
|
432
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6, rmSync, writeFileSync as writeFileSync4 } from "fs";
|
|
433
|
+
import { join as join6, relative as relative2 } from "path";
|
|
434
|
+
import { createInterface as createInterface2 } from "readline";
|
|
435
|
+
|
|
436
|
+
// src/cli/utils/detect-site.ts
|
|
437
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
|
|
438
|
+
import { join as join4 } from "path";
|
|
439
|
+
var DEV_PORTS = {
|
|
440
|
+
next: 3e3,
|
|
441
|
+
nuxt: 3e3,
|
|
442
|
+
angular: 4200,
|
|
443
|
+
astro: 4321,
|
|
444
|
+
react: 5173,
|
|
445
|
+
vue: 5173,
|
|
446
|
+
svelte: 5173,
|
|
447
|
+
sveltekit: 5173,
|
|
448
|
+
solid: 5173,
|
|
449
|
+
preact: 5173
|
|
450
|
+
};
|
|
451
|
+
function devOrigin(framework) {
|
|
452
|
+
const port = DEV_PORTS[framework];
|
|
453
|
+
return port ? `http://localhost:${port}` : null;
|
|
454
|
+
}
|
|
455
|
+
function toOrigin(input) {
|
|
456
|
+
const raw = input.trim();
|
|
457
|
+
if (!raw) return null;
|
|
458
|
+
try {
|
|
459
|
+
const url = new URL(/^[a-z]+:\/\//i.test(raw) ? raw : `https://${raw}`);
|
|
460
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
|
461
|
+
if (!url.hostname.includes(".") && url.hostname !== "localhost") return null;
|
|
462
|
+
return url.origin;
|
|
463
|
+
} catch {
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function guessSiteOrigins(root) {
|
|
468
|
+
const found = [];
|
|
469
|
+
try {
|
|
470
|
+
const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
|
|
471
|
+
const o = typeof pkg.homepage === "string" ? toOrigin(pkg.homepage) : null;
|
|
472
|
+
if (o && new URL(o).hostname !== "github.com") found.push(o);
|
|
473
|
+
} catch {
|
|
474
|
+
}
|
|
475
|
+
for (const cname of ["CNAME", "public/CNAME", "static/CNAME"]) {
|
|
476
|
+
const file = join4(root, cname);
|
|
477
|
+
if (existsSync4(file)) {
|
|
478
|
+
const o = toOrigin(readFileSync4(file, "utf8").split("\n")[0]);
|
|
479
|
+
if (o) found.push(o);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return [...new Set(found)];
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/cli/utils/project-config.ts
|
|
486
|
+
import { appendFileSync, chmodSync, mkdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
487
|
+
import { dirname as dirname2, join as join5 } from "path";
|
|
488
|
+
var projectConfigPath = (root) => join5(root, ".grabby", "config.json");
|
|
489
|
+
function readProjectConfig(root) {
|
|
490
|
+
try {
|
|
491
|
+
const parsed = JSON.parse(readFileSync5(projectConfigPath(root), "utf8"));
|
|
492
|
+
return parsed && typeof parsed.server === "string" ? parsed : null;
|
|
493
|
+
} catch {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function writeProjectConfig(root, config) {
|
|
498
|
+
const file = projectConfigPath(root);
|
|
499
|
+
mkdirSync(dirname2(file), { recursive: true });
|
|
500
|
+
writeFileSync3(file, `${JSON.stringify(config, null, 2)}
|
|
501
|
+
`, { mode: 384 });
|
|
502
|
+
try {
|
|
503
|
+
chmodSync(file, 384);
|
|
504
|
+
} catch {
|
|
505
|
+
}
|
|
506
|
+
return file;
|
|
507
|
+
}
|
|
508
|
+
function ensureGitignore(root) {
|
|
509
|
+
const file = join5(root, ".gitignore");
|
|
510
|
+
let current = "";
|
|
511
|
+
try {
|
|
512
|
+
current = readFileSync5(file, "utf8");
|
|
513
|
+
} catch (err) {
|
|
514
|
+
if (err.code !== "ENOENT") throw err;
|
|
515
|
+
}
|
|
516
|
+
if (/^\/?\.grabby\/?\s*$/m.test(current)) return false;
|
|
517
|
+
const sep = current && !current.endsWith("\n") ? "\n" : "";
|
|
518
|
+
appendFileSync(file, `${sep}# Grabby: collector settings and admin token
|
|
519
|
+
.grabby/
|
|
520
|
+
`);
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/cli/utils/server-cli.ts
|
|
525
|
+
import { spawn } from "child_process";
|
|
526
|
+
function runServer(args, options = {}) {
|
|
527
|
+
const local = process.env.GRABBY_SERVER_BIN;
|
|
528
|
+
const windows = process.platform === "win32";
|
|
529
|
+
const argv2 = local ? [local, ...args] : ["-y", SERVER_PACKAGE, ...args];
|
|
530
|
+
if (!local && windows && !argv2.every((a) => /^[\w@./:=,+-]+$/.test(a))) {
|
|
531
|
+
return Promise.reject(new Error(`unsupported characters in arguments; run it directly: npx ${argv2.join(" ")}`));
|
|
532
|
+
}
|
|
533
|
+
return new Promise((resolve, reject) => {
|
|
534
|
+
const child = spawn(local ? process.execPath : windows ? "npx.cmd" : "npx", argv2, {
|
|
535
|
+
stdio: ["inherit", options.captureStdout ? "pipe" : "inherit", "inherit"],
|
|
536
|
+
shell: !local && windows,
|
|
537
|
+
cwd: options.cwd,
|
|
538
|
+
env: { ...process.env, ...options.env }
|
|
539
|
+
});
|
|
540
|
+
let stdout = "";
|
|
541
|
+
child.stdout?.on("data", (chunk) => {
|
|
542
|
+
stdout += chunk.toString("utf8");
|
|
543
|
+
});
|
|
544
|
+
child.on("error", reject);
|
|
545
|
+
child.on("close", (code) => resolve({ code: code ?? 1, stdout }));
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// src/cli/commands/share.ts
|
|
550
|
+
var c2 = {
|
|
551
|
+
cyan: (s) => `\x1B[36m${s}\x1B[0m`,
|
|
552
|
+
yellow: (s) => `\x1B[33m${s}\x1B[0m`,
|
|
553
|
+
green: (s) => `\x1B[32m${s}\x1B[0m`,
|
|
554
|
+
bold: (s) => `\x1B[1m${s}\x1B[0m`,
|
|
555
|
+
dim: (s) => `\x1B[2m${s}\x1B[0m`
|
|
556
|
+
};
|
|
557
|
+
var log3 = (msg = "") => console.log(msg && `${c2.cyan("[grabby]")} ${msg}`);
|
|
558
|
+
var warn3 = (msg) => console.log(`${c2.yellow("[grabby]")} ${msg}`);
|
|
559
|
+
function trimSlashes(url) {
|
|
560
|
+
let end = url.length;
|
|
561
|
+
while (end > 0 && url[end - 1] === "/") end--;
|
|
562
|
+
return url.slice(0, end);
|
|
563
|
+
}
|
|
564
|
+
async function ask(question) {
|
|
565
|
+
if (!process.stdin.isTTY) return "";
|
|
566
|
+
const rl = createInterface2({ input: process.stdin, output: process.stdout });
|
|
567
|
+
const answer = await new Promise((resolve) => rl.question(question, resolve));
|
|
568
|
+
rl.close();
|
|
569
|
+
return answer.trim();
|
|
570
|
+
}
|
|
571
|
+
function siteTarget(stack) {
|
|
572
|
+
const first = (files) => files.map((f) => join6(stack.root, f)).find((f) => existsSync5(f));
|
|
573
|
+
if (stack.framework === "next") {
|
|
574
|
+
const layout = first(["app/layout.tsx", "app/layout.jsx", "app/layout.js", "src/app/layout.tsx", "src/app/layout.jsx", "src/app/layout.js"]);
|
|
575
|
+
if (layout) return { file: layout, kind: "next-app" };
|
|
576
|
+
const doc = first(["pages/_document.tsx", "pages/_document.jsx", "pages/_document.js", "src/pages/_document.tsx", "src/pages/_document.jsx", "src/pages/_document.js"]);
|
|
577
|
+
return doc ? { file: doc, kind: "jsx" } : null;
|
|
578
|
+
}
|
|
579
|
+
const html = first(["index.html", "src/index.html", "public/index.html", "src/app.html"]);
|
|
580
|
+
return html ? { file: html, kind: "html" } : null;
|
|
581
|
+
}
|
|
582
|
+
async function collector(server, path, token, init2 = {}) {
|
|
583
|
+
return fetch(`${server}${path}`, {
|
|
584
|
+
...init2,
|
|
585
|
+
headers: { Authorization: `Bearer ${token}`, ...init2.body ? { "Content-Type": "application/json" } : {} },
|
|
586
|
+
signal: AbortSignal.timeout(15e3)
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
async function resolveOrigins(stack, saved, options) {
|
|
590
|
+
const given = (options.origins ?? []).map((o) => {
|
|
591
|
+
const origin = toOrigin(o);
|
|
592
|
+
if (!origin) throw new Error(`"${o}" is not a web address (e.g. https://your-site.com)`);
|
|
593
|
+
return origin;
|
|
594
|
+
});
|
|
595
|
+
let sites = given.length ? given : saved?.origins.filter((o) => !o.startsWith("http://localhost")) ?? [];
|
|
596
|
+
if (!sites.length) sites = guessSiteOrigins(stack.root);
|
|
597
|
+
if (!sites.length) {
|
|
598
|
+
const answer = await ask(` Where is your site live? ${c2.dim("(e.g. https://my-app.netlify.app)")} `);
|
|
599
|
+
const origin = toOrigin(answer);
|
|
600
|
+
if (!origin) {
|
|
601
|
+
throw new Error(process.stdin.isTTY ? "a site address is needed, e.g. https://my-app.netlify.app" : "pass the site address: npx @githumbi/grabby share --origin https://your-site.com");
|
|
602
|
+
}
|
|
603
|
+
sites = [origin];
|
|
604
|
+
}
|
|
605
|
+
const merged = /* @__PURE__ */ new Set([...given.length ? [] : saved?.origins ?? [], ...sites]);
|
|
606
|
+
const dev = devOrigin(stack.framework);
|
|
607
|
+
if (dev && !options.noLocalhost) merged.add(dev);
|
|
608
|
+
return [...merged];
|
|
609
|
+
}
|
|
610
|
+
function projectKeyInSite(stack) {
|
|
611
|
+
const target = siteTarget(stack);
|
|
612
|
+
if (!target) return void 0;
|
|
613
|
+
const code = readFileSync6(target.file, "utf8");
|
|
614
|
+
if (!code.includes("/dist/loader.global.js")) return void 0;
|
|
615
|
+
return /data-project-key=["'](pk_[A-Za-z0-9_-]{8,64})["']/.exec(code)?.[1];
|
|
616
|
+
}
|
|
617
|
+
function patchSite(stack, tag, dryRun) {
|
|
618
|
+
const target = siteTarget(stack);
|
|
619
|
+
if (!target) return { file: null, result: null };
|
|
620
|
+
const result = patchLoaderTag(readFileSync6(target.file, "utf8"), tag, target.kind);
|
|
621
|
+
if (result.status === "patched" && !dryRun) writeFileSync4(target.file, result.code, "utf8");
|
|
622
|
+
return { file: target.file, result };
|
|
623
|
+
}
|
|
624
|
+
async function share(options = {}) {
|
|
625
|
+
const stack = detectStack(options.cwd);
|
|
626
|
+
const rel = (f) => relative2(stack.root, f) || f;
|
|
627
|
+
const saved = readProjectConfig(stack.root);
|
|
628
|
+
const keyInSite = saved ? void 0 : projectKeyInSite(stack);
|
|
629
|
+
const selfHosted = options.server ?? (saved?.deploy.kind === "server" ? saved.server : void 0);
|
|
630
|
+
const origins = await resolveOrigins(stack, saved, options);
|
|
631
|
+
const target = siteTarget(stack);
|
|
632
|
+
log3(`Project: ${stack.root}`);
|
|
633
|
+
log3(`Detected: ${stack.framework}${saved ? " \xB7 already shared, updating" : ""}`);
|
|
634
|
+
console.log("");
|
|
635
|
+
console.log(c2.bold(" Grabby will:"));
|
|
636
|
+
console.log(selfHosted ? ` \u2022 use your collector at ${c2.bold(selfHosted)}` : ` \u2022 ${saved ? "update" : "set up"} a feedback collector in ${c2.bold("your Cloudflare account")} ${c2.dim("(free, no card; a browser window opens to sign in the first time)")}`);
|
|
637
|
+
console.log(` \u2022 accept comments from ${origins.map((o) => c2.bold(o)).join(", ")}`);
|
|
638
|
+
console.log(target ? ` \u2022 add the Grabby script to ${c2.bold(rel(target.file))}` : ` \u2022 show you the script tag to add ${c2.dim("(no layout or index.html found to edit)")}`);
|
|
639
|
+
console.log(` \u2022 save settings in ${c2.bold(".grabby/config.json")} ${c2.dim("(private; added to .gitignore)")}`);
|
|
640
|
+
if (!options.noMcp) console.log(` \u2022 let your AI agent read feedback ${c2.dim("(.mcp.json)")}`);
|
|
641
|
+
if (options.slack) console.log(" \u2022 post new feedback to Slack");
|
|
642
|
+
console.log("");
|
|
643
|
+
if (options.dryRun) return;
|
|
644
|
+
if (!options.yes) {
|
|
645
|
+
const go = /^y(es)?$/i.test(await ask(" Go ahead? [y/N] "));
|
|
646
|
+
if (!go) {
|
|
647
|
+
warn3(process.stdin.isTTY ? "Nothing changed." : "Nothing changed (not a terminal; re-run with --yes to apply).");
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
let server;
|
|
652
|
+
let projectKey;
|
|
653
|
+
let adminToken;
|
|
654
|
+
let deploy;
|
|
655
|
+
if (selfHosted) {
|
|
656
|
+
server = trimSlashes(selfHosted);
|
|
657
|
+
adminToken = options.token ?? process.env.GRABBY_ADMIN_TOKEN ?? saved?.adminToken;
|
|
658
|
+
if (!adminToken) throw new Error("--server needs the collector's admin token: --token sk_\u2026 (or GRABBY_ADMIN_TOKEN)");
|
|
659
|
+
const res = await collector(server, "/v1/meta", adminToken).catch((err) => {
|
|
660
|
+
throw new Error(`could not reach ${server}: ${err.message}`);
|
|
661
|
+
});
|
|
662
|
+
if (res.status === 401) throw new Error(`${server} rejected the admin token`);
|
|
663
|
+
if (!res.ok) throw new Error(`${server}/v1/meta answered ${res.status}. Is it a Grabby collector, version 0.2 or newer?`);
|
|
664
|
+
const meta = await res.json();
|
|
665
|
+
const project = meta.projects[0];
|
|
666
|
+
if (!project?.publicKey) throw new Error(`${server} has no project key configured`);
|
|
667
|
+
projectKey = project.publicKey;
|
|
668
|
+
const missing = origins.filter((o) => !o.startsWith("http://localhost") && !project.allowedOrigins.includes(o));
|
|
669
|
+
if (missing.length) warn3(`Your collector doesn't accept ${missing.join(", ")} yet. Add it to GRABBY_ALLOWED_ORIGINS on the server.`);
|
|
670
|
+
deploy = { kind: "server" };
|
|
671
|
+
} else {
|
|
672
|
+
const resultFile = join6(stack.root, ".grabby", "cloudflare", "result.json");
|
|
673
|
+
const args = ["deploy", "cloudflare", "--out", resultFile, "--dir", join6(stack.root, ".grabby", "cloudflare"), ...origins.flatMap((o) => ["--origin", o])];
|
|
674
|
+
const key = saved?.projectKey ?? keyInSite;
|
|
675
|
+
if (key) args.push("--key", key);
|
|
676
|
+
if (options.rotateAdmin) args.push("--rotate-admin");
|
|
677
|
+
rmSync(resultFile, { force: true });
|
|
678
|
+
const run = await runServer(args, { env: { GRABBY_ADMIN_TOKEN: saved?.adminToken } });
|
|
679
|
+
let result2;
|
|
680
|
+
try {
|
|
681
|
+
result2 = JSON.parse(readFileSync6(resultFile, "utf8"));
|
|
682
|
+
} catch {
|
|
683
|
+
throw new Error("setting up the collector failed (see the messages above)");
|
|
684
|
+
} finally {
|
|
685
|
+
rmSync(resultFile, { force: true });
|
|
686
|
+
}
|
|
687
|
+
if (run.code !== 0) throw new Error("setting up the collector failed (see the messages above)");
|
|
688
|
+
server = result2.url;
|
|
689
|
+
projectKey = result2.projectKey;
|
|
690
|
+
adminToken = result2.adminToken ?? saved?.adminToken;
|
|
691
|
+
deploy = { kind: "cloudflare", worker: result2.worker, database: result2.database };
|
|
692
|
+
if (!adminToken) {
|
|
693
|
+
throw new Error("this collector already has an admin token that is not saved on this computer. Run again with --rotate-admin to replace it.");
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
let inbox = saved?.inbox && saved.server === server && !options.rotate ? saved.inbox : void 0;
|
|
697
|
+
if (inbox) {
|
|
698
|
+
const token = new URL(inbox).hash.replace(/^#k=/, "");
|
|
699
|
+
const check = await collector(server, "/v1/meta", token).catch(() => null);
|
|
700
|
+
if (check?.status === 401) inbox = void 0;
|
|
701
|
+
}
|
|
702
|
+
if (!inbox) {
|
|
703
|
+
const res = await collector(server, "/v1/admin/inbox-token", adminToken, { method: "POST" });
|
|
704
|
+
if (!res.ok) throw new Error(`could not create the inbox link (${res.status})`);
|
|
705
|
+
inbox = (await res.json()).url;
|
|
706
|
+
let sameCollector = false;
|
|
707
|
+
try {
|
|
708
|
+
sameCollector = typeof inbox === "string" && new URL(inbox).origin === new URL(server).origin;
|
|
709
|
+
} catch {
|
|
710
|
+
}
|
|
711
|
+
if (!sameCollector) throw new Error(`${server} returned an unexpected inbox link`);
|
|
712
|
+
}
|
|
713
|
+
if (options.slack) {
|
|
714
|
+
const res = await collector(server, "/v1/admin/alerts", adminToken, { method: "PUT", body: JSON.stringify({ slack: options.slack }) });
|
|
715
|
+
if (!res.ok) warn3(`Slack alerts not set: ${(await res.json().catch(() => ({}))).error ?? res.status}`);
|
|
716
|
+
}
|
|
717
|
+
const tag = liveTag(server, projectKey);
|
|
718
|
+
const { file, result } = patchSite(stack, tag, false);
|
|
719
|
+
let siteChanged = null;
|
|
720
|
+
if (file && result?.status === "patched") {
|
|
721
|
+
siteChanged = rel(file);
|
|
722
|
+
log3(`${c2.green("\u2713")} ${siteChanged}`);
|
|
723
|
+
} else if (file && result?.status === "already") {
|
|
724
|
+
log3(`${rel(file)}: already up to date`);
|
|
725
|
+
} else {
|
|
726
|
+
warn3(`Add this before </body> in your site's layout${file && result?.status === "unrecognised" ? ` (${rel(file)}: ${result.reason})` : ""}:`);
|
|
727
|
+
console.log(`
|
|
728
|
+
${renderTag(tag, "html")}
|
|
729
|
+
`);
|
|
730
|
+
}
|
|
731
|
+
writeProjectConfig(stack.root, { version: 1, server, projectKey, adminToken, inbox, origins, deploy });
|
|
732
|
+
if (ensureGitignore(stack.root)) log3(`${c2.green("\u2713")} .gitignore (added .grabby/)`);
|
|
733
|
+
log3(`${c2.green("\u2713")} .grabby/config.json`);
|
|
734
|
+
if (!options.noMcp) await addMcp({ cwd: stack.root, quiet: true });
|
|
735
|
+
const site = origins.find((o) => !o.startsWith("http://localhost")) ?? origins[0];
|
|
736
|
+
console.log("");
|
|
737
|
+
log3(c2.green("Grabby is ready."));
|
|
738
|
+
console.log("");
|
|
739
|
+
console.log(` ${c2.bold("1.")} ${siteChanged ? `Commit and deploy your site as usual (${siteChanged} changed).` : "Deploy your site as usual."}`);
|
|
740
|
+
console.log(` ${c2.bold("2.")} Send reviewers this link. They click Comment, pick anything, and type:`);
|
|
741
|
+
console.log(` ${c2.bold(`${site}/?grabby=${projectKey}`)}`);
|
|
742
|
+
console.log(` ${c2.bold("3.")} Read feedback in your private inbox ${c2.dim("(bookmark it; don't share it)")}:`);
|
|
743
|
+
console.log(` ${c2.bold(inbox)}`);
|
|
744
|
+
console.log(` or hand it to your AI agent: ${c2.bold("npx @githumbi/grabby pull")}`);
|
|
745
|
+
console.log("");
|
|
746
|
+
console.log(c2.dim(` Comments arrive even while your computer is off. Later: ${c2.bold("npx @githumbi/grabby inbox")} opens the inbox,`));
|
|
747
|
+
console.log(c2.dim(` ${c2.bold("npx @githumbi/grabby alerts --slack <webhook>")} posts new feedback to Slack.`));
|
|
748
|
+
console.log("");
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// src/cli/commands/inbox.ts
|
|
752
|
+
import { spawn as spawn2 } from "child_process";
|
|
753
|
+
function sharedConfig(cwd) {
|
|
754
|
+
const config = readProjectConfig(findProjectRoot(cwd));
|
|
755
|
+
if (!config) throw new Error("this project isn't shared yet. Run: npx @githumbi/grabby share");
|
|
756
|
+
return config;
|
|
757
|
+
}
|
|
758
|
+
async function openInbox(options = {}) {
|
|
759
|
+
const { inbox } = sharedConfig(options.cwd);
|
|
760
|
+
if (!inbox) throw new Error("no inbox link saved. Run: npx @githumbi/grabby share --rotate");
|
|
761
|
+
console.log(`\x1B[36m[grabby]\x1B[0m Your inbox (private, don't share it): ${inbox}`);
|
|
762
|
+
if (options.print || !process.stdout.isTTY) return;
|
|
763
|
+
const [cmd, args] = process.platform === "darwin" ? ["open", [inbox]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", inbox]] : ["xdg-open", [inbox]];
|
|
764
|
+
spawn2(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {
|
|
765
|
+
}).unref();
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// src/cli/commands/alerts.ts
|
|
769
|
+
async function alerts(options) {
|
|
770
|
+
const { server, adminToken } = sharedConfig(options.cwd);
|
|
771
|
+
if (!adminToken) throw new Error("no admin token saved for this project. Run: npx @githumbi/grabby share --rotate-admin");
|
|
772
|
+
const call = (path, init2 = {}) => fetch(`${server}${path}`, {
|
|
773
|
+
...init2,
|
|
774
|
+
headers: { Authorization: `Bearer ${adminToken}`, ...init2.body ? { "Content-Type": "application/json" } : {} },
|
|
775
|
+
signal: AbortSignal.timeout(15e3)
|
|
776
|
+
});
|
|
777
|
+
const say = (m) => console.log(`\x1B[36m[grabby]\x1B[0m ${m}`);
|
|
778
|
+
const body = {};
|
|
779
|
+
if (options.off) Object.assign(body, { slack: null, webhook: null });
|
|
780
|
+
if (options.slack) body.slack = options.slack;
|
|
781
|
+
if (options.webhook) body.webhook = options.webhook;
|
|
782
|
+
if (Object.keys(body).length) {
|
|
783
|
+
const res = await call("/v1/admin/alerts", { method: "PUT", body: JSON.stringify(body) });
|
|
784
|
+
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error ?? `the collector answered ${res.status}`);
|
|
785
|
+
say(options.off ? "Alerts are off." : "Alerts are on. New feedback is posted within about 20 seconds, one message per burst.");
|
|
786
|
+
}
|
|
787
|
+
if (options.test) {
|
|
788
|
+
const res = await call("/v1/admin/alerts/test", { method: "POST" });
|
|
789
|
+
say(res.ok ? "Sent a test alert." : "The test alert did not go through: is an alert set?");
|
|
790
|
+
}
|
|
791
|
+
if (!Object.keys(body).length && !options.test) {
|
|
792
|
+
const res = await call("/v1/admin/alerts");
|
|
793
|
+
const current = await res.json();
|
|
794
|
+
say(`Slack: ${current.slack ? "on" : "off"} \xB7 webhook: ${current.webhook ? "on" : "off"}`);
|
|
795
|
+
say("Set one with: npx @githumbi/grabby alerts --slack https://hooks.slack.com/services/\u2026");
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
370
799
|
// src/cli/index.ts
|
|
371
800
|
var HELP = `Grabby: point at any UI element, leave a comment, hand it to your AI agent.
|
|
372
801
|
|
|
373
802
|
Usage
|
|
374
|
-
npx @githumbi/grabby init Set up Grabby
|
|
803
|
+
npx @githumbi/grabby init Set up Grabby for local development (asks before changing files)
|
|
375
804
|
--yes Apply without asking
|
|
376
805
|
--dry-run Only show what would change
|
|
377
806
|
--no-install Don't install the package
|
|
378
|
-
|
|
379
|
-
|
|
807
|
+
|
|
808
|
+
npx @githumbi/grabby share Get feedback from others on your live site. Sets up a
|
|
809
|
+
collector in your own free Cloudflare account, adds the
|
|
810
|
+
script to your site, and gives you a feedback link and
|
|
811
|
+
a private inbox. Safe to re-run.
|
|
812
|
+
--origin <url> Your site's address (repeatable; asked if missing)
|
|
813
|
+
--server <url> --token <sk_\u2026>
|
|
814
|
+
Use a collector you run yourself instead
|
|
815
|
+
--slack <webhook> Post new feedback to Slack
|
|
816
|
+
--rotate Replace the private inbox link
|
|
817
|
+
--rotate-admin Replace the admin token
|
|
818
|
+
--no-localhost Don't accept comments from your local dev server
|
|
819
|
+
--no-mcp Don't add the MCP server to .mcp.json
|
|
820
|
+
--yes, --dry-run
|
|
821
|
+
|
|
822
|
+
npx @githumbi/grabby inbox Open your private feedback inbox (--print to only show the link)
|
|
823
|
+
npx @githumbi/grabby pull Print open comments for your AI agent, then mark them resolved
|
|
824
|
+
npx @githumbi/grabby alerts --slack <webhook> | --webhook <url> | --off | --test
|
|
380
825
|
npx @githumbi/grabby add mcp Let your AI agent read comments over MCP (.mcp.json)
|
|
381
|
-
npx @githumbi/grabby pull Print collected comments for your agent (runs grabby-server pull)
|
|
382
826
|
`;
|
|
383
827
|
function fail(err) {
|
|
384
828
|
console.error("\x1B[31mError:\x1B[0m", err instanceof Error ? err.message : String(err));
|
|
@@ -387,13 +831,43 @@ function fail(err) {
|
|
|
387
831
|
var argv = process.argv.slice(2);
|
|
388
832
|
var [command, subcommand] = argv;
|
|
389
833
|
if (command === "pull") {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
834
|
+
runServer(["pull", ...argv.slice(1)]).then(({ code }) => process.exit(code)).catch(fail);
|
|
835
|
+
} else if (command === "share") {
|
|
836
|
+
const { values } = parseArgs({
|
|
837
|
+
args: argv.slice(1),
|
|
838
|
+
options: {
|
|
839
|
+
origin: { type: "string", multiple: true },
|
|
840
|
+
server: { type: "string" },
|
|
841
|
+
token: { type: "string" },
|
|
842
|
+
slack: { type: "string" },
|
|
843
|
+
rotate: { type: "boolean" },
|
|
844
|
+
"rotate-admin": { type: "boolean" },
|
|
845
|
+
"no-localhost": { type: "boolean" },
|
|
846
|
+
"no-mcp": { type: "boolean" },
|
|
847
|
+
yes: { type: "boolean", short: "y" },
|
|
848
|
+
"dry-run": { type: "boolean" }
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
share({
|
|
852
|
+
origins: values.origin,
|
|
853
|
+
server: values.server,
|
|
854
|
+
token: values.token,
|
|
855
|
+
slack: values.slack,
|
|
856
|
+
rotate: values.rotate,
|
|
857
|
+
rotateAdmin: values["rotate-admin"],
|
|
858
|
+
noLocalhost: values["no-localhost"],
|
|
859
|
+
noMcp: values["no-mcp"],
|
|
860
|
+
yes: values.yes,
|
|
861
|
+
dryRun: values["dry-run"]
|
|
862
|
+
}).catch(fail);
|
|
863
|
+
} else if (command === "inbox") {
|
|
864
|
+
openInbox({ print: argv.includes("--print") }).catch(fail);
|
|
865
|
+
} else if (command === "alerts") {
|
|
866
|
+
const { values } = parseArgs({
|
|
867
|
+
args: argv.slice(1),
|
|
868
|
+
options: { slack: { type: "string" }, webhook: { type: "string" }, off: { type: "boolean" }, test: { type: "boolean" } }
|
|
869
|
+
});
|
|
870
|
+
alerts(values).catch(fail);
|
|
397
871
|
} else if (command === "add" && subcommand === "mcp") {
|
|
398
872
|
addMcp().catch(fail);
|
|
399
873
|
} else if (!command || command === "init") {
|