@commentkit/comment-kit 2.0.1 → 2.1.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +14 -6
  3. package/dist/node/cli/api.js +61 -15
  4. package/dist/node/cli/credentials.js +8 -0
  5. package/dist/node/cli/doctor.js +68 -5
  6. package/dist/node/cli/main.js +275 -52
  7. package/dist/node/cli/website.js +140 -0
  8. package/dist/node/types/next.d.ts +4 -4
  9. package/dist/npm/THIRD_PARTY_NOTICES.txt +47 -0
  10. package/dist/npm/chunks/{AgentSend-DOy3jhyF.js → AgentSend-pA7Ufvye.js} +3 -3
  11. package/dist/npm/chunks/Checklist-Cn9skOYK.js +269 -0
  12. package/dist/npm/chunks/Composer-D7H-pzGa.js +734 -0
  13. package/dist/npm/chunks/DatePicker-Nta5a1xD.js +161 -0
  14. package/dist/npm/chunks/{Guest-7hcN765o.js → Guest-Bi7hlzhs.js} +18 -17
  15. package/dist/npm/chunks/{MarkupEditor-6bJGpWGO.js → MarkupEditor-WU3USeTk.js} +2 -2
  16. package/dist/npm/chunks/{Panel-ChPUB68C.js → Panel-DhAzbUbC.js} +308 -309
  17. package/dist/npm/chunks/{Settings-CB5eEKnf.js → Settings-BmKqPX40.js} +34 -33
  18. package/dist/npm/chunks/{Shortcuts-eAyjJ89P.js → Shortcuts-Bl-c0Sez.js} +25 -23
  19. package/dist/npm/chunks/SignInFirst-CmGvSYkQ.js +35 -0
  20. package/dist/npm/chunks/{StyleEditor-CZTdAA5c.js → StyleEditor-D6fUnlwq.js} +4 -4
  21. package/dist/npm/chunks/{StylePanel-B4pHQUL9.js → StylePanel-C-Gikxt1.js} +3 -3
  22. package/dist/npm/chunks/TaskFields-CaKi523b.js +617 -0
  23. package/dist/npm/chunks/ThreadCard-d_3pUB5V.js +1142 -0
  24. package/dist/npm/chunks/{Viewer-DY6zb90M.js → Viewer-BULQsi9-.js} +9 -8
  25. package/dist/npm/chunks/{agent-MTQHr9ei.js → agent-DHdhIJ3s.js} +1 -1
  26. package/dist/npm/chunks/{ar-L5cQ-NPe.js → ar-B5UszrQp.js} +51 -12
  27. package/dist/npm/chunks/{card-bits-CTdrkYn8.js → card-bits-cV8GdFWX.js} +12 -10
  28. package/dist/npm/chunks/{client-7eVxvg5j.js → client-Cv8ddtuM.js} +13 -11
  29. package/dist/npm/chunks/{confetti-BIs5s14P.js → confetti-B9zlyILU.js} +1 -1
  30. package/dist/npm/chunks/{context-Cf6khm7A.js → context-CsHnabaA.js} +1 -1
  31. package/dist/npm/chunks/{de-D0C-v6tP.js → de-BE0Aaq8u.js} +51 -12
  32. package/dist/npm/chunks/{dpop-0A76OPa9.js → dpop-CwW9ifkq.js} +1 -1
  33. package/dist/npm/chunks/entrance-Bn_5M9uO.js +90 -0
  34. package/dist/npm/chunks/{es-Bw4Dj9tN.js → es-BQviao4d.js} +51 -12
  35. package/dist/npm/chunks/{extension-SmoH5AA4.js → extension-CnQTDC1j.js} +2 -2
  36. package/dist/npm/chunks/{extension-DFVOvciD.js → extension-DXhz81XD.js} +1 -1
  37. package/dist/npm/chunks/{files-4lV9YQIX.js → files-DLEr_wmh.js} +2 -2
  38. package/dist/npm/chunks/{fr-TkuQaIAa.js → fr-C5gu6A06.js} +51 -12
  39. package/dist/npm/chunks/{hi-DXSH2U8d.js → hi-DXfQ5EvY.js} +51 -12
  40. package/dist/npm/chunks/{i18n-aVSu9TcJ.js → i18n-Mgs9VOuk.js} +17 -21
  41. package/dist/npm/chunks/icons-_C6ZWmBY.js +141 -0
  42. package/dist/npm/chunks/{identify-BGYh2dVo.js → identify-BnQGJOa0.js} +1 -1
  43. package/dist/npm/chunks/{it-CiWA_bch.js → it-BPHt13FV.js} +51 -12
  44. package/dist/npm/chunks/{ja-C-QmR3yz.js → ja-BkCqyKR0.js} +50 -11
  45. package/dist/npm/chunks/late-words-D4Oo_yhJ.js +57 -0
  46. package/dist/npm/chunks/{live-BExWHzQ7.js → live-DXcxj_Af.js} +28 -22
  47. package/dist/npm/chunks/{nl-CEmZRqjX.js → nl-DZxdLLMU.js} +51 -12
  48. package/dist/npm/chunks/{page-key-HSY3Lze5.js → page-key-UqAozdZi.js} +1 -1
  49. package/dist/npm/chunks/{pick-B3sR7jtS.js → pick-C20RVUas.js} +1 -1
  50. package/dist/npm/chunks/{pkce-CfZhiNBi.js → pkce-BPvWoBrr.js} +1 -1
  51. package/dist/npm/chunks/{pt-BR-b-a8sxO8.js → pt-BR-lA9mJ05F.js} +51 -12
  52. package/dist/npm/chunks/{report-DaVuoRYS.js → report-BjUgUNnT.js} +1 -1
  53. package/dist/npm/chunks/{show-BoN8AC-F.js → show-BinoJyED.js} +7 -7
  54. package/dist/npm/chunks/signin-C2jjsxz9.js +101 -0
  55. package/dist/npm/chunks/{source-mk3rGBBQ.js → source-NuflODx3.js} +1 -1
  56. package/dist/npm/chunks/{src-C8rZFyL_.js → src-9o2Ocq8d.js} +21 -15
  57. package/dist/npm/chunks/start-Cbx6rMrr.js +1904 -0
  58. package/dist/npm/chunks/states-DLMCvwes.js +3 -0
  59. package/dist/npm/chunks/{upload-B2mkgMeJ.js → upload-C4NpM-jE.js} +1 -1
  60. package/dist/npm/chunks/uploads-CY4bDbaI.js +1236 -0
  61. package/dist/npm/chunks/{wrap-DW6EFbVQ.js → wrap-D-xTKIzj.js} +20 -20
  62. package/dist/npm/chunks/{zh-CN-JTscW8u8.js → zh-CN-yqaDHwBx.js} +51 -12
  63. package/dist/npm/element.js +7 -1
  64. package/dist/npm/headless.js +2 -2
  65. package/dist/npm/index.js +2 -2
  66. package/dist/npm/react.js +1 -1
  67. package/dist/npm/svelte.js +1 -1
  68. package/dist/npm/types/adapters/vue.d.ts +12 -0
  69. package/dist/npm/types/core/auth.d.ts +1 -0
  70. package/dist/npm/types/core/client.d.ts +5 -1
  71. package/dist/npm/types/core/types.d.ts +17 -2
  72. package/dist/npm/vue.js +5 -1
  73. package/package.json +2 -1
  74. package/dist/npm/chunks/Checklist-CW_SwMpS.js +0 -282
  75. package/dist/npm/chunks/Composer-Bveq5QrK.js +0 -727
  76. package/dist/npm/chunks/TaskFields-C8BX0Sgg.js +0 -289
  77. package/dist/npm/chunks/ThreadCard-B1EsX3PR.js +0 -1160
  78. package/dist/npm/chunks/late-words-80_VWt8S.js +0 -14
  79. package/dist/npm/chunks/signin-BOWr_WCo.js +0 -75
  80. package/dist/npm/chunks/start-CV4j78_q.js +0 -1894
  81. package/dist/npm/chunks/states-b9Bv3Ci7.js +0 -3
  82. package/dist/npm/chunks/uploads-8AxyRq7g.js +0 -1147
@@ -4,23 +4,26 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join, relative, resolve } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { parseArgs } from "node:util";
7
- import { CliError, endpointFrom, pollDevice, Project, registerClient, SIGN_IN_AGAIN, startDevice } from "./api.js";
7
+ import { CliError, Connection, endpointFrom, pollDevice, Project, registerClient, SIGN_IN_AGAIN, startDevice } from "./api.js";
8
8
  import { DASHBOARD } from "../shared/dashboard-places.js";
9
- import { forget, load, save } from "./credentials.js";
10
- import { doctor, render } from "./doctor.js";
9
+ import { forget, load, save, signInTarget } from "./credentials.js";
10
+ import { clean, CLI, doctor, render } from "./doctor.js";
11
11
  import { feedbackMarkdown } from "./format.js";
12
12
  import { describePlace, ignoreFolder, plan, PLUGIN_NODE_NOTE, setEnv } from "./init.js";
13
13
  import { AGENTS, backup, configPath, DEFAULT_SCOPE, entry, gitPlace, mergeJson, mergeToml, NEXT_STEP, readIfExists, writeAtomic } from "./mcp.js";
14
14
  import { openUrl } from "./open.js";
15
+ import { CHOOSE, chooseWebsite, describeChoice, findFolderChoice, folderChoiceText, FOLDER_FILE, matching, named, websiteWithKey, writeFolderChoice } from "./website.js";
15
16
  /** The publishable key format; a test keeps it equal to the pattern in contract/openapi-v1.yaml. */
16
17
  export const PUBLISHABLE_KEY = /^pk_(live|test)_[a-z0-9]{20,40}$/;
17
18
  const HELP = `CommentKit in your terminal.
18
19
 
19
20
  Usage: npx @commentkit/comment-kit <command> [options]
20
21
 
21
- login Sign in with your browser and choose a project
22
+ login Sign in with your browser: one website, or all websites in a workspace
22
23
  logout Forget the sign-in on this computer
23
- status Show who and which project you are signed in to
24
+ status Show the sign-in and which website this folder uses
25
+ websites List the websites the sign-in reaches
26
+ use [website] Choose the website for this folder (by id or name)
24
27
  init Add the key, the build plugin and the widget to your app
25
28
  doctor [url] Find out why the widget is not showing (this folder and your site)
26
29
  pull Save open feedback and tasks to .commentkit/feedback.md
@@ -36,10 +39,13 @@ Options:
36
39
  --key <pk_…> (init, doctor) Use this project key without signing in
37
40
  --all (pull) Include resolved feedback
38
41
  --out <file> (pull) Where to write (default .commentkit/feedback.md)
39
- --json (pull, token list, status, doctor) Print JSON
42
+ --json (pull, token list, status, doctor, websites) Print JSON
40
43
  --reply, --status (token create) Let the token reply / mark ready for review
41
44
  --days <n> (token create) Days until it expires (default 30, up to 90)
42
45
 
46
+ Which website a command uses: COMMENTKIT_PROJECT_ID (with COMMENTKIT_TOKEN), else the
47
+ folder's choice (use), else the publishable key in the folder, else the sign-in's only website.
48
+
43
49
  CI: set COMMENTKIT_TOKEN and COMMENTKIT_PROJECT_ID instead of logging in.
44
50
  Another server: set COMMENTKIT_ENDPOINT (default https://commentkit.dev).
45
51
  `;
@@ -47,7 +53,8 @@ const COMMAND_HELP = {
47
53
  login: `Usage: npx @commentkit/comment-kit login [--no-browser] [--scopes read,reply,status]
48
54
 
49
55
  Shows a short code and opens CommentKit in your browser. Confirm the code, then choose
50
- the project and what the CLI may do.
56
+ one website or all websites in a workspace (including websites added later), and what
57
+ the CLI may do. With a workspace, each code folder uses one website: see use.
51
58
 
52
59
  --no-browser Print the link instead of opening it
53
60
  --scopes <list> What to ask for (default read,reply,status)`,
@@ -57,10 +64,28 @@ Forgets the sign-in on this computer. To end it on the server too, disconnect it
57
64
  CommentKit, in Settings → Security, under Connected coding agents.`,
58
65
  status: `Usage: npx @commentkit/comment-kit status [--json]
59
66
 
60
- Which project you are signed in to, what the CLI may do, and whether agent changes wait
61
- for a person's approval.
67
+ What this computer is signed in to (one website, or all websites in a workspace), which
68
+ website this folder uses and how it was chosen, what the CLI may do, and whether agent
69
+ changes wait for a person's approval.
70
+
71
+ --json Print JSON`,
72
+ websites: `Usage: npx @commentkit/comment-kit websites [--json]
73
+
74
+ Lists the websites the sign-in reaches: name, address and id. The one this folder uses is
75
+ marked.
62
76
 
63
77
  --json Print JSON`,
78
+ use: `Usage: npx @commentkit/comment-kit use [website]
79
+
80
+ Chooses the website this folder uses, by id or exact name (any case). Without one, shows a
81
+ numbered list to choose from. Saved in .commentkit/project.json, for this folder on this
82
+ computer (.commentkit/ is not committed).
83
+
84
+ Which website a command uses, first match wins:
85
+ 1. COMMENTKIT_PROJECT_ID, with COMMENTKIT_TOKEN
86
+ 2. .commentkit/project.json in this folder or a parent (this command)
87
+ 3. the publishable key in this folder (env file, entry file, script tag)
88
+ 4. the sign-in's only website`,
64
89
  init: `Usage: npx @commentkit/comment-kit init [--yes] [--dry-run] [--install] [--key pk_…]
65
90
 
66
91
  Finds your framework (Next.js, Vite, SvelteKit, Astro, Nuxt, Laravel or a plain website) and
@@ -85,20 +110,22 @@ Exits 0 when nothing is wrong, 1 when something is.
85
110
  --json Print the result as JSON`,
86
111
  pull: `Usage: npx @commentkit/comment-kit pull [--all] [--out <file>] [--json]
87
112
 
88
- Saves open feedback and tasks to .commentkit/feedback.md for your coding agent. Reviewer
89
- text is fenced as untrusted content.
113
+ Saves open feedback and tasks of the website this folder uses to .commentkit/feedback.md
114
+ for your coding agent. Reviewer text is fenced as untrusted content.
90
115
 
91
116
  --all Include resolved feedback
92
117
  --out <file> Where to write (default .commentkit/feedback.md)
93
118
  --json Print JSON instead`,
94
119
  open: `Usage: npx @commentkit/comment-kit open [CK-12]
95
120
 
96
- Opens the task in your browser, or the task board without a reference.`,
121
+ Opens the task in your browser, or the task board without a reference, for the website
122
+ this folder uses.`,
97
123
  token: `Usage: npx @commentkit/comment-kit token list [--json]
98
124
  npx @commentkit/comment-kit token create "<name>" [--reply] [--status] [--days <n>]
99
125
  npx @commentkit/comment-kit token revoke <id>
100
126
 
101
- Tokens for CI (COMMENTKIT_TOKEN), never with more permissions than your sign-in.
127
+ Tokens for CI (COMMENTKIT_TOKEN), never with more permissions than your sign-in. A token is
128
+ for one website: the one this folder uses (see npx @commentkit/comment-kit status).
102
129
 
103
130
  --reply Let the token reply to feedback
104
131
  --status Let the token mark feedback ready for review and link commits
@@ -141,7 +168,11 @@ export async function main(argv, out = console_, cwd = process.cwd()) {
141
168
  return await logout(out);
142
169
  case "status":
143
170
  case "whoami":
144
- return await status(rest, out);
171
+ return await status(rest, out, cwd);
172
+ case "websites":
173
+ return await websites(rest, out, cwd);
174
+ case "use":
175
+ return await use(rest, out, cwd);
145
176
  case "init":
146
177
  return await init(rest, out, cwd);
147
178
  case "pull":
@@ -149,10 +180,10 @@ export async function main(argv, out = console_, cwd = process.cwd()) {
149
180
  case "doctor":
150
181
  return await runDoctor(rest, out, cwd);
151
182
  case "open":
152
- return await open(rest, out);
183
+ return await open(rest, out, cwd);
153
184
  case "token":
154
185
  case "tokens":
155
- return await token(rest, out);
186
+ return await token(rest, out, cwd);
156
187
  case "mcp":
157
188
  return await mcp(rest, out, cwd);
158
189
  case "--version":
@@ -171,7 +202,8 @@ export async function main(argv, out = console_, cwd = process.cwd()) {
171
202
  return 2;
172
203
  }
173
204
  out.error(error instanceof CliError || error instanceof Error ? `Error: ${error.message}` : String(error));
174
- return 1;
205
+ // Not knowing which website to use is a usage mistake, like a missing argument.
206
+ return error instanceof CliError && error.code === CHOOSE ? 2 : 1;
175
207
  }
176
208
  }
177
209
  function version() {
@@ -193,7 +225,9 @@ async function login(args, out) {
193
225
  await save(endpoint, { client_id: clientId });
194
226
  }
195
227
  const wanted = (values.scopes ?? "read,reply,status").split(",").map((s) => s.trim()).filter(Boolean);
196
- const scope = ["feedback:read", ...wanted.filter((s) => s !== "read").map((s) => `feedback:${s}`)].join(" ");
228
+ // `workspace` is not a permission: it tells CommentKit this CLI understands a sign-in for every website of a
229
+ // workspace, so the browser offers that choice next to one website (which stays the default).
230
+ const scope = ["feedback:read", ...wanted.filter((s) => s !== "read").map((s) => `feedback:${s}`), "workspace"].join(" ");
197
231
  let device;
198
232
  try {
199
233
  device = await startDevice(endpoint, clientId, scope);
@@ -210,7 +244,7 @@ async function login(args, out) {
210
244
  // Only the plain page is opened: a link with the code already in it is a phishing path (someone could send
211
245
  // their own link), so the person types the code they see here. Never a URL built with the code.
212
246
  out.log(`\nYour code: ${device.user_code}\n`);
213
- out.log(`Type this code on ${device.verification_uri}, then choose the project.`);
247
+ out.log(`Type this code on ${device.verification_uri}, then choose one website or all websites in a workspace.`);
214
248
  if (!values["no-browser"] && (await openUrl(device.verification_uri)))
215
249
  out.log("(Opened that page in your browser.)");
216
250
  out.log("Waiting for you to confirm…");
@@ -238,19 +272,28 @@ async function login(args, out) {
238
272
  throw new CliError("The code expired before it was confirmed. Run npx @commentkit/comment-kit login again.");
239
273
  }
240
274
  async function finishLogin(endpoint, clientId, answer, out) {
241
- if (!answer.project?.id)
242
- throw new CliError("Signed in, but CommentKit did not say which project was chosen. Update the CLI and try again.");
243
- await save(endpoint, {
244
- client_id: clientId,
245
- access_token: answer.access_token,
246
- refresh_token: answer.refresh_token,
247
- expires_at: Date.now() + answer.expires_in * 1000,
248
- scope: answer.scope,
249
- project_id: answer.project.id,
250
- project_name: answer.project.name,
251
- });
252
- out.log(`\nSigned in. Project: ${answer.project.name}. Allowed: ${permissions(answer.scope)}.`);
253
- return 0;
275
+ const tokens = { client_id: clientId, access_token: answer.access_token, refresh_token: answer.refresh_token, expires_at: Date.now() + answer.expires_in * 1000, scope: answer.scope };
276
+ if (answer.project?.id) {
277
+ // The workspace fields are cleared: an older sign-in's would otherwise stay next to this one.
278
+ await save(endpoint, { ...tokens, project_id: answer.project.id, project_name: answer.project.name, workspace_id: null, workspace_name: null });
279
+ out.log(`\nSigned in. Project: ${clean(answer.project.name, 80)}. Allowed: ${permissions(answer.scope)}.`);
280
+ return 0;
281
+ }
282
+ if (answer.workspace?.id) {
283
+ // project_id null: CLI 2.0.x reads it and answers "You are not signed in. Run login", never a wrong website.
284
+ await save(endpoint, { ...tokens, project_id: null, project_name: null, workspace_id: answer.workspace.id, workspace_name: answer.workspace.name });
285
+ out.log(`\nSigned in to all websites in “${clean(answer.workspace.name, 80)}”, including websites added later. Allowed: ${permissions(answer.scope)}.`);
286
+ try {
287
+ const list = await (await Connection.open(endpoint)).projects();
288
+ out.log(list.length ? `It reaches ${list.length} website${list.length === 1 ? "" : "s"}: ${list.slice(0, 5).map((p) => clean(p.name, 40)).join(", ")}${list.length > 5 ? ` and ${list.length - 5} more` : ""}.` : "It reaches no website right now.");
289
+ }
290
+ catch {
291
+ // The list is a convenience here; websites shows it (and any error) later.
292
+ }
293
+ out.log(`Each code folder uses one website: the one whose publishable key is in the folder, or the one you choose there with ${CLI} use.`);
294
+ return 0;
295
+ }
296
+ throw new CliError("Signed in, but CommentKit did not say which website or workspace was chosen. Update the CLI and try again.");
254
297
  }
255
298
  function permissions(scope) {
256
299
  const parts = scope.split(" ");
@@ -264,23 +307,154 @@ async function logout(out) {
264
307
  : "You were not signed in.");
265
308
  return 0;
266
309
  }
267
- async function status(args, out) {
310
+ /** Errors that mean "this folder has no usable website choice", which status and websites report instead of stopping. */
311
+ function choiceProblem(error) {
312
+ return error instanceof CliError && [CHOOSE, "folder_choice", "no_website"].includes(error.code);
313
+ }
314
+ /** What the credentials in use are for, in plain words. */
315
+ function describeAccess(connection) {
316
+ const access = connection.access;
317
+ if (access.kind === "token")
318
+ return `a CI token (COMMENTKIT_TOKEN) for website ${access.projectId}`;
319
+ if (access.kind === "website")
320
+ return `this computer, for one website: ${named(access)}`;
321
+ return `this computer, for all websites in “${clean(access.name, 80)}” (including websites added later)`;
322
+ }
323
+ async function status(args, out, cwd) {
268
324
  const { values } = parseArgs({ args, options: { json: { type: "boolean" } } });
269
325
  const endpoint = endpointFrom();
270
- const project = await Project.connect(endpoint);
271
- const info = await project.request("");
272
- const credential = load(endpoint);
326
+ const connection = await Connection.open(endpoint);
327
+ const credential = connection.access.kind === "token" ? null : load(endpoint);
328
+ let project = null;
329
+ let problem = null;
330
+ try {
331
+ project = await chooseWebsite(connection, cwd);
332
+ }
333
+ catch (error) {
334
+ if (!choiceProblem(error))
335
+ throw error;
336
+ problem = error;
337
+ }
338
+ const info = project ? (await project.request("")).data : null;
339
+ const access = connection.access;
340
+ if (values.json) {
341
+ out.log(JSON.stringify({
342
+ endpoint,
343
+ sign_in: access.kind === "token" ? { kind: "token", project_id: access.projectId } : { kind: access.kind, id: access.id, name: access.name },
344
+ project: info,
345
+ chosen_by: project ? project.chosenBy : null,
346
+ problem: problem?.message ?? null,
347
+ scope: credential?.scope ?? null,
348
+ }, null, 2));
349
+ return problem && problem.code !== CHOOSE ? 1 : 0;
350
+ }
351
+ out.log(`Endpoint: ${endpoint}`);
352
+ out.log(`Signed in: ${describeAccess(connection)}`);
353
+ if (project && info) {
354
+ out.log(`This folder: ${named(info)}, ${describeChoice(project.chosenBy, cwd)}`);
355
+ }
356
+ else {
357
+ out.log(`This folder: no website. ${problem.message}`);
358
+ }
359
+ if (credential?.scope)
360
+ out.log(`Allowed: ${permissions(credential.scope)}`);
361
+ if (info)
362
+ out.log(`Agent changes on ${named(info)} ${info.agent_approval ? "wait for a person's approval" : "apply right away"}.`);
363
+ return problem && problem.code !== CHOOSE ? 1 : 0;
364
+ }
365
+ async function websites(args, out, cwd) {
366
+ const { values } = parseArgs({ args, options: { json: { type: "boolean" } } });
367
+ const connection = await Connection.open();
368
+ const list = await connection.projects();
369
+ let current = null;
370
+ let problem = null;
371
+ try {
372
+ current = await chooseWebsite(connection, cwd);
373
+ }
374
+ catch (error) {
375
+ if (!choiceProblem(error))
376
+ throw error;
377
+ problem = error;
378
+ }
273
379
  if (values.json) {
274
- out.log(JSON.stringify({ endpoint, project: info.data, scope: credential.scope ?? null }, null, 2));
380
+ out.log(JSON.stringify({ websites: list.map((p) => ({ ...p, this_folder: p.id === current?.projectId })), this_folder: current ? { id: current.projectId, chosen_by: current.chosenBy } : null }, null, 2));
275
381
  return 0;
276
382
  }
277
- out.log(`Endpoint: ${endpoint}`);
278
- out.log(`Project: ${String(info.data.name)} (id ${project.projectId})`);
279
- if (credential.scope)
280
- out.log(`Allowed: ${permissions(credential.scope)}`);
281
- out.log(`Agent changes ${info.data.agent_approval ? "wait for a person's approval" : "apply right away"}.`);
383
+ const access = connection.access;
384
+ out.log(access.kind === "workspace"
385
+ ? `Websites this sign-in reaches (all websites in “${clean(access.name, 80)}”):`
386
+ : access.kind === "token" ? "The website this token reaches:" : "This sign-in is for one website:");
387
+ if (!list.length)
388
+ out.log(" (none right now)");
389
+ const width = Math.max(...list.map((p) => String(p.id).length), 2);
390
+ for (const p of list) {
391
+ const mark = p.id === current?.projectId ? ` ← this folder (${describeChoice(current.chosenBy, cwd)})` : "";
392
+ out.log(` ${String(p.id).padStart(width)} ${clean(p.name, 60)}${p.url ? ` ${clean(p.url, 80)}` : ""}${mark}`);
393
+ }
394
+ if (!current && problem && list.length > 1)
395
+ out.log(`\nNo website chosen for this folder yet. Choose one: ${CLI} use <id or name>`);
396
+ else if (!current && problem)
397
+ out.log(`\n${problem.message}`);
282
398
  return 0;
283
399
  }
400
+ async function use(args, out, cwd) {
401
+ const { positionals } = parseArgs({ args, allowPositionals: true, options: {} });
402
+ const asked = positionals.join(" ").trim();
403
+ const connection = await Connection.open();
404
+ const list = await connection.projects();
405
+ let chosen;
406
+ if (asked) {
407
+ const found = matching(list, asked);
408
+ if (found.length > 1)
409
+ throw new CliError(`More than one website is called “${clean(asked, 80)}”: ${found.map((p) => p.id).join(", ")}. Use its id: ${CLI} use <id>.`, CHOOSE);
410
+ if (!found.length) {
411
+ const hint = connection.access.kind === "workspace"
412
+ ? `${CLI} websites lists the ones this sign-in reaches.`
413
+ : `This sign-in is for ${list.map((p) => named(p)).join(", ") || "no website"} only: to reach others, run ${CLI} login and choose all websites in the workspace.`;
414
+ throw new CliError(`No website this sign-in reaches matches “${clean(asked, 80)}”. Use an id or the exact name. ${hint}`, CHOOSE);
415
+ }
416
+ chosen = found[0];
417
+ }
418
+ else {
419
+ if (!list.length)
420
+ throw new CliError("This sign-in reaches no website right now.", "no_website");
421
+ chosen = await pick(list, out);
422
+ if (!chosen)
423
+ throw new CliError(`Say which website: ${CLI} use <id or name> (${CLI} websites lists them).`, CHOOSE);
424
+ }
425
+ const file = writeFolderChoice(cwd, chosen);
426
+ out.log(`This folder now uses ${named(chosen)}. Saved in ${FOLDER_FILE}: the choice is for this folder on this computer.`);
427
+ const git = gitPlace(file);
428
+ if (git.repo && !git.ignored)
429
+ out.log(`Git does not ignore .commentkit/ here yet: add .commentkit/ to .gitignore so the choice stays on this computer (${CLI} init does this).`);
430
+ if (process.env.COMMENTKIT_TOKEN)
431
+ out.log("COMMENTKIT_TOKEN is set in this terminal: while it is, COMMENTKIT_PROJECT_ID decides the website instead.");
432
+ return 0;
433
+ }
434
+ /** @internal The terminal a numbered choice is asked in; tests replace it. */
435
+ export const terminal = {
436
+ interactive: () => Boolean(process.stdin.isTTY),
437
+ async question(text) {
438
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
439
+ try {
440
+ return await rl.question(text);
441
+ }
442
+ finally {
443
+ rl.close();
444
+ }
445
+ },
446
+ };
447
+ /** A numbered choice in a terminal; undefined when there is no terminal or no valid answer. */
448
+ async function pick(list, out) {
449
+ if (!terminal.interactive())
450
+ return undefined;
451
+ if (list.length === 1)
452
+ return list[0];
453
+ out.log("Which website is this folder for?");
454
+ list.forEach((p, i) => out.log(` ${String(i + 1).padStart(2)}. ${clean(p.name, 60)}${p.url ? ` ${clean(p.url, 80)}` : ""} (id ${p.id})`));
455
+ const n = Number((await terminal.question(`Number (1-${list.length}): `)).trim());
456
+ return Number.isInteger(n) && n >= 1 && n <= list.length ? list[n - 1] : undefined;
457
+ }
284
458
  async function ask(question, yes) {
285
459
  if (yes)
286
460
  return true;
@@ -306,12 +480,39 @@ async function init(args, out, cwd) {
306
480
  const yes = Boolean(values.yes);
307
481
  const dryRun = Boolean(values["dry-run"]);
308
482
  let key = values.key;
483
+ // With a workspace sign-in, the website whose key init installs is remembered for this folder.
484
+ let remember = null;
309
485
  if (!key) {
310
- const info = await (await Project.connect()).request("");
311
- key = info.data.publishable_keys.live ?? info.data.publishable_keys.test ?? undefined;
486
+ const connection = await Connection.open();
487
+ let project;
488
+ try {
489
+ project = await chooseWebsite(connection, cwd);
490
+ }
491
+ catch (error) {
492
+ // A workspace sign-in and nothing in the folder says which website yet: ask, in a terminal.
493
+ if (!(error instanceof CliError && error.code === CHOOSE))
494
+ throw error;
495
+ const chosen = await pick(await connection.projects(), out);
496
+ if (!chosen)
497
+ throw error;
498
+ project = new Project(connection, chosen.id, chosen.name);
499
+ }
500
+ const info = (await project.request("")).data;
501
+ key = info.publishable_keys.live ?? info.publishable_keys.test ?? undefined;
312
502
  if (!key)
313
503
  throw new CliError(`This website has no publishable key yet. In CommentKit, open ${DASHBOARD.install} and press Create the key, then try again.`);
314
- out.log(`Project: ${info.data.name}`);
504
+ out.log(`Project: ${clean(info.name, 80)}`);
505
+ if (connection.access.kind === "workspace")
506
+ remember = info;
507
+ }
508
+ else if (PUBLISHABLE_KEY.test(key) && !process.env.COMMENTKIT_TOKEN && savedSignInKind() === "workspace") {
509
+ // --key with a saved workspace sign-in: remember the website the key belongs to, when it is one of them.
510
+ try {
511
+ remember = websiteWithKey(await (await Connection.open()).projects(), key) ?? null;
512
+ }
513
+ catch (error) {
514
+ out.log(`Could not check which website the key belongs to (${error instanceof Error ? error.message : String(error)}), so no website was saved for this folder.`);
515
+ }
315
516
  }
316
517
  if (!PUBLISHABLE_KEY.test(key))
317
518
  throw new CliError("That is not a publishable key (pk_live_… or pk_test_…).");
@@ -340,6 +541,18 @@ async function init(args, out, cwd) {
340
541
  }
341
542
  const ignoreBefore = readOr(".gitignore");
342
543
  await change(".gitignore", ignoreBefore, ignoreFolder(ignoreBefore), "Add .commentkit/ to .gitignore (pulled feedback stays on your computer)?");
544
+ if (remember) {
545
+ let current = null;
546
+ try {
547
+ current = findFolderChoice(cwd);
548
+ }
549
+ catch {
550
+ // A damaged choice file is replaced below, after asking.
551
+ }
552
+ if (current?.projectId !== remember.id) {
553
+ await change(FOLDER_FILE, readOr(FOLDER_FILE), folderChoiceText(remember), `Remember ${named(remember)} as this folder's website in ${FOLDER_FILE} (for this folder on this computer)?`);
554
+ }
555
+ }
343
556
  const configBefore = p.configFile ? readOr(p.configFile) : "";
344
557
  if (p.configFile && p.configEdit) {
345
558
  await change(p.configFile, configBefore, p.configEdit, `Add the CommentKit build plugin to ${p.configFile}?`);
@@ -385,6 +598,15 @@ async function init(args, out, cwd) {
385
598
  out.log("Then start your dev server: the Comment button appears on localhost for your team.");
386
599
  return 0;
387
600
  }
601
+ /** What the saved sign-in is for, without the network; null when there is none or the file cannot be read. */
602
+ function savedSignInKind() {
603
+ try {
604
+ return signInTarget(load(endpointFrom()))?.kind ?? null;
605
+ }
606
+ catch {
607
+ return null;
608
+ }
609
+ }
388
610
  /** The lines `after` adds to `before`, marked with +, for a dry run. */
389
611
  export function addedLines(before, after) {
390
612
  const old = new Set(before.split("\n"));
@@ -459,7 +681,7 @@ async function runDoctor(args, out, cwd) {
459
681
  const PULL_MAX = 500;
460
682
  async function pull(args, out, cwd) {
461
683
  const { values } = parseArgs({ args, options: { out: { type: "string" }, json: { type: "boolean" }, all: { type: "boolean" } } });
462
- const project = await Project.connect();
684
+ const project = await Project.connect(undefined, undefined, undefined, cwd);
463
685
  const info = await project.request("");
464
686
  const threads = [];
465
687
  let cursor;
@@ -479,11 +701,11 @@ async function pull(args, out, cwd) {
479
701
  out.log(`Saved ${threads.length} item(s) to ${file}.${more ? ` There are more: only the ${PULL_MAX} with the latest activity were saved.` : ""}`);
480
702
  return 0;
481
703
  }
482
- async function open(args, out) {
704
+ async function open(args, out, cwd) {
483
705
  const ref = args[0];
484
706
  if (ref && !/^(CK-)?\d{1,9}$/i.test(ref))
485
707
  throw new CliError("Give a task reference like CK-12.");
486
- const project = await Project.connect();
708
+ const project = await Project.connect(undefined, undefined, undefined, cwd);
487
709
  const info = await project.request("");
488
710
  let url = info.data.tasks_url;
489
711
  if (ref) {
@@ -495,16 +717,17 @@ async function open(args, out) {
495
717
  out.log("(Open the link above in your browser.)");
496
718
  return 0;
497
719
  }
498
- async function token(args, out) {
720
+ async function token(args, out, cwd) {
499
721
  const [sub, ...rest] = args;
500
- const project = await Project.connect();
722
+ // A CI token is always for one website: the one this folder uses.
723
+ const project = await Project.connect(undefined, undefined, undefined, cwd);
501
724
  if (!sub || sub === "list") {
502
725
  const { values } = parseArgs({ args: rest, options: { json: { type: "boolean" } } });
503
726
  const list = await project.request("/tokens");
504
727
  if (values.json)
505
728
  out.log(JSON.stringify(list.data, null, 2));
506
729
  else if (!list.data.length)
507
- out.log("No agent tokens for this project.");
730
+ out.log(`No agent tokens for ${named({ id: project.projectId, name: project.name })}.`);
508
731
  else
509
732
  for (const t of list.data)
510
733
  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)}` : ""}`);
@@ -521,7 +744,7 @@ async function token(args, out) {
521
744
  method: "POST",
522
745
  body: { name, scopes: [values.reply ? "reply" : null, values.status ? "status" : null].filter(Boolean), ...(values.days ? { days: Number(values.days) } : {}) },
523
746
  });
524
- out.log(`Created “${created.data.name}” (id ${created.data.id}). It is shown only once:\n\n${created.data.token}\n`);
747
+ out.log(`Created “${clean(created.data.name, 80)}” (id ${created.data.id}) for ${named({ id: project.projectId, name: project.name })}. It is shown only once:\n\n${created.data.token}\n`);
525
748
  out.log(`In CI set COMMENTKIT_TOKEN to it and COMMENTKIT_PROJECT_ID=${project.projectId}.`);
526
749
  return 0;
527
750
  }
@@ -0,0 +1,140 @@
1
+ // Which website a command uses, and the folder file that remembers the choice.
2
+ //
3
+ // One sign-in can cover every website of a workspace, so each code folder says which website it is
4
+ // for. chooseWebsite is the one place that decides, for every command (pull, open, token, doctor, init,
5
+ // status); the first match wins:
6
+ // 1. COMMENTKIT_PROJECT_ID, with COMMENTKIT_TOKEN (a CI token is always one website);
7
+ // 2. .commentkit/project.json in this folder or a parent (written by `use` and `init`);
8
+ // 3. the publishable key written in this folder, matched against the keys of the sign-in's websites;
9
+ // 4. the sign-in's only website;
10
+ // 5. otherwise: stop and ask for `use`.
11
+ // A stored choice the sign-in does not reach is an error that names the fix, never a silent switch.
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { dirname, join, relative, resolve } from "node:path";
15
+ import { CliError, Project } from "./api.js";
16
+ import { clean, folderKey } from "./doctor.js";
17
+ const CLI = "npx @commentkit/comment-kit";
18
+ /** Where a folder keeps its choice, relative to the folder. */
19
+ export const FOLDER_FILE = join(".commentkit", "project.json");
20
+ /** Exit code 2, like other usage mistakes: the command needs to be told which website. */
21
+ export const CHOOSE = "usage";
22
+ /**
23
+ * .commentkit/project.json in `cwd` or the nearest parent that has one. The search stops at the
24
+ * repository root (a folder with .git) or the home folder, after looking there.
25
+ */
26
+ export function findFolderChoice(cwd, home = homedir()) {
27
+ const stop = resolve(home);
28
+ for (let dir = resolve(cwd);; dir = dirname(dir)) {
29
+ const file = join(dir, FOLDER_FILE);
30
+ if (existsSync(file))
31
+ return readFolderChoice(file);
32
+ if (existsSync(join(dir, ".git")) || dir === stop || dirname(dir) === dir)
33
+ return null;
34
+ }
35
+ }
36
+ function readFolderChoice(file) {
37
+ let data;
38
+ try {
39
+ data = JSON.parse(readFileSync(file, "utf8"));
40
+ }
41
+ catch {
42
+ data = null;
43
+ }
44
+ const id = data?.project_id;
45
+ if (!data || typeof data !== "object" || typeof id !== "number" || !Number.isInteger(id) || id < 1) {
46
+ throw new CliError(`${file} does not say which website this folder uses (it needs "project_id"). Run ${CLI} use to choose again.`, "folder_choice");
47
+ }
48
+ const name = data.name;
49
+ return { file, projectId: id, name: typeof name === "string" ? name : null };
50
+ }
51
+ /** Writes .commentkit/project.json in `cwd`. Returns its path. */
52
+ export function writeFolderChoice(cwd, website) {
53
+ const file = join(cwd, FOLDER_FILE);
54
+ mkdirSync(dirname(file), { recursive: true });
55
+ writeFileSync(file, folderChoiceText(website));
56
+ return file;
57
+ }
58
+ export function folderChoiceText(website) {
59
+ return `${JSON.stringify({ project_id: website.id, name: website.name }, null, 2)}\n`;
60
+ }
61
+ /** “Name” (id 12), safe for one terminal line. */
62
+ export function named(website) {
63
+ const name = clean(website.name ?? "", 80);
64
+ return name ? `“${name}” (id ${website.id})` : `website ${website.id}`;
65
+ }
66
+ /** The choice file as the person sees it: relative to the folder they are in when it is inside it. */
67
+ export function shownPath(file, cwd) {
68
+ const rel = relative(cwd, file);
69
+ return rel && !rel.startsWith("..") ? rel : file;
70
+ }
71
+ /** The website whose live or test publishable key is `key`. */
72
+ export function websiteWithKey(list, key) {
73
+ return list.find((p) => p.publishable_keys?.live === key || p.publishable_keys?.test === key);
74
+ }
75
+ /** The websites an id or exact name (any case) names: the hosted MCP server's rule (McpTools::matching). */
76
+ export function matching(list, asked) {
77
+ const wanted = asked.trim();
78
+ if (/^[0-9]{1,18}$/.test(wanted)) {
79
+ const byId = list.filter((p) => p.id === Number(wanted));
80
+ if (byId.length)
81
+ return byId;
82
+ }
83
+ const name = wanted.toLowerCase();
84
+ return list.filter((p) => String(p.name).toLowerCase() === name);
85
+ }
86
+ /**
87
+ * The website a command uses (see the order at the top of this file). Throws a CliError with a fix when
88
+ * there is no answer: code CHOOSE (exit 2) when the sign-in covers several websites and nothing in the
89
+ * folder says which; `folder_choice` when the folder's choice is one this sign-in does not reach.
90
+ */
91
+ export async function chooseWebsite(connection, cwd) {
92
+ const access = connection.access;
93
+ // 1. A CI token names its website in COMMENTKIT_PROJECT_ID (Connection.open checks it is set).
94
+ if (access.kind === "token")
95
+ return new Project(connection, access.projectId, null, { how: "env" });
96
+ // 2. The folder's own choice.
97
+ const stored = findFolderChoice(cwd);
98
+ const shown = stored ? shownPath(stored.file, cwd) : "";
99
+ if (access.kind === "website") {
100
+ if (stored && stored.projectId !== access.id) {
101
+ throw new CliError(`This folder uses ${named({ id: stored.projectId, name: stored.name })} (${shown}), but this computer is signed in to ${named(access)} only. Sign in again and choose that website or its whole workspace (${CLI} login), or use ${named(access)} here (${CLI} use ${access.id}).`, "folder_choice");
102
+ }
103
+ return new Project(connection, access.id, access.name || null, stored ? { how: "folder", file: stored.file } : { how: "sign-in" });
104
+ }
105
+ const list = await connection.projects();
106
+ if (stored) {
107
+ const found = list.find((p) => p.id === stored.projectId);
108
+ if (!found) {
109
+ throw new CliError(`This folder uses ${named({ id: stored.projectId, name: stored.name })} (${shown}), which this sign-in no longer reaches. Run ${CLI} use to choose another website for this folder (${CLI} websites lists them), or ask a workspace owner or admin for access.`, "folder_choice");
110
+ }
111
+ return new Project(connection, found.id, found.name, { how: "folder", file: stored.file });
112
+ }
113
+ // 3. The publishable key written in this folder.
114
+ const key = folderKey(cwd);
115
+ const byKey = key ? websiteWithKey(list, key.key) : undefined;
116
+ if (key && byKey)
117
+ return new Project(connection, byKey.id, byKey.name, { how: "key", key: key.key, source: key.source });
118
+ // 4. The only website.
119
+ if (list.length === 1)
120
+ return new Project(connection, list[0].id, list[0].name, { how: "only" });
121
+ // 5. Ask.
122
+ if (!list.length)
123
+ throw new CliError(`This sign-in reaches no website in “${clean(access.name, 80)}” right now. Ask a workspace owner or admin for access, or run ${CLI} login and choose another workspace.`, "no_website");
124
+ throw new CliError(`This sign-in covers ${list.length} websites. Run ${CLI} use to choose one for this folder.`, CHOOSE);
125
+ }
126
+ /** How the website was chosen, in plain words, for status and doctor. */
127
+ export function describeChoice(by, cwd) {
128
+ switch (by.how) {
129
+ case "env":
130
+ return "COMMENTKIT_PROJECT_ID (with COMMENTKIT_TOKEN)";
131
+ case "folder":
132
+ return `chosen for this folder in ${shownPath(by.file, cwd)}`;
133
+ case "key":
134
+ return `the publishable key ${by.key.slice(0, 12)}… in ${by.source}`;
135
+ case "only":
136
+ return "the only website this sign-in reaches";
137
+ case "sign-in":
138
+ return "the website this sign-in is for";
139
+ }
140
+ }