@eliya-oss/agent-diff 0.1.0-alpha.216 → 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 (60) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -1
  3. package/dist/main.js +9 -5
  4. package/dist/web/nitro.json +1 -1
  5. package/dist/web/public/assets/index-BCc7tdE9.js +12 -0
  6. package/dist/web/public/assets/index-Bh4VvgUA.css +2 -0
  7. package/dist/web/public/assets/{rolldown-runtime-XKyaHtl9.js → jsx-runtime-EIAPxkjE.js} +1 -1
  8. package/dist/web/public/assets/review-CLHgc7OK.js +44 -0
  9. package/dist/web/public/assets/routes-CS6_XKJl.js +1 -0
  10. package/dist/web/server/_libs/@base-ui/react+[...].mjs +2686 -4472
  11. package/dist/web/server/_libs/@tanstack/react-router+[...].mjs +1 -107
  12. package/dist/web/server/_libs/lucide-react.mjs +93 -268
  13. package/dist/web/server/_libs/react-markdown+[...].mjs +1 -1
  14. package/dist/web/server/_libs/valibot.mjs +1 -59
  15. package/dist/web/server/_ssr/highlight.server-Ch_kPZFd.mjs +199 -0
  16. package/dist/web/server/_ssr/{listener.functions-DygHonX4.mjs → listener.functions-r5sy6slm.mjs} +7 -7
  17. package/dist/web/server/_ssr/{listener.server-BUJSjrgf.mjs → listener.server-Ch_E4TJ7.mjs} +3 -2
  18. package/dist/web/server/_ssr/{review-block-DusFmCX_.mjs → review-CXA8hOed.mjs} +5200 -5492
  19. package/dist/web/server/_ssr/review-folder.server-DrhuBcAc.mjs +354 -0
  20. package/dist/web/server/_ssr/{adhoc.functions-CDadmCcu.mjs → review-link.functions-BvcyZSk2.mjs} +12 -11
  21. package/dist/web/server/_ssr/review-link.server-XUXU8Jjl.mjs +180 -0
  22. package/dist/web/server/_ssr/{review-parts.server-j_3LS0HZ.mjs → review-parts.server-CSSa-ZRv.mjs} +2 -2
  23. package/dist/web/server/_ssr/review-read.functions-Da-f7qpe.mjs +37 -0
  24. package/dist/web/server/_ssr/{live-schema-BYm_IvNp.mjs → review-schema-C0qXng9-.mjs} +5 -64
  25. package/dist/web/server/_ssr/review-target.server-C8IXgmE-.mjs +18 -0
  26. package/dist/web/server/_ssr/{review.functions-Cvig5BYP.mjs → review.functions-BYEhPk_l.mjs} +19 -17
  27. package/dist/web/server/_ssr/review.server-DFe2jCWt.mjs +847 -0
  28. package/dist/web/server/_ssr/{router-CpBxvGJX.mjs → router-DqvyAgJl.mjs} +119 -257
  29. package/dist/web/server/_ssr/routes-6k-4pwuW.mjs +20 -0
  30. package/dist/web/server/_ssr/ssr.mjs +36 -72
  31. package/dist/web/server/_ssr/{thread-code-BWhoBW-5.mjs → thread-code-CYNB3wg5.mjs} +2 -3
  32. package/dist/web/server/_ssr/{type-hover-DSq-tkS_.mjs → type-hover-BWVNL2Vt.mjs} +2 -3
  33. package/dist/web/server/_ssr/{type-hover.functions-B_9iC3Xs.mjs → type-hover.functions-oAqPixru.mjs} +6 -5
  34. package/dist/web/server/_tanstack-start-manifest_v-BBV9HPN6.mjs +30 -0
  35. package/dist/web/server/index.mjs +25 -88
  36. package/package.json +1 -1
  37. package/skills/adiff-web/SKILL.md +2 -2
  38. package/dist/web/public/assets/_deck-BmRfIUSA.js +0 -1
  39. package/dist/web/public/assets/_point-BVE7ChTL.js +0 -1
  40. package/dist/web/public/assets/adhoc.functions-C2dHzbMd.js +0 -1
  41. package/dist/web/public/assets/decks.functions-tXNTG2sC.js +0 -2
  42. package/dist/web/public/assets/index-B1ZY8zdK.css +0 -2
  43. package/dist/web/public/assets/index-aVNw-2pB.js +0 -11
  44. package/dist/web/public/assets/preload-helper-D5PXivxI.js +0 -1
  45. package/dist/web/public/assets/review-block-BEAsY2QM.js +0 -47
  46. package/dist/web/public/assets/review-w-sdAG51.js +0 -1
  47. package/dist/web/public/assets/routes-BvjPl7Jk.js +0 -1
  48. package/dist/web/public/assets/shortcuts-BsNWbUaT.js +0 -1
  49. package/dist/web/public/assets/use-window-event-BDUVK1pJ.js +0 -1
  50. package/dist/web/public/assets/viewed-store-Cwoyp53w.js +0 -1
  51. package/dist/web/server/_deck-DFij1FXC.mjs +0 -387
  52. package/dist/web/server/_libs/yaml.mjs +0 -6585
  53. package/dist/web/server/_point-CIICFuLm.mjs +0 -1528
  54. package/dist/web/server/_ssr/decks.functions-BHxu668D.mjs +0 -1073
  55. package/dist/web/server/_ssr/review-DBgvCWDX.mjs +0 -58
  56. package/dist/web/server/_ssr/review-target.server-DA41RDao.mjs +0 -1779
  57. package/dist/web/server/_ssr/routes-pAqxw-ZQ.mjs +0 -27
  58. package/dist/web/server/_ssr/shortcuts-B7llaLLc.mjs +0 -228
  59. package/dist/web/server/_ssr/viewed-store-CyYRWeAX.mjs +0 -198
  60. package/dist/web/server/_tanstack-start-manifest_v-Bf1fW3Lx.mjs +0 -56
@@ -0,0 +1,847 @@
1
+ import { ask, isJustRead, isStillRead, noteRead, signOf } from "./review-folder.server-DrhuBcAc.mjs";
2
+ import { toRendered } from "./highlight.server-Ch_kPZFd.mjs";
3
+ import { getRealWorktree, git } from "./review-link.server-XUXU8Jjl.mjs";
4
+ import { array, boolean, number, object, optional, parse, picklist, safeParse, string } from "../_libs/valibot.mjs";
5
+ import path from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ // node_modules/.nitro/vite/services/ssr/assets/review.server-DFe2jCWt.js
8
+ var standSchema = picklist([
9
+ "filed",
10
+ "waiting",
11
+ "answered",
12
+ "asked",
13
+ "settled",
14
+ "gone"
15
+ ]);
16
+ var partSchema = object({
17
+ path: string(),
18
+ /** The file's lines inside the layer's spans. */
19
+ added: number(),
20
+ removed: number(),
21
+ read: boolean(),
22
+ /** The part's open comments, and the loudest of their marks. */
23
+ open: number(),
24
+ stand: standSchema
25
+ });
26
+ var layerSchema = object({
27
+ title: string(),
28
+ note: optional(string(), ""),
29
+ files: array(string()),
30
+ spans: optional(array(object({
31
+ path: string(),
32
+ start: number(),
33
+ end: number()
34
+ })), []),
35
+ /** The note in pieces, each placed before (or `after`) a line of a file. */
36
+ prose: optional(array(object({
37
+ path: string(),
38
+ line: number(),
39
+ markdown: string(),
40
+ after: boolean()
41
+ })), []),
42
+ read: optional(array(string()), []),
43
+ vanished: optional(array(string()), []),
44
+ /** The added and removed lines inside the layer's own spans, as adiff counts them. */
45
+ added: number(),
46
+ removed: number(),
47
+ /** Every file in the layer is read. */
48
+ done: boolean(),
49
+ /** The layer adiff adds for the changed lines no layer claims. */
50
+ unclaimed: boolean(),
51
+ /** The layer's open comments, and the loudest of their marks. */
52
+ open: number(),
53
+ stand: standSchema,
54
+ parts: array(partSchema),
55
+ /** The number the screen shows: `3`, or `2.2` for a ticket's second sublayer. */
56
+ address: optional(string()),
57
+ /** A sublayer's ticket, by its number, and its place under that ticket from 1. */
58
+ ticket: optional(number()),
59
+ sublayer: optional(number())
60
+ });
61
+ /** A layer that holds sublayers, with them rolled up as adiff counts them. */
62
+ var ticketSchema = object({
63
+ number: number(),
64
+ address: string(),
65
+ title: string(),
66
+ note: optional(string(), ""),
67
+ /** Its sublayers' positions in `layers`, from 1. */
68
+ layers: array(number()),
69
+ sublayers: number(),
70
+ sublayersDone: optional(number(), 0),
71
+ files: array(string()),
72
+ added: number(),
73
+ removed: number(),
74
+ done: optional(boolean(), false),
75
+ open: optional(number(), 0),
76
+ stand: optional(standSchema, "gone")
77
+ });
78
+ var layersReportSchema = object({
79
+ stale: optional(boolean(), false),
80
+ summary: optional(string(), ""),
81
+ layers: array(layerSchema),
82
+ tickets: optional(array(ticketSchema), []),
83
+ /** The plain layers and tickets, the M in "Layer N of M". */
84
+ topLevel: optional(number())
85
+ });
86
+ var layersSchema = object({ layers: layersReportSchema });
87
+ var turnSchema = object({
88
+ voice: picklist(["reviewer", "agent"]),
89
+ body: string(),
90
+ at: string(),
91
+ choices: optional(array(string()))
92
+ });
93
+ var threadSchema = object({
94
+ id: string(),
95
+ file: string(),
96
+ side: picklist(["old", "new"]),
97
+ start: number(),
98
+ end: number(),
99
+ snippet: optional(string(), ""),
100
+ body: string(),
101
+ at: optional(string(), ""),
102
+ state: string(),
103
+ /** The lines it was written on changed, and it sits at that change. */
104
+ outdated: optional(boolean(), false),
105
+ settled: optional(boolean(), false),
106
+ unread: optional(number(), 0),
107
+ taken: optional(boolean(), false),
108
+ doing: optional(object({
109
+ body: string(),
110
+ at: string()
111
+ })),
112
+ turns: array(turnSchema),
113
+ stand: standSchema,
114
+ section: picklist([
115
+ "asked",
116
+ "filed",
117
+ "with",
118
+ "answered",
119
+ "movedOn",
120
+ "settled",
121
+ "removed"
122
+ ]),
123
+ /** Its code is gone from the diff, or changed past rewording: listed, never drawn on a line. */
124
+ movedPast: boolean(),
125
+ reworded: boolean(),
126
+ about: picklist(["branch", "line"]),
127
+ /** It has answers and every one is read: what `comment resolve --read` settles. */
128
+ settleable: boolean(),
129
+ /** The layers it is read in, from 1. */
130
+ layers: array(number())
131
+ });
132
+ /** A file's threads drawn on its lines: the open ones and their loudest mark, and the settled. */
133
+ var fileMarkSchema = object({
134
+ path: string(),
135
+ open: number(),
136
+ settled: number(),
137
+ stand: standSchema
138
+ });
139
+ /** A line threads are drawn on, and the loudest mark among all of them, settled counting least. */
140
+ var lineMarkSchema = object({
141
+ path: string(),
142
+ side: picklist(["old", "new"]),
143
+ line: number(),
144
+ open: number(),
145
+ settled: number(),
146
+ stand: standSchema
147
+ });
148
+ /** The headline's two numbers, as adiff counts them: questions waiting on you, answers to read. */
149
+ var countsSchema = object({
150
+ asked: number(),
151
+ unread: number()
152
+ });
153
+ var threadsSchema = object({
154
+ comments: array(threadSchema),
155
+ counts: optional(countsSchema),
156
+ files: array(fileMarkSchema),
157
+ lines: array(lineMarkSchema)
158
+ });
159
+ var markedSchema = object({ layers: optional(layersReportSchema) });
160
+ /**
161
+ * There is no comment about a whole branch in adiff, so a request about the branch (`layers ask`)
162
+ * sits on the first line of the first file and opens with this sentence, which the panel leaves out.
163
+ */
164
+ var BRANCH_ASK = "About this branch, not about this line. ";
165
+ var toThread = (thread) => ({
166
+ id: thread.id,
167
+ file: thread.about === "branch" ? "" : thread.file,
168
+ isAboutBranch: thread.about === "branch",
169
+ side: thread.side,
170
+ start: thread.start,
171
+ end: thread.end,
172
+ snippet: thread.snippet,
173
+ body: thread.about === "branch" ? thread.body.replace(BRANCH_ASK, "") : thread.body,
174
+ at: thread.at,
175
+ isSettled: thread.settled,
176
+ isMovedPast: thread.movedPast,
177
+ isOutdated: thread.outdated,
178
+ isTaken: thread.taken,
179
+ isSettleable: thread.settleable,
180
+ stand: thread.stand,
181
+ section: thread.section,
182
+ layers: thread.layers,
183
+ layerAddress: null,
184
+ state: thread.state,
185
+ unread: thread.unread,
186
+ doing: thread.doing,
187
+ turns: thread.turns
188
+ });
189
+ /** An adiff older than sublayers numbers each layer by its place, as it always did. */
190
+ var toLayer = ({ done, unclaimed, parts, address, ticket, sublayer, ...layer }, at) => ({
191
+ ...layer,
192
+ address: address ?? String(at + 1),
193
+ ticket: ticket ?? null,
194
+ sublayer: sublayer ?? null,
195
+ isDone: done,
196
+ isRemainder: unclaimed,
197
+ parts: parts.map(({ read, ...part }) => ({
198
+ ...part,
199
+ isRead: read
200
+ }))
201
+ });
202
+ var toTicket = ({ done, ...ticket }) => ({
203
+ ...ticket,
204
+ isDone: done
205
+ });
206
+ /** The layers and tickets a report answers, as the page keeps them. */
207
+ var toLayers = (told) => ({
208
+ layers: told.layers.map((layer, at) => toLayer(layer, at)),
209
+ tickets: told.tickets.map((ticket) => toTicket(ticket))
210
+ });
211
+ /** The outline's fields `layers show` answers. */
212
+ var toLayerFields = (told) => ({
213
+ summary: told.summary,
214
+ isLayersStale: told.stale,
215
+ unclaimedLines: told.layers.reduce((sum, layer) => layer.unclaimed ? sum + layer.added + layer.removed : sum, 0),
216
+ ...toLayers(told),
217
+ topLevel: told.topLevel ?? told.layers.filter((layer) => !layer.unclaimed).length
218
+ });
219
+ /**
220
+ * Names each thread's first layer by its address. A thread counts its layers by their place in
221
+ * `layers show`, and a sublayer's place is not the `2.2` the screen shows.
222
+ */
223
+ var nameThreadLayers = (threads, layers) => threads.map((thread) => {
224
+ const [first] = thread.layers;
225
+ const address = first === void 0 ? null : layers[first - 1]?.address ?? String(first);
226
+ return address === thread.layerAddress ? thread : {
227
+ ...thread,
228
+ layerAddress: address
229
+ };
230
+ });
231
+ /** The outline's fields `comment list` answers. */
232
+ var toCommentFields = (listed) => ({
233
+ threads: listed.comments.map((thread) => toThread(thread)),
234
+ fileMarks: listed.files,
235
+ lineMarks: listed.lines,
236
+ threadCounts: listed.counts ?? null
237
+ });
238
+ var rowSchema = object({
239
+ kind: picklist([
240
+ "context",
241
+ "added",
242
+ "removed",
243
+ "note"
244
+ ]),
245
+ old: optional(number()),
246
+ new: optional(number()),
247
+ text: string(),
248
+ /** The layers whose spans hold the row, from 1. */
249
+ layers: optional(array(number()), []),
250
+ /** The layers that, open, keep this changed row in place as a quiet line rather than fold it. */
251
+ quietIn: optional(array(number()), [])
252
+ });
253
+ var hunkSchema = object({
254
+ header: optional(string(), ""),
255
+ rows: array(rowSchema)
256
+ });
257
+ var patchFileSchema = object({
258
+ path: string(),
259
+ previousPath: optional(string(), ""),
260
+ status: picklist([
261
+ "added",
262
+ "deleted",
263
+ "renamed",
264
+ "copied",
265
+ "changed"
266
+ ]),
267
+ binary: optional(boolean(), false),
268
+ generated: optional(boolean(), false),
269
+ added: number(),
270
+ removed: number(),
271
+ hunks: array(hunkSchema),
272
+ enclosedBy: optional(array(number()), []),
273
+ scopes: optional(array(object({
274
+ line: number(),
275
+ text: string()
276
+ })), []),
277
+ /** The file's content as git names it, so a mark can name the version it was made on. */
278
+ blob: optional(string(), "")
279
+ });
280
+ var patchSchema = object({ patch: object({
281
+ branch: string(),
282
+ base: string(),
283
+ head: string(),
284
+ mergeBase: optional(string(), ""),
285
+ files: array(patchFileSchema),
286
+ /** Every path in the order the terminal's file tree lists them. */
287
+ order: array(string())
288
+ }) });
289
+ var sentSchema = object({ batch: object({ comments: array(object({ id: string() })) }) });
290
+ var failureSchema = object({ error: object({
291
+ type: string(),
292
+ suggestion: optional(string(), "")
293
+ }) });
294
+ var AdiffFailureError = class extends Error {
295
+ type;
296
+ constructor(type, message) {
297
+ super(message);
298
+ this.name = "AdiffFailureError";
299
+ this.type = type;
300
+ }
301
+ };
302
+ var toFailure = (answer) => {
303
+ const parsed = safeParse(failureSchema, answer);
304
+ return parsed.success ? new AdiffFailureError(parsed.output.error.type, parsed.output.error.suggestion || parsed.output.error.type) : new AdiffFailureError("AdiffFailed", JSON.stringify(answer));
305
+ };
306
+ var runAdiff = async (args) => {
307
+ const answered = await ask(args);
308
+ if (answered.exit !== 0) throw toFailure(answered.answer);
309
+ return answered.answer;
310
+ };
311
+ var runAdiffRaw = async (args) => JSON.stringify(await runAdiff(args));
312
+ var addressed = ({ repo, branch }) => [
313
+ "--repo",
314
+ repo,
315
+ "--branch",
316
+ branch
317
+ ];
318
+ var based = (address) => address.base === void 0 ? addressed(address) : [
319
+ ...addressed(address),
320
+ "--base",
321
+ address.base
322
+ ];
323
+ var getPatch = async (address, { context, file }) => {
324
+ const only = file === void 0 ? [] : ["--file", file];
325
+ const answer = await runAdiff([
326
+ "patch",
327
+ "show",
328
+ ...based(address),
329
+ "--context",
330
+ context,
331
+ ...only
332
+ ]);
333
+ return parse(patchSchema, answer).patch;
334
+ };
335
+ /** One file's diff from the version marked reviewed to the worktree now (`patch since`). */
336
+ var NO_LAYERS = {
337
+ stale: false,
338
+ summary: "",
339
+ layers: [],
340
+ tickets: []
341
+ };
342
+ var getLayers = async (address) => {
343
+ try {
344
+ return parse(layersSchema, await runAdiff([
345
+ "layers",
346
+ "show",
347
+ ...addressed(address)
348
+ ])).layers;
349
+ } catch (error) {
350
+ if (error instanceof AdiffFailureError && error.type === "NoLayers") return NO_LAYERS;
351
+ throw error;
352
+ }
353
+ };
354
+ var progressRaw = (address) => runAdiffRaw([
355
+ "review",
356
+ "progress",
357
+ ...based(address)
358
+ ]);
359
+ var layersRaw = async (address) => {
360
+ try {
361
+ return await runAdiffRaw([
362
+ "layers",
363
+ "show",
364
+ ...addressed(address)
365
+ ]);
366
+ } catch {
367
+ return "";
368
+ }
369
+ };
370
+ /**
371
+ * Marks a file reviewed, and answers with the layers as they stand after it, if any. `layer` is the
372
+ * layer's address (`2.2`), which `file review --layer` takes, not its place in the list.
373
+ */
374
+ var markReviewed = async (address, { path, layer, blob }) => {
375
+ const answer = await runAdiff([
376
+ "file",
377
+ "review",
378
+ ...based(address),
379
+ "--file",
380
+ path,
381
+ ...layer === null ? [] : ["--layer", layer],
382
+ ...blob === "" ? [] : ["--blob", blob]
383
+ ]);
384
+ const told = parse(markedSchema, answer).layers;
385
+ return told === void 0 ? null : toLayers(told);
386
+ };
387
+ var listRaw = (address) => runAdiffRaw([
388
+ "comment",
389
+ "list",
390
+ ...based(address)
391
+ ]);
392
+ var getThreads = async (address) => parse(threadsSchema, JSON.parse(await listRaw(address)));
393
+ var sendComment = async (address, thread) => {
394
+ const answer = await runAdiff([
395
+ "comment",
396
+ "send",
397
+ ...addressed(address),
398
+ "--file",
399
+ thread.path,
400
+ "--from",
401
+ thread.from,
402
+ "--to",
403
+ thread.to,
404
+ "--body",
405
+ thread.body
406
+ ]);
407
+ const sent = safeParse(sentSchema, answer);
408
+ return sent.success ? sent.output.batch.comments[0]?.id ?? null : null;
409
+ };
410
+ var replyComment = async (address, { id, body }) => {
411
+ await runAdiff([
412
+ "comment",
413
+ "reply",
414
+ ...addressed(address),
415
+ "--to",
416
+ id,
417
+ "--body",
418
+ body
419
+ ]);
420
+ };
421
+ var settleComment = async (address, { id, settled }) => {
422
+ await runAdiff([
423
+ "comment",
424
+ settled ? "resolve" : "reopen",
425
+ ...addressed(address),
426
+ "--id",
427
+ id
428
+ ]);
429
+ };
430
+ var sinceSchema = object({
431
+ path: string(),
432
+ at: optional(string(), ""),
433
+ reviewed: optional(string(), ""),
434
+ added: optional(number(), 0),
435
+ removed: optional(number(), 0),
436
+ places: optional(number(), 0),
437
+ /** The reviewed version is in git's object store, so the change since can be shown. */
438
+ kept: optional(boolean(), false),
439
+ deleted: optional(boolean(), false),
440
+ /** The layers whose lines changed since review, from 1. */
441
+ layers: array(number())
442
+ });
443
+ var progressSchema = object({
444
+ reviewed: array(string()),
445
+ since: array(sinceSchema),
446
+ /** How many files there are to review. */
447
+ total: number()
448
+ });
449
+ /** What adiff answers when there is no reviewed version to diff from: not marked, or not kept. */
450
+ var NO_SINCE = /* @__PURE__ */ new Set(["NotVouched", "VouchedVersionGone"]);
451
+ /** One file's diff from the version marked reviewed, or null when adiff has no such version. */
452
+ var getSince = async (address, file) => {
453
+ try {
454
+ const answer = await runAdiff([
455
+ "patch",
456
+ "since",
457
+ ...based(address),
458
+ "--file",
459
+ file,
460
+ "--context",
461
+ "all"
462
+ ]);
463
+ return parse(object({ file: patchFileSchema }), answer).file;
464
+ } catch (error) {
465
+ if (error instanceof AdiffFailureError && NO_SINCE.has(error.type)) return null;
466
+ throw error;
467
+ }
468
+ };
469
+ /** Which files are reviewed, which changed since, and how many there are to review. */
470
+ var getProgress = async (address) => parse(progressSchema, JSON.parse(await progressRaw(address)));
471
+ /**
472
+ * Runs `run` one at a time. A call made while it runs waits for that run, then shares one more,
473
+ * so it sees everything that happened before the call, and any number of calls meanwhile cost
474
+ * that one run. A review's live stream sends a change every second or two while an agent works,
475
+ * and a read can take longer than that: without this the reads pile up and every other request
476
+ * of the page, the file the reader opens among them, waits behind them.
477
+ */
478
+ var createCoalesced = (run) => {
479
+ const runs = {
480
+ running: null,
481
+ next: null
482
+ };
483
+ const start = async () => {
484
+ const started = run();
485
+ runs.running = started;
486
+ try {
487
+ return await started;
488
+ } finally {
489
+ if (runs.running === started) runs.running = null;
490
+ }
491
+ };
492
+ const after = async (running) => {
493
+ try {
494
+ await running;
495
+ } catch {}
496
+ runs.next = null;
497
+ return start();
498
+ };
499
+ return () => {
500
+ if (runs.running === null) return start();
501
+ runs.next ??= after(runs.running);
502
+ return runs.next;
503
+ };
504
+ };
505
+ /**
506
+ * A map that keeps only the `limit` entries used last: reading or writing an entry makes it the
507
+ * newest, and the oldest goes once the map is full. The server keeps whole reviews this way, so a
508
+ * day of opening branches does not keep every one of them in memory.
509
+ */
510
+ var keepRecent = (limit) => {
511
+ const entries = /* @__PURE__ */ new Map();
512
+ const touch = (key, value) => {
513
+ entries.delete(key);
514
+ entries.set(key, value);
515
+ const [oldest] = entries.keys();
516
+ if (entries.size > limit && oldest !== void 0) entries.delete(oldest);
517
+ return value;
518
+ };
519
+ const get = (key) => {
520
+ const value = entries.get(key);
521
+ return value === void 0 ? void 0 : touch(key, value);
522
+ };
523
+ return {
524
+ get,
525
+ set: touch
526
+ };
527
+ };
528
+ var IMAGE_TYPES = {
529
+ ".svg": "image/svg+xml",
530
+ ".png": "image/png",
531
+ ".jpg": "image/jpeg",
532
+ ".jpeg": "image/jpeg",
533
+ ".gif": "image/gif",
534
+ ".webp": "image/webp"
535
+ };
536
+ var OPS = {
537
+ context: " ",
538
+ added: "+",
539
+ removed: "-",
540
+ note: " "
541
+ };
542
+ var STATUSES = {
543
+ added: "added",
544
+ deleted: "deleted",
545
+ renamed: "renamed",
546
+ copied: "copied",
547
+ changed: "modified"
548
+ };
549
+ var getImageType = (file) => IMAGE_TYPES[path.extname(file).toLowerCase()];
550
+ var toRow = (row) => [
551
+ OPS[row.kind],
552
+ row.old ?? null,
553
+ row.new ?? null,
554
+ row.text
555
+ ];
556
+ var getSource = (rows) => {
557
+ const old = rows.filter((row) => row.old !== void 0);
558
+ return (old.length > 0 ? old : rows.filter((row) => row.new !== void 0)).map((row) => row.text);
559
+ };
560
+ /**
561
+ * The line adiff adds saying where a renamed or copied file came from. The file's status and previous
562
+ * path already say it, and drawn as a row it was a line of code with no number, folded to "…".
563
+ */
564
+ var MOVED_NOTE = /^(?:renamed|copied) from /u;
565
+ var isCode = (row) => row.kind !== "note" || !MOVED_NOTE.test(row.text);
566
+ var toFileDiff = (file, { head, mergeBase }) => {
567
+ const rows = file.hunks.flatMap((hunk) => hunk.rows).filter((row) => isCode(row));
568
+ return {
569
+ path: file.path,
570
+ oldSha: file.status === "added" ? null : mergeBase,
571
+ newSha: file.status === "deleted" ? null : head,
572
+ proposed: false,
573
+ oldAbs: null,
574
+ oldRoot: null,
575
+ newAbs: null,
576
+ newRoot: null,
577
+ isNew: file.status === "added",
578
+ source: getSource(rows),
579
+ rows: rows.map((row) => toRow(row))
580
+ };
581
+ };
582
+ var getImage = (file) => getImageType(file.path) === void 0 ? null : {
583
+ old: file.status !== "added",
584
+ new: file.status !== "deleted"
585
+ };
586
+ var hash = (text) => createHash("sha1").update(text).digest("hex");
587
+ /**
588
+ * What a file's rows are drawn from: its content and the base it is read against, never the
589
+ * branch head, so a commit that leaves a file alone leaves its rows cached on both sides.
590
+ */
591
+ var getFingerprint = (file, shas) => hash(JSON.stringify([
592
+ shas.mergeBase,
593
+ file.status,
594
+ file.previousPath,
595
+ file.blob,
596
+ file.hunks
597
+ ]));
598
+ var toFileMeta = (file, shas) => ({
599
+ path: file.path,
600
+ oldSha: file.status === "added" ? null : shas.mergeBase,
601
+ newSha: file.status === "deleted" ? null : shas.head,
602
+ proposed: false,
603
+ isNew: file.status === "added",
604
+ rows: [],
605
+ status: STATUSES[file.status],
606
+ previousPath: file.previousPath === "" ? file.path : file.previousPath,
607
+ isBinary: file.binary,
608
+ isGenerated: file.generated,
609
+ image: getImage(file),
610
+ fingerprint: getFingerprint(file, shas),
611
+ enclosedBy: [],
612
+ added: file.added,
613
+ removed: file.removed,
614
+ blob: file.blob
615
+ });
616
+ /**
617
+ * The rendered rows, each with the layers adiff says hold it and the layers that keep it in place
618
+ * quiet, matched one for one.
619
+ */
620
+ var withLayers = (file, rows) => {
621
+ const drawn = file.hunks.flatMap((hunk) => hunk.rows).filter((row) => isCode(row));
622
+ return rows.map((row, index) => {
623
+ const layers = drawn[index]?.layers ?? [];
624
+ const quietIn = drawn[index]?.quietIn ?? [];
625
+ const tagged = layers.length === 0 ? row : {
626
+ ...row,
627
+ layers
628
+ };
629
+ return quietIn.length === 0 ? tagged : {
630
+ ...tagged,
631
+ quietIn
632
+ };
633
+ });
634
+ };
635
+ var toReviewFile = (file, { shas, fingerprint }) => {
636
+ const rendered = toRendered(toFileDiff(file, shas));
637
+ return {
638
+ ...toFileMeta(file, shas),
639
+ ...rendered,
640
+ rows: withLayers(file, rendered.rows),
641
+ fingerprint,
642
+ enclosedBy: file.enclosedBy
643
+ };
644
+ };
645
+ var rendered = keepRecent(400);
646
+ var keep = (key, file) => rendered.set(key, file);
647
+ /** Whole reviews, kept for the few a reviewer moves between. */
648
+ var keepReviews = () => keepRecent(6);
649
+ /** A whole branch's patch is megabytes; only the reviews read last stay in memory. */
650
+ var patches = keepReviews();
651
+ var addressKey = (address) => `${address.repo}|${address.branch}|${address.base ?? ""}`;
652
+ var readPatch = async (address) => {
653
+ const patch = await getPatch(address, { context: "all" });
654
+ patches.set(addressKey(address), patch);
655
+ return patch;
656
+ };
657
+ var keptPatch = (address) => patches.get(addressKey(address));
658
+ var shasOf = (patch) => ({
659
+ head: patch.head,
660
+ mergeBase: patch.mergeBase || patch.base
661
+ });
662
+ var fromKept = (address, { file, fingerprint }) => {
663
+ const patch = keptPatch(address);
664
+ const found = patch?.files.find((candidate) => candidate.path === file);
665
+ if (patch === void 0 || found === void 0) return null;
666
+ const shas = shasOf(patch);
667
+ return toFileMeta(found, shas).fingerprint === fingerprint ? {
668
+ found,
669
+ shas
670
+ } : null;
671
+ };
672
+ var renderFile = async (address, file) => {
673
+ const patch = await getPatch(address, {
674
+ context: "all",
675
+ file
676
+ });
677
+ const shas = {
678
+ head: patch.head,
679
+ mergeBase: patch.mergeBase || patch.base
680
+ };
681
+ const found = patch.files.find((candidate) => candidate.path === file);
682
+ if (found === void 0) throw new Error(`${file} is not in this diff any more`);
683
+ return {
684
+ found,
685
+ shas
686
+ };
687
+ };
688
+ var getReviewFile = async (address, { path: file, fingerprint }) => {
689
+ const key = `${address.repo}|${address.branch}|${address.base ?? ""}|${file}|${fingerprint}`;
690
+ const kept = rendered.get(key);
691
+ if (kept !== void 0) return kept;
692
+ const { found, shas } = fromKept(address, {
693
+ file,
694
+ fingerprint
695
+ }) ?? await renderFile(address, file);
696
+ return keep(key, toReviewFile(found, {
697
+ shas,
698
+ fingerprint
699
+ }));
700
+ };
701
+ /** One file from the version marked reviewed to now, drawn as the branch's files are. */
702
+ var getSinceFile = async (address, { path: file, reviewed, blob }) => {
703
+ const key = `${address.repo}|${address.branch}|${file}|since|${reviewed}|${blob}`;
704
+ const kept = rendered.get(key);
705
+ if (kept !== void 0) return kept;
706
+ const found = await getSince(address, file);
707
+ const shas = {
708
+ head: keptPatch(address)?.head ?? "",
709
+ mergeBase: reviewed
710
+ };
711
+ return found === null ? null : keep(key, {
712
+ ...toReviewFile(found, {
713
+ shas,
714
+ fingerprint: hash(key)
715
+ }),
716
+ isSince: true
717
+ });
718
+ };
719
+ var toFailedOutline = (address, error) => ({
720
+ branch: address.branch,
721
+ base: {
722
+ sha: "",
723
+ label: address.base
724
+ },
725
+ head: { sha: "" },
726
+ worktree: null,
727
+ files: [],
728
+ order: [],
729
+ summary: "",
730
+ isLayersStale: false,
731
+ unclaimedLines: 0,
732
+ layers: [],
733
+ tickets: [],
734
+ topLevel: 0,
735
+ reviewed: [],
736
+ total: 0,
737
+ since: [],
738
+ threads: [],
739
+ fileMarks: [],
740
+ lineMarks: [],
741
+ threadCounts: null,
742
+ error: error instanceof Error ? error.message : String(error)
743
+ });
744
+ /**
745
+ * The outline carries every file's meta but no rows: the page loads the open file's rows on its
746
+ * own, and an outline reread on every change stays small however large the diff is. The first
747
+ * file is rendered here in the background, so its request finds it ready.
748
+ */
749
+ var warmFile = async (address, file) => {
750
+ try {
751
+ await getReviewFile(address, file);
752
+ } catch {}
753
+ };
754
+ var openFirst = async (address, { isWhole }) => {
755
+ const patch = (isWhole ? void 0 : keptPatch(address)) ?? await readPatch(address);
756
+ const shas = shasOf(patch);
757
+ const files = patch.files.map((file) => toFileMeta(file, shas));
758
+ const shown = files.find((file) => file.path === patch.order[0]);
759
+ if (shown !== void 0) setImmediate(() => {
760
+ warmFile(address, shown);
761
+ });
762
+ return {
763
+ patch,
764
+ files
765
+ };
766
+ };
767
+ var outlines = keepReviews();
768
+ var reading = /* @__PURE__ */ new Map();
769
+ var outlineKey = (address) => `${address.repo}|${address.branch}|${address.base ?? ""}`;
770
+ /** The spans each patch was read with: rows carry their layers, so new spans need a new read. */
771
+ var spansRead = /* @__PURE__ */ new Map();
772
+ var spansOf = (layers) => JSON.stringify(layers.map((layer) => layer.spans));
773
+ /** The patch, read again when the layers moved since it was read, so its rows name them right. */
774
+ var retagged = async (address, { isWhole, opened, layers }) => {
775
+ const key = outlineKey(address);
776
+ const tagged = isWhole || spansRead.get(key) === spansOf(layers) ? opened : await openFirst(address, { isWhole: true });
777
+ spansRead.set(key, spansOf(layers));
778
+ return tagged;
779
+ };
780
+ var makeKept = async (address, isWhole) => {
781
+ const sign = signOf(address, getBranchHead(address));
782
+ const made = await makeOutline(address, { isWhole });
783
+ if (made.error === null) {
784
+ outlines.set(outlineKey(address), made);
785
+ if (isWhole) noteRead(outlineKey(address), sign);
786
+ }
787
+ return made;
788
+ };
789
+ /** One read of a review at a time; asks while it runs share the one read after it. */
790
+ var readOutline = (address, isWhole = true) => {
791
+ const key = `${outlineKey(address)}|${String(isWhole)}`;
792
+ const read = reading.get(key) ?? createCoalesced(() => makeKept(address, isWhole));
793
+ reading.set(key, read);
794
+ return read();
795
+ };
796
+ var getReviewOutline = (address, { isFresh, isWhole }) => {
797
+ const kept = outlines.get(outlineKey(address));
798
+ return (!isFresh || isWhole && isJustRead(outlineKey(address), signOf(address, getBranchHead(address)))) && kept !== void 0 ? Promise.resolve(kept) : readOutline(address, isWhole);
799
+ };
800
+ var startOutline = (address) => {
801
+ readOutline(address);
802
+ };
803
+ /**
804
+ * The outline a page can carry and draw at once: only one nothing has moved under since it was
805
+ * read. An older one would draw, restore the reader's place against stale rows, then jump.
806
+ */
807
+ var keptOutline = (address) => isStillRead(outlineKey(address), signOf(address, getBranchHead(address))) ? outlines.get(outlineKey(address)) ?? null : null;
808
+ var makeOutline = async (address, { isWhole }) => {
809
+ try {
810
+ const [opened, told, progress, listed] = await Promise.all([
811
+ openFirst(address, { isWhole }),
812
+ getLayers(address),
813
+ getProgress(address),
814
+ getThreads(address)
815
+ ]);
816
+ const { patch, files } = await retagged(address, {
817
+ isWhole,
818
+ opened,
819
+ layers: told.layers
820
+ });
821
+ return {
822
+ branch: address.branch,
823
+ base: {
824
+ sha: patch.mergeBase,
825
+ label: patch.base
826
+ },
827
+ head: { sha: patch.head },
828
+ worktree: getRealWorktree(address),
829
+ files,
830
+ order: patch.order,
831
+ ...toLayerFields(told),
832
+ ...progress,
833
+ ...toCommentFields(listed),
834
+ error: null
835
+ };
836
+ } catch (error) {
837
+ return toFailedOutline(address, error);
838
+ }
839
+ };
840
+ var getBranchHead = (address) => {
841
+ try {
842
+ return git(address.repo, ["rev-parse", `refs/heads/${address.branch}`]).toString().trim();
843
+ } catch {
844
+ return "";
845
+ }
846
+ };
847
+ export { AdiffFailureError, addressed, based, createCoalesced, getBranchHead, getImageType, getLayers, getProgress, getReviewFile, getReviewOutline, getSinceFile, getThreads, hash, keptOutline, layersRaw, listRaw, markReviewed, nameThreadLayers, openFirst, outlineKey, outlines, progressRaw, replyComment, retagged, runAdiff, sendComment, settleComment, startOutline, toCommentFields, toLayerFields };