@1agh/maude 2.0.4 → 2.0.6

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 (129) hide show
  1. package/apps/hub/src/project-transactions/kernel.mjs +10 -1
  2. package/apps/studio/access/filters.ts +12 -5
  3. package/apps/studio/access/known-canvases.ts +24 -1
  4. package/apps/studio/access/refused-inputs.ts +89 -0
  5. package/apps/studio/actions/agents.ts +5 -0
  6. package/apps/studio/actions/defs/app.ts +12 -0
  7. package/apps/studio/actions.manifest.json +13 -1
  8. package/apps/studio/actions.parity.json +7 -1
  9. package/apps/studio/annotations/ui/element-node.tsx +139 -54
  10. package/apps/studio/annotations/ui/lod.tsx +1 -1
  11. package/apps/studio/annotations/ui/text-style.ts +1 -1
  12. package/apps/studio/annotations-layer.tsx +0 -12
  13. package/apps/studio/api.ts +42 -0
  14. package/apps/studio/artboard-live-gate.tsx +267 -0
  15. package/apps/studio/artboard-live.ts +336 -0
  16. package/apps/studio/artboard-webgl.ts +668 -0
  17. package/apps/studio/bin/_agent-browser-bin.mjs +8 -0
  18. package/apps/studio/bin/_agent-browser-safe.mjs +2 -1
  19. package/apps/studio/bin/_canvas-reasons.mjs +34 -0
  20. package/apps/studio/bin/_ds-check-live.mjs +37 -0
  21. package/apps/studio/bin/_ds-check.mjs +4 -1
  22. package/apps/studio/bin/_ds-prove-judge.mjs +167 -0
  23. package/apps/studio/bin/_ds-prove-playwright.mjs +183 -105
  24. package/apps/studio/bin/_import-asset.mjs +2 -1
  25. package/apps/studio/bin/_perf-probe.mjs +2 -1
  26. package/apps/studio/bin/_studio-verb.mjs +24 -3
  27. package/apps/studio/bin/_thumb-blank.mjs +70 -0
  28. package/apps/studio/bin/_thumb-cover.mjs +35 -0
  29. package/apps/studio/bin/_thumbs-playwright.mjs +89 -12
  30. package/apps/studio/bin/ds-check.sh +5 -1
  31. package/apps/studio/bin/perf.sh +11 -1
  32. package/apps/studio/bin/server-up.sh +7 -2
  33. package/apps/studio/bin/smoke.sh +19 -0
  34. package/apps/studio/canvas-lib.tsx +131 -12
  35. package/apps/studio/client/canvas-url.js +13 -0
  36. package/apps/studio/client/home/HomeAccounts.jsx +262 -0
  37. package/apps/studio/client/home/Shelves.jsx +4 -3
  38. package/apps/studio/client/home/home-accounts-model.js +121 -0
  39. package/apps/studio/client/home/home-api.js +6 -0
  40. package/apps/studio/client/home/home-app.jsx +141 -40
  41. package/apps/studio/client/home/home-model.js +172 -6
  42. package/apps/studio/client/home/home.css +169 -5
  43. package/apps/studio/client/home/shell-mode.js +8 -1
  44. package/apps/studio/client/hooks/use-project-data.jsx +2 -0
  45. package/apps/studio/client/panels/ChatPanel.jsx +27 -20
  46. package/apps/studio/client/panels/CreateProject.jsx +19 -5
  47. package/apps/studio/client/panels/caps-cache.js +46 -0
  48. package/apps/studio/client/shell/viewport.jsx +36 -8
  49. package/apps/studio/client/v2/access/access-client.js +2 -0
  50. package/apps/studio/client/v2/access/access-host.jsx +12 -1
  51. package/apps/studio/client/v2/access/trashed-banner.jsx +6 -3
  52. package/apps/studio/client/v2/ai/Advanced.jsx +12 -0
  53. package/apps/studio/client/v2/ai/Composer.jsx +27 -10
  54. package/apps/studio/client/v2/code/canvas-imports-card.jsx +15 -14
  55. package/apps/studio/client/v2/code/canvas-imports-words.js +44 -0
  56. package/apps/studio/client/v2/code/code-bus.js +5 -0
  57. package/apps/studio/client/v2/ds/advanced-host.jsx +11 -26
  58. package/apps/studio/client/v2/ds/ds-refresh.js +161 -0
  59. package/apps/studio/client/v2/ds/library-host.jsx +45 -45
  60. package/apps/studio/client/v2/ds/make-host.jsx +13 -15
  61. package/apps/studio/client/v2/ds/off-system-host.jsx +18 -19
  62. package/apps/studio/client/v2/ds/review-host.jsx +7 -1
  63. package/apps/studio/client/v2/ds/truth-host.jsx +15 -17
  64. package/apps/studio/client/v2/ds/upgrade-host.jsx +26 -10
  65. package/apps/studio/client/v2/history/branch-actions.js +13 -9
  66. package/apps/studio/client/v2/history/git-advanced.jsx +8 -1
  67. package/apps/studio/client/v2/history/git-model.js +3 -1
  68. package/apps/studio/client/v2/history/git-parts.jsx +16 -1
  69. package/apps/studio/client/v2/presence/faces.jsx +42 -14
  70. package/apps/studio/client/v2/shell/account-card.jsx +10 -4
  71. package/apps/studio/client/v2/shell/canvas-crash-guard.js +137 -0
  72. package/apps/studio/client/v2/shell/github-signin-host.jsx +42 -0
  73. package/apps/studio/client/v2/shell/menu-runner.js +11 -0
  74. package/apps/studio/client/v2/shell/project-account-card.jsx +203 -0
  75. package/apps/studio/client/v2/shell/project-account-model.js +182 -0
  76. package/apps/studio/client/v2/shell/share-cluster-host.jsx +137 -10
  77. package/apps/studio/client/v2/shell/share-cluster.css +58 -0
  78. package/apps/studio/client/v2/shell/share-cluster.jsx +26 -7
  79. package/apps/studio/client/v2/shell/team-switch.js +94 -0
  80. package/apps/studio/client/v2/shell/too-heavy-card.jsx +38 -0
  81. package/apps/studio/client/v2/shell/use-account.js +8 -1
  82. package/apps/studio/collab/persistence.ts +9 -1
  83. package/apps/studio/collab/registry.ts +32 -0
  84. package/apps/studio/collab/room.ts +8 -0
  85. package/apps/studio/config-reload-wire.ts +53 -0
  86. package/apps/studio/dist/client.bundle.js +1232 -1232
  87. package/apps/studio/dist/styles.css +1 -1
  88. package/apps/studio/ds/board/specimen.tsx +12 -1
  89. package/apps/studio/ds/canvas-cli.ts +58 -2
  90. package/apps/studio/ds/check.ts +26 -1
  91. package/apps/studio/ds/cli.ts +7 -3
  92. package/apps/studio/ds/convert.ts +34 -6
  93. package/apps/studio/ds/ds-verb.ts +13 -0
  94. package/apps/studio/ds/post-build.ts +38 -0
  95. package/apps/studio/ds/upgrade-apply.ts +27 -5
  96. package/apps/studio/ds/upgrade-cli.ts +22 -2
  97. package/apps/studio/ds/upgrade-prove.ts +198 -15
  98. package/apps/studio/ds/upgrade-stage.ts +4 -1
  99. package/apps/studio/history/trash.ts +6 -0
  100. package/apps/studio/home/accounts.ts +87 -0
  101. package/apps/studio/home/index-reader.ts +24 -2
  102. package/apps/studio/home/routes.ts +19 -0
  103. package/apps/studio/http.ts +14 -2
  104. package/apps/studio/routes/ds-convert.ts +18 -0
  105. package/apps/studio/routes/trash.ts +16 -1
  106. package/apps/studio/server.ts +8 -10
  107. package/apps/studio/sync/accepted-cold-start.ts +28 -13
  108. package/apps/studio/sync/asset-push.ts +146 -23
  109. package/apps/studio/sync/asset-state.ts +3 -2
  110. package/apps/studio/sync/file-membership.ts +28 -3
  111. package/apps/studio/sync/file-plane.ts +40 -9
  112. package/apps/studio/sync/file-pull.ts +304 -33
  113. package/apps/studio/sync/hub-link.ts +1 -2
  114. package/apps/studio/sync/index.ts +308 -150
  115. package/apps/studio/sync/journal-client.ts +94 -5
  116. package/apps/studio/sync/pending-deletes.ts +100 -0
  117. package/apps/studio/sync/projection.ts +77 -12
  118. package/apps/studio/sync/seed-progress.ts +12 -1
  119. package/apps/studio/sync/status.ts +3 -1
  120. package/apps/studio/thumbs/service.ts +12 -2
  121. package/apps/studio/thumbs/validate.ts +7 -0
  122. package/apps/studio/ui-prefs-migrate.ts +4 -0
  123. package/apps/studio/video-comp.tsx +23 -0
  124. package/apps/studio/whats-new.json +72 -0
  125. package/cli/lib/bash-guard.mjs +13 -1
  126. package/cli/lib/design-help.gen.mjs +1 -1
  127. package/cli/lib/design-hook.mjs +20 -0
  128. package/cli/lib/studio-locate.mjs +35 -10
  129. package/package.json +8 -8
@@ -69,6 +69,8 @@ const withKey = (label, def, ctx) => {
69
69
  * @param present the Present spec while presenting (Artboards · Canvas are two columns of the table)
70
70
  * @param accountSlot the account chip + card (S1.22a, account-card.jsx) — first, desktop only
71
71
  * @param cloud this shell is a cloud tab: no sentence names a Mac (rc3-i)
72
+ * @param onAccount 2.0.5 W4 — your own face opens this project's account card (null: the face is a face)
73
+ * @param accountOpen the account card is showing (the face's aria-expanded)
72
74
  */
73
75
  export function ShareCluster({
74
76
  faces,
@@ -93,6 +95,8 @@ export function ShareCluster({
93
95
  mode = null,
94
96
  present = null,
95
97
  accountSlot = null,
98
+ onAccount = null,
99
+ accountOpen = false,
96
100
  cloud,
97
101
  }) {
98
102
  const cluster = mode ? modeCell('share-cluster', mode, present) : 'full';
@@ -133,7 +137,13 @@ export function ShareCluster({
133
137
  data-zen={panelsHidden ? 'true' : undefined}
134
138
  >
135
139
  {accountSlot}
136
- <PresenceFaces faces={faces} onFollow={onFollow} presence={presence} />
140
+ <PresenceFaces
141
+ faces={faces}
142
+ onFollow={onFollow}
143
+ presence={presence}
144
+ onYou={onAccount}
145
+ youOpen={accountOpen}
146
+ />
137
147
  {access ? (
138
148
  <span
139
149
  className="sh-saved"
@@ -145,21 +155,30 @@ export function ShareCluster({
145
155
  </span>
146
156
  ) : status ? (
147
157
  <>
148
- <span
149
- className={`sh-saved${status.tone ? ` sh-saved--${status.tone}` : ''}`}
158
+ {/* 2.0.5 W4 — the word is a button in every sync state: Diagnostics › Sync (`diag.sync`, the
159
+ registry row the menu and ⌘K run), or — while a held conflict waits — that conflict's
160
+ Compare. The live region is the word inside, so a state change is still announced. */}
161
+ <button
162
+ type="button"
163
+ className={`sh-saved sh-saved--btn${status.tone ? ` sh-saved--${status.tone}` : ''}`}
150
164
  data-testid="share-cluster-status"
151
165
  data-status={status.kind}
152
166
  // The old status-bar chip's detail (its tooltip and its short label — "3 to review",
153
167
  // "1 refused", "12/40") rides on the word: hover for the sentence; `data-sync-label` is
154
168
  // the short form for scenarios and scripts (V2-4.8b).
155
169
  data-sync-label={status.syncLabel || undefined}
156
- role="status"
157
- aria-live="polite"
158
170
  title={status.detail || status.title || undefined}
171
+ aria-label={`${status.word} — ${status.conflict ? 'Compare' : 'Sync details'}`}
172
+ onClick={() => {
173
+ if (status.conflict) onStatusAction?.('compare');
174
+ else run('diag.sync');
175
+ }}
159
176
  >
160
177
  <StIcon name={status.icon} size={16} />
161
- <span className="sh-saved-w">{status.word}</span>
162
- </span>
178
+ <span className="sh-saved-w" role="status" aria-live="polite">
179
+ {status.word}
180
+ </span>
181
+ </button>
163
182
  {status.actions.map((a) => (
164
183
  <button
165
184
  key={a.id}
@@ -0,0 +1,94 @@
1
+ // client/v2/shell/team-switch.js — 2.0.5 W4b: Switch / Sign in for a team-server project.
2
+ //
3
+ // Option A of the W4 open point: a team server's credential lands in the project's PROFILE
4
+ // (`hubs.json`), so signing in as someone else on a profile other projects share would re-sign them
5
+ // too — V2-3.8 forbids it. So, in the app:
6
+ // 1. `team_sign_in_prepare` (Rust, project tabs only; the caller's label + origin are checked
7
+ // there). `true` = this project shared its profile: it is now bound to a fresh profile of its
8
+ // own and its server restarts onto it — the page reloads signed out, and the person signs in
9
+ // there (the card then offers "Sign in to <host>…"). Stop here.
10
+ // 2. `false` = this project is alone on its profile: run the team server's own sign-in page
11
+ // (`/_api/hub-signin/start` → `open_team_server_signin` → poll). The server's route restarts
12
+ // sync for this project's own server once the new sign-in is stored.
13
+ // No credential crosses this page; it only passes the server address and an attempt id.
14
+ //
15
+ // Pure over its effects (`invoke`, `api`, `openPage`, `wait`) so the test drives it with stubs.
16
+
17
+ const POLL_MS = 1500;
18
+ const POLL_CAP = 400; // 10 min at 1.5 s — the attempt's own lifetime
19
+
20
+ export const TEAM_SWITCH_WORDS = Object.freeze({
21
+ moved:
22
+ 'This project now has an account of its own on this Mac. Sign in to the team server again once it reloads.',
23
+ refused: 'Maude won’t open that address. Check the server address in Settings › Connections.',
24
+ failed: 'Maude couldn’t open your browser. Try again.',
25
+ start: 'The sign-in could not start. Try again.',
26
+ unfinished: 'The sign-in did not finish. Try again.',
27
+ needsApp: 'Switching a team-server account needs the Maude desktop app.',
28
+ });
29
+
30
+ const hostOf = (url) => {
31
+ try {
32
+ return new URL(String(url)).host;
33
+ } catch {
34
+ return String(url || '');
35
+ }
36
+ };
37
+
38
+ /**
39
+ * @returns {Promise<{ ok: boolean, moved?: boolean, url?: string, user?: string|null, error?: string }>}
40
+ */
41
+ export async function runTeamSwitch({ url, native, invoke, api, openPage, wait, cancelled }) {
42
+ if (!native || typeof invoke !== 'function')
43
+ return { ok: false, error: TEAM_SWITCH_WORDS.needsApp };
44
+ if (!url) return { ok: false, error: TEAM_SWITCH_WORDS.start };
45
+ let moved;
46
+ try {
47
+ moved = await invoke('team_sign_in_prepare');
48
+ } catch (e) {
49
+ return { ok: false, error: String(e?.message || e || TEAM_SWITCH_WORDS.start) };
50
+ }
51
+ if (moved === true) return { ok: true, moved: true, message: TEAM_SWITCH_WORDS.moved };
52
+
53
+ const post = (path, body) =>
54
+ api(path, {
55
+ method: 'POST',
56
+ headers: { 'content-type': 'application/json' },
57
+ body: JSON.stringify(body),
58
+ });
59
+ const r = await post('/_api/hub-signin/start', { url });
60
+ if (!r?.ok || !r.json?.ok || !r.json.id)
61
+ return { ok: false, error: r?.json?.error || TEAM_SWITCH_WORDS.start };
62
+ const id = r.json.id;
63
+ const opened = await openPage(r.json.signInUrl);
64
+ if (opened !== 'ok') {
65
+ void post('/_api/hub-signin/cancel', { id });
66
+ return {
67
+ ok: false,
68
+ error: opened === 'refused' ? TEAM_SWITCH_WORDS.refused : TEAM_SWITCH_WORDS.failed,
69
+ };
70
+ }
71
+ for (let i = 0; i < POLL_CAP; i++) {
72
+ await wait(POLL_MS);
73
+ if (cancelled?.()) {
74
+ void post('/_api/hub-signin/cancel', { id });
75
+ return { ok: false, cancelled: true };
76
+ }
77
+ const p = await post('/_api/hub-signin/poll', { id });
78
+ if (p?.json?.pending) continue;
79
+ if (p?.ok && p.json?.ok && p.json.url) {
80
+ const user = typeof p.json.user?.email === 'string' ? p.json.user.email : null;
81
+ return {
82
+ ok: true,
83
+ url: p.json.url,
84
+ user,
85
+ message: user
86
+ ? `Signed in to ${hostOf(p.json.url)} as ${user}.`
87
+ : `Signed in to ${hostOf(p.json.url)}.`,
88
+ };
89
+ }
90
+ return { ok: false, error: p?.json?.error || TEAM_SWITCH_WORDS.unfinished };
91
+ }
92
+ void post('/_api/hub-signin/cancel', { id });
93
+ return { ok: false, error: TEAM_SWITCH_WORDS.unfinished };
94
+ }
@@ -0,0 +1,38 @@
1
+ // client/v2/shell/too-heavy-card.jsx — 2.0.5: the card a tab shows instead of a canvas that keeps crashing
2
+ // the page (canvas-crash-guard.js). The viewport mounts it INSTEAD of the frame, like the not-local card:
3
+ // no frame, so nothing heavy runs until the person picks a way in.
4
+
5
+ import { Empty } from '../empty/empty.jsx';
6
+
7
+ /** @param {{ name: string, onLight: () => void, onAll: () => void }} props */
8
+ export function TooHeavyCanvas({ name, onLight, onAll }) {
9
+ return (
10
+ <Empty
11
+ size="canvas"
12
+ glyph="offline"
13
+ title="This canvas is too heavy to show all at once."
14
+ next={`Maude had to reload twice while ${name} was drawing. Show the artboards near where you look; the rest draw as you move to them.`}
15
+ testid="canvas-too-heavy"
16
+ actions={
17
+ <>
18
+ <button
19
+ type="button"
20
+ className="btn btn--sm btn--primary"
21
+ data-testid="canvas-too-heavy-light"
22
+ onClick={onLight}
23
+ >
24
+ Show visible artboards only
25
+ </button>
26
+ <button
27
+ type="button"
28
+ className="btn btn--sm"
29
+ data-testid="canvas-too-heavy-all"
30
+ onClick={onAll}
31
+ >
32
+ Show everything
33
+ </button>
34
+ </>
35
+ }
36
+ />
37
+ );
38
+ }
@@ -24,7 +24,14 @@ export function useAccount(enabled) {
24
24
  .then((r) => r.json().catch(() => ({})))
25
25
  .then((j) => {
26
26
  if (!gone)
27
- setState((s) => ({ ...s, connected: !!j?.connected, email: j?.email ?? null }));
27
+ setState((s) => ({
28
+ ...s,
29
+ connected: !!j?.connected,
30
+ email: j?.email ?? null,
31
+ // 2.0.5 W4 — the project account card's kind: the cloud address and this folder's link
32
+ cloudUrl: typeof j?.url === 'string' ? j.url : '',
33
+ linkedHub: j?.linkedHub ?? null,
34
+ }));
28
35
  })
29
36
  .catch(() => {
30
37
  if (!gone) setState((s) => ({ ...s, connected: false, email: null }));
@@ -2,6 +2,7 @@
2
2
  // snapshots (Phase 6 _comments/<slug>.json) + the annotations board (DDR-242) + the
3
3
  // new `.ydoc.bin` cache under _state/<slug>.ydoc.bin.
4
4
 
5
+ import { rmSync } from 'node:fs';
5
6
  import path from 'node:path';
6
7
 
7
8
  import * as Y from 'yjs';
@@ -378,5 +379,12 @@ export function createPersistence(deps: PersistenceDeps): RoomCallbacks {
378
379
  await Bun.write(ydocBinPath(slug), state);
379
380
  }
380
381
 
381
- return { seed, persistJson, persistBinary };
382
+ // fix/205 — a cache, never content (DDR-051: JSON is canonical): the canvas
383
+ // it cached was deleted, and a room seeded from it would carry the deleted
384
+ // lineage into a canvas re-created at the same slug.
385
+ async function forget(slug: string): Promise<void> {
386
+ rmSync(ydocBinPath(slug), { force: true });
387
+ }
388
+
389
+ return { seed, persistJson, persistBinary, forget };
382
390
  }
@@ -145,6 +145,17 @@ export interface Registry {
145
145
  * under the new slug via `get()`. No-op if no room is live for the slug.
146
146
  */
147
147
  forceDrop(slug: string): Promise<void>;
148
+ /**
149
+ * fix/205 — throw away the room of a canvas that LEFT the project (deleted
150
+ * here, deleted in the project, moved away): no flush, and with
151
+ * `forgetCache` its `.ydoc.bin` goes too (`RoomCallbacks.forget`). Its Y.Doc is the deleted canvas's
152
+ * whole lineage; a canvas re-created at the same slug must start from a
153
+ * fresh doc, or the hub's new body merges onto the old one and the body
154
+ * doubles. Only an unpinned room with no browser connection is discarded —
155
+ * a connected browser's room is left to the last-browser-leaves `drop`.
156
+ * Returns whether a room was discarded.
157
+ */
158
+ discard(slug: string, opts?: { forgetCache?: boolean }): Promise<boolean>;
148
159
  /** Test/introspection. */
149
160
  size(): number;
150
161
  }
@@ -344,6 +355,26 @@ export function createRegistry(callbacks: RoomCallbacks): Registry {
344
355
  await room.destroy();
345
356
  }
346
357
 
358
+ async function discard(slug: string, opts: { forgetCache?: boolean } = {}): Promise<boolean> {
359
+ if (pinned.has(slug)) return false;
360
+ const room = rooms.get(slug);
361
+ if (room && room.size() > 0) return false;
362
+ if (opts.forgetCache) {
363
+ try {
364
+ await callbacks.forget?.(slug);
365
+ } catch (err) {
366
+ console.warn(`[collab/${slug}] could not drop the cached document:`, err);
367
+ }
368
+ }
369
+ if (!room) return false;
370
+ teardownBridge(slug);
371
+ rooms.delete(slug);
372
+ // destroy() marks the room destroyed BEFORE its final flush, so nothing of
373
+ // the deleted canvas is written back (comments, annotations, the cache).
374
+ await room.destroy();
375
+ return true;
376
+ }
377
+
347
378
  async function destroyAll(): Promise<void> {
348
379
  for (const slug of Array.from(bridges.keys())) teardownBridge(slug);
349
380
  hubAwareness.clear();
@@ -375,6 +406,7 @@ export function createRegistry(callbacks: RoomCallbacks): Registry {
375
406
  destroyAll,
376
407
  drop,
377
408
  forceDrop,
409
+ discard,
378
410
  size: () => rooms.size,
379
411
  };
380
412
  }
@@ -130,6 +130,14 @@ export interface RoomCallbacks {
130
130
  */
131
131
  seed(slug: string, doc: Y.Doc): Promise<void> | void;
132
132
 
133
+ /**
134
+ * fix/205 — the canvas left the project: drop whatever persistence caches
135
+ * for its doc (the `.ydoc.bin`), so a room re-created for the same slug can
136
+ * never seed from the deleted canvas's lineage. Optional; absent = nothing
137
+ * cached outside the room.
138
+ */
139
+ forget?(slug: string): Promise<void> | void;
140
+
133
141
  /**
134
142
  * Accepted revisions (DDR-241 §7): while true, this room's document is a
135
143
  * replica of the project's accepted state — no browser connection may write
@@ -0,0 +1,53 @@
1
+ // Config hot-reload wiring — `/design:setup-ds` (or a hand edit) rewrites
2
+ // `.design/config.json` mid-session; without a re-read the server keeps
3
+ // serving the boot snapshot and a newly added canvas group (`system`) never
4
+ // reaches /_index-data. On change: swap ctx.cfg in place (reloadConfig) and
5
+ // let the caller react (canvas-list refresh, `config-updated` to shells).
6
+ // RCA: .ai/logs/rca/issue-ds-scaffold-files-not-in-filetree-stale-config.md
7
+ //
8
+ // 2.0.5 (#205): a cell's studio child has no file watcher, so it never sees
9
+ // `fs:json`; the hub's journal heal announces a peer's write as `fs:any`
10
+ // only (sync/cell-file-events.ts). Listening on `fs:json` alone left a cell
11
+ // judging design-system boards with the config it booted with. Both events
12
+ // share ONE debounce, so a watcher's `fs:json` + `fs:any` pair (or a watcher
13
+ // event plus a heal event) for the same write reloads once.
14
+
15
+ import { type Context, reloadConfig } from './context.ts';
16
+
17
+ export const CONFIG_RELOAD_DEBOUNCE_MS = 150;
18
+
19
+ export interface ConfigReloadWire {
20
+ /** Drop a pending reload and stop listening. */
21
+ stop(): void;
22
+ }
23
+
24
+ function isConfigJson(rel: unknown): boolean {
25
+ return typeof rel === 'string' && rel.replace(/\\/g, '/').replace(/^\/+/, '') === 'config.json';
26
+ }
27
+
28
+ export function wireConfigReload(
29
+ ctx: Context,
30
+ opts: { onReloaded?: () => void; debounceMs?: number } = {}
31
+ ): ConfigReloadWire {
32
+ const debounceMs = opts.debounceMs ?? CONFIG_RELOAD_DEBOUNCE_MS;
33
+ let timer: ReturnType<typeof setTimeout> | null = null;
34
+ const onEvent = (rel: unknown) => {
35
+ if (!isConfigJson(rel)) return;
36
+ if (timer) clearTimeout(timer);
37
+ timer = setTimeout(() => {
38
+ timer = null;
39
+ if (!reloadConfig(ctx)) return;
40
+ opts.onReloaded?.();
41
+ }, debounceMs);
42
+ };
43
+ const offJson = ctx.bus.on('fs:json', onEvent);
44
+ const offAny = ctx.bus.on('fs:any', onEvent);
45
+ return {
46
+ stop() {
47
+ if (timer) clearTimeout(timer);
48
+ timer = null;
49
+ offJson();
50
+ offAny();
51
+ },
52
+ };
53
+ }