@whzxc/agent-design-gallery 0.14.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +29 -16
  2. package/package.json +2 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +1284 -521
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +85 -48
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +129 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +51 -14
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +9 -0
  19. package/public/index.html +26 -10
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/motion-flow.js +28 -0
  23. package/public/motion-identity.js +100 -0
  24. package/public/motion-paint.js +332 -0
  25. package/public/motion-scene.js +165 -0
  26. package/public/motion-specimens.js +335 -0
  27. package/public/player.css +270 -0
  28. package/public/player.js +753 -0
  29. package/public/recent-updates.js +535 -0
  30. package/public/selection.js +1 -1
  31. package/public/style.css +91 -154
  32. package/public/switcher.css +5 -4
  33. package/public/switcher.js +109 -34
  34. package/public/token-catalog.js +8 -3
  35. package/public/tokens.css +20 -1
  36. package/public/view-boards.css +131 -0
  37. package/public/view-boards.js +350 -0
  38. package/public/view-route.js +1 -2
  39. package/src/boards/board.mjs +30 -0
  40. package/src/boards/motion-board.mjs +202 -0
  41. package/src/boards/token-board.mjs +200 -0
  42. package/src/cli-output.mjs +10 -5
  43. package/src/cli.mjs +89 -35
  44. package/src/comments.mjs +293 -0
  45. package/src/http.mjs +7 -5
  46. package/src/hub/project-link.mjs +41 -0
  47. package/src/hub/registry.mjs +5 -0
  48. package/src/hub.mjs +14 -10
  49. package/src/link.mjs +13 -1
  50. package/src/recent-frames.mjs +295 -0
  51. package/src/recent-history.mjs +100 -0
  52. package/src/recent-job.mjs +63 -0
  53. package/src/recent-worker.mjs +171 -0
  54. package/src/server.mjs +285 -110
  55. package/src/service.mjs +46 -12
  56. package/src/toolkit/arch-git.mjs +8 -14
  57. package/src/toolkit/arch.mjs +3 -2
  58. package/src/toolkit/asset-rules.mjs +24 -1
  59. package/src/toolkit/browser.mjs +1 -13
  60. package/src/toolkit/build-store.mjs +9 -1
  61. package/src/toolkit/build-worker.mjs +6 -0
  62. package/src/toolkit/build.mjs +22 -16
  63. package/src/toolkit/commands.mjs +105 -9
  64. package/src/toolkit/compare.mjs +13 -11
  65. package/src/toolkit/config.mjs +2 -2
  66. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  67. package/src/toolkit/diff-inputs.mjs +97 -52
  68. package/src/toolkit/diff.mjs +198 -43
  69. package/src/toolkit/frame-declarations.mjs +36 -0
  70. package/src/toolkit/git-blobs.mjs +50 -0
  71. package/src/toolkit/impact-inputs.mjs +11 -19
  72. package/src/toolkit/impact-selection.mjs +27 -12
  73. package/src/toolkit/impact.mjs +49 -15
  74. package/src/toolkit/implementation-map.mjs +17 -6
  75. package/src/toolkit/input-generation.mjs +15 -0
  76. package/src/toolkit/inspect-output.mjs +1 -1
  77. package/src/toolkit/inspect.d.ts +9 -1
  78. package/src/toolkit/inspect.mjs +25 -1
  79. package/src/toolkit/motion-check.mjs +382 -0
  80. package/src/toolkit/motion-css.mjs +105 -0
  81. package/src/toolkit/motion-flows.mjs +95 -0
  82. package/src/toolkit/motion-impact.mjs +87 -0
  83. package/src/toolkit/motion-inventory.mjs +202 -0
  84. package/src/toolkit/motion-label.mjs +111 -0
  85. package/src/toolkit/motion-patterns.mjs +216 -0
  86. package/src/toolkit/motion-primitives.mjs +94 -0
  87. package/src/toolkit/motion-queries.mjs +169 -0
  88. package/src/toolkit/motion.mjs +300 -0
  89. package/src/toolkit/move-pairing.mjs +140 -0
  90. package/src/toolkit/owner.mjs +19 -6
  91. package/src/toolkit/play-endpoint.mjs +66 -0
  92. package/src/toolkit/project-index.mjs +4 -4
  93. package/src/toolkit/recent-structure.mjs +201 -0
  94. package/src/toolkit/results.mjs +3 -3
  95. package/src/toolkit/review-document.mjs +440 -0
  96. package/src/toolkit/review-embed-document.mjs +671 -0
  97. package/src/toolkit/review-filmstrip.mjs +76 -0
  98. package/src/toolkit/review-groups.mjs +29 -0
  99. package/src/toolkit/review-motion-card.mjs +51 -0
  100. package/src/toolkit/review-motion.mjs +159 -0
  101. package/src/toolkit/review-observation.mjs +131 -0
  102. package/src/toolkit/review-playback.js +123 -0
  103. package/src/toolkit/review-sheet.mjs +125 -0
  104. package/src/toolkit/review-specimens.mjs +60 -0
  105. package/src/toolkit/review.mjs +240 -0
  106. package/src/toolkit/runtime.mjs +8 -2
  107. package/src/toolkit/theme.mjs +16 -0
  108. package/src/viewer-cache.mjs +48 -12
  109. package/public/annotations.js +0 -816
  110. package/public/labels.js +0 -122
  111. package/src/annotations.mjs +0 -238
@@ -0,0 +1,295 @@
1
+ import { lstat, readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { isSourcePath, isFeatureInternal, sourceFeature } from './toolkit/project.mjs';
5
+ import { dirtyGeneration, git, visitRange, visitRevision } from './recent-history.mjs';
6
+
7
+ import { gitBlobs } from './toolkit/git-blobs.mjs';
8
+ const pageSize = 20;
9
+ const key = (source, frame) => JSON.stringify([source, frame]);
10
+
11
+ async function sourceHistory(repository, head, since, after) {
12
+ if (!head) return [];
13
+ // Sort by committer time before asking Git for file names in bounded batches.
14
+ // First-parent traversal alone can contain commits with out-of-order clocks.
15
+ const log = await git(repository, 'log', '--first-parent', '-z', '--format=%H%x00%P%x00%ct%x00%s',
16
+ ...(since ? [since + '..' + head] : [...(after ? ['--since-as-filter=@' + Math.floor(after / 1000)] : []), head]),
17
+ '--');
18
+ const fields = log.split('\0'), commits = [];
19
+ for (let i = 0; i + 3 < fields.length; i += 4) {
20
+ const [sha, parents, time, subject] = fields.slice(i, i + 4);
21
+ commits.push({ sha, base: parents.split(' ')[0] || null, time: Number(time) * 1000, subject });
22
+ }
23
+ return commits.sort((a, b) => b.time - a.time);
24
+ }
25
+
26
+ async function nameOnly(repository, commits, specs) {
27
+ const log = await git(repository, 'log', '--no-walk=unsorted', '--root', '--diff-merges=first-parent',
28
+ '--no-renames', '-z', '--format=%x00%H', '--name-only', ...commits.map(commit => commit.sha), '--', ...specs);
29
+ const fields = log.split('\0'), names = new Map();
30
+ for (let i = 1; i < fields.length - 1;) {
31
+ const sha = fields[i++], files = [];
32
+ while (i < fields.length && fields[i]) files.push(fields[i++].replace(/^\n/, ''));
33
+ while (i < fields.length && !fields[i]) i++;
34
+ names.set(sha, files);
35
+ }
36
+ return names;
37
+ }
38
+
39
+ function revisionTrees(repository, paths, head, changes) {
40
+ const trees = new Map(), blobs = new Map();
41
+ let reader;
42
+ async function tree(sha) {
43
+ if (!sha) return new Map();
44
+ if (!trees.has(sha)) trees.set(sha, (async () => {
45
+ const raw = await git(repository, 'ls-tree', '-r', '-z', sha, '--', ...paths);
46
+ const files = new Map();
47
+ for (const line of raw.split('\0')) {
48
+ const separator = line.indexOf('\t');
49
+ if (separator < 0) continue;
50
+ const [mode, type, oid] = line.slice(0, separator).split(' ');
51
+ if (type === 'blob' && mode.startsWith('100')) files.set(path.join(repository, line.slice(separator + 1)), oid);
52
+ }
53
+ return files;
54
+ })());
55
+ return trees.get(sha);
56
+ }
57
+ const blob = oid => {
58
+ if (!blobs.has(oid)) blobs.set(oid, (reader ??= gitBlobs(repository)).read(oid));
59
+ return blobs.get(oid);
60
+ };
61
+ return {
62
+ tree,
63
+ close: () => reader?.close(),
64
+ async working() {
65
+ const files = new Map(await tree(head));
66
+ await Promise.all(changes.map(async ({ before, after }) => {
67
+ if (before) files.delete(path.join(repository, before));
68
+ if (after && paths.some(prefix => prefix === '.' || after.startsWith(prefix + '/'))) {
69
+ const file = path.join(repository, after);
70
+ if ((await lstat(file)).isFile()) files.set(file, file);
71
+ }
72
+ }));
73
+ return files;
74
+ },
75
+ files(tree) {
76
+ return {
77
+ has: file => tree.has(file),
78
+ async read(file, encoding) {
79
+ const oid = tree.get(file);
80
+ if (!oid) throw Error('Source input is absent: ' + path.relative(repository, file));
81
+ const bytes = path.isAbsolute(oid) ? await readFile(oid) : await blob(oid);
82
+ return encoding ? bytes.toString(encoding) : bytes;
83
+ }
84
+ };
85
+ }
86
+ };
87
+ }
88
+
89
+ function designPaths(config, repository) {
90
+ const design = path.relative(repository, config.design);
91
+ const arch = config.archDirectory && path.relative(repository, config.archDirectory);
92
+ const paths = [...new Set([design || '.', ...(arch ? [arch] : [])])];
93
+ const specs = config.sources.map(dir => ':(glob)' + path.posix.join(design, dir, '**/*.tsx'));
94
+ if (arch) for (const ext of ['mmd', 'md']) specs.push(':(glob)' + path.posix.join(arch, '**/*.' + ext));
95
+ function candidate(file) {
96
+ const name = path.posix.relative(design || '.', file);
97
+ if (isSourcePath(name, config.sources))
98
+ return isFeatureInternal(name, config.sources) ? path.posix.join(path.posix.dirname(file), 'index.tsx') : file;
99
+ if (arch && file.startsWith(arch + '/') && /\.(mmd|md)$/.test(file))
100
+ return file.replace(/\.md$/, '.mmd');
101
+ }
102
+ return { paths, specs, candidate };
103
+ }
104
+
105
+ function sameOrigin(code, origins, frame) {
106
+ const origin = origins.get(frame);
107
+ return origin && code.get(path.resolve(origin.fileName))?.site({ line: origin.lineNumber, column: origin.columnNumber });
108
+ }
109
+
110
+ async function diffSources({ config, repository, trees, commit, before, after, candidates, allowed, exactFrame, failures, enough }) {
111
+ const { buildSource } = await import('./toolkit/build.mjs');
112
+ const { captureFrameOrigins } = await import('./toolkit/runtime.mjs');
113
+ const { declarations } = await import('./toolkit/frame-declarations.mjs');
114
+ const { frameOwners } = await import('./toolkit/source-facts.mjs');
115
+ const origins = captureFrameOrigins();
116
+ const changed = commit.files.map(file => path.join(repository, file));
117
+ const current = trees.files(after), original = trees.files(before);
118
+ const rows = [];
119
+ const mayMove = candidates.some(source => !after.has(path.join(repository, source)));
120
+ let compared = 0;
121
+ async function compare(source) {
122
+ const file = path.join(repository, source), relative = path.relative(config.design, file);
123
+ const timestamp = commit.times?.get(source) ?? commit.time;
124
+ const direct = changed.filter(name => name === file || (isSourcePath(path.relative(config.design, name), config.sources) &&
125
+ sourceFeature(path.relative(config.design, name), config.sources) === sourceFeature(relative, config.sources)));
126
+ if (!before.has(file) && !after.has(file)) return [];
127
+ if (source.endsWith('.mmd')) {
128
+ if (exactFrame && exactFrame !== 'default') return [];
129
+ const note = file.replace(/\.mmd$/, '.md');
130
+ const signature = async fs => fs.has(file)
131
+ ? JSON.stringify([await fs.read(file, 'utf8'), fs.has(note) && await fs.read(note, 'utf8')])
132
+ : undefined;
133
+ const [old, next] = await Promise.all([signature(original), signature(current)]);
134
+ return old === next ? [] : [{ frame: 'default', status: !old ? 'added' : !next ? 'removed' : 'changed' }];
135
+ }
136
+ // Evaluate the old entry with new shared inputs. Changed files inside the
137
+ // feature stay on their respective sides. Old-only imports remain resolvable.
138
+ const local = new Set(direct);
139
+ const old = before.has(file) && after.has(file) ? trees.files({
140
+ has: name => local.has(name) ? before.has(name) : after.has(name) || before.has(name),
141
+ get: name => local.has(name) ? before.get(name) : after.get(name) ?? before.get(name)
142
+ }) : original;
143
+ const build = fs => fs.has(file)
144
+ ? buildSource(config, file, { write: false, files: fs, framesOnly: true }).then(result => result.frames)
145
+ : [];
146
+ let comparable = true;
147
+ const prior = Promise.resolve(build(old)).catch(error => {
148
+ if (old === original) throw error;
149
+ comparable = false;
150
+ return build(original);
151
+ });
152
+ const [left, right] = await Promise.all([prior, build(current)]);
153
+ const code = async fs => new Map(await Promise.all(direct.filter(name => fs.has(name))
154
+ .map(async name => [name, declarations(await fs.read(name, 'utf8'))])));
155
+ const both = left.length && right.length;
156
+ const [leftCode, rightCode] = both ? await Promise.all([code(comparable ? old : original), code(current)]) : [new Map(), new Map()];
157
+ const a = new Map(left.map(frame => [frame.name, frame])), b = new Map(right.map(frame => [frame.name, frame]));
158
+ return [...new Set([...b.keys(), ...a.keys()])].flatMap(frame => {
159
+ if (exactFrame && exactFrame !== frame) return [];
160
+ const previous = a.get(frame), next = b.get(frame);
161
+ if (!previous || !next) return [{ frame, status: next ? 'added' : 'removed' }];
162
+ const partChanged = [...frameOwners(previous.html), ...frameOwners(next.html)].some(({ source, export: name }) => {
163
+ const owner = path.join(config.design, source);
164
+ return leftCode.get(owner)?.part(name) !== rightCode.get(owner)?.part(name);
165
+ });
166
+ return partChanged || (comparable && JSON.stringify(previous) !== JSON.stringify(next)) ||
167
+ sameOrigin(leftCode, origins, previous) !== sameOrigin(rightCode, origins, next)
168
+ ? [{ frame, status: 'changed' }] : [];
169
+ }).map(row => ({ ...row, time: timestamp }));
170
+ }
171
+ for (const group of batches(candidates, 6)) {
172
+ const results = await Promise.all(group.map(async source => {
173
+ try {
174
+ return (await compare(source)).map(row => ({ source, ...row, time: row.time ?? commit.times?.get(source) ?? commit.time }));
175
+ } catch (error) {
176
+ failures.add(source + ': ' + error.message);
177
+ return [];
178
+ }
179
+ }));
180
+ compared += group.length;
181
+ rows.push(...results.flat());
182
+ if (commit.sha && !mayMove && enough(rows)) break;
183
+ }
184
+ const removed = rows.filter(row => row.status === 'removed'), added = rows.filter(row => row.status === 'added');
185
+ const consumed = new Set();
186
+ for (const next of added) {
187
+ const matches = removed.filter(old => old.frame === next.frame);
188
+ if (matches.length !== 1 || added.filter(row => row.frame === next.frame).length !== 1) continue;
189
+ const old = matches[0];
190
+ next.status = 'moved';
191
+ next.former = { source: old.source, frame: old.frame };
192
+ consumed.add(old);
193
+ }
194
+ return { rows: rows.filter(row => !consumed.has(row) && allowed(row.source))
195
+ .sort((a, b) => b.time - a.time), compared };
196
+ }
197
+
198
+ function* batches(items, size) {
199
+ for (let i = 0; i < items.length; i += size) yield items.slice(i, i + size);
200
+ }
201
+
202
+ export async function recentFrameState(config, { day, week, since, latest, scope, visible, frame }, repository) {
203
+ const { head, branch } = await visitRevision(config.root);
204
+ if (!branch) return { available: false, rows: [] };
205
+ const [dirty, rangeInfo] = await Promise.all([
206
+ dirtyGeneration(config.root, head, config.output, { includeChanges: true, repository }),
207
+ head ? visitRange(config.root, head, since) : { since: null, notice: null }
208
+ ]);
209
+ const snapshot = createHash('sha256').update(JSON.stringify([
210
+ head, branch, dirty.generation, config.design, config.archDirectory, config.sources, day, week, since, latest, scope, visible, frame
211
+ ])).digest('hex');
212
+ return { available: true, head, branch, snapshot, dirty, rangeInfo };
213
+ }
214
+
215
+ export async function recentFrames({ config, state, offset, week, latest, scope, visible, frame, preparationMs }) {
216
+ const start = performance.now();
217
+ const { head, branch, dirty, rangeInfo, snapshot } = state;
218
+ const { since, notice } = rangeInfo;
219
+ const { repository } = dirty;
220
+ const root = config.root;
221
+ let trees;
222
+ try {
223
+ const { paths, specs, candidate } = designPaths(config, repository);
224
+ const projectPath = file => path.relative(root, path.join(repository, file));
225
+ const designPath = file => path.relative(config.design, path.join(repository, file));
226
+ const shown = new Set(visible);
227
+ const allowed = file => scope === 'all' || shown.has(designPath(file)) || shown.has(projectPath(file)) ||
228
+ (scope?.startsWith('layer:') && designPath(file).startsWith(scope.slice(6) + '/')) ||
229
+ (scope?.startsWith('group:') && path.posix.dirname(designPath(file)) === scope.slice(6));
230
+ const history = await sourceHistory(repository, head, since, latest && !notice ? null : week);
231
+ const changes = dirty.changes.flatMap(({ before, after }) => [...new Set([before, after].filter(Boolean))]);
232
+ const dirtyTimes = new Map();
233
+ await Promise.all(dirty.changes.map(async ({ before, after }) => {
234
+ const source = candidate(after ?? before);
235
+ if (!source) return;
236
+ const time = after ? await lstat(path.join(repository, after)).then(info => Math.floor(info.mtimeMs)) : Date.now();
237
+ dirtyTimes.set(source, Math.max(time, dirtyTimes.get(source) ?? 0));
238
+ }));
239
+ if (dirtyTimes.size) history.unshift({ sha: null, base: head, time: Date.now(), times: dirtyTimes, subject: 'Uncommitted changes', files: changes });
240
+
241
+ const scanEnd = performance.now();
242
+ trees = revisionTrees(repository, paths, head, dirty.changes);
243
+ const unique = new Map(), failures = new Set();
244
+ let sources = 0, commits = 0, pathScanMs = 0;
245
+ const feedFull = nextTime => [...unique.values()]
246
+ .filter(row => row && row.time >= nextTime).length > offset + pageSize;
247
+ let processed = 0;
248
+ for (const batch of batches(history, 24)) {
249
+ const committed = batch.filter(commit => commit.sha);
250
+ const scanStart = performance.now();
251
+ const names = committed.length ? await nameOnly(repository, committed, specs) : new Map();
252
+ pathScanMs += performance.now() - scanStart;
253
+ for (const commit of batch) {
254
+ if (feedFull(commit.time)) break;
255
+ processed++;
256
+ commit.files ??= names.get(commit.sha) ?? [];
257
+ const candidates = [...new Set(commit.files.map(candidate).filter(Boolean))];
258
+ if (!candidates.some(allowed)) continue;
259
+ // Retain other paths in this commit when they could be former locations.
260
+ const [before, after] = await Promise.all([trees.tree(commit.base), commit.sha ? trees.tree(commit.sha) : trees.working()]);
261
+ const relevant = candidates.filter(file => allowed(file) ||
262
+ before.has(path.join(repository, file)) && !after.has(path.join(repository, file)));
263
+ commits++;
264
+ const { rows, compared } = await diffSources({
265
+ config, repository, trees, commit, before, after, candidates: relevant, allowed, exactFrame: frame, failures,
266
+ enough: rows => [...unique.values()].filter(row => row && row.time >= commit.time).length +
267
+ rows.filter(row => !unique.has(key(row.source, row.frame))).length > offset + pageSize
268
+ });
269
+ sources += compared;
270
+ for (const row of rows) {
271
+ const id = key(row.source, row.frame);
272
+ if (!unique.has(id)) unique.set(id, {
273
+ ...row, source: projectPath(row.source), subject: commit.subject, commit: commit.sha,
274
+ ...(row.former && { former: { ...row.former, source: projectPath(row.former.source) } })
275
+ });
276
+ if (row.former) unique.set(key(row.former.source, row.former.frame), null);
277
+ }
278
+ }
279
+ if (feedFull(history[processed]?.time ?? -Infinity)) break;
280
+ }
281
+ const diffEnd = performance.now();
282
+ const frameDiffMs = diffEnd - scanEnd - pathScanMs;
283
+ const rows = [...unique.values()].filter(Boolean).sort((a, b) => b.time - a.time);
284
+ const result = { available: true, head, branch, generation: dirty.generation, notice,
285
+ snapshot, rows: rows.slice(offset, offset + pageSize), hasMore: rows.length > offset + pageSize,
286
+ failures: [...failures].slice(0, 5) };
287
+ const [current, final] = await Promise.all([
288
+ visitRevision(root), dirtyGeneration(root, head, config.output, { repository })
289
+ ]);
290
+ if (head !== current.head || branch !== current.branch || dirty.generation !== final.generation) return { stale: true };
291
+ return { ...result, timings: { gitScanMs: preparationMs + scanEnd - start + pathScanMs, frameDiffMs, validationMs: performance.now() - diffEnd, sources, commits } };
292
+ } finally {
293
+ await trees?.close();
294
+ }
295
+ }
@@ -0,0 +1,100 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { createHash } from 'node:crypto';
4
+ import { lstat, readlink, realpath } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { createReadStream } from 'node:fs';
7
+ import { revisionChanges } from './toolkit/arch-git.mjs';
8
+
9
+ const exec = promisify(execFile);
10
+ export const git = async (root, ...args) =>
11
+ (await exec('git', ['--no-optional-locks', '-C', root, ...args], { maxBuffer: 64 * 1024 * 1024 })).stdout;
12
+ export async function visitRevision(root) {
13
+ try {
14
+ const [head, branch] = (await git(root, 'rev-parse', 'HEAD', '--abbrev-ref', 'HEAD')).trim().split('\n');
15
+ return { head, branch };
16
+ } catch (error) {
17
+ if (error.code !== 128) throw error;
18
+ try {
19
+ return { head: null, branch: (await git(root, 'symbolic-ref', '--short', 'HEAD')).trim() };
20
+ } catch {
21
+ return { head: null, branch: null };
22
+ }
23
+ }
24
+ }
25
+
26
+ export async function emptyTree(root) {
27
+ // The empty tree is addressable without creating objects, including before the first commit.
28
+ const child = exec('git', ['-C', root, 'hash-object', '-t', 'tree', '--stdin']);
29
+ child.child.stdin.end();
30
+ return (await child).stdout.trim();
31
+ }
32
+
33
+ export async function dirtyGeneration(root, head, output, { includeChanges = false, repository } = {}) {
34
+ repository ??= await realpath((await git(root, 'rev-parse', '--show-toplevel')).trim());
35
+ const changes = (await revisionChanges({ root: repository, sha: head ?? (await emptyTree(root)) })).filter((c) =>
36
+ [c.before, c.after].filter(Boolean).some((n) => {
37
+ const file = path.resolve(repository, n);
38
+ return !(file === output || file.startsWith(output + path.sep) || n.split('/').includes('.adg'));
39
+ })
40
+ );
41
+ const hash = createHash('sha256').update(JSON.stringify(changes));
42
+ for (const { after } of changes) {
43
+ if (!after) continue;
44
+ const file = path.join(repository, after);
45
+ const stat = await lstat(file);
46
+ if (stat.isSymbolicLink()) hash.update(await readlink(file));
47
+ else if (stat.isFile()) {
48
+ const content = createHash('sha256');
49
+ for await (const bytes of createReadStream(file)) content.update(bytes);
50
+ hash.update(content.digest());
51
+ } else hash.update(String(stat.mtimeMs));
52
+ }
53
+ return { repository, count: changes.length, generation: hash.digest('hex'), ...(includeChanges && { changes }) };
54
+ }
55
+
56
+ export async function visitRange(root, head, since) {
57
+ let notice = null;
58
+ if (since) {
59
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(since)) throw Error('Invalid visit revision.');
60
+ try {
61
+ await git(root, 'merge-base', '--is-ancestor', since, head);
62
+ } catch {
63
+ notice = 'History changed since your last visit. Showing this week.';
64
+ since = null;
65
+ }
66
+ }
67
+ return { since, notice };
68
+ }
69
+
70
+ export async function historyPeriods(root, head, { day, week, since }) {
71
+ const range = await visitRange(root, head, since);
72
+ ({ since } = range);
73
+ const raw = await git(
74
+ root,
75
+ 'log',
76
+ '--first-parent',
77
+ '--format=%H%x00%P%x00%ct%x00%s',
78
+ '-z',
79
+ ...(since ? [since + '..' + head] : ['--since-as-filter=@' + Math.floor(week / 1000), head]),
80
+ '--'
81
+ );
82
+ const fields = raw.split('\0'),
83
+ periods = [];
84
+ for (let i = 0; i + 3 < fields.length; i += 4) {
85
+ const [sha, parents, time, subject] = fields.slice(i, i + 4);
86
+ const ms = Number(time) * 1000;
87
+ const title = ms >= day ? 'Today' : ms >= week ? 'Earlier this week' : 'Earlier';
88
+ let period = periods.at(-1);
89
+ if (period?.title !== title) {
90
+ period = { title, head: sha, firstTime: ms, lastTime: ms, subjects: [] };
91
+ periods.push(period);
92
+ }
93
+ period.firstTime = Math.min(period.firstTime, ms);
94
+ period.lastTime = Math.max(period.lastTime, ms);
95
+ period.base = parents.split(' ')[0] || null;
96
+ period.subjects.push(subject);
97
+ }
98
+ if (since && periods.length) periods.at(-1).base = since;
99
+ return { periods, notice: range.notice };
100
+ }
@@ -0,0 +1,63 @@
1
+ import { fork, execFile } from 'node:child_process';
2
+ import { mkdtemp, mkdir, realpath, readFile, rm } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ // One request owns the worker and its materializations. Only completed period rows outlive it.
6
+ export async function runRecentJob(options, signal, onProgress) {
7
+ await mkdir(options.directory, { recursive: true });
8
+ const temporaryDirectory = await realpath(await mkdtemp(path.join(options.directory, 'job-')));
9
+ let child, timer;
10
+ try {
11
+ signal.throwIfAborted();
12
+ child = fork(new URL('./recent-worker.mjs', import.meta.url), [], {
13
+ detached: process.platform !== 'win32',
14
+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
15
+ execArgv: [],
16
+ env: {
17
+ ...process.env,
18
+ TMPDIR: temporaryDirectory,
19
+ TMP: temporaryDirectory,
20
+ TEMP: temporaryDirectory,
21
+ GIT_OPTIONAL_LOCKS: '0'
22
+ }
23
+ });
24
+ const kill = (force) => {
25
+ if (!child.pid || child.exitCode !== null || child.signalCode) return;
26
+ if (process.platform === 'win32') execFile('taskkill', ['/pid', String(child.pid), '/T', '/F'], () => {});
27
+ else {
28
+ try {
29
+ process.kill(-child.pid, force ? 'SIGKILL' : 'SIGTERM');
30
+ } catch (error) {
31
+ if (error.code !== 'ESRCH') throw error;
32
+ }
33
+ }
34
+ };
35
+ const abort = () => {
36
+ kill(false);
37
+ timer = setTimeout(() => kill(true), 1200);
38
+ timer.unref();
39
+ };
40
+ signal.addEventListener('abort', abort, { once: true });
41
+ try {
42
+ const code = await new Promise((resolve, reject) => {
43
+ if (onProgress)
44
+ child.on('message', ({ progress }) => {
45
+ if (progress && !signal.aborted) onProgress(progress);
46
+ });
47
+ child.once('error', reject);
48
+ child.once('exit', resolve);
49
+ child.send({ ...options, temporaryDirectory });
50
+ });
51
+ signal.throwIfAborted();
52
+ if (code !== 0) throw Error('The history comparison worker stopped before completing.');
53
+ const reply = JSON.parse(await readFile(path.join(temporaryDirectory, 'result.json'), 'utf8'));
54
+ if (reply.error) throw Error(reply.error);
55
+ return reply.result;
56
+ } finally {
57
+ signal.removeEventListener('abort', abort);
58
+ clearTimeout(timer);
59
+ }
60
+ } finally {
61
+ await rm(temporaryDirectory, { recursive: true, force: true, maxRetries: 3 });
62
+ }
63
+ }
@@ -0,0 +1,171 @@
1
+ import path from 'node:path';
2
+ import { readFile, readdir, writeFile } from 'node:fs/promises';
3
+
4
+ export async function recentHistory({
5
+ root,
6
+ directory,
7
+ temporaryDirectory,
8
+ day,
9
+ week,
10
+ since,
11
+ environment,
12
+ visual,
13
+ onProgress
14
+ }) {
15
+ const [
16
+ { createHash }, { release }, { loadConfig }, { openDiffRevision }, { createIndexStore },
17
+ { trackedHash, inputBytes }, { dirtyGeneration, emptyTree, historyPeriods, visitRevision }
18
+ ] = await Promise.all([
19
+ import('node:crypto'), import('node:os'), import('./toolkit/config.mjs'), import('./toolkit/diff-inputs.mjs'),
20
+ import('./toolkit/index-store.mjs'), import('./toolkit/input-generation.mjs'), import('./recent-history.mjs')
21
+ ]);
22
+ async function validDependencies(entries) {
23
+ for (const [file, hash] of entries) if (trackedHash(await inputBytes(file)) !== hash) return false;
24
+ return true;
25
+ }
26
+ const config = await loadConfig(root);
27
+ const { head, branch } = await visitRevision(root);
28
+ if (!branch) return { available: false, complete: false, periods: [] };
29
+ const dirty = await dirtyGeneration(root, head, config.output);
30
+ const { periods, notice } = head
31
+ ? await historyPeriods(root, head, { day, week, since })
32
+ : { periods: [], notice: null };
33
+ periods.unshift({ title: 'Uncommitted', subjects: [], base: head, head: null });
34
+ const pool = new Map();
35
+ async function openRevision(sha) {
36
+ if (!pool.has(sha))
37
+ pool.set(sha, await openDiffRevision({ root: dirty.repository, sha, rev: sha }, root, temporaryDirectory));
38
+ return { ...pool.get(sha), close: async () => {} };
39
+ }
40
+ const store = await createIndexStore({ directory, diskLimit: 32 * 1024 * 1024 });
41
+ try {
42
+ // All comparisons reuse the installed dependency environment of the project.
43
+ const inputs = createHash('sha256').update(
44
+ JSON.stringify([environment, process.version, process.arch, release(), config.diff])
45
+ );
46
+ const toolkit = new URL('./toolkit/', import.meta.url);
47
+ for (const file of (await readdir(toolkit)).sort().filter((name) => name.endsWith('.mjs')))
48
+ inputs.update(await readFile(new URL(file, toolkit)));
49
+ for (const name of ['./recent-worker.mjs', '../package.json'])
50
+ inputs.update(await readFile(new URL(name, import.meta.url)));
51
+ for (let d = root; ; d = path.dirname(d)) {
52
+ for (const name of [
53
+ 'package.json',
54
+ 'package-lock.json',
55
+ 'pnpm-lock.yaml',
56
+ 'yarn.lock',
57
+ 'bun.lock',
58
+ 'bun.lockb',
59
+ 'npm-shrinkwrap.json',
60
+ 'node_modules/.package-lock.json'
61
+ ]) {
62
+ const bytes = await inputBytes(path.join(d, name));
63
+ if (bytes) inputs.update(bytes);
64
+ }
65
+ if (d === dirty.repository || d === path.dirname(d)) break;
66
+ }
67
+ const context = inputs.digest('hex');
68
+ let dirtyCache;
69
+ for (const period of periods) period.base ??= await emptyTree(root);
70
+ const selected = visual
71
+ ? periods.filter((p) => (p.base ?? '') === visual.base && (p.head ?? '') === visual.head)
72
+ : periods;
73
+ if (visual && (selected.length !== 1 || (!visual.head && visual.generation !== dirty.generation)))
74
+ throw Error('Period changed. Refresh Recently updated.');
75
+ for (const period of selected) {
76
+ if (!period.head && !dirty.count) {
77
+ Object.assign(period, { rows: [], complete: true });
78
+ continue;
79
+ }
80
+ const key = visual
81
+ ? JSON.stringify([
82
+ 'visual',
83
+ root,
84
+ period.base,
85
+ period.head,
86
+ period.head ? null : dirty.generation,
87
+ context
88
+ ])
89
+ : JSON.stringify([
90
+ 1,
91
+ root,
92
+ head,
93
+ period.base,
94
+ period.head,
95
+ period.head ? null : dirty.generation,
96
+ day,
97
+ week,
98
+ context
99
+ ]);
100
+ let result = await store.get(key);
101
+ const cached = !!result && (await validDependencies(result.dependencies));
102
+ if (!cached) {
103
+ try {
104
+ const compare = visual ? (await import('./toolkit/review.mjs')).reviewFrameChanges : (await import('./toolkit/recent-structure.mjs')).structuralChanges;
105
+ result = await compare(config, {
106
+ onProgress,
107
+ base: period.base,
108
+ head: period.head ?? undefined,
109
+ openRevision,
110
+ temporaryDirectory
111
+ });
112
+ if (result.complete) {
113
+ if (period.head) await store.put(key, result);
114
+ else dirtyCache = { key, result };
115
+ }
116
+ } catch (error) {
117
+ result = { rows: [], complete: false, failures: [{ message: error.message }] };
118
+ }
119
+ }
120
+ const { dependencies, ...projection } = result;
121
+ Object.assign(period, projection, { cached });
122
+ }
123
+ const latest = await visitRevision(root);
124
+ if (
125
+ latest.head !== head ||
126
+ latest.branch !== branch ||
127
+ (await dirtyGeneration(root, head, config.output)).generation !== dirty.generation
128
+ )
129
+ return {
130
+ available: true,
131
+ complete: false,
132
+ stale: true,
133
+ periods: [],
134
+ notice: 'Project changed. Refreshing recent frames…'
135
+ };
136
+ if (dirtyCache) await store.put(dirtyCache.key, dirtyCache.result);
137
+ return {
138
+ available: true,
139
+ head,
140
+ branch,
141
+ generation: dirty.generation,
142
+ notice,
143
+ periods: selected,
144
+ complete: selected.every((p) => p.complete)
145
+ };
146
+ } finally {
147
+ try {
148
+ await store.close();
149
+ } finally {
150
+ await Promise.all([...pool.values()].map((rev) => rev.close()));
151
+ }
152
+ }
153
+ }
154
+ if (process.send)
155
+ process.once('message', async (args) => {
156
+ let reply;
157
+ try {
158
+ reply = {
159
+ result: args.feed ? await (await import('./recent-frames.mjs')).recentFrames(args) : await recentHistory({
160
+ ...args,
161
+ onProgress: args.visual ? (progress) => process.send({ progress }) : undefined
162
+ })
163
+ };
164
+ } catch (error) {
165
+ reply = { error: error.message };
166
+ }
167
+ // Large frame lists can exceed the IPC pipe buffer. Close only after the
168
+ // complete reply is in the request's private directory.
169
+ await writeFile(path.join(args.temporaryDirectory, 'result.json'), JSON.stringify(reply));
170
+ process.disconnect();
171
+ });