@dcaldeira/tooling 0.0.0-stage → 0.2.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 (56) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +33 -2
  3. package/checks/a11y.mjs +206 -0
  4. package/checks/architecture.mjs +137 -0
  5. package/checks/audit.mjs +121 -0
  6. package/checks/bundle.mjs +126 -0
  7. package/checks/dependencies.mjs +277 -0
  8. package/checks/duplication.mjs +135 -0
  9. package/checks/lint-scss.mjs +363 -0
  10. package/checks/package.mjs +30 -0
  11. package/checks/playwright-summary.mjs +53 -0
  12. package/checks/sass.mjs +67 -0
  13. package/checks/scan-secrets.mjs +58 -0
  14. package/checks/shared.mjs +86 -0
  15. package/checks/style-property-order.json +498 -0
  16. package/checks/translations.mjs +55 -0
  17. package/checks/visual-compare.mjs +148 -0
  18. package/checks/visual-report-html.mjs +470 -0
  19. package/checks/visual-report.mjs +13 -0
  20. package/config.schema.json +977 -0
  21. package/configs/eslint.mjs +27 -0
  22. package/configs/knip.json +11 -0
  23. package/configs/playwright.mjs +15 -0
  24. package/configs/prettier.mjs +1 -0
  25. package/configs/tsconfig.json +16 -0
  26. package/configs/vitest.mjs +16 -0
  27. package/package.json +103 -4
  28. package/release/evidence.mjs +62 -0
  29. package/release/finalize.mjs +65 -0
  30. package/release/gh.mjs +25 -0
  31. package/release/github.mjs +64 -0
  32. package/release/prepare.mjs +30 -0
  33. package/runner/browsers.mjs +73 -0
  34. package/runner/cache.mjs +121 -0
  35. package/runner/ci-plan.mjs +54 -0
  36. package/runner/cli.mjs +251 -0
  37. package/runner/config.mjs +148 -0
  38. package/runner/docs-install.mjs +93 -0
  39. package/runner/execute.mjs +298 -0
  40. package/runner/generate.mjs +122 -0
  41. package/runner/git.mjs +122 -0
  42. package/runner/graph.mjs +250 -0
  43. package/runner/index.mjs +4 -0
  44. package/runner/insights.mjs +313 -0
  45. package/runner/provision.mjs +53 -0
  46. package/runner/repo-standard.mjs +104 -0
  47. package/runner/report.mjs +35 -0
  48. package/runner/serve-static.mjs +76 -0
  49. package/runner/setup.mjs +241 -0
  50. package/runner/summary.mjs +112 -0
  51. package/runner/watch.mjs +82 -0
  52. package/templates/ci.yml +25 -0
  53. package/templates/dependabot-merge.yml +13 -0
  54. package/templates/dependabot.yml +26 -0
  55. package/templates/pre-push +13 -0
  56. package/templates/release.yml +23 -0
@@ -0,0 +1,298 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { inside } from './config.mjs';
5
+ import { matches } from './graph.mjs';
6
+
7
+ const bins = {
8
+ prettier: 'prettier',
9
+ eslint: 'eslint',
10
+ vitest: 'vitest',
11
+ playwright: '@playwright/test',
12
+ knip: 'knip',
13
+ tsc: 'typescript',
14
+ lhci: '@lhci/cli',
15
+ };
16
+
17
+ export function packageManifest(root, name) {
18
+ for (let directory = resolve(root); ; directory = dirname(directory)) {
19
+ const manifest = join(directory, 'node_modules', name, 'package.json');
20
+ if (existsSync(manifest)) return manifest;
21
+ if (dirname(directory) === directory) return null;
22
+ }
23
+ }
24
+
25
+ export function executable(root, name) {
26
+ if (isAbsolute(name)) return existsSync(name) ? [name] : null;
27
+ if (name === 'initdb' && process.env.PG_BIN) {
28
+ const target = join(process.env.PG_BIN, process.platform === 'win32' ? 'initdb.exe' : 'initdb');
29
+ if (existsSync(target)) return [target];
30
+ }
31
+ if (name === 'node') return [process.execPath];
32
+ if (name === 'npm') {
33
+ const candidates = [
34
+ process.env.npm_execpath,
35
+ join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
36
+ ];
37
+ const cli = candidates.find((p) => p && /npm-cli\.js$/.test(p) && existsSync(p));
38
+ if (cli) return [process.execPath, cli];
39
+ }
40
+ const pkg = bins[name] ?? name;
41
+ for (let directory = resolve(root); ; directory = dirname(directory)) {
42
+ const manifest = join(directory, 'node_modules', pkg, 'package.json');
43
+ if (existsSync(manifest)) {
44
+ const { bin } = JSON.parse(readFileSync(manifest, 'utf8'));
45
+ const entry = typeof bin === 'string' ? bin : bin?.[name];
46
+ if (entry) return [process.execPath, resolve(dirname(manifest), entry)];
47
+ }
48
+ if (dirname(directory) === directory) break;
49
+ }
50
+ const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
51
+ for (const directory of (process.env.PATH ?? '').split(delimiter))
52
+ for (const extension of extensions) {
53
+ const candidate = join(directory, `${name}${extension}`);
54
+ if (existsSync(candidate)) return [candidate];
55
+ }
56
+ return null;
57
+ }
58
+
59
+ export function invoke(command, root, { cwd = root, extra = [], quiet = false, env = {} } = {}) {
60
+ let file, args, shell;
61
+ if (Array.isArray(command)) {
62
+ const binary = executable(cwd, command[0]);
63
+ if (!binary)
64
+ return Promise.resolve({
65
+ status: 'unavailable',
66
+ reason: `Missing executable: ${command[0]}`,
67
+ });
68
+ [file, ...args] = [...binary, ...command.slice(1), ...extra];
69
+ shell = false;
70
+ } else {
71
+ if (extra.length) throw new Error('Changed-file commands must use an argument array');
72
+ file = command;
73
+ args = [];
74
+ shell = true;
75
+ }
76
+ return new Promise((done) => {
77
+ const started = Date.now();
78
+ let settled = false;
79
+ const finish = (result) => {
80
+ if (!settled) {
81
+ settled = true;
82
+ done({ ...result, milliseconds: Date.now() - started });
83
+ }
84
+ };
85
+ const child = spawn(file, args, {
86
+ cwd,
87
+ shell,
88
+ stdio: quiet ? 'ignore' : 'inherit',
89
+ env: {
90
+ ...process.env,
91
+ ...env,
92
+ PATH: `${join(cwd, 'node_modules/.bin')}${delimiter}${join(root, 'node_modules/.bin')}${delimiter}${process.env.PATH}`,
93
+ },
94
+ });
95
+ child.once('error', (error) => finish({ status: 'unavailable', reason: error.message }));
96
+ child.once('exit', (code, signal) =>
97
+ finish({
98
+ status: code === 0 ? 'passed' : 'failed',
99
+ code,
100
+ ...(signal ? { reason: signal } : {}),
101
+ }),
102
+ );
103
+ });
104
+ }
105
+
106
+ export async function execute(
107
+ root,
108
+ selection,
109
+ {
110
+ bail = false,
111
+ concurrency = bail ? 1 : 2,
112
+ platform = process.platform,
113
+ run = invoke,
114
+ cache,
115
+ toolCache = true,
116
+ } = {},
117
+ ) {
118
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
119
+ throw new Error('Concurrency must be an integer between 1 and 16');
120
+ const excluded = new Set([
121
+ ...selection.excluded,
122
+ ...selection.checks.filter((c) => c.excluded).map((c) => c.id),
123
+ ]);
124
+ const statuses = new Map([...excluded].map((id) => [id, 'excluded']));
125
+ const outcomes = new Map(
126
+ [...excluded].map((id) => [
127
+ id,
128
+ { id, status: 'excluded', reason: 'Required check intentionally excluded' },
129
+ ]),
130
+ );
131
+ const pending = selection.checks.filter((c) => !c.excluded);
132
+ const running = new Map();
133
+ const resources = new Set();
134
+ let stopped = false;
135
+ const broad = selection.groups.some((g) =>
136
+ ['all', 'tooling', 'dependencies', 'unknown'].includes(g),
137
+ );
138
+
139
+ async function perform(check) {
140
+ const cwd = inside(root, check.cwd ?? '.');
141
+ const selectedFiles = check.files ?? selection.files;
142
+ if (check.platforms && !check.platforms.includes(platform))
143
+ return {
144
+ status: 'unavailable',
145
+ reason: 'Requires ' + check.platforms.join('/') + '; use Linux via WSL or a container',
146
+ };
147
+ const missing = (check.tools ?? []).filter((tool) => !executable(cwd, tool));
148
+ if (missing.length)
149
+ return { status: 'unavailable', reason: 'Missing tools: ' + missing.join(', ') };
150
+ const deleted =
151
+ selectedFiles !== 'all' &&
152
+ check.devAllCommand &&
153
+ selectedFiles.some(
154
+ (file) =>
155
+ check.devFiles?.some((pattern) => matches(file, pattern)) &&
156
+ !existsSync(inside(root, file)),
157
+ );
158
+ const devFiles =
159
+ selection.profile === 'dev' && !broad && !deleted && check.devCommand && check.devFiles;
160
+ const files = devFiles
161
+ ? selectedFiles.filter(
162
+ (file) =>
163
+ check.devFiles.some((pattern) => matches(file, pattern)) &&
164
+ existsSync(inside(root, file)),
165
+ )
166
+ : [];
167
+ if (devFiles && !files.length)
168
+ return {
169
+ status: 'passed',
170
+ reason: 'No remaining matching files (deleted files are checked by full profiles)',
171
+ };
172
+ let command = devFiles
173
+ ? check.devCommand
174
+ : selection.profile === 'dev'
175
+ ? (check.devAllCommand ?? check.command)
176
+ : check.command;
177
+ if (!toolCache && Array.isArray(command) && command[0] === 'eslint') {
178
+ command = command.filter(
179
+ (value, index, args) =>
180
+ value !== '--cache' &&
181
+ value !== '--cache-strategy' &&
182
+ args[index - 1] !== '--cache-strategy',
183
+ );
184
+ }
185
+ if (
186
+ !toolCache &&
187
+ Array.isArray(command) &&
188
+ command[0] === 'tsc' &&
189
+ command.includes('--build') &&
190
+ !command.includes('--force')
191
+ )
192
+ command = [...command, '--force'];
193
+ if (
194
+ Array.isArray(command) &&
195
+ command[0] === 'eslint' &&
196
+ command.includes('--cache') &&
197
+ !command.includes('--cache-location')
198
+ ) {
199
+ command = [...command];
200
+ const end = command.indexOf('--');
201
+ command.splice(
202
+ end === -1 ? command.length : end,
203
+ 0,
204
+ '--cache-location',
205
+ join(root, '.tooling/cache/eslint', `${check.id}.cache`),
206
+ );
207
+ }
208
+ const cached = cache?.get(check, command, files);
209
+ if (cached) return cached;
210
+ console.log(
211
+ '\n> ' +
212
+ check.id +
213
+ ': ' +
214
+ (Array.isArray(command) ? command.join(' ') : command) +
215
+ (files.length ? ' (' + files.length + ' files)' : ''),
216
+ );
217
+ const env = {
218
+ TOOLING_ROOT: root,
219
+ TOOLING_CHECK_ID: check.id,
220
+ TOOLING_BUILT: (check.dependsOn ?? ['build']).some(
221
+ (id) =>
222
+ statuses.get(id) === 'passed' &&
223
+ selection.checks.some(
224
+ (candidate) => candidate.id === id && (candidate.kind ?? candidate.id) === 'build',
225
+ ),
226
+ )
227
+ ? '1'
228
+ : '',
229
+ };
230
+ // Full-profile runs of change-scoped checks still get the selected files, as a list file
231
+ // (a command line could overflow on large diffs). `--all` runs leave it unset.
232
+ if (
233
+ (check.kind ?? check.id) === 'duplication' &&
234
+ Array.isArray(selectedFiles) &&
235
+ !files.length
236
+ ) {
237
+ const list = join(root, '.tooling/state', `${check.id}-changed.txt`);
238
+ mkdirSync(dirname(list), { recursive: true });
239
+ writeFileSync(list, selectedFiles.join('\n'));
240
+ env.TOOLING_CHANGED_FILES = list;
241
+ }
242
+ if ((check.kind ?? check.id) === 'unit' && process.env.TOOLING_REPORT_DIR)
243
+ env.TOOLING_UNIT_OUTPUT_DIR = join(process.env.TOOLING_REPORT_DIR, `${check.id}-results`);
244
+ if (['e2e', 'visual'].includes(check.kind ?? check.id) && process.env.TOOLING_REPORT_DIR) {
245
+ env.PLAYWRIGHT_HTML_OUTPUT_DIR = join(process.env.TOOLING_REPORT_DIR, check.id);
246
+ env.TOOLING_TEST_OUTPUT_DIR = join(process.env.TOOLING_REPORT_DIR, check.id + '-results');
247
+ }
248
+ return run(command, root, { cwd, extra: files.map((file) => resolve(root, file)), env });
249
+ }
250
+
251
+ function record(check, result) {
252
+ outcomes.set(check.id, { id: check.id, kind: check.kind ?? check.id, ...result });
253
+ statuses.set(check.id, result.status);
254
+ if (bail && result.status !== 'passed') stopped = true;
255
+ }
256
+
257
+ while (pending.length || running.size) {
258
+ for (let i = 0; i < pending.length;) {
259
+ const check = pending[i];
260
+ const deps = check.dependsOn ?? [];
261
+ if (stopped || deps.some((id) => statuses.has(id) && statuses.get(id) !== 'passed')) {
262
+ pending.splice(i, 1);
263
+ record(check, {
264
+ status: 'unavailable',
265
+ reason: stopped ? 'Not run after --bail' : 'Dependency did not pass',
266
+ });
267
+ continue;
268
+ }
269
+ if (
270
+ running.size >= concurrency ||
271
+ deps.some((id) => !statuses.has(id)) ||
272
+ (check.resources ?? []).some((key) => resources.has(key))
273
+ ) {
274
+ i++;
275
+ continue;
276
+ }
277
+ pending.splice(i, 1);
278
+ for (const key of check.resources ?? []) resources.add(key);
279
+ const task = Promise.resolve()
280
+ .then(() => perform(check))
281
+ .catch((error) => ({ status: 'unavailable', reason: error.message }))
282
+ .then((result) => {
283
+ record(check, result);
284
+ running.delete(check.id);
285
+ for (const key of check.resources ?? []) resources.delete(key);
286
+ });
287
+ running.set(check.id, task);
288
+ }
289
+ if (running.size) await Promise.race(running.values());
290
+ else if (pending.length) {
291
+ for (const check of pending.splice(0))
292
+ record(check, { status: 'unavailable', reason: 'Unresolved dependencies' });
293
+ }
294
+ }
295
+ const ids = [...new Set([...excluded, ...selection.checks.map((c) => c.id)])];
296
+ const results = ids.map((id) => outcomes.get(id));
297
+ return { results, complete: results.every((r) => r.status === 'passed') };
298
+ }
@@ -0,0 +1,122 @@
1
+ import { existsSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
2
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { inside, loadConfig } from './config.mjs';
4
+
5
+ const kebab = (name) =>
6
+ name
7
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
8
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
9
+ .toLowerCase();
10
+
11
+ export function generateFiles(root, kind, { name, path, designSystem = false } = {}, config = {}) {
12
+ if (!['component', 'hook'].includes(kind)) throw new Error('Generator must be component or hook');
13
+ if (
14
+ !name ||
15
+ (kind === 'component'
16
+ ? !/^[A-Z][A-Za-z0-9]*$/.test(name)
17
+ : !/^use[A-Z][A-Za-z0-9]*$/.test(name))
18
+ )
19
+ throw new Error(
20
+ kind === 'component'
21
+ ? 'Use a PascalCase component name'
22
+ : 'Hook names must start with use followed by PascalCase',
23
+ );
24
+ const settings = config.generators ?? {};
25
+ const directory =
26
+ path ??
27
+ (kind === 'component'
28
+ ? (settings.components ?? 'src/components')
29
+ : (settings.hooks ?? 'src/hooks'));
30
+ inside(root, directory);
31
+ const files = new Map();
32
+ if (kind === 'component') {
33
+ const block =
34
+ config.styles?.preset === 'rookie' || config.styles?.rules?.componentName
35
+ ? name.replace(/(?<!^)(?=[A-Z])/g, '-').toLowerCase()
36
+ : kebab(name),
37
+ base = `${directory}/${name}`;
38
+ let source;
39
+ if (designSystem) {
40
+ const ds = settings.designSystem;
41
+ if (!ds?.package || !ds.component)
42
+ throw new Error(
43
+ 'Configure generators.designSystem.package and component before using --design-system',
44
+ );
45
+ if (
46
+ !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(ds.package) ||
47
+ !/^[A-Z][A-Za-z0-9]*$/.test(ds.component)
48
+ )
49
+ throw new Error('Invalid design-system import');
50
+ source = `import type { ComponentProps } from 'react';\nimport { ${ds.component} as Primitive } from '${ds.package}';\nimport styles from './${name}.module.scss';\n\nexport type ${name}Props = ComponentProps<typeof Primitive>;\n\nexport function ${name}({ className, ...props }: ${name}Props) {\n return <Primitive className={[styles['${block}'], className].filter(Boolean).join(' ')} {...props} />;\n}\n`;
51
+ } else {
52
+ source = `import type { HTMLAttributes } from 'react';\nimport styles from './${name}.module.scss';\n\nexport type ${name}Props = HTMLAttributes<HTMLDivElement>;\n\nexport function ${name}({ className, ...props }: ${name}Props) {\n return <div className={[styles['${block}'], className].filter(Boolean).join(' ')} {...props} />;\n}\n`;
53
+ }
54
+ files.set(`${base}/${name}.tsx`, source);
55
+ files.set(`${base}/${name}.module.scss`, `.${block} {\n display: block;\n}\n`);
56
+ files.set(
57
+ `${base}/${name}.test.tsx`,
58
+ `// @vitest-environment jsdom\nimport { cleanup, render, screen } from '@testing-library/react';\nimport { afterEach, describe, expect, it } from 'vitest';\nimport { ${name} } from './${name}';\n\nafterEach(cleanup);\n\ndescribe('${name}', () => {\n it('renders its content and forwards DOM attributes', () => {\n render(<${name} data-testid="subject" className="custom">Content</${name}>);\n const element = screen.getByTestId('subject');\n expect(element.textContent).toBe('Content');\n expect(element.classList.contains('custom')).toBe(true);\n });\n});\n`,
59
+ );
60
+ files.set(
61
+ `${base}/index.ts`,
62
+ `export { ${name} } from './${name}';\nexport type { ${name}Props } from './${name}';\n`,
63
+ );
64
+ } else {
65
+ files.set(
66
+ `${directory}/${name}.ts`,
67
+ `import { useState } from 'react';\n\n// Replace this initial state scaffold with the hook's domain behaviour.\nexport function ${name}<T>(initialValue: T) {\n return useState(initialValue);\n}\n`,
68
+ );
69
+ files.set(
70
+ `${directory}/${name}.test.ts`,
71
+ `// @vitest-environment jsdom\nimport { act, cleanup, renderHook } from '@testing-library/react';\nimport { afterEach, describe, expect, it } from 'vitest';\nimport { ${name} } from './${name}';\n\nafterEach(cleanup);\n\ndescribe('${name}', () => {\n it('initializes state and accepts updates', () => {\n const { result } = renderHook(() => ${name}('initial'));\n expect(result.current[0]).toBe('initial');\n act(() => result.current[1]('updated'));\n expect(result.current[0]).toBe('updated');\n });\n});\n`,
72
+ );
73
+ }
74
+ return files;
75
+ }
76
+
77
+ export function writeGenerated(root, files, { dryRun = false } = {}) {
78
+ const canonicalRoot = realpathSync(root);
79
+ for (const path of files.keys()) {
80
+ const target = inside(root, path);
81
+ if (existsSync(target)) throw new Error(`Refusing to overwrite ${path}`);
82
+ let parent = dirname(target);
83
+ while (!existsSync(parent)) parent = dirname(parent);
84
+ const rel = relative(canonicalRoot, realpathSync(parent));
85
+ if (
86
+ isAbsolute(rel) ||
87
+ rel === '..' ||
88
+ rel.startsWith(`..${sep}`) ||
89
+ resolve(canonicalRoot, rel) !== realpathSync(parent)
90
+ )
91
+ throw new Error(`Generator destination escapes repository: ${path}`);
92
+ }
93
+ if (dryRun) return;
94
+ for (const [path, content] of files) {
95
+ const target = inside(root, path);
96
+ mkdirSync(dirname(target), { recursive: true });
97
+ writeFileSync(target, content, { flag: 'wx' });
98
+ }
99
+ }
100
+
101
+ export function generateCommand(root, kind, options) {
102
+ let config;
103
+ try {
104
+ config = loadConfig(root, options.config).config;
105
+ } catch (error) {
106
+ if (options.config || error.code !== 'ENOENT') throw error;
107
+ config = {};
108
+ }
109
+ const files = generateFiles(
110
+ root,
111
+ kind,
112
+ { name: options.name, path: options.path, designSystem: options['design-system'] },
113
+ config,
114
+ );
115
+ writeGenerated(root, files, { dryRun: options['dry-run'] });
116
+ console.log(
117
+ options['dry-run']
118
+ ? JSON.stringify({ files: [...files].map(([path, content]) => ({ path, content })) }, null, 2)
119
+ : `Generated ${[...files.keys()].join(', ')}`,
120
+ );
121
+ return 0;
122
+ }
package/runner/git.mjs ADDED
@@ -0,0 +1,122 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { lstatSync, readFileSync, readlinkSync } from 'node:fs';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { executable } from './execute.mjs';
6
+
7
+ export const git = (root, ...args) =>
8
+ execFileSync('git', args, {
9
+ cwd: root,
10
+ encoding: 'utf8',
11
+ maxBuffer: 64 * 1024 * 1024,
12
+ stdio: ['ignore', 'pipe', 'pipe'],
13
+ }).trimEnd();
14
+ const nul = (value) => value.split('\0').filter(Boolean);
15
+
16
+ export function changedFiles(root, base, { committed = false, head = 'HEAD' } = {}) {
17
+ const ancestor = git(root, 'merge-base', base, head);
18
+ const changes = nul(git(root, 'diff', '--name-only', '--no-renames', '-z', ancestor, head));
19
+ if (!committed)
20
+ changes.push(
21
+ ...nul(git(root, 'diff', '--name-only', '--no-renames', '-z', 'HEAD')),
22
+ ...nul(git(root, 'ls-files', '--others', '--exclude-standard', '-z')),
23
+ );
24
+ return [...new Set(changes)].sort();
25
+ }
26
+
27
+ export function toolIdentity(root, tool) {
28
+ const name = typeof tool === 'string' ? tool : tool.name;
29
+ const cwd = typeof tool === 'string' ? root : resolve(root, tool.cwd ?? '.');
30
+ const command = executable(cwd, name);
31
+ if (!command) return { name, cwd, command: null };
32
+ if (name === 'node') return { name, cwd, command, version: process.version };
33
+ if (command[0] === process.execPath && command[1]) {
34
+ for (let directory = dirname(command[1]); ; directory = dirname(directory)) {
35
+ try {
36
+ const manifest = readFileSync(join(directory, 'package.json'), 'utf8');
37
+ const entry = createHash('sha256').update(readFileSync(command[1])).digest('hex');
38
+ return { name, cwd, command, manifest, entry };
39
+ } catch (error) {
40
+ if (error.code !== 'ENOENT') throw error;
41
+ }
42
+ if (dirname(directory) === directory) break;
43
+ }
44
+ }
45
+ let version;
46
+ try {
47
+ version = execFileSync(command[0], [...command.slice(1), '--version'], {
48
+ cwd,
49
+ encoding: 'utf8',
50
+ timeout: 5000,
51
+ stdio: ['ignore', 'pipe', 'pipe'],
52
+ });
53
+ } catch {
54
+ version = 'version-unavailable';
55
+ }
56
+ return { name, cwd, command, version };
57
+ }
58
+
59
+ export function captureSnapshot(
60
+ root,
61
+ { base, version, config, environment = [], tools = [], inputs = [] },
62
+ ) {
63
+ const hash = createHash('sha256');
64
+ const add = (value) => {
65
+ const text = String(value);
66
+ hash.update(`${Buffer.byteLength(text)}:`);
67
+ hash.update(text);
68
+ };
69
+ add(version);
70
+ add(process.version);
71
+ add(process.platform);
72
+ add(config);
73
+ for (const file of ['node_modules/.package-lock.json', ...inputs]) {
74
+ add(file);
75
+ try {
76
+ const bytes = readFileSync(resolve(root, file));
77
+ add(bytes.length);
78
+ hash.update(bytes);
79
+ } catch (error) {
80
+ if (error.code !== 'ENOENT') throw error;
81
+ add('absent');
82
+ }
83
+ }
84
+ for (const key of environment) {
85
+ add(key);
86
+ add(process.env[key] ?? '');
87
+ }
88
+ const context = hash.copy().digest('hex');
89
+ const identities = tools.map((tool) => toolIdentity(root, tool));
90
+ for (const identity of identities) add(JSON.stringify(identity));
91
+ add(git(root, 'rev-parse', 'HEAD'));
92
+ add(git(root, 'rev-parse', `${base}^{commit}`));
93
+ const files = new Set(
94
+ nul(git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z')),
95
+ );
96
+ const digests = {};
97
+ for (const file of [...files].sort()) {
98
+ const content = createHash('sha256');
99
+ const part = (value) => content.update(JSON.stringify(value));
100
+ try {
101
+ const stat = lstatSync(resolve(root, file));
102
+ part(stat.mode & 0o111);
103
+ if (stat.isSymbolicLink()) part(readlinkSync(resolve(root, file)));
104
+ else if (stat.isFile()) {
105
+ const bytes = readFileSync(resolve(root, file));
106
+ part(bytes.length);
107
+ content.update(bytes);
108
+ } else part('directory');
109
+ } catch (error) {
110
+ if (error.code !== 'ENOENT') throw error;
111
+ part('deleted');
112
+ }
113
+ digests[file] = content.digest('hex');
114
+ add(file);
115
+ add(digests[file]);
116
+ }
117
+ return { fingerprint: hash.digest('hex'), context, files: digests, tools: identities };
118
+ }
119
+
120
+ export const snapshot = (root, context) => captureSnapshot(root, context).fingerprint;
121
+
122
+ export const clean = (root) => !git(root, 'status', '--porcelain', '--untracked-files=all');