@eliya-oss/agent-diff 0.1.0-alpha.217 → 0.1.0-alpha.218

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 (58) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/main.js +1 -1
  3. package/dist/web/nitro.json +1 -1
  4. package/dist/web/public/assets/index-BCc7tdE9.js +12 -0
  5. package/dist/web/public/assets/index-Bh4VvgUA.css +2 -0
  6. package/dist/web/public/assets/{rolldown-runtime-XKyaHtl9.js → jsx-runtime-EIAPxkjE.js} +1 -1
  7. package/dist/web/public/assets/review-CLHgc7OK.js +44 -0
  8. package/dist/web/public/assets/routes-CS6_XKJl.js +1 -0
  9. package/dist/web/server/_libs/@base-ui/react+[...].mjs +2686 -4472
  10. package/dist/web/server/_libs/@tanstack/react-router+[...].mjs +1 -107
  11. package/dist/web/server/_libs/lucide-react.mjs +93 -268
  12. package/dist/web/server/_libs/react-markdown+[...].mjs +1 -1
  13. package/dist/web/server/_libs/valibot.mjs +1 -59
  14. package/dist/web/server/_ssr/highlight.server-Ch_kPZFd.mjs +199 -0
  15. package/dist/web/server/_ssr/{listener.functions-DygHonX4.mjs → listener.functions-r5sy6slm.mjs} +7 -7
  16. package/dist/web/server/_ssr/{listener.server-BUJSjrgf.mjs → listener.server-Ch_E4TJ7.mjs} +3 -2
  17. package/dist/web/server/_ssr/{review-block-BpqPNXDo.mjs → review-CXA8hOed.mjs} +5200 -5492
  18. package/dist/web/server/_ssr/review-folder.server-DrhuBcAc.mjs +354 -0
  19. package/dist/web/server/_ssr/{adhoc.functions-CDadmCcu.mjs → review-link.functions-BvcyZSk2.mjs} +12 -11
  20. package/dist/web/server/_ssr/review-link.server-XUXU8Jjl.mjs +180 -0
  21. package/dist/web/server/_ssr/{review-parts.server-j_3LS0HZ.mjs → review-parts.server-CSSa-ZRv.mjs} +2 -2
  22. package/dist/web/server/_ssr/review-read.functions-Da-f7qpe.mjs +37 -0
  23. package/dist/web/server/_ssr/{live-schema-BYm_IvNp.mjs → review-schema-C0qXng9-.mjs} +5 -64
  24. package/dist/web/server/_ssr/review-target.server-C8IXgmE-.mjs +18 -0
  25. package/dist/web/server/_ssr/{review.functions-Cvig5BYP.mjs → review.functions-BYEhPk_l.mjs} +19 -17
  26. package/dist/web/server/_ssr/review.server-DFe2jCWt.mjs +847 -0
  27. package/dist/web/server/_ssr/{router-CD3AbIAr.mjs → router-DqvyAgJl.mjs} +119 -257
  28. package/dist/web/server/_ssr/routes-6k-4pwuW.mjs +20 -0
  29. package/dist/web/server/_ssr/ssr.mjs +36 -72
  30. package/dist/web/server/_ssr/{thread-code-BWhoBW-5.mjs → thread-code-CYNB3wg5.mjs} +2 -3
  31. package/dist/web/server/_ssr/{type-hover-DSq-tkS_.mjs → type-hover-BWVNL2Vt.mjs} +2 -3
  32. package/dist/web/server/_ssr/{type-hover.functions-B_9iC3Xs.mjs → type-hover.functions-oAqPixru.mjs} +6 -5
  33. package/dist/web/server/_tanstack-start-manifest_v-BBV9HPN6.mjs +30 -0
  34. package/dist/web/server/index.mjs +25 -88
  35. package/package.json +1 -1
  36. package/dist/web/public/assets/_deck-CklUZ5Lb.js +0 -1
  37. package/dist/web/public/assets/_point-CXnTY-uf.js +0 -1
  38. package/dist/web/public/assets/adhoc.functions-C2dHzbMd.js +0 -1
  39. package/dist/web/public/assets/decks.functions-tXNTG2sC.js +0 -2
  40. package/dist/web/public/assets/index-B1ZY8zdK.css +0 -2
  41. package/dist/web/public/assets/index-DwC305SP.js +0 -11
  42. package/dist/web/public/assets/preload-helper-D5PXivxI.js +0 -1
  43. package/dist/web/public/assets/review-DAeFpudT.js +0 -1
  44. package/dist/web/public/assets/review-block-ILzR6Z95.js +0 -47
  45. package/dist/web/public/assets/routes-CVPv3eOL.js +0 -1
  46. package/dist/web/public/assets/shortcuts-BsNWbUaT.js +0 -1
  47. package/dist/web/public/assets/use-window-event-BDUVK1pJ.js +0 -1
  48. package/dist/web/public/assets/viewed-store-CbsF-9u7.js +0 -1
  49. package/dist/web/server/_deck-yL0m-bqz.mjs +0 -387
  50. package/dist/web/server/_libs/yaml.mjs +0 -6585
  51. package/dist/web/server/_point-C3P2_j2t.mjs +0 -1528
  52. package/dist/web/server/_ssr/decks.functions-BHxu668D.mjs +0 -1073
  53. package/dist/web/server/_ssr/review-CsjxwbVP.mjs +0 -58
  54. package/dist/web/server/_ssr/review-target.server-DA41RDao.mjs +0 -1779
  55. package/dist/web/server/_ssr/routes-CvszJ1sA.mjs +0 -27
  56. package/dist/web/server/_ssr/shortcuts-B7llaLLc.mjs +0 -228
  57. package/dist/web/server/_ssr/viewed-store-DGoAmvYO.mjs +0 -198
  58. package/dist/web/server/_tanstack-start-manifest_v-D8b_yVnx.mjs +0 -56
@@ -1,1779 +0,0 @@
1
- import { array, boolean, literal, minLength, nullish, number, object, optional, parse as parse$1, picklist, pipe, record, safeParse, string, trim, union, variant } from "../_libs/valibot.mjs";
2
- import { require_dist } from "../_libs/yaml.mjs";
3
- import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statSync, watch } from "node:fs";
4
- import path, { delimiter, dirname, join, sep } from "node:path";
5
- import { execFileSync, spawn } from "node:child_process";
6
- import os, { homedir } from "node:os";
7
- import { once } from "node:events";
8
- import { createInterface } from "node:readline";
9
- import { createHash } from "node:crypto";
10
- import Prism from "prismjs";
11
- import loadLanguages from "prismjs/components/index.js";
12
- // node_modules/.nitro/vite/services/ssr/assets/review-target.server-DA41RDao.js
13
- var import_dist = require_dist();
14
- var toAdhocPoint = ({ repo, base }) => new URLSearchParams(base === void 0 ? { repo } : {
15
- repo,
16
- base
17
- }).toString();
18
- var readAdhocPoint = (point) => {
19
- const query = new URLSearchParams(point);
20
- return {
21
- repo: query.get("repo") ?? "",
22
- base: query.get("base") ?? void 0
23
- };
24
- };
25
- /**
26
- * The environment for the git the page runs, and for adiff, which runs git too. Every such call
27
- * only reads, and `git status` otherwise refreshes the index under index.lock, so an agent that
28
- * commits in the worktree while the page polls fails with "index.lock exists".
29
- */
30
- var READ_ONLY_GIT = {
31
- ...process.env,
32
- GIT_OPTIONAL_LOCKS: "0"
33
- };
34
- var expandHome = (path) => path.replace(/^~(?=$|\/)/u, homedir());
35
- var getRepoRoots = () => (process.env["REVIEW_REPO_ROOTS"] ?? homedir()).split(":").filter(Boolean).map((root) => realpathSync(expandHome(root)));
36
- var isUnder = (path, root) => path === root || path.startsWith(`${root}${sep}`);
37
- var findAdhocTarget = ({ point, branch }) => {
38
- const { repo, base } = readAdhocPoint(point);
39
- const real = realpathSync(repo);
40
- if (!getRepoRoots().some((root) => isUnder(real, root))) throw new Error(`${repo} is outside REVIEW_REPO_ROOTS`);
41
- return {
42
- address: {
43
- repo: real,
44
- branch,
45
- base
46
- },
47
- block: {
48
- kind: "review",
49
- branch,
50
- base,
51
- repo: real
52
- }
53
- };
54
- };
55
- var readGit = (dir, args) => execFileSync("git", [
56
- "-C",
57
- dir,
58
- ...args
59
- ], {
60
- env: READ_ONLY_GIT,
61
- stdio: [
62
- "ignore",
63
- "pipe",
64
- "pipe"
65
- ]
66
- }).toString().trim();
67
- var resolveAdhocReview = (link) => {
68
- const dir = link.worktree ?? link.repo;
69
- if (dir === void 0) throw new Error("The link names neither a repo nor a worktree");
70
- const place = expandHome(dir);
71
- const common = readGit(place, [
72
- "rev-parse",
73
- "--path-format=absolute",
74
- "--git-common-dir"
75
- ]);
76
- const branch = link.branch ?? readGit(place, [
77
- "symbolic-ref",
78
- "--short",
79
- "HEAD"
80
- ]);
81
- const point = toAdhocPoint({
82
- repo: dirname(common),
83
- base: link.base
84
- });
85
- findAdhocTarget({
86
- point,
87
- branch
88
- });
89
- return {
90
- deck: "~",
91
- point,
92
- branch
93
- };
94
- };
95
- var standSchema = picklist([
96
- "filed",
97
- "waiting",
98
- "answered",
99
- "asked",
100
- "settled",
101
- "gone"
102
- ]);
103
- var partSchema = object({
104
- path: string(),
105
- /** The file's lines inside the layer's spans. */
106
- added: number(),
107
- removed: number(),
108
- read: boolean(),
109
- /** The part's open comments, and the loudest of their marks. */
110
- open: number(),
111
- stand: standSchema
112
- });
113
- var layerSchema = object({
114
- title: string(),
115
- note: optional(string(), ""),
116
- files: array(string()),
117
- spans: optional(array(object({
118
- path: string(),
119
- start: number(),
120
- end: number()
121
- })), []),
122
- /** The note in pieces, each placed before (or `after`) a line of a file. */
123
- prose: optional(array(object({
124
- path: string(),
125
- line: number(),
126
- markdown: string(),
127
- after: boolean()
128
- })), []),
129
- read: optional(array(string()), []),
130
- vanished: optional(array(string()), []),
131
- /** The added and removed lines inside the layer's own spans, as adiff counts them. */
132
- added: number(),
133
- removed: number(),
134
- /** Every file in the layer is read. */
135
- done: boolean(),
136
- /** The layer adiff adds for the changed lines no layer claims. */
137
- unclaimed: boolean(),
138
- /** The layer's open comments, and the loudest of their marks. */
139
- open: number(),
140
- stand: standSchema,
141
- parts: array(partSchema),
142
- /** The number the screen shows: `3`, or `2.2` for a ticket's second sublayer. */
143
- address: optional(string()),
144
- /** A sublayer's ticket, by its number, and its place under that ticket from 1. */
145
- ticket: optional(number()),
146
- sublayer: optional(number())
147
- });
148
- /** A layer that holds sublayers, with them rolled up as adiff counts them. */
149
- var ticketSchema = object({
150
- number: number(),
151
- address: string(),
152
- title: string(),
153
- note: optional(string(), ""),
154
- /** Its sublayers' positions in `layers`, from 1. */
155
- layers: array(number()),
156
- sublayers: number(),
157
- sublayersDone: optional(number(), 0),
158
- files: array(string()),
159
- added: number(),
160
- removed: number(),
161
- done: optional(boolean(), false),
162
- open: optional(number(), 0),
163
- stand: optional(standSchema, "gone")
164
- });
165
- var layersReportSchema = object({
166
- stale: optional(boolean(), false),
167
- summary: optional(string(), ""),
168
- layers: array(layerSchema),
169
- tickets: optional(array(ticketSchema), []),
170
- /** The plain layers and tickets, the M in "Layer N of M". */
171
- topLevel: optional(number())
172
- });
173
- var layersSchema = object({ layers: layersReportSchema });
174
- var turnSchema = object({
175
- voice: picklist(["reviewer", "agent"]),
176
- body: string(),
177
- at: string(),
178
- choices: optional(array(string()))
179
- });
180
- var threadSchema = object({
181
- id: string(),
182
- file: string(),
183
- side: picklist(["old", "new"]),
184
- start: number(),
185
- end: number(),
186
- snippet: optional(string(), ""),
187
- body: string(),
188
- at: optional(string(), ""),
189
- state: string(),
190
- /** The lines it was written on changed, and it sits at that change. */
191
- outdated: optional(boolean(), false),
192
- settled: optional(boolean(), false),
193
- unread: optional(number(), 0),
194
- taken: optional(boolean(), false),
195
- doing: optional(object({
196
- body: string(),
197
- at: string()
198
- })),
199
- turns: array(turnSchema),
200
- stand: standSchema,
201
- section: picklist([
202
- "asked",
203
- "filed",
204
- "with",
205
- "answered",
206
- "movedOn",
207
- "settled",
208
- "removed"
209
- ]),
210
- /** Its code is gone from the diff, or changed past rewording: listed, never drawn on a line. */
211
- movedPast: boolean(),
212
- reworded: boolean(),
213
- about: picklist(["branch", "line"]),
214
- /** It has answers and every one is read: what `comment resolve --read` settles. */
215
- settleable: boolean(),
216
- /** The layers it is read in, from 1. */
217
- layers: array(number())
218
- });
219
- /** A file's threads drawn on its lines: the open ones and their loudest mark, and the settled. */
220
- var fileMarkSchema = object({
221
- path: string(),
222
- open: number(),
223
- settled: number(),
224
- stand: standSchema
225
- });
226
- /** A line threads are drawn on, and the loudest mark among all of them, settled counting least. */
227
- var lineMarkSchema = object({
228
- path: string(),
229
- side: picklist(["old", "new"]),
230
- line: number(),
231
- open: number(),
232
- settled: number(),
233
- stand: standSchema
234
- });
235
- /** The headline's two numbers, as adiff counts them: questions waiting on you, answers to read. */
236
- var countsSchema = object({
237
- asked: number(),
238
- unread: number()
239
- });
240
- var threadsSchema = object({
241
- comments: array(threadSchema),
242
- counts: optional(countsSchema),
243
- files: array(fileMarkSchema),
244
- lines: array(lineMarkSchema)
245
- });
246
- var markedSchema = object({ layers: optional(layersReportSchema) });
247
- /**
248
- * There is no comment about a whole branch in adiff, so a request about the branch (`layers ask`)
249
- * sits on the first line of the first file and opens with this sentence, which the panel leaves out.
250
- */
251
- var BRANCH_ASK = "About this branch, not about this line. ";
252
- var toThread = (thread) => ({
253
- id: thread.id,
254
- file: thread.about === "branch" ? "" : thread.file,
255
- isAboutBranch: thread.about === "branch",
256
- side: thread.side,
257
- start: thread.start,
258
- end: thread.end,
259
- snippet: thread.snippet,
260
- body: thread.about === "branch" ? thread.body.replace(BRANCH_ASK, "") : thread.body,
261
- at: thread.at,
262
- isSettled: thread.settled,
263
- isMovedPast: thread.movedPast,
264
- isOutdated: thread.outdated,
265
- isTaken: thread.taken,
266
- isSettleable: thread.settleable,
267
- stand: thread.stand,
268
- section: thread.section,
269
- layers: thread.layers,
270
- layerAddress: null,
271
- state: thread.state,
272
- unread: thread.unread,
273
- doing: thread.doing,
274
- turns: thread.turns
275
- });
276
- /** An adiff older than sublayers numbers each layer by its place, as it always did. */
277
- var toLayer = ({ done, unclaimed, parts, address, ticket, sublayer, ...layer }, at) => ({
278
- ...layer,
279
- address: address ?? String(at + 1),
280
- ticket: ticket ?? null,
281
- sublayer: sublayer ?? null,
282
- isDone: done,
283
- isRemainder: unclaimed,
284
- parts: parts.map(({ read, ...part }) => ({
285
- ...part,
286
- isRead: read
287
- }))
288
- });
289
- var toTicket = ({ done, ...ticket }) => ({
290
- ...ticket,
291
- isDone: done
292
- });
293
- /** The layers and tickets a report answers, as the page keeps them. */
294
- var toLayers = (told) => ({
295
- layers: told.layers.map((layer, at) => toLayer(layer, at)),
296
- tickets: told.tickets.map((ticket) => toTicket(ticket))
297
- });
298
- /** The outline's fields `layers show` answers. */
299
- var toLayerFields = (told) => ({
300
- summary: told.summary,
301
- isLayersStale: told.stale,
302
- unclaimedLines: told.layers.reduce((sum, layer) => layer.unclaimed ? sum + layer.added + layer.removed : sum, 0),
303
- ...toLayers(told),
304
- topLevel: told.topLevel ?? told.layers.filter((layer) => !layer.unclaimed).length
305
- });
306
- /**
307
- * Names each thread's first layer by its address. A thread counts its layers by their place in
308
- * `layers show`, and a sublayer's place is not the `2.2` the screen shows.
309
- */
310
- var nameThreadLayers = (threads, layers) => threads.map((thread) => {
311
- const [first] = thread.layers;
312
- const address = first === void 0 ? null : layers[first - 1]?.address ?? String(first);
313
- return address === thread.layerAddress ? thread : {
314
- ...thread,
315
- layerAddress: address
316
- };
317
- });
318
- /** The outline's fields `comment list` answers. */
319
- var toCommentFields = (listed) => ({
320
- threads: listed.comments.map((thread) => toThread(thread)),
321
- fileMarks: listed.files,
322
- lineMarks: listed.lines,
323
- threadCounts: listed.counts ?? null
324
- });
325
- /**
326
- * The oldest adiff the page runs. The page draws what adiff decides, and before 0.1.0-alpha.203
327
- * adiff does not say which rows a layer keeps in place as quiet lines, so the page would fold them;
328
- * before 0.1.0-alpha.200 it does not answer the mark on each line or how many settled threads a
329
- * file and a line hold, and rewrites the branch's state without what newer versions keep there.
330
- */
331
- var OLDEST = "0.1.0-alpha.203";
332
- /** How long a refusal stands before the version is read again, so an update takes effect. */
333
- var RECHECK_MS = 3e4;
334
- /** The parts of a version to compare in order: 0.1.0-alpha.195 is [0, 1, 0, 195]. */
335
- var partsOf = (version) => (version.match(/\d+/gu) ?? []).map(Number);
336
- var isOlder = (version, than) => {
337
- const mine = partsOf(version);
338
- const theirs = partsOf(than);
339
- const at = mine.findIndex((part, index) => part !== (theirs[index] ?? 0));
340
- return at === -1 ? mine.length < theirs.length && version.includes("-") : (mine[at] ?? 0) < (theirs[at] ?? 0);
341
- };
342
- /** Where a bare command name resolves on PATH, as the spawn will find it. */
343
- var resolve$1 = (bin) => {
344
- if (bin.includes("/")) return bin;
345
- const found = (process.env["PATH"] ?? "").split(delimiter).find((dir) => {
346
- try {
347
- accessSync(join(dir, bin), constants.X_OK);
348
- return true;
349
- } catch {
350
- return false;
351
- }
352
- });
353
- return found === void 0 ? bin : join(found, bin);
354
- };
355
- var readVersion = (command) => {
356
- const [bin = "adiff", ...lead] = command;
357
- try {
358
- return execFileSync(bin, [...lead, "--version"], { stdio: [
359
- "ignore",
360
- "pipe",
361
- "ignore"
362
- ] }).toString().trim();
363
- } catch {
364
- return null;
365
- }
366
- };
367
- var checked = {
368
- at: -Infinity,
369
- refusal: null
370
- };
371
- var refusalFor = (command) => {
372
- const version = readVersion(command);
373
- return version !== null && isOlder(version, OLDEST) ? `${resolve$1(command[0] ?? "adiff")} is adiff ${version}; the page needs ${OLDEST} or later. Install the newest release, or point ADIFF_BIN at it.` : null;
374
- };
375
- /**
376
- * Why the page will not run this adiff, else null: read once, and again every 30 seconds while
377
- * it refuses. An adiff whose version cannot be read is left to fail on its own. The refusal is
378
- * the error every review call answers with, so the page shows it.
379
- */
380
- var getRefusal = (command) => {
381
- if (checked.refusal === null && checked.at > -Infinity || Date.now() - checked.at < RECHECK_MS) return checked.refusal;
382
- checked.at = Date.now();
383
- checked.refusal = refusalFor(command);
384
- return checked.refusal;
385
- };
386
- var RETRY_MS = 3e4;
387
- var SHARED = Symbol.for("adiff-web.serve");
388
- /**
389
- * One adiff serve for the whole server, held on the global object rather than in this module:
390
- * Vite runs the module again after an edit in dev, and a copy with its own state started another
391
- * serve each time, leaving the old ones running for as long as the server did.
392
- */
393
- var shared = globalThis;
394
- shared[SHARED] ??= {
395
- served: null,
396
- downUntil: 0,
397
- nextId: 0
398
- };
399
- var state = shared[SHARED];
400
- var getCommand = () => (process.env["ADIFF_BIN"] ?? "adiff").split(" ").filter(Boolean);
401
- var isObject = (value) => typeof value === "object" && value !== null;
402
- var readLine = (line) => {
403
- try {
404
- const parsed = JSON.parse(line);
405
- return isObject(parsed) && typeof parsed["id"] === "number" ? parsed : null;
406
- } catch {
407
- return null;
408
- }
409
- };
410
- var hear = (current, line) => {
411
- const heard = readLine(line);
412
- const id = Number(heard?.["id"]);
413
- if (heard === null) return;
414
- if (heard["event"] === "changed") {
415
- const what = Array.isArray(heard["what"]) ? heard["what"].map(String) : ["other"];
416
- current.watchers.get(id)?.onChange(what);
417
- return;
418
- }
419
- current.pending.get(id)?.resolve({
420
- exit: Number(heard["exit"] ?? 1),
421
- answer: heard["answer"]
422
- });
423
- current.pending.delete(id);
424
- };
425
- var lose = (current) => {
426
- if (state.served === current) {
427
- state.served = null;
428
- state.downUntil = Date.now() + RETRY_MS;
429
- }
430
- current.pending.forEach((waiting) => {
431
- waiting.reject(/* @__PURE__ */ new Error("adiff serve stopped"));
432
- });
433
- current.pending.clear();
434
- const lost = [...current.watchers.values()];
435
- current.watchers.clear();
436
- lost.forEach((watcher) => {
437
- watcher.onLost();
438
- });
439
- };
440
- var spawnServed = () => {
441
- const [bin = "adiff", ...lead] = getCommand();
442
- const child = spawn(bin, [...lead, "serve"], {
443
- env: READ_ONLY_GIT,
444
- stdio: [
445
- "pipe",
446
- "pipe",
447
- "pipe"
448
- ]
449
- });
450
- const current = {
451
- child,
452
- pending: /* @__PURE__ */ new Map(),
453
- watchers: /* @__PURE__ */ new Map()
454
- };
455
- createInterface({ input: child.stdout }).on("line", (line) => {
456
- hear(current, line);
457
- });
458
- child.on("exit", () => {
459
- lose(current);
460
- });
461
- child.on("error", () => {
462
- lose(current);
463
- });
464
- child.stdin.on("error", () => {
465
- lose(current);
466
- });
467
- return current;
468
- };
469
- var start = () => {
470
- if (state.served === null && Date.now() >= state.downUntil) state.served = spawnServed();
471
- return state.served;
472
- };
473
- var send = (current, request) => {
474
- current.child.stdin.write(`${JSON.stringify(request)}\n`);
475
- };
476
- var lastJson = (said) => said.split("\n").findLast((candidate) => candidate.startsWith("{")) ?? "{}";
477
- var toAnswered = (said, exit) => {
478
- try {
479
- return {
480
- exit,
481
- answer: JSON.parse(lastJson(said))
482
- };
483
- } catch {
484
- return {
485
- exit: 1,
486
- answer: {
487
- ok: false,
488
- error: {
489
- type: "AdiffFailed",
490
- suggestion: said
491
- }
492
- }
493
- };
494
- }
495
- };
496
- var collect = (stream) => {
497
- const chunks = [];
498
- stream.setEncoding("utf8");
499
- stream.on("data", (chunk) => {
500
- chunks.push(chunk);
501
- });
502
- return chunks;
503
- };
504
- var spawned = async (args) => {
505
- const [bin = "adiff", ...lead] = getCommand();
506
- const child = spawn(bin, [...lead, ...args], {
507
- env: READ_ONLY_GIT,
508
- stdio: [
509
- "ignore",
510
- "pipe",
511
- "pipe"
512
- ]
513
- });
514
- const stdout = collect(child.stdout);
515
- const stderr = collect(child.stderr);
516
- const closed = await once(child, "close");
517
- const exit = Number(closed[0] ?? 1);
518
- return toAnswered((exit === 0 ? stdout : stderr).join(""), exit);
519
- };
520
- var isNotServed = (answered) => isObject(answered.answer) && isObject(answered.answer["error"]) && ["UnknownCommand", "NotServed"].includes(String(answered.answer["error"]["type"]));
521
- var takeId = () => {
522
- state.nextId += 1;
523
- return state.nextId;
524
- };
525
- var askServed = (current, args) => {
526
- const id = takeId();
527
- const waiting = Promise.withResolvers();
528
- current.pending.set(id, waiting);
529
- send(current, {
530
- id,
531
- args
532
- });
533
- return waiting.promise;
534
- };
535
- var ask = async (args) => {
536
- const refusal = getRefusal(getCommand());
537
- if (refusal !== null) return {
538
- exit: 1,
539
- answer: {
540
- ok: false,
541
- error: {
542
- type: "AdiffTooOld",
543
- suggestion: refusal
544
- }
545
- }
546
- };
547
- const current = start();
548
- if (current === null) return spawned(args);
549
- try {
550
- const answered = await askServed(current, args);
551
- return isNotServed(answered) ? await spawned(args) : answered;
552
- } catch {
553
- return spawned(args);
554
- }
555
- };
556
- var watch$1 = (address, handlers) => {
557
- const current = getRefusal(getCommand()) === null ? start() : null;
558
- if (current === null) return null;
559
- const id = takeId();
560
- current.watchers.set(id, handlers);
561
- send(current, {
562
- id,
563
- watch: address
564
- });
565
- return () => {
566
- current.watchers.delete(id);
567
- if (state.served === current) send(current, {
568
- id,
569
- unwatch: true
570
- });
571
- };
572
- };
573
- var prewarm = () => {
574
- if (getRefusal(getCommand()) === null) start();
575
- };
576
- var rowSchema = object({
577
- kind: picklist([
578
- "context",
579
- "added",
580
- "removed",
581
- "note"
582
- ]),
583
- old: optional(number()),
584
- new: optional(number()),
585
- text: string(),
586
- /** The layers whose spans hold the row, from 1. */
587
- layers: optional(array(number()), []),
588
- /** The layers that, open, keep this changed row in place as a quiet line rather than fold it. */
589
- quietIn: optional(array(number()), [])
590
- });
591
- var hunkSchema = object({
592
- header: optional(string(), ""),
593
- rows: array(rowSchema)
594
- });
595
- var patchFileSchema = object({
596
- path: string(),
597
- previousPath: optional(string(), ""),
598
- status: picklist([
599
- "added",
600
- "deleted",
601
- "renamed",
602
- "copied",
603
- "changed"
604
- ]),
605
- binary: optional(boolean(), false),
606
- generated: optional(boolean(), false),
607
- added: number(),
608
- removed: number(),
609
- hunks: array(hunkSchema),
610
- enclosedBy: optional(array(number()), []),
611
- scopes: optional(array(object({
612
- line: number(),
613
- text: string()
614
- })), []),
615
- /** The file's content as git names it, so a mark can name the version it was made on. */
616
- blob: optional(string(), "")
617
- });
618
- var patchSchema = object({ patch: object({
619
- branch: string(),
620
- base: string(),
621
- head: string(),
622
- mergeBase: optional(string(), ""),
623
- files: array(patchFileSchema),
624
- /** Every path in the order the terminal's file tree lists them. */
625
- order: array(string())
626
- }) });
627
- var sentSchema = object({ batch: object({ comments: array(object({ id: string() })) }) });
628
- var failureSchema = object({ error: object({
629
- type: string(),
630
- suggestion: optional(string(), "")
631
- }) });
632
- var AdiffFailureError = class extends Error {
633
- type;
634
- constructor(type, message) {
635
- super(message);
636
- this.name = "AdiffFailureError";
637
- this.type = type;
638
- }
639
- };
640
- var toFailure = (answer) => {
641
- const parsed = safeParse(failureSchema, answer);
642
- return parsed.success ? new AdiffFailureError(parsed.output.error.type, parsed.output.error.suggestion || parsed.output.error.type) : new AdiffFailureError("AdiffFailed", JSON.stringify(answer));
643
- };
644
- var runAdiff = async (args) => {
645
- const answered = await ask(args);
646
- if (answered.exit !== 0) throw toFailure(answered.answer);
647
- return answered.answer;
648
- };
649
- var runAdiffRaw = async (args) => JSON.stringify(await runAdiff(args));
650
- var addressed = ({ repo, branch }) => [
651
- "--repo",
652
- repo,
653
- "--branch",
654
- branch
655
- ];
656
- var based = (address) => address.base === void 0 ? addressed(address) : [
657
- ...addressed(address),
658
- "--base",
659
- address.base
660
- ];
661
- var getPatch = async (address, { context, file }) => {
662
- const only = file === void 0 ? [] : ["--file", file];
663
- const answer = await runAdiff([
664
- "patch",
665
- "show",
666
- ...based(address),
667
- "--context",
668
- context,
669
- ...only
670
- ]);
671
- return parse$1(patchSchema, answer).patch;
672
- };
673
- /** One file's diff from the version marked reviewed to the worktree now (`patch since`). */
674
- var NO_LAYERS = {
675
- stale: false,
676
- summary: "",
677
- layers: [],
678
- tickets: []
679
- };
680
- var getLayers = async (address) => {
681
- try {
682
- return parse$1(layersSchema, await runAdiff([
683
- "layers",
684
- "show",
685
- ...addressed(address)
686
- ])).layers;
687
- } catch (error) {
688
- if (error instanceof AdiffFailureError && error.type === "NoLayers") return NO_LAYERS;
689
- throw error;
690
- }
691
- };
692
- var progressRaw = (address) => runAdiffRaw([
693
- "review",
694
- "progress",
695
- ...based(address)
696
- ]);
697
- var layersRaw = async (address) => {
698
- try {
699
- return await runAdiffRaw([
700
- "layers",
701
- "show",
702
- ...addressed(address)
703
- ]);
704
- } catch {
705
- return "";
706
- }
707
- };
708
- /**
709
- * Marks a file reviewed, and answers with the layers as they stand after it, if any. `layer` is the
710
- * layer's address (`2.2`), which `file review --layer` takes, not its place in the list.
711
- */
712
- var markReviewed = async (address, { path, layer, blob }) => {
713
- const answer = await runAdiff([
714
- "file",
715
- "review",
716
- ...based(address),
717
- "--file",
718
- path,
719
- ...layer === null ? [] : ["--layer", layer],
720
- ...blob === "" ? [] : ["--blob", blob]
721
- ]);
722
- const told = parse$1(markedSchema, answer).layers;
723
- return told === void 0 ? null : toLayers(told);
724
- };
725
- var listRaw = (address) => runAdiffRaw([
726
- "comment",
727
- "list",
728
- ...based(address)
729
- ]);
730
- var getThreads = async (address) => parse$1(threadsSchema, JSON.parse(await listRaw(address)));
731
- var sendComment = async (address, thread) => {
732
- const answer = await runAdiff([
733
- "comment",
734
- "send",
735
- ...addressed(address),
736
- "--file",
737
- thread.path,
738
- "--from",
739
- thread.from,
740
- "--to",
741
- thread.to,
742
- "--body",
743
- thread.body
744
- ]);
745
- const sent = safeParse(sentSchema, answer);
746
- return sent.success ? sent.output.batch.comments[0]?.id ?? null : null;
747
- };
748
- var replyComment = async (address, { id, body }) => {
749
- await runAdiff([
750
- "comment",
751
- "reply",
752
- ...addressed(address),
753
- "--to",
754
- id,
755
- "--body",
756
- body
757
- ]);
758
- };
759
- var settleComment = async (address, { id, settled }) => {
760
- await runAdiff([
761
- "comment",
762
- settled ? "resolve" : "reopen",
763
- ...addressed(address),
764
- "--id",
765
- id
766
- ]);
767
- };
768
- var sinceSchema = object({
769
- path: string(),
770
- at: optional(string(), ""),
771
- reviewed: optional(string(), ""),
772
- added: optional(number(), 0),
773
- removed: optional(number(), 0),
774
- places: optional(number(), 0),
775
- /** The reviewed version is in git's object store, so the change since can be shown. */
776
- kept: optional(boolean(), false),
777
- deleted: optional(boolean(), false),
778
- /** The layers whose lines changed since review, from 1. */
779
- layers: array(number())
780
- });
781
- var progressSchema = object({
782
- reviewed: array(string()),
783
- since: array(sinceSchema),
784
- /** How many files there are to review. */
785
- total: number()
786
- });
787
- /** What adiff answers when there is no reviewed version to diff from: not marked, or not kept. */
788
- var NO_SINCE = /* @__PURE__ */ new Set(["NotVouched", "VouchedVersionGone"]);
789
- /** One file's diff from the version marked reviewed, or null when adiff has no such version. */
790
- var getSince = async (address, file) => {
791
- try {
792
- const answer = await runAdiff([
793
- "patch",
794
- "since",
795
- ...based(address),
796
- "--file",
797
- file,
798
- "--context",
799
- "all"
800
- ]);
801
- return parse$1(object({ file: patchFileSchema }), answer).file;
802
- } catch (error) {
803
- if (error instanceof AdiffFailureError && NO_SINCE.has(error.type)) return null;
804
- throw error;
805
- }
806
- };
807
- /** Which files are reviewed, which changed since, and how many there are to review. */
808
- var getProgress = async (address) => parse$1(progressSchema, JSON.parse(await progressRaw(address)));
809
- /**
810
- * Runs `run` one at a time. A call made while it runs waits for that run, then shares one more,
811
- * so it sees everything that happened before the call, and any number of calls meanwhile cost
812
- * that one run. A review's live stream sends a change every second or two while an agent works,
813
- * and a read can take longer than that: without this the reads pile up and every other request
814
- * of the page, the file the reader opens among them, waits behind them.
815
- */
816
- var createCoalesced = (run) => {
817
- const runs = {
818
- running: null,
819
- next: null
820
- };
821
- const start = async () => {
822
- const started = run();
823
- runs.running = started;
824
- try {
825
- return await started;
826
- } finally {
827
- if (runs.running === started) runs.running = null;
828
- }
829
- };
830
- const after = async (running) => {
831
- try {
832
- await running;
833
- } catch {}
834
- runs.next = null;
835
- return start();
836
- };
837
- return () => {
838
- if (runs.running === null) return start();
839
- runs.next ??= after(runs.running);
840
- return runs.next;
841
- };
842
- };
843
- var nullableString = nullish(string());
844
- var segmentSchema = object({
845
- sha: string(),
846
- path: string(),
847
- start: nullableString,
848
- anchor: nullableString,
849
- at: nullish(number())
850
- });
851
- var paneSchema = object({
852
- label: string(),
853
- text: string(),
854
- proposed: boolean(),
855
- segments: array(segmentSchema)
856
- });
857
- var codeBlockSchema = object({
858
- kind: literal("code"),
859
- title: optional(string()),
860
- summary: optional(string()),
861
- before: paneSchema,
862
- after: paneSchema
863
- });
864
- var shotSchema = object({
865
- label: string(),
866
- src: string(),
867
- alt: string(),
868
- width: optional(number()),
869
- story: optional(string())
870
- });
871
- var mediaBlockSchema = object({
872
- kind: literal("media"),
873
- title: optional(string()),
874
- shots: array(shotSchema)
875
- });
876
- var takeBlockSchema = object({
877
- kind: literal("take"),
878
- markdown: string()
879
- });
880
- var storyBlockSchema = object({
881
- kind: literal("story"),
882
- storyId: string(),
883
- title: string(),
884
- component: string(),
885
- image: string(),
886
- url: string(),
887
- pr: string(),
888
- source: optional(string())
889
- });
890
- var recordingBlockSchema = object({
891
- kind: literal("recording"),
892
- title: string(),
893
- spec: string(),
894
- file: string(),
895
- pr: string(),
896
- worktree: optional(string()),
897
- video: string(),
898
- poster: optional(string())
899
- });
900
- var wordingRowSchema = object({
901
- label: optional(string()),
902
- before: string(),
903
- after: string()
904
- });
905
- var wordingBlockSchema = object({
906
- kind: literal("wording"),
907
- title: optional(string()),
908
- rows: array(wordingRowSchema)
909
- });
910
- var reviewFileSchema = object({
911
- path: string(),
912
- status: picklist([
913
- "added",
914
- "modified",
915
- "deleted"
916
- ])
917
- });
918
- var reviewBlockSchema = object({
919
- kind: literal("review"),
920
- title: optional(string()),
921
- branch: string(),
922
- base: optional(union([string(), object({
923
- sha: string(),
924
- label: optional(string())
925
- })])),
926
- repo: optional(string()),
927
- head: optional(object({ sha: string() })),
928
- files: optional(array(reviewFileSchema))
929
- });
930
- var blockSchema = variant("kind", [
931
- codeBlockSchema,
932
- reviewBlockSchema,
933
- mediaBlockSchema,
934
- takeBlockSchema,
935
- storyBlockSchema,
936
- recordingBlockSchema,
937
- wordingBlockSchema
938
- ]);
939
- var optionSchema = object({
940
- value: string(),
941
- label: string(),
942
- hint: optional(string()),
943
- recommended: optional(boolean()),
944
- blocks: optional(array(blockSchema))
945
- });
946
- var pointFrontmatterSchema = object({
947
- id: string(),
948
- num: string(),
949
- title: string(),
950
- short: optional(string()),
951
- section: string(),
952
- options: array(optionSchema),
953
- notePlaceholder: optional(string()),
954
- blocks: array(blockSchema)
955
- });
956
- var sectionSchema = object({
957
- id: string(),
958
- title: string(),
959
- domain: pipe(string(), trim(), minLength(1, "every section needs a sidebar domain name"))
960
- });
961
- var deckSchema = object({
962
- title: string(),
963
- repo: string(),
964
- worktrees: record(string(), string()),
965
- sections: array(sectionSchema),
966
- order: array(string())
967
- });
968
- var deckExtrasSchema = object({
969
- sections: optional(array(sectionSchema), []),
970
- order: optional(array(string()), [])
971
- });
972
- var FRONTMATTER = /^---\n(?<yaml>[\s\S]*?)\n---\n?(?<body>[\s\S]*)$/u;
973
- var getDecksDir = () => process.env["REVIEW_DECKS_DIR"] ?? path.join(os.homedir(), "review-decks");
974
- var getDeckDir = (deck) => path.join(getDecksDir(), deck);
975
- var listDecks = () => readdirSync(getDecksDir(), { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(getDecksDir(), entry.name, "deck.yaml"))).map((entry) => entry.name).toSorted();
976
- var loadExtras = (deck) => {
977
- const file = path.join(getDeckDir(deck), "extras.yaml");
978
- return parse$1(deckExtrasSchema, existsSync(file) ? (0, import_dist.parse)(readFileSync(file, "utf8")) : {});
979
- };
980
- var loadDeck = (deck) => {
981
- const base = parse$1(deckSchema, (0, import_dist.parse)(readFileSync(path.join(getDeckDir(deck), "deck.yaml"), "utf8")));
982
- const extras = loadExtras(deck);
983
- return {
984
- ...base,
985
- sections: [...base.sections, ...extras.sections],
986
- order: [...base.order, ...extras.order]
987
- };
988
- };
989
- var parsePoint = (source) => {
990
- const match = FRONTMATTER.exec(source);
991
- if (!match?.groups) throw new Error("point file has no frontmatter");
992
- return {
993
- ...parse$1(pointFrontmatterSchema, (0, import_dist.parse)(match.groups["yaml"] ?? "")),
994
- prose: (match.groups["body"] ?? "").trim()
995
- };
996
- };
997
- var loadPoints = (deck) => {
998
- const { order } = loadDeck(deck);
999
- const folder = path.join(getDeckDir(deck), "points");
1000
- return order.map((id) => parsePoint(readFileSync(path.join(folder, `${id}.md`), "utf8")));
1001
- };
1002
- var MAX_BUFFER = 67108864;
1003
- /** A porcelain status entry is two status letters, a space, then the path. */
1004
- var STATUS_WIDTH = 2;
1005
- var PATH_AT = 3;
1006
- /** How long the files must be still before the worktree is looked at again. */
1007
- var SETTLE_MS = 300;
1008
- var git = (repo, args) => execFileSync("git", [
1009
- "-C",
1010
- repo,
1011
- ...args
1012
- ], {
1013
- maxBuffer: MAX_BUFFER,
1014
- env: READ_ONLY_GIT,
1015
- stdio: [
1016
- "ignore",
1017
- "pipe",
1018
- "ignore"
1019
- ]
1020
- });
1021
- var getWorktree = (address) => {
1022
- return git(address.repo, [
1023
- "worktree",
1024
- "list",
1025
- "--porcelain"
1026
- ]).toString().split("\n\n").find((candidate) => candidate.split("\n").includes(`branch refs/heads/${address.branch}`))?.split("\n")[0]?.replace(/^worktree /u, "") ?? null;
1027
- };
1028
- var getRealWorktree = (address) => {
1029
- try {
1030
- const worktree = getWorktree(address);
1031
- return worktree === null ? null : realpathSync(worktree);
1032
- } catch {
1033
- return null;
1034
- }
1035
- };
1036
- var statOf = (worktree, path) => {
1037
- try {
1038
- const { mtimeMs, size } = statSync(join(worktree, path));
1039
- return `${path}:${String(mtimeMs)}:${String(size)}`;
1040
- } catch {
1041
- return `${path}:gone`;
1042
- }
1043
- };
1044
- /**
1045
- * A cheap mark of what the worktree holds beyond its last commit: every file git calls changed or
1046
- * new, with its time and size. It moves when an uncommitted file is written again, which git's
1047
- * status alone would not show. Ignored files never count.
1048
- */
1049
- var getWorktreeMark = (worktree) => {
1050
- try {
1051
- return git(worktree, [
1052
- "status",
1053
- "--porcelain=v1",
1054
- "-z",
1055
- "--untracked-files=all"
1056
- ]).toString().split("\0").filter(Boolean).map((entry) => `${entry.slice(0, STATUS_WIDTH)} ${statOf(worktree, entry.slice(PATH_AT))}`).join("\n");
1057
- } catch {
1058
- return "";
1059
- }
1060
- };
1061
- var isInsideGit = (name) => name === null || name === ".git" || name.startsWith(`.git/`) || name.includes("node_modules/");
1062
- var startWatch = (worktree, onEvent) => {
1063
- try {
1064
- return watch(worktree, { recursive: true }, (_event, name) => {
1065
- onEvent(name);
1066
- });
1067
- } catch {
1068
- return null;
1069
- }
1070
- };
1071
- /**
1072
- * Calls `onChange` when the worktree's uncommitted files change: written, added, removed or reverted.
1073
- * The file system says something moved, then the mark decides, so a build writing ignored files or
1074
- * git rewriting its own folder tells nobody. Returns the stop, or null when the folder cannot be
1075
- * watched.
1076
- */
1077
- var watchWorktree = (worktree, onChange) => {
1078
- const kept = {
1079
- mark: getWorktreeMark(worktree),
1080
- timer: void 0
1081
- };
1082
- const look = () => {
1083
- const now = getWorktreeMark(worktree);
1084
- if (now !== kept.mark) {
1085
- kept.mark = now;
1086
- onChange();
1087
- }
1088
- };
1089
- const watcher = startWatch(worktree, (name) => {
1090
- if (isInsideGit(name)) return;
1091
- clearTimeout(kept.timer);
1092
- kept.timer = setTimeout(look, SETTLE_MS);
1093
- });
1094
- if (watcher === null) return null;
1095
- watcher.on("error", () => {
1096
- watcher.close();
1097
- });
1098
- return () => {
1099
- clearTimeout(kept.timer);
1100
- watcher.close();
1101
- };
1102
- };
1103
- /** The file a listening agent rewrites every half second: it says nothing about the review. */
1104
- var HEARTBEAT = "watch.json";
1105
- var getAdiffRoot = () => process.env["ADIFF_ROOT"] ?? join(homedir(), ".adiff");
1106
- /** Adiff keys a review by `<git common dir>#<branch>`, each run of other characters as "-". */
1107
- var getReviewKey = (address) => {
1108
- const common = execFileSync("git", [
1109
- "-C",
1110
- address.repo,
1111
- "rev-parse",
1112
- "--path-format=absolute",
1113
- "--git-common-dir"
1114
- ], {
1115
- env: READ_ONLY_GIT,
1116
- stdio: [
1117
- "ignore",
1118
- "pipe",
1119
- "ignore"
1120
- ]
1121
- }).toString().trim();
1122
- return `${realpathSync(common)}#${address.branch}`.replaceAll(/[^a-zA-Z0-9]+/gu, "-");
1123
- };
1124
- /** Where adiff keeps a review's comments, marks, layers and drafts, or null when git cannot say. */
1125
- var getReviewFolder = (address) => {
1126
- try {
1127
- return join(getAdiffRoot(), "branches", getReviewKey(address));
1128
- } catch {
1129
- return null;
1130
- }
1131
- };
1132
- var markOf = (folder, name) => {
1133
- try {
1134
- const { mtimeMs, size } = statSync(join(folder, name));
1135
- return `${name}:${String(mtimeMs)}:${String(size)}`;
1136
- } catch {
1137
- return `${name}:gone`;
1138
- }
1139
- };
1140
- /**
1141
- * A cheap mark of the review's files, the heartbeat aside, which says whether an outline read is
1142
- * still current. A folder that is not there yet has the empty mark.
1143
- */
1144
- var getFolderMark = (folder) => {
1145
- try {
1146
- return readdirSync(folder).filter((name) => name !== HEARTBEAT).toSorted().map((name) => markOf(folder, name)).join("\n");
1147
- } catch {
1148
- return "";
1149
- }
1150
- };
1151
- var places = /* @__PURE__ */ new Map();
1152
- var placesOf = (address) => {
1153
- const key = `${address.repo}|${address.branch}`;
1154
- const known = places.get(key) ?? {
1155
- folder: getReviewFolder(address),
1156
- worktree: getRealWorktree(address)
1157
- };
1158
- places.set(key, known);
1159
- return known;
1160
- };
1161
- /**
1162
- * What a read of the review depends on: the branch head, the times of adiff's files for it, and the
1163
- * worktree's uncommitted files.
1164
- */
1165
- var signOf = (address, head) => {
1166
- const { folder, worktree } = placesOf(address);
1167
- return [
1168
- head,
1169
- folder === null ? "" : getFolderMark(folder),
1170
- worktree === null ? "" : getWorktreeMark(worktree)
1171
- ].join("\n");
1172
- };
1173
- /** How long a whole read answers the next request for a fresh one, when nothing moved since. */
1174
- var JUST_READ_MS = 2e3;
1175
- var justRead = /* @__PURE__ */ new Map();
1176
- var noteRead = (key, sign) => {
1177
- justRead.set(key, {
1178
- sign,
1179
- at: Date.now()
1180
- });
1181
- };
1182
- /**
1183
- * A page that opens asks for the outline it can have at once, then for a fresh one. When the first
1184
- * had to be read, the second would read the same thing again, seconds of adiff on a large branch,
1185
- * so a whole read that has just ended answers it while the head and adiff's files are as they were.
1186
- */
1187
- var isJustRead = (key, sign) => {
1188
- const read = justRead.get(key);
1189
- return read !== void 0 && Date.now() - read.at < JUST_READ_MS && read.sign === sign;
1190
- };
1191
- /** Nothing the outline was read from has moved since: the head, adiff's files and the worktree. */
1192
- var isStillRead = (key, sign) => justRead.get(key)?.sign === sign;
1193
- /** Tells `onChange` what changed in the review, as adiff's watch names it, until the watch is lost. */
1194
- var watchReview = (address, handlers) => watch$1([
1195
- "--repo",
1196
- address.repo,
1197
- "--branch",
1198
- address.branch
1199
- ], handlers);
1200
- var SUFFIX_LINES = 60;
1201
- var OPS$1 = {
1202
- " ": "ctx",
1203
- "-": "del",
1204
- "+": "add"
1205
- };
1206
- /**
1207
- * The grammar each file is read with, by its extension, or by its whole name for files that have
1208
- * none. A file in no language here shows plain, never another language's colours: tokenized as
1209
- * TSX, SQL kept its strings and lost its keywords and comments.
1210
- */
1211
- var BY_EXTENSION = {
1212
- ts: "typescript",
1213
- mts: "typescript",
1214
- cts: "typescript",
1215
- tsx: "tsx",
1216
- js: "javascript",
1217
- mjs: "javascript",
1218
- cjs: "javascript",
1219
- jsx: "jsx",
1220
- json: "json",
1221
- jsonc: "json",
1222
- css: "css",
1223
- scss: "scss",
1224
- html: "markup",
1225
- svg: "markup",
1226
- xml: "markup",
1227
- vue: "markup",
1228
- sql: "sql",
1229
- psql: "sql",
1230
- py: "python",
1231
- go: "go",
1232
- rs: "rust",
1233
- rb: "ruby",
1234
- java: "java",
1235
- kt: "kotlin",
1236
- swift: "swift",
1237
- cc: "cpp",
1238
- cpp: "cpp",
1239
- hpp: "cpp",
1240
- sh: "bash",
1241
- bash: "bash",
1242
- zsh: "bash",
1243
- yaml: "yaml",
1244
- yml: "yaml",
1245
- toml: "toml",
1246
- ini: "ini",
1247
- md: "markdown",
1248
- mdx: "markdown",
1249
- graphql: "graphql",
1250
- gql: "graphql",
1251
- tf: "hcl",
1252
- hcl: "hcl",
1253
- diff: "diff",
1254
- patch: "diff"
1255
- };
1256
- /** One-letter extensions, kept apart from the table, whose keys must be longer. */
1257
- var SHORT = /* @__PURE__ */ new Map([["c", "c"], ["h", "c"]]);
1258
- var BY_NAME = {
1259
- Dockerfile: "docker",
1260
- Makefile: "makefile",
1261
- ".env": "bash"
1262
- };
1263
- loadLanguages([.../* @__PURE__ */ new Set([
1264
- ...Object.values(BY_EXTENSION),
1265
- ...SHORT.values(),
1266
- ...Object.values(BY_NAME)
1267
- ])]);
1268
- var getLanguage = (file) => {
1269
- const name = file.slice(file.lastIndexOf("/") + 1);
1270
- const dot = name.lastIndexOf(".");
1271
- const extension = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
1272
- return BY_NAME[name] ?? BY_EXTENSION[extension] ?? SHORT.get(extension);
1273
- };
1274
- var escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1275
- var getGrammar = (file) => {
1276
- const language = getLanguage(file);
1277
- return language === void 0 ? void 0 : Prism.languages[language];
1278
- };
1279
- /** A fence's language as written (`ts`, `sql`, `shell`): an extension we know, else Prism's own name or alias. */
1280
- var getFenceGrammar = (name) => {
1281
- const language = name.trim().toLowerCase();
1282
- return Prism.languages[BY_EXTENSION[language] ?? SHORT.get(language) ?? language];
1283
- };
1284
- /**
1285
- * Prism's markdown grammar only marks a fence's code; Prism colours it in a hook that runs when it
1286
- * writes HTML, which this file does itself. So the code is tokenized here, in the fence's language.
1287
- */
1288
- var findPart = (parts, type) => parts.find((part) => typeof part !== "string" && part.type === type);
1289
- var embedFence = (token) => {
1290
- if (token.type !== "code" || !Array.isArray(token.content)) return;
1291
- const named = findPart(token.content, "code-language")?.content;
1292
- const grammar = typeof named === "string" ? getFenceGrammar(named) : void 0;
1293
- const block = findPart(token.content, "code-block");
1294
- if (grammar !== void 0 && block !== void 0 && typeof block.content === "string") block.content = Prism.tokenize(block.content, grammar);
1295
- };
1296
- var getAliases = (alias) => [alias].flat().filter((name) => typeof name === "string");
1297
- var emit = (output, token, classes) => {
1298
- if (typeof token === "string") {
1299
- token.split("\n").forEach((piece, index) => {
1300
- if (index > 0) output.push("");
1301
- const html = classes.length > 0 ? `<span class="${classes.join(" ")}">${escapeHtml(piece)}</span>` : escapeHtml(piece);
1302
- output.splice(-1, 1, `${output.at(-1) ?? ""}${piece ? html : ""}`);
1303
- });
1304
- return;
1305
- }
1306
- embedFence(token);
1307
- const next = [
1308
- "token",
1309
- token.type,
1310
- ...getAliases(token.alias)
1311
- ];
1312
- (Array.isArray(token.content) ? token.content : [token.content]).forEach((child) => {
1313
- emit(output, child, next);
1314
- });
1315
- };
1316
- var tokenizeLines = (lines, grammar) => {
1317
- if (!grammar) return null;
1318
- const output = [""];
1319
- Prism.tokenize(lines.join("\n"), grammar).forEach((token) => {
1320
- emit(output, token, []);
1321
- });
1322
- return output;
1323
- };
1324
- var highlightLines = (lines, file) => tokenizeLines(lines, getGrammar(file));
1325
- var highlightTypeScript = (lines) => {
1326
- const highlighted = tokenizeLines(lines, Prism.languages["typescript"]);
1327
- return lines.map((line, index) => highlighted?.[index] ?? escapeHtml(line));
1328
- };
1329
- var splitHunks = (rows) => rows.reduce((hunks, row) => {
1330
- if (row[0] === "~") {
1331
- hunks.push([]);
1332
- return hunks;
1333
- }
1334
- hunks.at(-1)?.push(row);
1335
- return hunks;
1336
- }, [[]]);
1337
- var getSide = (hunk, { source, file, op }) => {
1338
- const base = hunk.find((row) => row[1] !== null)?.[1] ?? hunk.find((row) => row[2] !== null)?.[2] ?? 1;
1339
- const end = hunk.findLast((row) => row[1] !== null)?.[1] ?? base - 1;
1340
- const prefix = source.slice(0, Math.max(0, base - 1));
1341
- const lines = hunk.filter((row) => row[0] !== op).map((row) => row[3]);
1342
- const highlighted = highlightLines([
1343
- ...prefix,
1344
- ...lines,
1345
- ...source.slice(end, end + SUFFIX_LINES)
1346
- ], file);
1347
- return lines.map((line, index) => highlighted?.[prefix.length + index] ?? escapeHtml(line));
1348
- };
1349
- var toRendered = (diff) => {
1350
- const hunks = splitHunks(diff.rows);
1351
- const context = {
1352
- source: diff.source,
1353
- file: diff.path
1354
- };
1355
- const oldHtml = hunks.flatMap((hunk) => getSide(hunk, {
1356
- ...context,
1357
- op: "+"
1358
- }));
1359
- const newHtml = hunks.flatMap((hunk) => getSide(hunk, {
1360
- ...context,
1361
- op: "-"
1362
- }));
1363
- const cursor = {
1364
- old: 0,
1365
- new: 0
1366
- };
1367
- const rows = diff.rows.map(([op, old, next, code]) => {
1368
- if (op === "~") return {
1369
- op: "gap",
1370
- old: null,
1371
- new: null,
1372
- code: "",
1373
- html: ""
1374
- };
1375
- const html = op === "-" ? oldHtml[cursor.old] : newHtml[cursor.new];
1376
- cursor.old += op === "+" ? 0 : 1;
1377
- cursor.new += op === "-" ? 0 : 1;
1378
- return {
1379
- op: OPS$1[op],
1380
- old,
1381
- new: next,
1382
- code,
1383
- html: html ?? escapeHtml(code)
1384
- };
1385
- });
1386
- return {
1387
- path: diff.path,
1388
- oldSha: diff.oldSha,
1389
- newSha: diff.newSha,
1390
- proposed: diff.proposed,
1391
- isNew: diff.isNew,
1392
- rows
1393
- };
1394
- };
1395
- /**
1396
- * A map that keeps only the `limit` entries used last: reading or writing an entry makes it the
1397
- * newest, and the oldest goes once the map is full. The server keeps whole reviews this way, so a
1398
- * day of opening branches does not keep every one of them in memory.
1399
- */
1400
- var keepRecent = (limit) => {
1401
- const entries = /* @__PURE__ */ new Map();
1402
- const touch = (key, value) => {
1403
- entries.delete(key);
1404
- entries.set(key, value);
1405
- const [oldest] = entries.keys();
1406
- if (entries.size > limit && oldest !== void 0) entries.delete(oldest);
1407
- return value;
1408
- };
1409
- const get = (key) => {
1410
- const value = entries.get(key);
1411
- return value === void 0 ? void 0 : touch(key, value);
1412
- };
1413
- return {
1414
- get,
1415
- set: touch
1416
- };
1417
- };
1418
- var IMAGE_TYPES = {
1419
- ".svg": "image/svg+xml",
1420
- ".png": "image/png",
1421
- ".jpg": "image/jpeg",
1422
- ".jpeg": "image/jpeg",
1423
- ".gif": "image/gif",
1424
- ".webp": "image/webp"
1425
- };
1426
- var OPS = {
1427
- context: " ",
1428
- added: "+",
1429
- removed: "-",
1430
- note: " "
1431
- };
1432
- var STATUSES = {
1433
- added: "added",
1434
- deleted: "deleted",
1435
- renamed: "renamed",
1436
- copied: "copied",
1437
- changed: "modified"
1438
- };
1439
- var getImageType = (file) => IMAGE_TYPES[path.extname(file).toLowerCase()];
1440
- var toRow = (row) => [
1441
- OPS[row.kind],
1442
- row.old ?? null,
1443
- row.new ?? null,
1444
- row.text
1445
- ];
1446
- var getSource = (rows) => {
1447
- const old = rows.filter((row) => row.old !== void 0);
1448
- return (old.length > 0 ? old : rows.filter((row) => row.new !== void 0)).map((row) => row.text);
1449
- };
1450
- /**
1451
- * The line adiff adds saying where a renamed or copied file came from. The file's status and previous
1452
- * path already say it, and drawn as a row it was a line of code with no number, folded to "…".
1453
- */
1454
- var MOVED_NOTE = /^(?:renamed|copied) from /u;
1455
- var isCode = (row) => row.kind !== "note" || !MOVED_NOTE.test(row.text);
1456
- var toFileDiff = (file, { head, mergeBase }) => {
1457
- const rows = file.hunks.flatMap((hunk) => hunk.rows).filter((row) => isCode(row));
1458
- return {
1459
- path: file.path,
1460
- oldSha: file.status === "added" ? null : mergeBase,
1461
- newSha: file.status === "deleted" ? null : head,
1462
- proposed: false,
1463
- oldAbs: null,
1464
- oldRoot: null,
1465
- newAbs: null,
1466
- newRoot: null,
1467
- isNew: file.status === "added",
1468
- source: getSource(rows),
1469
- rows: rows.map((row) => toRow(row))
1470
- };
1471
- };
1472
- var getImage = (file) => getImageType(file.path) === void 0 ? null : {
1473
- old: file.status !== "added",
1474
- new: file.status !== "deleted"
1475
- };
1476
- var hash = (text) => createHash("sha1").update(text).digest("hex");
1477
- /**
1478
- * What a file's rows are drawn from: its content and the base it is read against, never the
1479
- * branch head, so a commit that leaves a file alone leaves its rows cached on both sides.
1480
- */
1481
- var getFingerprint = (file, shas) => hash(JSON.stringify([
1482
- shas.mergeBase,
1483
- file.status,
1484
- file.previousPath,
1485
- file.blob,
1486
- file.hunks
1487
- ]));
1488
- var toFileMeta = (file, shas) => ({
1489
- path: file.path,
1490
- oldSha: file.status === "added" ? null : shas.mergeBase,
1491
- newSha: file.status === "deleted" ? null : shas.head,
1492
- proposed: false,
1493
- isNew: file.status === "added",
1494
- rows: [],
1495
- status: STATUSES[file.status],
1496
- previousPath: file.previousPath === "" ? file.path : file.previousPath,
1497
- isBinary: file.binary,
1498
- isGenerated: file.generated,
1499
- image: getImage(file),
1500
- fingerprint: getFingerprint(file, shas),
1501
- enclosedBy: [],
1502
- added: file.added,
1503
- removed: file.removed,
1504
- blob: file.blob
1505
- });
1506
- /**
1507
- * The rendered rows, each with the layers adiff says hold it and the layers that keep it in place
1508
- * quiet, matched one for one.
1509
- */
1510
- var withLayers = (file, rows) => {
1511
- const drawn = file.hunks.flatMap((hunk) => hunk.rows).filter((row) => isCode(row));
1512
- return rows.map((row, index) => {
1513
- const layers = drawn[index]?.layers ?? [];
1514
- const quietIn = drawn[index]?.quietIn ?? [];
1515
- const tagged = layers.length === 0 ? row : {
1516
- ...row,
1517
- layers
1518
- };
1519
- return quietIn.length === 0 ? tagged : {
1520
- ...tagged,
1521
- quietIn
1522
- };
1523
- });
1524
- };
1525
- var toReviewFile = (file, { shas, fingerprint }) => {
1526
- const rendered = toRendered(toFileDiff(file, shas));
1527
- return {
1528
- ...toFileMeta(file, shas),
1529
- ...rendered,
1530
- rows: withLayers(file, rendered.rows),
1531
- fingerprint,
1532
- enclosedBy: file.enclosedBy
1533
- };
1534
- };
1535
- var rendered = keepRecent(400);
1536
- var keep = (key, file) => rendered.set(key, file);
1537
- /** Whole reviews, kept for the few a reviewer moves between. */
1538
- var keepReviews = () => keepRecent(6);
1539
- /** A whole branch's patch is megabytes; only the reviews read last stay in memory. */
1540
- var patches = keepReviews();
1541
- var addressKey = (address) => `${address.repo}|${address.branch}|${address.base ?? ""}`;
1542
- var readPatch = async (address) => {
1543
- const patch = await getPatch(address, { context: "all" });
1544
- patches.set(addressKey(address), patch);
1545
- return patch;
1546
- };
1547
- var keptPatch = (address) => patches.get(addressKey(address));
1548
- var shasOf = (patch) => ({
1549
- head: patch.head,
1550
- mergeBase: patch.mergeBase || patch.base
1551
- });
1552
- var fromKept = (address, { file, fingerprint }) => {
1553
- const patch = keptPatch(address);
1554
- const found = patch?.files.find((candidate) => candidate.path === file);
1555
- if (patch === void 0 || found === void 0) return null;
1556
- const shas = shasOf(patch);
1557
- return toFileMeta(found, shas).fingerprint === fingerprint ? {
1558
- found,
1559
- shas
1560
- } : null;
1561
- };
1562
- var renderFile = async (address, file) => {
1563
- const patch = await getPatch(address, {
1564
- context: "all",
1565
- file
1566
- });
1567
- const shas = {
1568
- head: patch.head,
1569
- mergeBase: patch.mergeBase || patch.base
1570
- };
1571
- const found = patch.files.find((candidate) => candidate.path === file);
1572
- if (found === void 0) throw new Error(`${file} is not in this diff any more`);
1573
- return {
1574
- found,
1575
- shas
1576
- };
1577
- };
1578
- var getReviewFile = async (address, { path: file, fingerprint }) => {
1579
- const key = `${address.repo}|${address.branch}|${address.base ?? ""}|${file}|${fingerprint}`;
1580
- const kept = rendered.get(key);
1581
- if (kept !== void 0) return kept;
1582
- const { found, shas } = fromKept(address, {
1583
- file,
1584
- fingerprint
1585
- }) ?? await renderFile(address, file);
1586
- return keep(key, toReviewFile(found, {
1587
- shas,
1588
- fingerprint
1589
- }));
1590
- };
1591
- /** One file from the version marked reviewed to now, drawn as the branch's files are. */
1592
- var getSinceFile = async (address, { path: file, reviewed, blob }) => {
1593
- const key = `${address.repo}|${address.branch}|${file}|since|${reviewed}|${blob}`;
1594
- const kept = rendered.get(key);
1595
- if (kept !== void 0) return kept;
1596
- const found = await getSince(address, file);
1597
- const shas = {
1598
- head: keptPatch(address)?.head ?? "",
1599
- mergeBase: reviewed
1600
- };
1601
- return found === null ? null : keep(key, {
1602
- ...toReviewFile(found, {
1603
- shas,
1604
- fingerprint: hash(key)
1605
- }),
1606
- isSince: true
1607
- });
1608
- };
1609
- var getBaseRef = (block) => typeof block.base === "string" ? block.base : block.base?.label ?? block.base?.sha;
1610
- var toAddress = (deck, block) => ({
1611
- repo: block.repo ?? deck.repo,
1612
- branch: block.branch,
1613
- base: getBaseRef(block)
1614
- });
1615
- var toFailedReview = (block, error) => ({
1616
- kind: "review",
1617
- title: block.title,
1618
- branch: block.branch,
1619
- base: {
1620
- sha: "",
1621
- label: getBaseRef(block)
1622
- },
1623
- head: { sha: "" },
1624
- worktree: null,
1625
- files: [],
1626
- order: [],
1627
- summary: "",
1628
- isLayersStale: false,
1629
- unclaimedLines: 0,
1630
- layers: [],
1631
- tickets: [],
1632
- topLevel: 0,
1633
- reviewed: [],
1634
- total: 0,
1635
- since: [],
1636
- threads: [],
1637
- fileMarks: [],
1638
- lineMarks: [],
1639
- threadCounts: null,
1640
- error: error instanceof Error ? error.message : String(error)
1641
- });
1642
- var toFailedOutline = (block, error) => {
1643
- const { kind: _kind, title: _title, ...rest } = toFailedReview(block, error);
1644
- return rest;
1645
- };
1646
- /**
1647
- * The outline carries every file's meta but no rows: the page loads the open file's rows on its
1648
- * own, and an outline reread on every change stays small however large the diff is. The first
1649
- * file is rendered here in the background, so its request finds it ready.
1650
- */
1651
- var warmFile = async (address, file) => {
1652
- try {
1653
- await getReviewFile(address, file);
1654
- } catch {}
1655
- };
1656
- var openFirst = async (address, { isWhole }) => {
1657
- const patch = (isWhole ? void 0 : keptPatch(address)) ?? await readPatch(address);
1658
- const shas = shasOf(patch);
1659
- const files = patch.files.map((file) => toFileMeta(file, shas));
1660
- const shown = files.find((file) => file.path === patch.order[0]);
1661
- if (shown !== void 0) setImmediate(() => {
1662
- warmFile(address, shown);
1663
- });
1664
- return {
1665
- patch,
1666
- files
1667
- };
1668
- };
1669
- var outlines = keepReviews();
1670
- var reading = /* @__PURE__ */ new Map();
1671
- var outlineKey = (address) => `${address.repo}|${address.branch}|${address.base ?? ""}`;
1672
- /** The spans each patch was read with: rows carry their layers, so new spans need a new read. */
1673
- var spansRead = /* @__PURE__ */ new Map();
1674
- var spansOf = (layers) => JSON.stringify(layers.map((layer) => layer.spans));
1675
- /** The patch, read again when the layers moved since it was read, so its rows name them right. */
1676
- var retagged = async (address, { isWhole, opened, layers }) => {
1677
- const key = outlineKey(address);
1678
- const tagged = isWhole || spansRead.get(key) === spansOf(layers) ? opened : await openFirst(address, { isWhole: true });
1679
- spansRead.set(key, spansOf(layers));
1680
- return tagged;
1681
- };
1682
- var makeKept = async (address, block, isWhole) => {
1683
- const sign = signOf(address, getBranchHead(address));
1684
- const made = await makeOutline(address, block, { isWhole });
1685
- if (made.error === null) {
1686
- outlines.set(outlineKey(address), made);
1687
- if (isWhole) noteRead(outlineKey(address), sign);
1688
- }
1689
- return made;
1690
- };
1691
- /** One read of a review at a time; asks while it runs share the one read after it. */
1692
- var readOutline = (address, block, isWhole = true) => {
1693
- const key = `${outlineKey(address)}|${String(isWhole)}`;
1694
- const read = reading.get(key) ?? createCoalesced(() => makeKept(address, block, isWhole));
1695
- reading.set(key, read);
1696
- return read();
1697
- };
1698
- var getReviewOutline = (address, block, { isFresh, isWhole }) => {
1699
- const kept = outlines.get(outlineKey(address));
1700
- return (!isFresh || isWhole && isJustRead(outlineKey(address), signOf(address, getBranchHead(address)))) && kept !== void 0 ? Promise.resolve(kept) : readOutline(address, block, isWhole);
1701
- };
1702
- var startOutline = (address, block) => {
1703
- readOutline(address, block);
1704
- };
1705
- /**
1706
- * The outline a page can carry and draw at once: only one nothing has moved under since it was
1707
- * read. An older one would draw, restore the reader's place against stale rows, then jump.
1708
- */
1709
- var keptOutline = (address) => isStillRead(outlineKey(address), signOf(address, getBranchHead(address))) ? outlines.get(outlineKey(address)) ?? null : null;
1710
- var makeOutline = async (address, block, { isWhole }) => {
1711
- try {
1712
- const [opened, told, progress, listed] = await Promise.all([
1713
- openFirst(address, { isWhole }),
1714
- getLayers(address),
1715
- getProgress(address),
1716
- getThreads(address)
1717
- ]);
1718
- const { patch, files } = await retagged(address, {
1719
- isWhole,
1720
- opened,
1721
- layers: told.layers
1722
- });
1723
- return {
1724
- branch: block.branch,
1725
- base: {
1726
- sha: patch.mergeBase,
1727
- label: patch.base
1728
- },
1729
- head: { sha: patch.head },
1730
- worktree: getRealWorktree(address),
1731
- files,
1732
- order: patch.order,
1733
- ...toLayerFields(told),
1734
- ...progress,
1735
- ...toCommentFields(listed),
1736
- error: null
1737
- };
1738
- } catch (error) {
1739
- return toFailedOutline(block, error);
1740
- }
1741
- };
1742
- var getAllBlocks = (blocks, options) => [...blocks, ...options.flatMap((option) => option.blocks ?? [])];
1743
- var findDeckTarget = ({ deck, point, branch }) => {
1744
- const loaded = loadDeck(deck);
1745
- const found = loadPoints(deck).find((candidate) => candidate.id === point);
1746
- const block = getAllBlocks(found?.blocks ?? [], found?.options ?? []).find((candidate) => candidate.kind === "review" && candidate.branch === branch);
1747
- if (block === void 0) throw new Error(`no review of ${branch} on point ${point}`);
1748
- return {
1749
- address: toAddress(loaded, block),
1750
- block
1751
- };
1752
- };
1753
- var getBranchHead = (address) => {
1754
- try {
1755
- return git(address.repo, ["rev-parse", `refs/heads/${address.branch}`]).toString().trim();
1756
- } catch {
1757
- return "";
1758
- }
1759
- };
1760
- var findReviewTarget = (target) => target.deck === "~" ? findAdhocTarget(target) : findDeckTarget(target);
1761
- var findReviewBlock = (target) => findReviewTarget(target).address;
1762
- var getTargetOutline = (target, shape) => {
1763
- const { address, block } = findReviewTarget(target);
1764
- return getReviewOutline(address, block, shape);
1765
- };
1766
- /**
1767
- * The outline the server already holds for the target, to send with the page, or null. Only when
1768
- * it holds none current does a read start, so the page's own request finds it under way; a page
1769
- * reloaded by the router no longer reads the review again each time.
1770
- */
1771
- var openTargetOutline = (target) => {
1772
- const { address, block } = findReviewTarget(target);
1773
- const kept = keptOutline(address);
1774
- if (kept === null) startOutline(address, block);
1775
- return kept;
1776
- };
1777
- /** The outline the server already holds for the target, without starting a read. */
1778
- var keptTargetOutline = (target) => keptOutline(findReviewTarget(target).address);
1779
- export { AdiffFailureError, READ_ONLY_GIT, addressed, based, createCoalesced, findReviewBlock, getAdiffRoot, getBranchHead, getDeckDir, getImageType, getLayers, getProgress, getRealWorktree, getReviewFile, getReviewKey, getSinceFile, getTargetOutline, getThreads, getWorktree, git, hash, highlightTypeScript, keptOutline, keptTargetOutline, layersRaw, listDecks, listRaw, loadDeck, loadPoints, markReviewed, nameThreadLayers, openFirst, openTargetOutline, outlineKey, outlines, parsePoint, prewarm, progressRaw, replyComment, resolveAdhocReview, retagged, runAdiff, sendComment, settleComment, startOutline, toAddress, toCommentFields, toLayerFields, toRendered, watchReview, watchWorktree };