@commentkit/comment-kit 1.6.0 → 2.0.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 +281 -597
- package/README.md +334 -154
- package/SECURITY.md +47 -46
- package/dist/node/THIRD_PARTY_NOTICES.txt +56 -0
- package/dist/node/browser.js +17 -0
- package/dist/node/cli/api.js +226 -0
- package/dist/node/cli/bin.js +18 -0
- package/dist/node/cli/credentials.js +268 -0
- package/dist/node/cli/doctor.js +725 -0
- package/dist/node/cli/format.js +54 -0
- package/dist/node/cli/init.js +372 -0
- package/dist/node/cli/main.js +519 -0
- package/dist/node/cli/mcp.js +114 -0
- package/dist/node/cli/open.js +20 -0
- package/dist/node/plugins/astro-B5y1Gtbf.js +31 -0
- package/dist/node/plugins/astro.js +26 -0
- package/dist/node/plugins/git-BIXLbL3f.js +92 -0
- package/dist/node/plugins/jsx-Bg4BdSph.js +7958 -0
- package/dist/node/plugins/next.js +48 -0
- package/dist/node/plugins/options-THop1K92.js +71 -0
- package/dist/node/plugins/transform-CKiAuSbk.js +1155 -0
- package/dist/node/plugins/vite-BdAYUW10.js +74 -0
- package/dist/node/plugins/vite.js +1 -0
- package/dist/node/plugins/webpack-R2U2DLlY.js +35 -0
- package/dist/node/plugins/webpack-loader.cjs +21 -0
- package/dist/node/plugins/webpack-loader.js +18 -0
- package/dist/node/plugins/webpack.js +1 -0
- package/dist/node/shared/endpoint.js +26 -0
- package/dist/node/shared/format.js +63 -0
- package/dist/node/types/astro.d.ts +11 -0
- package/dist/node/types/next.d.ts +34 -0
- package/dist/node/types/options.d.ts +59 -0
- package/dist/node/types/vite.d.ts +11 -0
- package/dist/node/types/webpack-loader.d.ts +22 -0
- package/dist/node/types/webpack.d.ts +27 -0
- package/dist/npm/THIRD_PARTY_NOTICES.txt +6 -6
- package/dist/npm/chunks/AgentSend-DxRJIYiz.js +68 -0
- package/dist/npm/chunks/Checklist-CnlfeSbc.js +282 -0
- package/dist/npm/chunks/Composer-B1bBVszY.js +725 -0
- package/dist/npm/chunks/Guest-vvNPz8h-.js +267 -0
- package/dist/npm/chunks/MarkupEditor-VCOXh9d2.js +338 -0
- package/dist/npm/chunks/Panel-F37vIL1K.js +1206 -0
- package/dist/npm/chunks/Settings-BGoZS2iV.js +231 -0
- package/dist/npm/chunks/Shortcuts-B2OMvczr.js +62 -0
- package/dist/npm/chunks/StyleEditor-CJ_d8Huf.js +46 -0
- package/dist/npm/chunks/StylePanel-yQzHHlY7.js +199 -0
- package/dist/npm/chunks/TaskFields-fmy6_HtK.js +289 -0
- package/dist/npm/chunks/ThreadCard-D51slKST.js +1113 -0
- package/dist/npm/chunks/Viewer-BOBadqmC.js +111 -0
- package/dist/npm/chunks/{agent-BDMQtOzH.js → agent-C1OQzBAm.js} +9 -9
- package/dist/npm/chunks/{anchor-BsradQhn.js → anchor-BsQNVkHj.js} +108 -85
- package/dist/npm/chunks/{ar-8tPch6W4.js → ar-CAJ3XT8e.js} +69 -19
- package/dist/npm/chunks/card-bits-CAnzrqx3.js +53 -0
- package/dist/npm/chunks/{client-EFTWxHbJ.js → client-kNAo2TTG.js} +282 -290
- package/dist/npm/chunks/confetti-CkBdSu19.js +49 -0
- package/dist/npm/chunks/context-B8UAzve0.js +20 -0
- package/dist/npm/chunks/context-BuMl7A07.js +48 -0
- package/dist/npm/chunks/{de-C63897uD.js → de-Dl18G48t.js} +60 -18
- package/dist/npm/chunks/dialog-GO04oC3D.js +3 -0
- package/dist/npm/chunks/dpop-U48QIQd7.js +96 -0
- package/dist/npm/chunks/drafts-B0ctr1g9.js +21 -0
- package/dist/npm/chunks/{es-CI2bSpvB.js → es-Dxk79lS9.js} +60 -18
- package/dist/npm/chunks/extension-CKFpPWmi.js +62 -0
- package/dist/npm/chunks/{extension-BST6LH1q.js → extension-E81hWyiT.js} +20 -12
- package/dist/npm/chunks/files-DyD5BZgp.js +114 -0
- package/dist/npm/chunks/{fr-rsVe-Lqk.js → fr-8BebGKYD.js} +118 -76
- package/dist/npm/chunks/{hi-cvwbSaWP.js → hi-BIN6Yy_p.js} +61 -19
- package/dist/npm/chunks/{i18n-C4v0M-6z.js → i18n-DOBt8e9U.js} +91 -56
- package/dist/npm/chunks/identify-CN-3xzqL.js +106 -0
- package/dist/npm/chunks/{it-C8tnV0BF.js → it-Cr6EwpPQ.js} +79 -37
- package/dist/npm/chunks/{ja-BWxDfC2f.js → ja-Iy3s5aur.js} +58 -16
- package/dist/npm/chunks/late-words-B2bmZceJ.js +12 -0
- package/dist/npm/chunks/live-CelVeZfP.js +85 -0
- package/dist/npm/chunks/locale-D8Q4Q2Nt.js +26 -0
- package/dist/npm/chunks/{nl-DNQ6eCht.js → nl-B84WHqqe.js} +61 -19
- package/dist/npm/chunks/page-key-DepmJzC1.js +62 -0
- package/dist/npm/chunks/{pick-CLyOdjnD.js → pick-yTyqtxN0.js} +45 -44
- package/dist/npm/chunks/pkce-ChKGSW_4.js +8 -0
- package/dist/npm/chunks/placement-BF_HOUDD.js +74 -0
- package/dist/npm/chunks/privacy-BWUGlHw5.js +57 -0
- package/dist/npm/chunks/{pt-BR-CkG7vpU2.js → pt-BR-DOkdlfoe.js} +60 -18
- package/dist/npm/chunks/{realtime-DIo-Wth4.js → realtime-C79zF50C.js} +14 -12
- package/dist/npm/chunks/report-CrIqQZDI.js +44 -0
- package/dist/npm/chunks/show-BgVC8gWY.js +97 -0
- package/dist/npm/chunks/signin-Dd1rb2BP.js +75 -0
- package/dist/npm/chunks/{source-CS7C6wJA.js → source-pXVve2Cx.js} +1 -1
- package/dist/npm/chunks/src-BTMy4Gyc.js +208 -0
- package/dist/npm/chunks/start-DtVlpt7p.js +1878 -0
- package/dist/npm/chunks/states-sfTbjZz8.js +3 -0
- package/dist/npm/chunks/upload-MgPYqPyE.js +42 -0
- package/dist/npm/chunks/uploads-D49mywwz.js +1146 -0
- package/dist/npm/chunks/wrap-Bl0gbnFa.js +69 -0
- package/dist/npm/chunks/{zh-CN-BKuZOLBE.js → zh-CN-Z5fQCb7G.js} +59 -17
- package/dist/npm/element.js +58 -21
- package/dist/npm/headless.js +7 -3
- package/dist/npm/index.js +3 -3
- package/dist/npm/react.js +18 -11
- package/dist/npm/svelte.js +28 -12
- package/dist/npm/types/adapters/react.d.ts +4 -1
- package/dist/npm/types/adapters/svelte.d.ts +4 -1
- package/dist/npm/types/adapters/vue.d.ts +35 -2
- package/dist/npm/types/anchor/index.d.ts +19 -0
- package/dist/npm/types/capture/privacy.d.ts +14 -0
- package/dist/npm/types/core/api.d.ts +20 -1
- package/dist/npm/types/core/auth.d.ts +40 -21
- package/dist/npm/types/core/client.d.ts +60 -4
- package/dist/npm/types/core/page-key.d.ts +42 -0
- package/dist/npm/types/core/types.d.ts +87 -4
- package/dist/npm/types/element.d.ts +17 -7
- package/dist/npm/types/headless.d.ts +2 -1
- package/dist/npm/types/index.d.ts +16 -6
- package/dist/npm/vue.js +44 -9
- package/package.json +88 -14
- package/dist/npm/chunks/AgentSend-2JPDseOo.js +0 -63
- package/dist/npm/chunks/Checklist-BpDXQebo.js +0 -257
- package/dist/npm/chunks/Composer-CAyj-c8e.js +0 -677
- package/dist/npm/chunks/Guest-ZdFmTcXI.js +0 -187
- package/dist/npm/chunks/MarkupEditor-BFplZwFy.js +0 -332
- package/dist/npm/chunks/Panel-BhZ4XRDR.js +0 -861
- package/dist/npm/chunks/Settings-SPG9EHUZ.js +0 -204
- package/dist/npm/chunks/Shortcuts-C28HVDw6.js +0 -58
- package/dist/npm/chunks/StyleEditor-ByZMtq10.js +0 -43
- package/dist/npm/chunks/StylePanel-Iwhce2tE.js +0 -197
- package/dist/npm/chunks/TaskFields-BsP_fVJg.js +0 -273
- package/dist/npm/chunks/ThreadCard-BzVZdDCb.js +0 -1030
- package/dist/npm/chunks/Viewer-CqtGrdD8.js +0 -108
- package/dist/npm/chunks/card-bits-Bna-g3Py.js +0 -124
- package/dist/npm/chunks/confetti-DTKpwF3O.js +0 -40
- package/dist/npm/chunks/drafts-akdBsOd0.js +0 -50
- package/dist/npm/chunks/extension-D-V3utTm.js +0 -53
- package/dist/npm/chunks/live-BCpJVBeN.js +0 -33
- package/dist/npm/chunks/report-BBrT3r89.js +0 -27
- package/dist/npm/chunks/src-C4FsVoUp.js +0 -148
- package/dist/npm/chunks/start-i9M-r3aH.js +0 -1800
- package/dist/npm/chunks/upload-DSv7EyBD.js +0 -41
- package/dist/npm/chunks/uploads-I01kdqQF.js +0 -1103
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
// The `commentkit` command.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { CliError, endpointFrom, pollDevice, Project, registerClient, SIGN_IN_AGAIN, startDevice } from "./api.js";
|
|
8
|
+
import { forget, load, save } from "./credentials.js";
|
|
9
|
+
import { doctor, render } from "./doctor.js";
|
|
10
|
+
import { feedbackMarkdown } from "./format.js";
|
|
11
|
+
import { ignoreFolder, plan, setEnv } from "./init.js";
|
|
12
|
+
import { AGENTS, backup, configPath, DEFAULT_SCOPE, entry, mergeJson, mergeToml, NEXT_STEP, readIfExists, writeAtomic } from "./mcp.js";
|
|
13
|
+
import { openUrl } from "./open.js";
|
|
14
|
+
/** The publishable key format; a test keeps it equal to the pattern in contract/openapi-v1.yaml. */
|
|
15
|
+
export const PUBLISHABLE_KEY = /^pk_(live|test)_[a-z0-9]{20,40}$/;
|
|
16
|
+
const HELP = `CommentKit in your terminal.
|
|
17
|
+
|
|
18
|
+
Usage: npx @commentkit/comment-kit <command> [options]
|
|
19
|
+
|
|
20
|
+
login Sign in with your browser and choose a project
|
|
21
|
+
logout Forget the sign-in on this computer
|
|
22
|
+
status Show who and which project you are signed in to
|
|
23
|
+
init Add the key, the build plugin and the widget to your app
|
|
24
|
+
doctor [url] Find out why the widget is not showing (this folder and your site)
|
|
25
|
+
pull Save open feedback and tasks to .commentkit/feedback.md
|
|
26
|
+
open [CK-12] Open a task (or the task board) in the browser
|
|
27
|
+
token list|create|revoke Manage tokens for CI
|
|
28
|
+
mcp install <agent> Add CommentKit to Cursor, VS Code, Claude Code or Codex
|
|
29
|
+
|
|
30
|
+
Options:
|
|
31
|
+
--help Show help for a command (npx @commentkit/comment-kit init --help)
|
|
32
|
+
--yes (init, mcp install) Apply every change without asking
|
|
33
|
+
--dry-run (init, mcp install) Show what would change, change nothing
|
|
34
|
+
--install (init) Also install the package
|
|
35
|
+
--key <pk_…> (init, doctor) Use this project key without signing in
|
|
36
|
+
--all (pull) Include resolved feedback
|
|
37
|
+
--out <file> (pull) Where to write (default .commentkit/feedback.md)
|
|
38
|
+
--json (pull, token list, status, doctor) Print JSON
|
|
39
|
+
--reply, --status (token create) Let the token reply / mark ready for review
|
|
40
|
+
--days <n> (token create) Days until it expires (default 30, up to 90)
|
|
41
|
+
|
|
42
|
+
CI: set COMMENTKIT_TOKEN and COMMENTKIT_PROJECT_ID instead of logging in.
|
|
43
|
+
Another server: set COMMENTKIT_ENDPOINT (default https://commentkit.dev).
|
|
44
|
+
`;
|
|
45
|
+
const COMMAND_HELP = {
|
|
46
|
+
login: `Usage: npx @commentkit/comment-kit login [--no-browser] [--scopes read,reply,status]
|
|
47
|
+
|
|
48
|
+
Shows a short code and opens CommentKit in your browser. Confirm the code, then choose
|
|
49
|
+
the project and what the CLI may do.
|
|
50
|
+
|
|
51
|
+
--no-browser Print the link instead of opening it
|
|
52
|
+
--scopes <list> What to ask for (default read,reply,status)`,
|
|
53
|
+
logout: `Usage: npx @commentkit/comment-kit logout
|
|
54
|
+
|
|
55
|
+
Forgets the sign-in on this computer. To end it on the server too, disconnect it in
|
|
56
|
+
CommentKit under Settings > Sessions.`,
|
|
57
|
+
status: `Usage: npx @commentkit/comment-kit status [--json]
|
|
58
|
+
|
|
59
|
+
Which project you are signed in to, what the CLI may do, and whether agent changes wait
|
|
60
|
+
for a person's approval.
|
|
61
|
+
|
|
62
|
+
--json Print JSON`,
|
|
63
|
+
init: `Usage: npx @commentkit/comment-kit init [--yes] [--dry-run] [--install] [--key pk_…]
|
|
64
|
+
|
|
65
|
+
Finds your framework (Next.js, Vite, SvelteKit, Astro, Nuxt or a plain website) and sets
|
|
66
|
+
CommentKit up: the key in your env file, the build plugin in your config, .commentkit/ in
|
|
67
|
+
.gitignore, and the widget in your layout or entry file. Asks before each change.
|
|
68
|
+
|
|
69
|
+
--yes, -y Make every change without asking
|
|
70
|
+
--dry-run Show what would change, change nothing
|
|
71
|
+
--install Also install the package
|
|
72
|
+
--key <pk_…> Use this project key without signing in`,
|
|
73
|
+
doctor: `Usage: npx @commentkit/comment-kit doctor [url] [--key pk_…] [--json]
|
|
74
|
+
|
|
75
|
+
Finds out why the widget is not showing. Checks the package or script tag and the key in this
|
|
76
|
+
folder, and the key with CommentKit (unknown, paused or read-only). With your site's address it
|
|
77
|
+
also checks that the site is on the project's allowed websites, that the page has CommentKit,
|
|
78
|
+
and that its Content Security Policy lets CommentKit load. Sends no cookies or passwords.
|
|
79
|
+
Exits 0 when nothing is wrong, 1 when something is.
|
|
80
|
+
|
|
81
|
+
url Your website, http:// or https:// (for example https://staging.acme.com)
|
|
82
|
+
--key <pk_…> Check this project key instead of the one found in this folder
|
|
83
|
+
--json Print the result as JSON`,
|
|
84
|
+
pull: `Usage: npx @commentkit/comment-kit pull [--all] [--out <file>] [--json]
|
|
85
|
+
|
|
86
|
+
Saves open feedback and tasks to .commentkit/feedback.md for your coding agent. Reviewer
|
|
87
|
+
text is fenced as untrusted content.
|
|
88
|
+
|
|
89
|
+
--all Include resolved feedback
|
|
90
|
+
--out <file> Where to write (default .commentkit/feedback.md)
|
|
91
|
+
--json Print JSON instead`,
|
|
92
|
+
open: `Usage: npx @commentkit/comment-kit open [CK-12]
|
|
93
|
+
|
|
94
|
+
Opens the task in your browser, or the task board without a reference.`,
|
|
95
|
+
token: `Usage: npx @commentkit/comment-kit token list [--json]
|
|
96
|
+
npx @commentkit/comment-kit token create "<name>" [--reply] [--status] [--days <n>]
|
|
97
|
+
npx @commentkit/comment-kit token revoke <id>
|
|
98
|
+
|
|
99
|
+
Tokens for CI (COMMENTKIT_TOKEN), never with more permissions than your sign-in.
|
|
100
|
+
|
|
101
|
+
--reply Let the token reply to feedback
|
|
102
|
+
--status Let the token mark feedback ready for review and link commits
|
|
103
|
+
--days <n> Days until it expires (default 30, 1 to 90)
|
|
104
|
+
--json (list) Print JSON`,
|
|
105
|
+
mcp: `Usage: npx @commentkit/comment-kit mcp install <cursor|vscode|claude|codex> [--scope user|project] [--dry-run] [--yes]
|
|
106
|
+
|
|
107
|
+
Adds the hosted CommentKit MCP server (https://commentkit.dev/mcp) to your coding agent's
|
|
108
|
+
config file. Nothing else in the file changes, and it is backed up first. Your agent asks
|
|
109
|
+
you to sign in the first time.
|
|
110
|
+
|
|
111
|
+
cursor ~/.cursor/mcp.json (--scope project: .cursor/mcp.json)
|
|
112
|
+
vscode .vscode/mcp.json (--scope user: your VS Code profile's mcp.json)
|
|
113
|
+
claude ~/.claude.json (--scope project: .mcp.json)
|
|
114
|
+
codex ~/.codex/config.toml
|
|
115
|
+
|
|
116
|
+
--scope <s> user or project (defaults above)
|
|
117
|
+
--dry-run Show the change, write nothing
|
|
118
|
+
--yes, -y Replace an existing commentkit entry without asking`,
|
|
119
|
+
};
|
|
120
|
+
COMMAND_HELP.whoami = COMMAND_HELP.status;
|
|
121
|
+
COMMAND_HELP.tokens = COMMAND_HELP.token;
|
|
122
|
+
const console_ = { log: (t) => process.stdout.write(`${t}\n`), error: (t) => process.stderr.write(`${t}\n`) };
|
|
123
|
+
export async function main(argv, out = console_, cwd = process.cwd()) {
|
|
124
|
+
const [command, ...rest] = argv;
|
|
125
|
+
if (!command || command === "--help" || command === "-h" || command === "help") {
|
|
126
|
+
out.log(HELP);
|
|
127
|
+
return 0;
|
|
128
|
+
}
|
|
129
|
+
// Per-command help never needs a sign-in or the network.
|
|
130
|
+
if (rest.includes("--help") || rest.includes("-h")) {
|
|
131
|
+
out.log(COMMAND_HELP[command] ?? HELP);
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
switch (command) {
|
|
136
|
+
case "login":
|
|
137
|
+
return await login(rest, out);
|
|
138
|
+
case "logout":
|
|
139
|
+
return await logout(out);
|
|
140
|
+
case "status":
|
|
141
|
+
case "whoami":
|
|
142
|
+
return await status(rest, out);
|
|
143
|
+
case "init":
|
|
144
|
+
return await init(rest, out, cwd);
|
|
145
|
+
case "pull":
|
|
146
|
+
return await pull(rest, out, cwd);
|
|
147
|
+
case "doctor":
|
|
148
|
+
return await runDoctor(rest, out, cwd);
|
|
149
|
+
case "open":
|
|
150
|
+
return await open(rest, out);
|
|
151
|
+
case "token":
|
|
152
|
+
case "tokens":
|
|
153
|
+
return await token(rest, out);
|
|
154
|
+
case "mcp":
|
|
155
|
+
return await mcp(rest, out, cwd);
|
|
156
|
+
case "--version":
|
|
157
|
+
case "-v":
|
|
158
|
+
out.log(version());
|
|
159
|
+
return 0;
|
|
160
|
+
default:
|
|
161
|
+
out.error(`Unknown command “${command}”. Run npx @commentkit/comment-kit --help.`);
|
|
162
|
+
return 2;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
// node:util parseArgs: an unknown option or a missing value is a usage mistake, not a crash.
|
|
167
|
+
if (error instanceof Error && String(error.code).startsWith("ERR_PARSE_ARGS")) {
|
|
168
|
+
out.error(`${error.message} Run npx @commentkit/comment-kit ${command} --help.`);
|
|
169
|
+
return 2;
|
|
170
|
+
}
|
|
171
|
+
out.error(error instanceof CliError || error instanceof Error ? `Error: ${error.message}` : String(error));
|
|
172
|
+
return 1;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function version() {
|
|
176
|
+
try {
|
|
177
|
+
// dist/node/cli/main.js → the package root.
|
|
178
|
+
return JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8")).version;
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return "unknown";
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
185
|
+
async function login(args, out) {
|
|
186
|
+
const { values } = parseArgs({ args, options: { "no-browser": { type: "boolean" }, scopes: { type: "string" } }, allowPositionals: false });
|
|
187
|
+
const endpoint = endpointFrom();
|
|
188
|
+
let clientId = load(endpoint).client_id;
|
|
189
|
+
if (!clientId) {
|
|
190
|
+
clientId = await registerClient(endpoint);
|
|
191
|
+
await save(endpoint, { client_id: clientId });
|
|
192
|
+
}
|
|
193
|
+
const wanted = (values.scopes ?? "read,reply,status").split(",").map((s) => s.trim()).filter(Boolean);
|
|
194
|
+
const scope = ["feedback:read", ...wanted.filter((s) => s !== "read").map((s) => `feedback:${s}`)].join(" ");
|
|
195
|
+
let device;
|
|
196
|
+
try {
|
|
197
|
+
device = await startDevice(endpoint, clientId, scope);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (error instanceof CliError && error.code === "invalid_client") {
|
|
201
|
+
clientId = await registerClient(endpoint);
|
|
202
|
+
await save(endpoint, { client_id: clientId });
|
|
203
|
+
device = await startDevice(endpoint, clientId, scope);
|
|
204
|
+
}
|
|
205
|
+
else
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
// Only the plain page is opened: a link with the code already in it is a phishing path (someone could send
|
|
209
|
+
// their own link), so the person types the code they see here. Never a URL built with the code.
|
|
210
|
+
out.log(`\nYour code: ${device.user_code}\n`);
|
|
211
|
+
out.log(`Type this code on ${device.verification_uri}, then choose the project.`);
|
|
212
|
+
if (!values["no-browser"] && (await openUrl(device.verification_uri)))
|
|
213
|
+
out.log("(Opened that page in your browser.)");
|
|
214
|
+
out.log("Waiting for you to confirm…");
|
|
215
|
+
let interval = Math.max(1, device.interval) * 1000;
|
|
216
|
+
const deadline = Date.now() + device.expires_in * 1000;
|
|
217
|
+
while (Date.now() < deadline) {
|
|
218
|
+
await sleep(interval);
|
|
219
|
+
const answer = await pollDevice(endpoint, clientId, device.device_code);
|
|
220
|
+
if (typeof answer !== "string")
|
|
221
|
+
return finishLogin(endpoint, clientId, answer, out);
|
|
222
|
+
if (answer === "authorization_pending")
|
|
223
|
+
continue;
|
|
224
|
+
if (answer === "slow_down") {
|
|
225
|
+
interval += 5000;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (answer === "access_denied")
|
|
229
|
+
throw new CliError("Sign-in was cancelled in the browser.");
|
|
230
|
+
if (answer === "expired_token")
|
|
231
|
+
break;
|
|
232
|
+
if (answer === "invalid_client")
|
|
233
|
+
throw new CliError(SIGN_IN_AGAIN, "signed_out");
|
|
234
|
+
throw new CliError(`Sign-in failed (${answer}). Run npx @commentkit/comment-kit login again.`);
|
|
235
|
+
}
|
|
236
|
+
throw new CliError("The code expired before it was confirmed. Run npx @commentkit/comment-kit login again.");
|
|
237
|
+
}
|
|
238
|
+
async function finishLogin(endpoint, clientId, answer, out) {
|
|
239
|
+
if (!answer.project?.id)
|
|
240
|
+
throw new CliError("Signed in, but CommentKit did not say which project was chosen. Update the CLI and try again.");
|
|
241
|
+
await save(endpoint, {
|
|
242
|
+
client_id: clientId,
|
|
243
|
+
access_token: answer.access_token,
|
|
244
|
+
refresh_token: answer.refresh_token,
|
|
245
|
+
expires_at: Date.now() + answer.expires_in * 1000,
|
|
246
|
+
scope: answer.scope,
|
|
247
|
+
project_id: answer.project.id,
|
|
248
|
+
project_name: answer.project.name,
|
|
249
|
+
});
|
|
250
|
+
out.log(`\nSigned in. Project: ${answer.project.name}. Allowed: ${permissions(answer.scope)}.`);
|
|
251
|
+
return 0;
|
|
252
|
+
}
|
|
253
|
+
function permissions(scope) {
|
|
254
|
+
const parts = scope.split(" ");
|
|
255
|
+
return ["read", parts.includes("feedback:reply") ? "reply" : null, parts.includes("feedback:status") ? "status and commit links" : null, parts.includes("cli") ? "CI tokens" : null].filter(Boolean).join(", ");
|
|
256
|
+
}
|
|
257
|
+
async function logout(out) {
|
|
258
|
+
// CommentKit has no endpoint yet for a terminal sign-in to end itself, so this is local only.
|
|
259
|
+
const had = await forget(endpointFrom());
|
|
260
|
+
out.log(had
|
|
261
|
+
? "Signed out on this computer. The sign-in still works on the server until it expires (30 days unused); to end it now, disconnect it in CommentKit under Settings > Sessions."
|
|
262
|
+
: "You were not signed in.");
|
|
263
|
+
return 0;
|
|
264
|
+
}
|
|
265
|
+
async function status(args, out) {
|
|
266
|
+
const { values } = parseArgs({ args, options: { json: { type: "boolean" } } });
|
|
267
|
+
const endpoint = endpointFrom();
|
|
268
|
+
const project = await Project.connect(endpoint);
|
|
269
|
+
const info = await project.request("");
|
|
270
|
+
const credential = load(endpoint);
|
|
271
|
+
if (values.json) {
|
|
272
|
+
out.log(JSON.stringify({ endpoint, project: info.data, scope: credential.scope ?? null }, null, 2));
|
|
273
|
+
return 0;
|
|
274
|
+
}
|
|
275
|
+
out.log(`Endpoint: ${endpoint}`);
|
|
276
|
+
out.log(`Project: ${String(info.data.name)} (id ${project.projectId})`);
|
|
277
|
+
if (credential.scope)
|
|
278
|
+
out.log(`Allowed: ${permissions(credential.scope)}`);
|
|
279
|
+
out.log(`Agent changes ${info.data.agent_approval ? "wait for a person's approval" : "apply right away"}.`);
|
|
280
|
+
return 0;
|
|
281
|
+
}
|
|
282
|
+
async function ask(question, yes) {
|
|
283
|
+
if (yes)
|
|
284
|
+
return true;
|
|
285
|
+
if (!process.stdin.isTTY)
|
|
286
|
+
return false;
|
|
287
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
288
|
+
try {
|
|
289
|
+
return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
rl.close();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function run(command, cwd) {
|
|
296
|
+
return new Promise((resolve) => {
|
|
297
|
+
const child = spawn(command[0], command.slice(1), { cwd, stdio: "inherit", shell: process.platform === "win32" });
|
|
298
|
+
child.on("error", () => resolve(1));
|
|
299
|
+
child.on("exit", (code) => resolve(code ?? 1));
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
async function init(args, out, cwd) {
|
|
303
|
+
const { values } = parseArgs({ args, options: { yes: { type: "boolean", short: "y" }, install: { type: "boolean" }, key: { type: "string" }, "dry-run": { type: "boolean" } } });
|
|
304
|
+
const yes = Boolean(values.yes);
|
|
305
|
+
const dryRun = Boolean(values["dry-run"]);
|
|
306
|
+
let key = values.key;
|
|
307
|
+
if (!key) {
|
|
308
|
+
const info = await (await Project.connect()).request("");
|
|
309
|
+
key = info.data.publishable_keys.live ?? info.data.publishable_keys.test ?? undefined;
|
|
310
|
+
if (!key)
|
|
311
|
+
throw new CliError("This project has no publishable key yet. Open Setup in CommentKit once, then try again.");
|
|
312
|
+
out.log(`Project: ${info.data.name}`);
|
|
313
|
+
}
|
|
314
|
+
if (!PUBLISHABLE_KEY.test(key))
|
|
315
|
+
throw new CliError("That is not a publishable key (pk_live_… or pk_test_…).");
|
|
316
|
+
const p = plan(cwd, key);
|
|
317
|
+
out.log(`Found ${p.label}.${dryRun ? " Dry run: nothing is changed." : ""}\n`);
|
|
318
|
+
let skipped = 0;
|
|
319
|
+
// Each change is shown and confirmed (or --yes) before it is written; --dry-run only shows it.
|
|
320
|
+
const change = async (file, before, after, question) => {
|
|
321
|
+
if (after === before)
|
|
322
|
+
return;
|
|
323
|
+
if (dryRun) {
|
|
324
|
+
out.log(`Would ${before ? "change" : "create"} ${file}:\n${addedLines(before, after)}\n`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (await ask(question, yes)) {
|
|
328
|
+
mkdirSync(dirname(join(cwd, file)), { recursive: true });
|
|
329
|
+
writeFileSync(join(cwd, file), after);
|
|
330
|
+
}
|
|
331
|
+
else
|
|
332
|
+
skipped++;
|
|
333
|
+
};
|
|
334
|
+
const readOr = (file) => (existsSync(join(cwd, file)) ? readFileSync(join(cwd, file), "utf8") : "");
|
|
335
|
+
if (p.envVar) {
|
|
336
|
+
const before = readOr(p.envFile);
|
|
337
|
+
await change(p.envFile, before, setEnv(before, p.envVar, key), `Add ${p.envVar} to ${p.envFile}?`);
|
|
338
|
+
}
|
|
339
|
+
const ignoreBefore = readOr(".gitignore");
|
|
340
|
+
await change(".gitignore", ignoreBefore, ignoreFolder(ignoreBefore), "Add .commentkit/ to .gitignore (pulled feedback stays on your computer)?");
|
|
341
|
+
if (p.configFile && p.configEdit) {
|
|
342
|
+
await change(p.configFile, readOr(p.configFile), p.configEdit, `Add the CommentKit build plugin to ${p.configFile}?`);
|
|
343
|
+
}
|
|
344
|
+
else if (p.configFile && !p.configEdit) {
|
|
345
|
+
out.log(`Could not edit ${p.configFile} safely, so it was left as it is. Add the build plugin by hand:\n ${p.configSnippet}\n(more: https://commentkit.dev/docs/frameworks)`);
|
|
346
|
+
}
|
|
347
|
+
if (p.entry && p.entry !== "done") {
|
|
348
|
+
const { file, content, created } = p.entry;
|
|
349
|
+
await change(file, created ? "" : readOr(file), content, created ? `Create ${file} to show the widget?` : `Show the widget: add it to ${file}?`);
|
|
350
|
+
}
|
|
351
|
+
for (const line of p.manual)
|
|
352
|
+
out.log(`By hand: ${line}`);
|
|
353
|
+
if (p.install.length) {
|
|
354
|
+
if (values.install && !dryRun) {
|
|
355
|
+
for (const command of p.install) {
|
|
356
|
+
out.log(`$ ${command.join(" ")}`);
|
|
357
|
+
if ((await run(command, cwd)) !== 0)
|
|
358
|
+
throw new CliError(`${command.join(" ")} failed.`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
out.log("\nInstall the package:");
|
|
363
|
+
for (const command of p.install)
|
|
364
|
+
out.log(` ${command.join(" ")}`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (p.entry === "done")
|
|
368
|
+
out.log("\nThe widget is already in your app.");
|
|
369
|
+
else if (!p.entry)
|
|
370
|
+
out.log(`\nLast step, show the widget. ${p.snippet}\n`);
|
|
371
|
+
if (dryRun) {
|
|
372
|
+
out.log("\nRun it again without --dry-run to make these changes.");
|
|
373
|
+
return 0;
|
|
374
|
+
}
|
|
375
|
+
if (skipped && !process.stdin.isTTY && !yes)
|
|
376
|
+
out.log(`${skipped} change(s) were not made. Run npx @commentkit/comment-kit init --yes to apply them.`);
|
|
377
|
+
out.log("Then start your dev server: the Comment button appears on localhost for your team.");
|
|
378
|
+
return 0;
|
|
379
|
+
}
|
|
380
|
+
/** The lines `after` adds to `before`, marked with +, for a dry run. */
|
|
381
|
+
export function addedLines(before, after) {
|
|
382
|
+
const old = new Set(before.split("\n"));
|
|
383
|
+
return after.split("\n").filter((line) => !old.has(line)).map((line) => ` + ${line}`).join("\n");
|
|
384
|
+
}
|
|
385
|
+
async function mcp(args, out, cwd) {
|
|
386
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { scope: { type: "string" }, "dry-run": { type: "boolean" }, yes: { type: "boolean", short: "y" } } });
|
|
387
|
+
const [sub, agent] = positionals;
|
|
388
|
+
if (sub !== "install")
|
|
389
|
+
throw new CliError("Use: npx @commentkit/comment-kit mcp install <cursor|vscode|claude|codex>");
|
|
390
|
+
if (!AGENTS.includes(agent))
|
|
391
|
+
throw new CliError(`Which agent? Use one of: ${AGENTS.join(", ")}.`);
|
|
392
|
+
const target = agent;
|
|
393
|
+
if (values.scope !== undefined && values.scope !== "user" && values.scope !== "project")
|
|
394
|
+
throw new CliError("--scope is user or project.");
|
|
395
|
+
const scope = values.scope ?? DEFAULT_SCOPE[target];
|
|
396
|
+
const url = `${endpointFrom()}/mcp`;
|
|
397
|
+
const file = configPath(target, scope, cwd);
|
|
398
|
+
const before = readIfExists(file);
|
|
399
|
+
let merged;
|
|
400
|
+
try {
|
|
401
|
+
merged = target === "codex" ? mergeToml(before, url) : mergeJson(before, target, url);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
const manual = target === "codex" ? `[mcp_servers.commentkit]\nurl = "${url}"` : JSON.stringify({ [target === "vscode" ? "servers" : "mcpServers"]: { commentkit: entry(target, url) } }, null, 2);
|
|
405
|
+
out.error(`Did not change ${file}: ${error instanceof Error ? error.message : String(error)}. Add this by hand:\n\n${manual}\n`);
|
|
406
|
+
return 1;
|
|
407
|
+
}
|
|
408
|
+
if (merged.status === "same") {
|
|
409
|
+
out.log(`CommentKit is already set up in ${file}.`);
|
|
410
|
+
out.log(NEXT_STEP[target]);
|
|
411
|
+
return 0;
|
|
412
|
+
}
|
|
413
|
+
if (values["dry-run"]) {
|
|
414
|
+
out.log(`Would ${before === null ? "create" : merged.status === "replaced" ? "replace the commentkit entry in" : "add CommentKit to"} ${file}:\n${addedLines(before ?? "", merged.content)}`);
|
|
415
|
+
out.log("\nRun it again without --dry-run to write it.");
|
|
416
|
+
return 0;
|
|
417
|
+
}
|
|
418
|
+
if (merged.status === "replaced" && !(await ask(`${file} already has a different commentkit entry. Replace it?`, Boolean(values.yes)))) {
|
|
419
|
+
out.log("Left it as it is. Use --yes to replace it.");
|
|
420
|
+
return 1;
|
|
421
|
+
}
|
|
422
|
+
const copy = before !== null ? backup(file) : null;
|
|
423
|
+
writeAtomic(file, merged.content);
|
|
424
|
+
out.log(`${merged.status === "replaced" ? "Replaced" : "Added"} CommentKit (${url}) in ${file}.${copy ? ` Backup: ${copy}` : ""}`);
|
|
425
|
+
out.log(NEXT_STEP[target]);
|
|
426
|
+
return 0;
|
|
427
|
+
}
|
|
428
|
+
async function runDoctor(args, out, cwd) {
|
|
429
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: "boolean" }, key: { type: "string" } } });
|
|
430
|
+
if (positionals.length > 1)
|
|
431
|
+
throw new CliError("Give one website address, for example: npx @commentkit/comment-kit doctor https://staging.acme.com");
|
|
432
|
+
const result = await doctor({ cwd, url: positionals[0], key: values.key });
|
|
433
|
+
if (values.json)
|
|
434
|
+
out.log(JSON.stringify(result, null, 2));
|
|
435
|
+
else
|
|
436
|
+
for (const line of render(result))
|
|
437
|
+
out.log(line);
|
|
438
|
+
return result.ok ? 0 : 1;
|
|
439
|
+
}
|
|
440
|
+
/** pull saves at most this many items (the most recently active first). */
|
|
441
|
+
const PULL_MAX = 500;
|
|
442
|
+
async function pull(args, out, cwd) {
|
|
443
|
+
const { values } = parseArgs({ args, options: { out: { type: "string" }, json: { type: "boolean" }, all: { type: "boolean" } } });
|
|
444
|
+
const project = await Project.connect();
|
|
445
|
+
const info = await project.request("");
|
|
446
|
+
const threads = [];
|
|
447
|
+
let cursor;
|
|
448
|
+
do {
|
|
449
|
+
const page = await project.request("/threads", { query: { kind: "all", status: values.all ? "all" : "active", limit: 100, cursor } });
|
|
450
|
+
threads.push(...page.data);
|
|
451
|
+
cursor = page.next_cursor ?? undefined;
|
|
452
|
+
} while (cursor && threads.length < PULL_MAX);
|
|
453
|
+
const more = Boolean(cursor);
|
|
454
|
+
if (values.json) {
|
|
455
|
+
out.log(JSON.stringify(threads, null, 2));
|
|
456
|
+
return 0;
|
|
457
|
+
}
|
|
458
|
+
const file = resolve(cwd, values.out ?? ".commentkit/feedback.md");
|
|
459
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
460
|
+
writeFileSync(file, feedbackMarkdown(info.data.name, threads, new Date(), more));
|
|
461
|
+
out.log(`Saved ${threads.length} item(s) to ${file}.${more ? ` There are more: only the ${PULL_MAX} with the latest activity were saved.` : ""}`);
|
|
462
|
+
return 0;
|
|
463
|
+
}
|
|
464
|
+
async function open(args, out) {
|
|
465
|
+
const ref = args[0];
|
|
466
|
+
if (ref && !/^(CK-)?\d{1,9}$/i.test(ref))
|
|
467
|
+
throw new CliError("Give a task reference like CK-12.");
|
|
468
|
+
const project = await Project.connect();
|
|
469
|
+
const info = await project.request("");
|
|
470
|
+
let url = info.data.tasks_url;
|
|
471
|
+
if (ref) {
|
|
472
|
+
const thread = await project.request(`/threads/${encodeURIComponent(ref.toUpperCase())}`);
|
|
473
|
+
url = `${info.data.tasks_url}?task=${encodeURIComponent(thread.data.id)}`;
|
|
474
|
+
}
|
|
475
|
+
out.log(url);
|
|
476
|
+
if (!(await openUrl(url)))
|
|
477
|
+
out.log("(Open the link above in your browser.)");
|
|
478
|
+
return 0;
|
|
479
|
+
}
|
|
480
|
+
async function token(args, out) {
|
|
481
|
+
const [sub, ...rest] = args;
|
|
482
|
+
const project = await Project.connect();
|
|
483
|
+
if (!sub || sub === "list") {
|
|
484
|
+
const { values } = parseArgs({ args: rest, options: { json: { type: "boolean" } } });
|
|
485
|
+
const list = await project.request("/tokens");
|
|
486
|
+
if (values.json)
|
|
487
|
+
out.log(JSON.stringify(list.data, null, 2));
|
|
488
|
+
else if (!list.data.length)
|
|
489
|
+
out.log("No agent tokens for this project.");
|
|
490
|
+
else
|
|
491
|
+
for (const t of list.data)
|
|
492
|
+
out.log(`${String(t.id).padEnd(6)} ${t.name.padEnd(28)} ${["read", ...t.scopes].join(",").padEnd(18)} ${t.expires_at ? `expires ${t.expires_at.slice(0, 10)}` : ""}`);
|
|
493
|
+
return 0;
|
|
494
|
+
}
|
|
495
|
+
if (sub === "create") {
|
|
496
|
+
const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { reply: { type: "boolean" }, status: { type: "boolean" }, days: { type: "string" } } });
|
|
497
|
+
const name = positionals.join(" ").trim();
|
|
498
|
+
if (!name)
|
|
499
|
+
throw new CliError('Give the token a name, for example: npx @commentkit/comment-kit token create "GitHub Actions" --status');
|
|
500
|
+
if (values.days !== undefined && !/^(?:[1-9]|[1-8]\d|90)$/.test(values.days.trim()))
|
|
501
|
+
throw new CliError("--days is a whole number from 1 to 90.");
|
|
502
|
+
const created = await project.request("/tokens", {
|
|
503
|
+
method: "POST",
|
|
504
|
+
body: { name, scopes: [values.reply ? "reply" : null, values.status ? "status" : null].filter(Boolean), ...(values.days ? { days: Number(values.days) } : {}) },
|
|
505
|
+
});
|
|
506
|
+
out.log(`Created “${created.data.name}” (id ${created.data.id}). It is shown only once:\n\n${created.data.token}\n`);
|
|
507
|
+
out.log(`In CI set COMMENTKIT_TOKEN to it and COMMENTKIT_PROJECT_ID=${project.projectId}.`);
|
|
508
|
+
return 0;
|
|
509
|
+
}
|
|
510
|
+
if (sub === "revoke") {
|
|
511
|
+
const id = Number(rest[0]);
|
|
512
|
+
if (!Number.isInteger(id) || id < 1)
|
|
513
|
+
throw new CliError("Give the token id from npx @commentkit/comment-kit token list.");
|
|
514
|
+
await project.request(`/tokens/${id}`, { method: "DELETE" });
|
|
515
|
+
out.log(`Revoked token ${id}.`);
|
|
516
|
+
return 0;
|
|
517
|
+
}
|
|
518
|
+
throw new CliError(`Unknown token command “${sub}”. Use list, create or revoke.`);
|
|
519
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// `npx @commentkit/comment-kit mcp install <agent>`: add the hosted MCP server to a coding agent's config file.
|
|
2
|
+
// Merges into what is there, backs the file up first, and never replaces an entry without asking.
|
|
3
|
+
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { CliError } from "./api.js";
|
|
7
|
+
export const AGENTS = ["cursor", "vscode", "claude", "codex"];
|
|
8
|
+
const NAME = "commentkit";
|
|
9
|
+
/** The scope each agent's own docs lead with. */
|
|
10
|
+
export const DEFAULT_SCOPE = { cursor: "user", vscode: "project", claude: "user", codex: "user" };
|
|
11
|
+
export const NEXT_STEP = {
|
|
12
|
+
cursor: "Restart Cursor (or open Settings > MCP) and sign in when it asks.",
|
|
13
|
+
vscode: "Open the file in VS Code, click Start above the commentkit entry, and sign in when it asks.",
|
|
14
|
+
claude: "Restart Claude Code, run /mcp and choose Authenticate.",
|
|
15
|
+
codex: "Run: codex mcp login commentkit",
|
|
16
|
+
};
|
|
17
|
+
export function configPath(agent, scope, cwd, env = process.env, platform = process.platform) {
|
|
18
|
+
const home = (platform === "win32" ? env.USERPROFILE : env.HOME) || homedir();
|
|
19
|
+
switch (agent) {
|
|
20
|
+
case "cursor":
|
|
21
|
+
return scope === "project" ? join(cwd, ".cursor", "mcp.json") : join(home, ".cursor", "mcp.json");
|
|
22
|
+
case "claude":
|
|
23
|
+
return scope === "project" ? join(cwd, ".mcp.json") : join(home, ".claude.json");
|
|
24
|
+
case "codex":
|
|
25
|
+
if (scope === "project")
|
|
26
|
+
throw new CliError("Codex reads MCP servers from ~/.codex/config.toml only. Leave out --scope project.");
|
|
27
|
+
return join(env.CODEX_HOME || join(home, ".codex"), "config.toml");
|
|
28
|
+
case "vscode": {
|
|
29
|
+
if (scope === "project")
|
|
30
|
+
return join(cwd, ".vscode", "mcp.json");
|
|
31
|
+
const base = platform === "darwin" ? join(home, "Library", "Application Support") : platform === "win32" ? (env.APPDATA ?? join(home, "AppData", "Roaming")) : (env.XDG_CONFIG_HOME || join(home, ".config"));
|
|
32
|
+
return join(base, "Code", "User", "mcp.json");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** The entry each agent expects for a remote (Streamable HTTP) server. */
|
|
37
|
+
export function entry(agent, url) {
|
|
38
|
+
return agent === "cursor" ? { url } : { type: "http", url };
|
|
39
|
+
}
|
|
40
|
+
/** Add or replace mcpServers.commentkit (servers.commentkit for VS Code), keeping everything else. */
|
|
41
|
+
export function mergeJson(text, agent, url) {
|
|
42
|
+
let root = {};
|
|
43
|
+
if (text !== null && text.trim() !== "") {
|
|
44
|
+
try {
|
|
45
|
+
root = JSON.parse(text);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new CliError("it is not plain JSON (comments or trailing commas?), so it was left alone");
|
|
49
|
+
}
|
|
50
|
+
if (!root || typeof root !== "object" || Array.isArray(root))
|
|
51
|
+
throw new CliError("it does not hold a JSON object, so it was left alone");
|
|
52
|
+
}
|
|
53
|
+
const key = agent === "vscode" ? "servers" : "mcpServers";
|
|
54
|
+
const servers = root[key] ?? {};
|
|
55
|
+
if (!servers || typeof servers !== "object" || Array.isArray(servers))
|
|
56
|
+
throw new CliError(`its "${key}" is not an object, so it was left alone`);
|
|
57
|
+
const wanted = entry(agent, url);
|
|
58
|
+
const current = servers[NAME];
|
|
59
|
+
if (current !== undefined && JSON.stringify(current) === JSON.stringify(wanted))
|
|
60
|
+
return { status: "same", content: text ?? "" };
|
|
61
|
+
root[key] = { ...servers, [NAME]: wanted };
|
|
62
|
+
return { status: current === undefined ? "added" : "replaced", content: `${JSON.stringify(root, null, 2)}\n` };
|
|
63
|
+
}
|
|
64
|
+
const TABLE = /^[ \t]*\[[ \t]*mcp_servers[ \t]*\.[ \t]*"?commentkit"?[ \t]*\][ \t]*(#.*)?$/m;
|
|
65
|
+
/** Add or replace [mcp_servers.commentkit] in Codex's config.toml, as text, so comments and layout stay. */
|
|
66
|
+
export function mergeToml(text, url) {
|
|
67
|
+
const source = text ?? "";
|
|
68
|
+
const block = `[mcp_servers.${NAME}]\nurl = ${JSON.stringify(url)}\n`;
|
|
69
|
+
// Other spellings (dotted keys, an inline table under [mcp_servers]) are left to a person.
|
|
70
|
+
const dotted = /^[ \t]*mcp_servers[ \t]*\.[ \t]*"?commentkit"?[ \t]*[.=]/m.test(source);
|
|
71
|
+
const inline = /^[ \t]*\[[ \t]*mcp_servers[ \t]*\][ \t]*$/m.test(source) && /^[ \t]*"?commentkit"?[ \t]*=/m.test(source);
|
|
72
|
+
if (dotted || inline)
|
|
73
|
+
throw new CliError("it already names commentkit in a form this command does not edit, so it was left alone");
|
|
74
|
+
const match = TABLE.exec(source);
|
|
75
|
+
if (!match) {
|
|
76
|
+
const sep = source === "" ? "" : source.endsWith("\n\n") ? "" : source.endsWith("\n") ? "\n" : "\n\n";
|
|
77
|
+
return { status: "added", content: `${source}${sep}${block}` };
|
|
78
|
+
}
|
|
79
|
+
// The table runs to the next header that is not one of its own sub-tables (such as .env).
|
|
80
|
+
const start = match.index;
|
|
81
|
+
const bodyStart = start + match[0].length;
|
|
82
|
+
const rest = source.slice(bodyStart);
|
|
83
|
+
const next = /^[ \t]*\[(?![ \t]*mcp_servers[ \t]*\.[ \t]*"?commentkit"?[ \t]*\.)/m.exec(rest);
|
|
84
|
+
const end = next ? bodyStart + next.index : source.length;
|
|
85
|
+
const current = source.slice(start, end);
|
|
86
|
+
const lines = current.split("\n").map((l) => l.replace(/#.*$/, "").trim()).filter(Boolean);
|
|
87
|
+
if (lines.length === 2 && lines[1].replace(/\s+/g, "") === `url=${JSON.stringify(url)}`)
|
|
88
|
+
return { status: "same", content: source };
|
|
89
|
+
const tail = source.slice(end);
|
|
90
|
+
return { status: "replaced", content: `${source.slice(0, start)}${block}${tail ? `\n${tail}` : ""}` };
|
|
91
|
+
}
|
|
92
|
+
/** A copy next to the file, named by the time, with the same permissions. */
|
|
93
|
+
export function backup(file, now = new Date()) {
|
|
94
|
+
const copy = `${file}.bak-${now.toISOString().replace(/[:.]/g, "-")}`;
|
|
95
|
+
copyFileSync(file, copy);
|
|
96
|
+
try {
|
|
97
|
+
chmodSync(copy, statSync(file).mode & 0o777);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// Windows: permissions come from the folder.
|
|
101
|
+
}
|
|
102
|
+
return copy;
|
|
103
|
+
}
|
|
104
|
+
/** Replace the file in one step, keeping its permissions. */
|
|
105
|
+
export function writeAtomic(file, content) {
|
|
106
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
107
|
+
const mode = existsSync(file) ? statSync(file).mode & 0o777 : 0o644;
|
|
108
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
109
|
+
writeFileSync(tmp, content, { mode });
|
|
110
|
+
renameSync(tmp, file);
|
|
111
|
+
}
|
|
112
|
+
export function readIfExists(file) {
|
|
113
|
+
return existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
114
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
/** Open a web address in the default browser, without a shell. Returns false when it could not. */
|
|
3
|
+
export function openUrl(url) {
|
|
4
|
+
if (!/^https?:\/\//.test(url) || process.env.COMMENTKIT_NO_BROWSER)
|
|
5
|
+
return Promise.resolve(false);
|
|
6
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
7
|
+
return new Promise((resolve) => {
|
|
8
|
+
try {
|
|
9
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
10
|
+
child.on("error", () => resolve(false));
|
|
11
|
+
child.on("spawn", () => {
|
|
12
|
+
child.unref();
|
|
13
|
+
resolve(true);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
resolve(false);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|