git-tm 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { api, html, raw, $, $$, icons, toast, storage, WORKTREE } from "./ui.js";
1
+ import { api, html, raw, $, $$, icons, toast, storage, copyText, openContextMenu, clearAvatars, historyWriteState, WORKTREE } from "./ui.js";
2
2
  import { createHistory } from "./history.js";
3
3
  import { createCompare } from "./compare.js";
4
4
  import { createReflog } from "./reflog.js";
@@ -36,6 +36,22 @@ const app = {
36
36
  renderRepo();
37
37
  renderSidebar();
38
38
  },
39
+
40
+ /** After git-tm itself changed history: refresh every view without the "changed on disk" banner. */
41
+ async afterEdit() {
42
+ await app.reloadRepo();
43
+ try {
44
+ fingerprint = (await api("state")).fingerprint;
45
+ } catch {
46
+ /* the next poll catches up */
47
+ }
48
+ $("#banner").hidden = true;
49
+ app.views.history.reload();
50
+ app.views.reflog.invalidate();
51
+ app.views.insights.invalidate();
52
+ if (app.current === "reflog") app.views.reflog.load();
53
+ else if (app.current === "compare") route();
54
+ },
39
55
  };
40
56
 
41
57
  // ------------------------------------------------------------------ search
@@ -88,12 +104,43 @@ async function onSearch(e) {
88
104
 
89
105
  // ------------------------------------------------------------------ header + sidebar
90
106
 
107
+ // In the VS Code extension, edit mode is a setting rather than a command-line flag.
108
+ const inVsCode = Boolean(globalThis.gitTmBridge);
109
+
91
110
  function renderRepo() {
92
111
  const r = app.repo;
93
112
  const where = r.branch ?? (r.head ? `detached at ${r.head.slice(0, 7)}` : "no commits yet");
94
113
  $("#repo").innerHTML = String(html`<span class="repo-name" title="${r.root}">${r.name}</span>
95
- <span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>`);
114
+ <span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>
115
+ ${r.edit ? html`<span class="edit-badge" title="${inVsCode ? "gitTm.enableEditMode is on" : "Started with --edit"}: history can be changed. Every edit is backed up and can be undone.">Edit mode</span>` : ""}`);
96
116
  document.title = `${r.name} · Git Time Machine`;
117
+ const mb = $("#mode-banner");
118
+ if (mb) {
119
+ if (r.edit) {
120
+ mb.className = "mode-banner edit";
121
+ mb.dataset.mode = "edit";
122
+ mb.hidden = false;
123
+ mb.innerHTML = String(html`<span><strong>Edit mode active</strong> — read-only protection is off. History can be rewritten here; every edit is previewed and backed up for Undo.</span>`);
124
+ mb.onclick = null;
125
+ } else {
126
+ const show = !storage.get("hide-edit-hint", false);
127
+ mb.className = "mode-banner";
128
+ mb.hidden = !show;
129
+ // Redraw when switching from edit mode (the setting can change while the page is open).
130
+ if (show && mb.dataset.mode !== "read-only") {
131
+ mb.dataset.mode = "read-only";
132
+ const how = inVsCode ? html`Turn on the <code>gitTm.enableEditMode</code> setting` : html`Restart with <code>git-tm --edit</code>`;
133
+ mb.innerHTML = String(html`<span><strong>Read-only mode</strong> — want to reword, squash, drop, or revert commits? ${how}</span>
134
+ <button class="icon-btn" data-act="dismiss-mode" title="Dismiss" aria-label="Dismiss">${raw(icons.close)}</button>`);
135
+ mb.onclick = (e) => {
136
+ if (e.target.closest("[data-act=dismiss-mode]")) {
137
+ mb.hidden = true;
138
+ storage.set("hide-edit-hint", true);
139
+ }
140
+ };
141
+ }
142
+ }
143
+ }
97
144
  }
98
145
 
99
146
  const collapsed = new Set(storage.get("collapsed", ["tags"]));
@@ -243,8 +290,18 @@ let offline = false;
243
290
 
244
291
  async function poll() {
245
292
  if (document.hidden && !offline) return;
293
+ // While git-tm itself moves a branch, or if it did during this request, the change isn't news:
294
+ // afterEdit() picks up the new state.
295
+ const before = historyWriteState();
296
+ if (before.busy) return;
246
297
  try {
247
298
  const { fingerprint: fp } = await api("state");
299
+ const after = historyWriteState();
300
+ if (after.seq !== before.seq) return;
301
+ if (fp === after.fingerprint && fp !== fingerprint) {
302
+ fingerprint = fp; // the state right after git-tm's own edit
303
+ return;
304
+ }
248
305
  if (fingerprint && fp !== fingerprint) {
249
306
  await app.reloadRepo();
250
307
  showBanner("changed");
@@ -347,6 +404,8 @@ function onKey(e) {
347
404
  return;
348
405
  }
349
406
  if (typing || e.metaKey || e.ctrlKey || e.altKey) return;
407
+ // A modal dialog (Edit) is open: its own buttons handle the keyboard, not the views behind it.
408
+ if (document.querySelector("dialog[open]")) return;
350
409
  if (pendingG) {
351
410
  pendingG = false;
352
411
  const to = { h: "#/", c: "#/compare", r: "#/reflog", i: "#/insights" }[e.key];
@@ -380,6 +439,27 @@ async function boot() {
380
439
  if (!$("#search").value && app.filter) app.setFilter(null);
381
440
  });
382
441
  $("#sidebar").addEventListener("click", onSidebarClick);
442
+ $("#sidebar").addEventListener("contextmenu", (e) => {
443
+ const item = e.target.closest("[data-ref]");
444
+ if (!item || !item.dataset.ref) return;
445
+ const ref = item.dataset.ref;
446
+ const base = app.repo.branch || "HEAD";
447
+ openContextMenu(e, [
448
+ { label: "View history", icon: icons.history, onClick: () => app.setRef(ref) },
449
+ ref !== base
450
+ ? {
451
+ label: `Compare with ${base}`,
452
+ icon: icons.compare,
453
+ onClick: () => {
454
+ closeSidebar();
455
+ app.navigate(`#/compare/${encodeURIComponent(base)}...${encodeURIComponent(ref)}`);
456
+ },
457
+ }
458
+ : null,
459
+ "sep",
460
+ { label: "Copy ref name", icon: icons.copy, onClick: () => copyText(ref, "Ref name copied") },
461
+ ]);
462
+ });
383
463
  $("#sidebar").addEventListener("keydown", (e) => {
384
464
  if (e.key === "Enter" && e.target.matches("[data-ref]")) app.setRef(e.target.dataset.ref || null);
385
465
  });
@@ -411,6 +491,28 @@ async function boot() {
411
491
  setInterval(poll, 3000);
412
492
  poll();
413
493
  document.addEventListener("visibilitychange", poll);
494
+
495
+ // VS Code extension: open filtered (File History), retarget an open panel, or pick up changed settings.
496
+ const applyQuery = (q) => {
497
+ if (typeof q !== "string") return;
498
+ $("#search").value = q;
499
+ app.setFilter(q.trim() ? parseQuery(q) : null);
500
+ };
501
+ if (globalThis.gitTmBridge?.initialQuery) applyQuery(globalThis.gitTmBridge.initialQuery);
502
+ window.addEventListener("gtm-query", (e) => applyQuery(e.detail));
503
+ window.addEventListener("gtm-refresh", async () => {
504
+ try {
505
+ clearAvatars(); // refilled by the next responses if avatars are still on
506
+ await app.reloadRepo();
507
+ app.views.history.reload();
508
+ app.views.history.redrawDetail(); // its Edit button follows the setting
509
+ app.views.reflog.invalidate();
510
+ app.views.insights.invalidate();
511
+ if (app.current !== "history") route();
512
+ } catch (err) {
513
+ toast(err.message, "error");
514
+ }
515
+ });
414
516
  }
415
517
 
416
518
  boot();
@@ -1,6 +1,7 @@
1
1
  // Reflog view: recent HEAD movements and read-only recovery of lost commits.
2
2
 
3
- import { api, html, raw, $, avatar, refBadges, relTime, fullDate, short, plural, icons, copyText, loading, errorBox, empty } from "./ui.js";
3
+ import { api, html, raw, $, avatar, refBadges, relTime, fullDate, short, plural, icons, copyText, openContextMenu, loading, errorBox, empty } from "./ui.js";
4
+ import { mountBackups } from "./edit.js";
4
5
 
5
6
  const PAGE = 200;
6
7
 
@@ -17,12 +18,12 @@ const ACTION_KIND = {
17
18
  branch: "move",
18
19
  };
19
20
 
20
- function rescueCommands(hash) {
21
- const s = short(hash);
21
+ // Commands use the full hash: a 7-character one can match several objects in big repositories.
22
+ export function rescueCommands(hash) {
22
23
  return [
23
- { cmd: `git branch rescue-${s} ${s}`, note: "Create a new branch pointing at this commit (safest)" },
24
- { cmd: `git cherry-pick ${s}`, note: "Apply this commit onto your current branch" },
25
- { cmd: `git checkout ${s}`, note: "Inspect this commit in detached HEAD" },
24
+ { cmd: `git branch rescue-${short(hash)} ${hash}`, note: "Create a new branch pointing at this commit (safest)" },
25
+ { cmd: `git cherry-pick ${hash}`, note: "Apply this commit onto your current branch" },
26
+ { cmd: `git checkout ${hash}`, note: "Inspect this commit in detached HEAD" },
26
27
  ];
27
28
  }
28
29
 
@@ -50,6 +51,7 @@ export function createReflog(app) {
50
51
  entries = [];
51
52
  done = true;
52
53
  expanded.clear();
54
+ backupsEl = null;
53
55
  el.innerHTML = String(html`
54
56
  <div class="page-head">
55
57
  <h1>Reflog</h1>
@@ -136,10 +138,34 @@ export function createReflog(app) {
136
138
  <h1>Reflog</h1>
137
139
  <p class="muted">Recent <code>HEAD</code> movements — read-only.</p>
138
140
  </div>
141
+ ${backupsSlot()}
139
142
  ${empty("No reflog entries", "Git records HEAD movements here as you commit, checkout, reset, or rebase.")}`);
143
+ mountSlot();
140
144
  return;
141
145
  }
142
146
 
147
+ drawFull();
148
+ }
149
+
150
+ // Edits made in edit mode, with Undo, shown above the reflog while edit mode is on.
151
+ // One element per load, moved into place on each redraw, so typing in the filter doesn't refetch it.
152
+ let backupsEl = null;
153
+ function backupsSlot() {
154
+ return app.repo?.edit ? html`<div id="edit-backups"></div>` : "";
155
+ }
156
+
157
+ function mountSlot() {
158
+ const slot = $("#edit-backups", el);
159
+ if (!slot) return;
160
+ if (!backupsEl) {
161
+ backupsEl = document.createElement("section");
162
+ backupsEl.className = "edit-backups";
163
+ mountBackups(backupsEl, app);
164
+ }
165
+ slot.replaceWith(backupsEl);
166
+ }
167
+
168
+ function drawFull() {
143
169
  const lostCount = entries.filter((e) => e.orphaned).length;
144
170
  const list = filtered();
145
171
  const hadFocus = document.activeElement?.id === "reflog-filter";
@@ -150,6 +176,7 @@ export function createReflog(app) {
150
176
  <h1>Reflog</h1>
151
177
  <p class="muted">Recent <code>HEAD</code> movements — inspect or recover commits lost to <code>reset</code>, <code>rebase</code>, <code>amend</code>, or deleted branches.</p>
152
178
  </div>
179
+ ${backupsSlot()}
153
180
  <div class="reflog-bar">
154
181
  <div class="seg" role="group" aria-label="Filter reflog">
155
182
  <button data-filter="all" aria-pressed="${!onlyLost}">All <span class="seg-count">${entries.length}</span></button>
@@ -164,6 +191,8 @@ export function createReflog(app) {
164
191
  : empty(onlyLost ? "No lost commits in reflog" : "No matching reflog entries", onlyLost ? "Every recent HEAD commit is reachable from a branch or tag." : "Try clearing the filter.")}
165
192
  ${!done ? html`<div class="reflog-more"><button class="btn" data-act="more">Load older entries</button></div>` : ""}`);
166
193
 
194
+ mountSlot();
195
+
167
196
  if (hadFocus) {
168
197
  const inp = $("#reflog-filter", el);
169
198
  if (inp) {
@@ -198,6 +227,23 @@ export function createReflog(app) {
198
227
  }
199
228
  });
200
229
 
230
+ el.addEventListener("contextmenu", (e) => {
231
+ const item = e.target.closest(".reflog-item");
232
+ if (!item) return;
233
+ const entry = entries.find((x) => x.index === Number(item.dataset.index));
234
+ if (!entry) return;
235
+ const isHead = app.repo?.head && entry.hash === app.repo.head;
236
+ const rescueCmd = rescueCommands(entry.hash)[0].cmd;
237
+ openContextMenu(e, [
238
+ { label: "Open commit", icon: icons.file, onClick: () => app.navigate(`#/commit/${entry.hash}`) },
239
+ !isHead && app.repo?.head ? { label: "Compare to HEAD", icon: icons.compare, onClick: () => app.navigate(`#/compare/${entry.hash}..HEAD`) } : null,
240
+ "sep",
241
+ { label: `Copy SHA (${short(entry.hash)})`, icon: icons.copy, onClick: () => copyText(entry.hash, "Commit SHA copied") },
242
+ entry.orphaned ? "sep" : null,
243
+ entry.orphaned ? { label: "Copy rescue command", icon: icons.copy, cls: "warn", onClick: () => copyText(rescueCmd, "Rescue command copied") } : null,
244
+ ]);
245
+ });
246
+
201
247
  el.addEventListener("input", (e) => {
202
248
  if (e.target.id === "reflog-filter") {
203
249
  query = e.target.value;
@@ -4,16 +4,63 @@ export const WORKTREE = "WORKTREE";
4
4
 
5
5
  const avatarMap = Object.create(null);
6
6
 
7
- export async function api(path, params = {}, { method = "GET" } = {}) {
7
+ /** Forget avatar URLs (after avatars were turned off). */
8
+ export function clearAvatars() {
9
+ for (const k of Object.keys(avatarMap)) delete avatarMap[k];
10
+ }
11
+
12
+ // Requests that move branches. Change polling ignores results that overlap one, since git-tm
13
+ // itself made that change (see poll() in main.js).
14
+ let historyWrites = 0;
15
+ let historyWriteSeq = 0;
16
+ let ownFingerprint = null;
17
+ /**
18
+ * { busy, seq, fingerprint }: busy while an apply or undo runs; seq changes whenever one starts or
19
+ * ends; fingerprint is the repository state right after git-tm's latest write.
20
+ */
21
+ export const historyWriteState = () => ({ busy: historyWrites > 0, seq: historyWriteSeq, fingerprint: ownFingerprint });
22
+
23
+ export async function api(path, params = {}, opts = {}) {
24
+ const writes = path === "edit/apply" || path === "edit/undo";
25
+ if (!writes) return request(path, params, opts);
26
+ historyWrites++;
27
+ historyWriteSeq++;
28
+ try {
29
+ const data = await request(path, params, opts);
30
+ try {
31
+ ownFingerprint = (await request("state")).fingerprint;
32
+ } catch {
33
+ /* the next poll may show the banner; harmless */
34
+ }
35
+ return data;
36
+ } finally {
37
+ historyWrites--;
38
+ historyWriteSeq++;
39
+ }
40
+ }
41
+
42
+ async function request(path, params = {}, { method = "GET", body } = {}) {
8
43
  const qs = new URLSearchParams();
9
44
  for (const [k, v] of Object.entries(params)) {
10
45
  if (v !== undefined && v !== null && v !== "" && v !== false) qs.set(k, v === true ? "1" : String(v));
11
46
  }
12
47
  const query = qs.toString();
48
+ // Inside the VS Code extension there is no HTTP server: requests go to the extension host over postMessage.
49
+ const bridge = globalThis.gitTmBridge;
50
+ if (bridge && typeof bridge.request === "function") {
51
+ const res = await bridge.request({ method, path: `/api/${path}`, query, body });
52
+ const data = res?.data ?? {};
53
+ const status = res?.status ?? 500;
54
+ if (status !== 200) throw Object.assign(new Error(data.error || `Request failed (${status})`), { status, conflicts: data.conflicts });
55
+ if (data.avatars) Object.assign(avatarMap, data.avatars);
56
+ return data;
57
+ }
13
58
  const url = `/api/${path}${query ? `?${query}` : ""}`;
14
59
  let res;
15
60
  try {
16
- res = await fetch(url, { method, headers: method === "GET" ? {} : { "x-git-tm": "1" } });
61
+ const headers = method === "GET" ? {} : { "x-git-tm": "1" };
62
+ if (body !== undefined) headers["content-type"] = "application/json";
63
+ res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
17
64
  } catch {
18
65
  // No HTTP response. Either git-tm stopped, or the browser cancelled the
19
66
  // request (ad blockers do this to URLs that look like tracking). Ask the
@@ -31,7 +78,7 @@ export async function api(path, params = {}, { method = "GET" } = {}) {
31
78
  } catch {
32
79
  throw new Error(`Request failed (${res.status})`);
33
80
  }
34
- if (!res.ok) throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status });
81
+ if (!res.ok) throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status, conflicts: data.conflicts });
35
82
  if (data && data.avatars) Object.assign(avatarMap, data.avatars);
36
83
  return data;
37
84
  }
@@ -176,18 +223,33 @@ export const icons = {
176
223
 
177
224
  // ------------------------------------------------------------------ toasts
178
225
 
179
- export function toast(message, type = "info", ms = 3500) {
226
+ /** Show a toast. `action` ({ label, onClick }) adds a button, for example Undo. */
227
+ export function toast(message, type = "info", ms = 3500, action = null) {
180
228
  const box = document.getElementById("toasts");
181
229
  const el = document.createElement("div");
182
230
  el.className = `toast toast-${type}`;
183
231
  el.setAttribute("role", type === "error" ? "alert" : "status");
184
- el.textContent = message;
185
- box.append(el);
186
- requestAnimationFrame(() => el.classList.add("in"));
187
- setTimeout(() => {
232
+ const text = document.createElement("span");
233
+ text.textContent = message;
234
+ el.append(text);
235
+ const close = () => {
188
236
  el.classList.remove("in");
189
237
  setTimeout(() => el.remove(), 250);
190
- }, ms);
238
+ };
239
+ if (action) {
240
+ el.classList.add("has-action");
241
+ const btn = document.createElement("button");
242
+ btn.className = "btn btn-sm";
243
+ btn.textContent = action.label;
244
+ btn.addEventListener("click", () => {
245
+ close();
246
+ action.onClick();
247
+ });
248
+ el.append(btn);
249
+ }
250
+ box.append(el);
251
+ requestAnimationFrame(() => el.classList.add("in"));
252
+ setTimeout(close, ms);
191
253
  }
192
254
 
193
255
  export async function copyText(text, label = "Copied") {
@@ -226,3 +288,98 @@ export const storage = {
226
288
  } catch {}
227
289
  },
228
290
  };
291
+
292
+ // ------------------------------------------------------------------ context menu
293
+
294
+ let activeMenu = null;
295
+
296
+ export function closeContextMenu() {
297
+ if (!activeMenu) return;
298
+ activeMenu.cleanup();
299
+ activeMenu = null;
300
+ }
301
+
302
+ /**
303
+ * Show a floating context menu at the pointer location.
304
+ * items: Array<{ label, icon?, cls?, onClick } | "sep">
305
+ * anchorEl: where to show the menu when it was opened from the keyboard (defaults to the event target).
306
+ */
307
+ export function openContextMenu(e, items, anchorEl = null) {
308
+ if (typeof document === "undefined") return;
309
+ const list = items.filter(Boolean);
310
+ if (!list.length) return;
311
+ e.preventDefault();
312
+ closeContextMenu();
313
+
314
+ const menu = document.createElement("div");
315
+ menu.className = "ctx-menu";
316
+ menu.setAttribute("role", "menu");
317
+ const handlers = [];
318
+ menu.innerHTML = String(
319
+ html`${list.map((item) => {
320
+ if (item === "sep") return raw('<div class="ctx-sep" role="separator"></div>');
321
+ const idx = handlers.push(item.onClick) - 1;
322
+ return html`<button type="button" class="ctx-item${item.cls ? ` ${item.cls}` : ""}" role="menuitem" data-idx="${idx}">${item.icon ? raw(item.icon) : ""}<span>${item.label}</span></button>`;
323
+ })}`,
324
+ );
325
+ document.body.append(menu);
326
+
327
+ // Opened from the keyboard (Shift+F10 or the Menu key) there is no pointer position: anchor to the element.
328
+ const trigger = anchorEl || (e.target instanceof Element ? e.target : null);
329
+ const fromKeyboard = e.clientX === 0 && e.clientY === 0 && trigger;
330
+ const anchor = fromKeyboard ? trigger.getBoundingClientRect() : null;
331
+ const px = anchor ? anchor.left + Math.min(24, anchor.width / 2) : e.clientX;
332
+ const py = anchor ? anchor.bottom : e.clientY;
333
+ const rect = menu.getBoundingClientRect();
334
+ const x = Math.max(8, Math.min(px, window.innerWidth - rect.width - 8));
335
+ const y = Math.max(8, Math.min(py, window.innerHeight - rect.height - 8));
336
+ menu.style.left = `${x}px`;
337
+ menu.style.top = `${y}px`;
338
+
339
+ const onDown = (ev) => {
340
+ if (!menu.contains(ev.target)) closeContextMenu();
341
+ };
342
+ const onKey = (ev) => {
343
+ if (ev.key === "Escape") {
344
+ ev.preventDefault();
345
+ closeContextMenu();
346
+ return;
347
+ }
348
+ const btns = [...menu.querySelectorAll(".ctx-item")];
349
+ if (!btns.length) return;
350
+ if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
351
+ ev.preventDefault();
352
+ const i = btns.indexOf(document.activeElement);
353
+ const next = ev.key === "ArrowDown" ? (i + 1) % btns.length : (i - 1 + btns.length) % btns.length;
354
+ btns[next].focus();
355
+ }
356
+ };
357
+ const onScroll = () => closeContextMenu();
358
+ menu.addEventListener("click", (ev) => {
359
+ const btn = ev.target.closest("[data-idx]");
360
+ if (!btn) return;
361
+ const fn = handlers[Number(btn.dataset.idx)];
362
+ closeContextMenu();
363
+ fn?.();
364
+ });
365
+
366
+ document.addEventListener("pointerdown", onDown, true);
367
+ document.addEventListener("keydown", onKey, true);
368
+ window.addEventListener("scroll", onScroll, true);
369
+ window.addEventListener("resize", onScroll);
370
+
371
+ const returnFocus = document.activeElement;
372
+ if (fromKeyboard) menu.querySelector(".ctx-item")?.focus();
373
+
374
+ activeMenu = {
375
+ cleanup() {
376
+ const hadFocus = menu.contains(document.activeElement);
377
+ menu.remove();
378
+ if (hadFocus && returnFocus instanceof HTMLElement) returnFocus.focus({ preventScroll: true });
379
+ document.removeEventListener("pointerdown", onDown, true);
380
+ document.removeEventListener("keydown", onKey, true);
381
+ window.removeEventListener("scroll", onScroll, true);
382
+ window.removeEventListener("resize", onScroll);
383
+ },
384
+ };
385
+ }
package/src/server.js CHANGED
@@ -3,11 +3,12 @@
3
3
  // header so other websites cannot read the repository via DNS rebinding.
4
4
 
5
5
  import http from "node:http";
6
- import { createHash } from "node:crypto";
6
+ import { createHash, randomBytes } from "node:crypto";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { GitError } from "./git.js";
11
+ import { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
11
12
 
12
13
  const PUBLIC_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "public");
13
14
 
@@ -32,6 +33,8 @@ const CSP = [
32
33
  ].join("; ");
33
34
 
34
35
  const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
36
+ const MAX_BODY = 64 * 1024;
37
+ const PLAN_TTL = 10 * 60 * 1000;
35
38
 
36
39
  function md5(s) {
37
40
  return createHash("md5").update(s).digest("hex");
@@ -59,14 +62,23 @@ function attachAvatars(enabled, ...lists) {
59
62
  return map;
60
63
  }
61
64
 
62
- export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {}) {
63
- const staticCache = new Map();
64
- const checkHost = LOOPBACK.has(host);
65
+ /**
66
+ * The JSON API without a transport: the HTTP server and the VS Code extension both use it, so
67
+ * routes, validation and edit tokens live in one place.
68
+ * handle({ method, path, query, body }) resolves to { status, data } and never throws.
69
+ * `body` is a parsed object, or a function returning a promise of one (read only by routes that need it).
70
+ */
71
+ export function createApiHandler(repo, { avatars = true, edit = false, onEdit, onLog, editOffMessage } = {}) {
72
+ // Previewed plans, by one-time token, so apply can only move a branch to a tip git-tm computed.
73
+ const plans = new Map();
74
+ const requireEdit = () => {
75
+ if (!edit) throw new GitError(editOffMessage || "Edit mode is off. Start git-tm with --edit to change history.", 403);
76
+ };
65
77
 
66
78
  const bool = (v) => v === "1" || v === "true";
67
79
 
68
80
  const routes = {
69
- "GET /api/repo": async () => ({ ...(await repo.info()), avatars }),
81
+ "GET /api/repo": async () => ({ ...(await repo.info()), avatars, edit }),
70
82
  "GET /api/state": async () => ({ fingerprint: await repo.fingerprint() }),
71
83
  "GET /api/history": async (q) => {
72
84
  const res = await repo.log({
@@ -119,8 +131,94 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
119
131
  await repo.fetch();
120
132
  return { ok: true };
121
133
  },
134
+ "GET /api/edit/backups": async () => {
135
+ requireEdit();
136
+ return { backups: await listBackups(repo) };
137
+ },
138
+ "POST /api/edit/preview": async (q, readBody) => {
139
+ requireEdit();
140
+ const body = await readBody();
141
+ const plan = await planEdit(repo, {
142
+ type: body.op,
143
+ commit: body.commit,
144
+ branch: body.branch || undefined,
145
+ message: body.message,
146
+ author: body.author,
147
+ });
148
+ const now = Date.now();
149
+ for (const [k, v] of plans) if (v.expires < now) plans.delete(k);
150
+ if (plans.size > 50) plans.delete(plans.keys().next().value);
151
+ const token = randomBytes(16).toString("hex");
152
+ plans.set(token, { plan, expires: now + PLAN_TTL });
153
+ return { token, plan };
154
+ },
155
+ "POST /api/edit/apply": async (q, readBody) => {
156
+ requireEdit();
157
+ const body = await readBody();
158
+ const entry = typeof body.token === "string" ? plans.get(body.token) : null;
159
+ if (!entry || entry.expires < Date.now()) throw new GitError("This preview has expired. Preview the edit again.", 400);
160
+ // A double click must not run the same edit twice (duplicate backups and log entries).
161
+ if (entry.busy) throw new GitError("This edit is already being applied.", 409);
162
+ entry.busy = true;
163
+ let result;
164
+ try {
165
+ result = await applyEdit(repo, entry.plan, { allowPushed: body.allowPushed === true });
166
+ } finally {
167
+ entry.busy = false; // a failed apply (for example, unconfirmed pushed commits) can be retried
168
+ }
169
+ plans.delete(body.token);
170
+ onEdit?.({ ...result, op: entry.plan.type, summary: entry.plan.summary, count: entry.plan.rewritten.length || entry.plan.added.length });
171
+ return result;
172
+ },
173
+ "POST /api/edit/undo": async (q, readBody) => {
174
+ requireEdit();
175
+ const body = await readBody();
176
+ const result = await undoEdit(repo, body.id, { newBranch: body.newBranch });
177
+ onEdit?.({ ...result, op: body.newBranch ? "restore" : "undo" });
178
+ return result;
179
+ },
180
+ };
181
+
182
+ // A broken logger must never fail a request, or get the same request logged twice by the error path.
183
+ const logRequest = (event) => {
184
+ if (!onLog || event.path === "/api/state") return;
185
+ try {
186
+ onLog(event);
187
+ } catch (err) {
188
+ console.error(`onLog failed: ${err?.stack || err}`);
189
+ }
122
190
  };
123
191
 
192
+ return {
193
+ /** True when `method path` is a known endpoint. */
194
+ has: (method, path) => Object.hasOwn(routes, `${method} ${path}`),
195
+ async handle({ method = "GET", path, query, body } = {}) {
196
+ const started = performance.now();
197
+ const q = query instanceof URLSearchParams ? query : new URLSearchParams(query || "");
198
+ const route = routes[`${method} ${path}`];
199
+ if (!route) return { status: 404, data: { error: "Unknown endpoint" } };
200
+ const readBody = typeof body === "function" ? body : async () => checkObject(body ?? {});
201
+ try {
202
+ const data = await route(q, readBody);
203
+ logRequest({ method, path, query: q, status: 200, ms: Math.round(performance.now() - started) });
204
+ return { status: 200, data };
205
+ } catch (err) {
206
+ const status = err instanceof GitError ? err.status : 500;
207
+ if (status >= 500) console.error(`${method} ${path}: ${err instanceof GitError ? err.message : err?.stack || err}`);
208
+ logRequest({ method, path, query: q, status, ms: Math.round(performance.now() - started), error: err?.message });
209
+ return { status, data: { error: err?.message || "Internal error", ...(err?.conflicts ? { conflicts: err.conflicts } : {}) } };
210
+ }
211
+ },
212
+ };
213
+ }
214
+
215
+ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit = false, onEdit, onLog } = {}) {
216
+ const staticCache = new Map();
217
+ const checkHost = LOOPBACK.has(host);
218
+ // Changing history from another device is a different risk from reading it: edit mode is local only.
219
+ if (edit && !checkHost) throw new Error("Edit mode only works on a loopback host (127.0.0.1, localhost or ::1)");
220
+ const api = createApiHandler(repo, { avatars, edit, onEdit, onLog });
221
+
124
222
  async function serveStatic(res, pathname) {
125
223
  let rel = "index.html";
126
224
  if (pathname !== "/") {
@@ -157,21 +255,44 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1" } = {})
157
255
  if (req.method !== "GET" && req.method !== "HEAD") return send(res, 405, "Method not allowed");
158
256
  return await serveStatic(res, url.pathname);
159
257
  }
160
- const route = routes[`${req.method} ${url.pathname}`];
161
- if (!route) return json(res, 404, { error: "Unknown endpoint" });
258
+ if (!api.has(req.method, url.pathname)) return json(res, 404, { error: "Unknown endpoint" });
162
259
  // Simple CSRF guard: browsers will not send this custom header cross-origin without a preflight.
163
260
  if (req.method !== "GET" && req.headers["x-git-tm"] !== "1") return json(res, 403, { error: "Forbidden" });
164
- const data = await route(url.searchParams);
165
- json(res, 200, data);
261
+ const { status, data } = await api.handle({ method: req.method, path: url.pathname, query: url.searchParams, body: () => readJson(req) });
262
+ json(res, status, data);
166
263
  } catch (err) {
167
- const status = err instanceof GitError ? err.status : 500;
168
- if (status >= 500) console.error(`${req.method} ${req.url}: ${err instanceof GitError ? err.message : err.stack}`);
264
+ console.error(`${req.method} ${req.url}: ${err?.stack || err}`);
169
265
  if (res.headersSent) res.destroy();
170
- else json(res, status, { error: err.message || "Internal error" });
266
+ else json(res, 500, { error: "Internal error" });
171
267
  }
172
268
  });
173
269
  }
174
270
 
271
+ /** Read a small JSON object body. Requiring application/json also forces a CORS preflight for cross-site requests. */
272
+ async function readJson(req) {
273
+ if (!/^application\/json(;|$)/i.test(req.headers["content-type"] || "")) throw new GitError("Expected a JSON body", 415);
274
+ const chunks = [];
275
+ let size = 0;
276
+ // Keep reading past the limit (discarding) so the client gets a clean 413 instead of a reset connection.
277
+ for await (const chunk of req) {
278
+ size += chunk.length;
279
+ if (size <= MAX_BODY) chunks.push(chunk);
280
+ }
281
+ if (size > MAX_BODY) throw new GitError("Request body too large", 413);
282
+ let data;
283
+ try {
284
+ data = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
285
+ } catch {
286
+ throw new GitError("Invalid JSON body", 400);
287
+ }
288
+ return checkObject(data);
289
+ }
290
+
291
+ function checkObject(data) {
292
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new GitError("Expected a JSON object", 400);
293
+ return data;
294
+ }
295
+
175
296
  function required(q, name) {
176
297
  const v = q.get(name);
177
298
  if (!v) throw new GitError(`Missing parameter: ${name}`, 400);