@williamthorsen/nmr-core 0.13.5 โ†’ 0.14.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,49 @@
1
1
  [
2
+ {
3
+ "version": "0.14.0",
4
+ "date": "2026-10-27",
5
+ "sections": [
6
+ {
7
+ "title": "๐ŸŽ‰ Features",
8
+ "audience": "all",
9
+ "items": [
10
+ {
11
+ "description": "Report the time that a build-cache hit saved (#1112)",
12
+ "body": "Adds the time that a build-cache hit saved to the skip line printed by `nmr-compile`, as in `Skipping build, saved ~2.1s.`, when the skipped emit took at least a second. The change also measures the durations that nmr reports on the monotonic clock, so that an adjustment of the system clock during a run no longer shortens or negates them.",
13
+ "hash": "ead0549c50d886ef371cb03d979883e027b051c2"
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "title": "โ™ป๏ธ Refactoring",
19
+ "audience": "dev",
20
+ "items": [
21
+ {
22
+ "description": "Renames nmr-core's identifiers to follow the naming conventions, changing the exported option keys `dryRun` and `overwrite` to `isDryRun` and `shouldOverwrite` and the constant `GIT_OUTPUT_LIMIT` to `GIT_OUTPUT_LIMIT_BYTES`, and updates their call sites in nmr, release-kit, and v11y-check. (#1125)",
23
+ "hash": "2cb60f628512ed6ec2273a219a7b6c71aa35b1bf",
24
+ "entry": 1
25
+ }
26
+ ]
27
+ }
28
+ ]
29
+ },
30
+ {
31
+ "version": "0.13.6",
32
+ "date": "2026-10-24",
33
+ "sections": [
34
+ {
35
+ "title": "๐Ÿงช Tests",
36
+ "audience": "dev",
37
+ "items": [
38
+ {
39
+ "description": "Captures the output that passing tests leaked into the run, asserting on each error, hint, and `TAG_RESOLVE_FAILED` YAML warning emitted by the code under test, and pipes the stdio of the child processes run by tool tests so that their output does not reach the worker's streams. (#1097)",
40
+ "hash": "ed6e4187d7f30fa27eb59b495c5f51cf07eacdbc",
41
+ "entry": 2
42
+ }
43
+ ]
44
+ }
45
+ ]
46
+ },
2
47
  {
3
48
  "version": "0.13.5",
4
49
  "date": "2026-10-21",
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## 0.14.0 โ€” 2026-10-27
6
+
7
+ ### ๐ŸŽ‰ Features
8
+
9
+ - Report the time that a build-cache hit saved (#1112)
10
+
11
+ Adds the time that a build-cache hit saved to the skip line printed by `nmr-compile`, as in `Skipping build, saved ~2.1s.`, when the skipped emit took at least a second. The change also measures the durations that nmr reports on the monotonic clock, so that an adjustment of the system clock during a run no longer shortens or negates them.
12
+
13
+ ### โ™ป๏ธ Refactoring
14
+
15
+ - Renames nmr-core's identifiers to follow the naming conventions, changing the exported option keys `dryRun` and `overwrite` to `isDryRun` and `shouldOverwrite` and the constant `GIT_OUTPUT_LIMIT` to `GIT_OUTPUT_LIMIT_BYTES`, and updates their call sites in nmr, release-kit, and v11y-check. (#1125)
16
+
17
+ ## 0.13.6 โ€” 2026-10-24
18
+
19
+ ### ๐Ÿงช Tests
20
+
21
+ - Captures the output that passing tests leaked into the run, asserting on each error, hint, and `TAG_RESOLVE_FAILED` YAML warning emitted by the code under test, and pipes the stdio of the child processes run by tool tests so that their output does not reach the worker's streams. (#1097)
22
+
5
23
  ## 0.13.5 โ€” 2026-10-21
6
24
 
7
25
  ### ๐Ÿ› Bug fixes
package/README.md CHANGED
@@ -7,13 +7,13 @@ Shared utilities for node-monorepo-tools packages.
7
7
  This package serves as the shared library foundation for the monorepo. For the nmr CLI tool, see [`@williamthorsen/nmr`](../nmr).
8
8
 
9
9
  <!-- section:release-notes -->
10
- ## Release notes โ€” v0.13.5 (2026-10-21)
10
+ ## Release notes โ€” v0.14.0 (2026-10-27)
11
11
 
12
- ### ๐Ÿ› Bug fixes
12
+ ### ๐ŸŽ‰ Features
13
13
 
14
- - Key the check cache on the working tree's git tree id (#1078)
14
+ - Report the time that a build-cache hit saved (#1112)
15
15
 
16
- Keys `nmr`'s check-result cache on the git tree id that `git add --all` would record for the working tree, so that committing a tree that has already passed a check no longer makes the next run repeat it. Invalidates every pass recorded by earlier versions of `nmr`, and the first run after the upgrade repeats each of those checks. Also fixes the issue that the snapshot sent to the host by `nmr --delegate` could omit a file edited in the same second as git's last write of the index.
16
+ Adds the time that a build-cache hit saved to the skip line printed by `nmr-compile`, as in `Skipping build, saved ~2.1s.`, when the skipped emit took at least a second. The change also measures the durations that nmr reports on the monotonic clock, so that an adjustment of the system clock during a run no longer shortens or negates them.
17
17
  <!-- /section:release-notes -->
18
18
 
19
19
  ## Installation
@@ -27,6 +27,12 @@ export interface CacheEntryRef extends CacheDirRef {
27
27
  * miss, never an error: The caller's fallback is to do the work again, which is always correct.
28
28
  */
29
29
  export declare function readCacheEntry(entryPath: string): Promise<string | undefined>;
30
+ /**
31
+ * Reads the value that `writeGuardedCacheEntry` recorded under `token`, or `undefined` when the entry is missing,
32
+ * unreadable, recorded under another token, or holds a value that `isValidValue` rejects. A token that no longer
33
+ * matches means that the value describes inputs other than the current ones.
34
+ */
35
+ export declare function readGuardedCacheEntry<T>(entryPath: string, token: string, isValidValue: (value: unknown) => value is T): Promise<T | undefined>;
30
36
  /**
31
37
  * Reads a JSON entry and narrows it with `isValidEntry`, returning `undefined` when the entry is missing,
32
38
  * unparseable, or of the wrong shape. Content written in an older format therefore reads as a miss rather than
@@ -57,3 +63,8 @@ export declare function resolveCacheEntryPath(ref: CacheEntryRef): string;
57
63
  * for whom a failed cache write is not worth failing over catches it.
58
64
  */
59
65
  export declare function writeCacheEntry(entryPath: string, content: string): Promise<void>;
66
+ /**
67
+ * Writes `value` with the token under which `readGuardedCacheEntry` returns it, atomically as `writeCacheEntry`
68
+ * does. Throws when the write cannot be completed.
69
+ */
70
+ export declare function writeGuardedCacheEntry(entryPath: string, token: string, value: unknown): Promise<void>;
@@ -3,7 +3,7 @@ import { readFile, rm } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { findDirectoryChainMatch } from '@williamthorsen/toolbelt.filesystem';
5
5
  import { writeAtomic } from '@williamthorsen/toolbelt.filesystem/candidate';
6
- const DIGEST_LENGTH = 8;
6
+ const DIGEST_LENGTH_CHARS = 8;
7
7
  export async function readCacheEntry(entryPath) {
8
8
  try {
9
9
  return await readFile(entryPath, 'utf8');
@@ -12,19 +12,26 @@ export async function readCacheEntry(entryPath) {
12
12
  return undefined;
13
13
  }
14
14
  }
15
+ export async function readGuardedCacheEntry(entryPath, token, isValidValue) {
16
+ const entry = await readJsonCacheEntry(entryPath, isGuardedEntry);
17
+ if (entry?.token !== token) {
18
+ return undefined;
19
+ }
20
+ return isValidValue(entry.value) ? entry.value : undefined;
21
+ }
15
22
  export async function readJsonCacheEntry(entryPath, isValidEntry) {
16
- const raw = await readCacheEntry(entryPath);
17
- if (raw === undefined) {
23
+ const rawContent = await readCacheEntry(entryPath);
24
+ if (rawContent === undefined) {
18
25
  return undefined;
19
26
  }
20
- let parsed;
27
+ let parsedValue;
21
28
  try {
22
- parsed = JSON.parse(raw);
29
+ parsedValue = JSON.parse(rawContent);
23
30
  }
24
31
  catch {
25
32
  return undefined;
26
33
  }
27
- return isValidEntry(parsed) ? parsed : undefined;
34
+ return isValidEntry(parsedValue) ? parsedValue : undefined;
28
35
  }
29
36
  export async function removeCacheDir(ref) {
30
37
  await rm(resolveCacheDir(ref), { force: true, recursive: true });
@@ -35,17 +42,28 @@ export async function removeCacheEntry(entryPath) {
35
42
  export function resolveCacheDir(ref) {
36
43
  const absoluteScopeDir = path.resolve(ref.scopeDir);
37
44
  const stopAtDir = ref.stopAtDir === undefined ? undefined : path.resolve(ref.stopAtDir);
38
- const home = findDirectoryChainMatch(absoluteScopeDir, ['node_modules'], { stopAtDir })?.dir ?? absoluteScopeDir;
39
- return path.join(home, 'node_modules', '.cache', ref.tool);
45
+ const homeDir = findDirectoryChainMatch(absoluteScopeDir, ['node_modules'], { stopAtDir })?.dir ?? absoluteScopeDir;
46
+ return path.join(homeDir, 'node_modules', '.cache', ref.tool);
40
47
  }
41
48
  export function resolveCacheEntryPath(ref) {
42
49
  const absoluteScopeDir = path.resolve(ref.scopeDir);
43
50
  const digest = createHash('sha256')
44
51
  .update([absoluteScopeDir, ...(ref.discriminators ?? [])].join('\0'))
45
52
  .digest('hex')
46
- .slice(0, DIGEST_LENGTH);
53
+ .slice(0, DIGEST_LENGTH_CHARS);
47
54
  return path.join(resolveCacheDir(ref), `${ref.slug}-${digest}${ref.extension}`);
48
55
  }
49
56
  export async function writeCacheEntry(entryPath, content) {
50
57
  await writeAtomic(entryPath, content);
51
58
  }
59
+ export async function writeGuardedCacheEntry(entryPath, token, value) {
60
+ const entry = { token, value };
61
+ await writeCacheEntry(entryPath, JSON.stringify(entry));
62
+ }
63
+ function isGuardedEntry(value) {
64
+ return (typeof value === 'object' &&
65
+ value !== null &&
66
+ 'token' in value &&
67
+ typeof value.token === 'string' &&
68
+ 'value' in value);
69
+ }
@@ -46,13 +46,13 @@ function extractField(record, fieldIndex) {
46
46
  }
47
47
  function extractPath(record, precedingFieldCount) {
48
48
  let index = 0;
49
- for (let field = 0; field < precedingFieldCount; field++) {
50
- const separator = record.indexOf(' ', index);
51
- if (separator === -1) {
49
+ for (let fieldIndex = 0; fieldIndex < precedingFieldCount; fieldIndex++) {
50
+ const separatorIndex = record.indexOf(' ', index);
51
+ if (separatorIndex === -1) {
52
52
  return undefined;
53
53
  }
54
- index = separator + 1;
54
+ index = separatorIndex + 1;
55
55
  }
56
- const extracted = record.slice(index);
57
- return extracted === '' ? undefined : extracted;
56
+ const extractedPath = record.slice(index);
57
+ return extractedPath === '' ? undefined : extractedPath;
58
58
  }
@@ -7,27 +7,27 @@ export function parseObjectFormat(value) {
7
7
  return value === 'sha1' || value === 'sha256' ? value : undefined;
8
8
  }
9
9
  export function parseTreeObject(format, content) {
10
- const idLength = format === 'sha1' ? 20 : 32;
10
+ const idLengthBytes = format === 'sha1' ? 20 : 32;
11
11
  const entries = [];
12
12
  let offset = 0;
13
13
  while (offset < content.length) {
14
- const space = content.indexOf(0x20, offset);
15
- const nul = content.indexOf(0, space + 1);
16
- if (space === -1 || nul === -1 || nul + 1 + idLength > content.length) {
14
+ const spaceIndex = content.indexOf(0x20, offset);
15
+ const nulIndex = content.indexOf(0, spaceIndex + 1);
16
+ if (spaceIndex === -1 || nulIndex === -1 || nulIndex + 1 + idLengthBytes > content.length) {
17
17
  return undefined;
18
18
  }
19
19
  entries.push({
20
- id: content.subarray(nul + 1, nul + 1 + idLength),
21
- mode: content.toString('latin1', offset, space),
22
- name: content.toString('latin1', space + 1, nul),
20
+ id: content.subarray(nulIndex + 1, nulIndex + 1 + idLengthBytes),
21
+ mode: content.toString('latin1', offset, spaceIndex),
22
+ name: content.toString('latin1', spaceIndex + 1, nulIndex),
23
23
  });
24
- offset = nul + 1 + idLength;
24
+ offset = nulIndex + 1 + idLengthBytes;
25
25
  }
26
26
  return entries;
27
27
  }
28
28
  export function serializeTreeObject(entries) {
29
- const sorted = [...entries].toSorted((left, right) => compareStrings(sortKeyOf(left), sortKeyOf(right)));
30
- return Buffer.concat(sorted.flatMap((entry) => [Buffer.from(`${entry.mode} ${entry.name}\0`, 'latin1'), entry.id]));
29
+ const sortedEntries = [...entries].toSorted((left, right) => compareStrings(getSortKey(left), getSortKey(right)));
30
+ return Buffer.concat(sortedEntries.flatMap((entry) => [Buffer.from(`${entry.mode} ${entry.name}\0`, 'latin1'), entry.id]));
31
31
  }
32
32
  function compareStrings(left, right) {
33
33
  if (left === right) {
@@ -35,6 +35,6 @@ function compareStrings(left, right) {
35
35
  }
36
36
  return left < right ? -1 : 1;
37
37
  }
38
- function sortKeyOf(entry) {
38
+ function getSortKey(entry) {
39
39
  return entry.mode === TREE_MODE ? `${entry.name}/` : entry.name;
40
40
  }
@@ -5,4 +5,4 @@
5
5
  * Past the limit, Node kills the child and reports `ENOBUFS`, an error that names the spawned program rather than
6
6
  * the output that overflowed. A call site that omits the option fails this way only once its repo has grown enough.
7
7
  */
8
- export declare const GIT_OUTPUT_LIMIT: number;
8
+ export declare const GIT_OUTPUT_LIMIT_BYTES: number;
@@ -1 +1 @@
1
- export const GIT_OUTPUT_LIMIT = 64 * 1_024 * 1_024;
1
+ export const GIT_OUTPUT_LIMIT_BYTES = 64 * 1_024 * 1_024;
@@ -76,7 +76,7 @@ function buildTreeId(options) {
76
76
  const { trees } = treesResult;
77
77
  for (const [changedPath, entry] of changes) {
78
78
  const { name, parent } = splitPath(changedPath);
79
- const tree = entriesAt(trees, parent);
79
+ const tree = ensureEntries(trees, parent);
80
80
  if (entry === undefined) {
81
81
  tree.delete(name);
82
82
  }
@@ -84,14 +84,14 @@ function buildTreeId(options) {
84
84
  tree.set(name, { ...entry, name });
85
85
  }
86
86
  }
87
- const deepestFirst = [...directories].toSorted((left, right) => depthOf(right) - depthOf(left));
88
- for (const directory of deepestFirst) {
87
+ const deepestFirstDirectories = [...directories].toSorted((left, right) => measureDepth(right) - measureDepth(left));
88
+ for (const directory of deepestFirstDirectories) {
89
89
  if (directory === '') {
90
90
  continue;
91
91
  }
92
92
  const { name, parent } = splitPath(directory);
93
- const parentTree = entriesAt(trees, parent);
94
- const tree = entriesAt(trees, directory);
93
+ const parentTree = ensureEntries(trees, parent);
94
+ const tree = ensureEntries(trees, directory);
95
95
  if (tree.size === 0) {
96
96
  if (parentTree.get(name)?.mode === TREE_MODE) {
97
97
  parentTree.delete(name);
@@ -104,13 +104,13 @@ function buildTreeId(options) {
104
104
  name,
105
105
  });
106
106
  }
107
- const rootId = hashGitObject(format, 'tree', serializeTreeObject(entriesAt(trees, '').values()));
107
+ const rootId = hashGitObject(format, 'tree', serializeTreeObject(ensureEntries(trees, '').values()));
108
108
  return { ok: true, treeId: rootId.toString('hex') };
109
109
  }
110
- function depthOf(directory) {
110
+ function measureDepth(directory) {
111
111
  return directory === '' ? 0 : directory.split('/').length;
112
112
  }
113
- function entriesAt(trees, directory) {
113
+ function ensureEntries(trees, directory) {
114
114
  let entries = trees.get(directory);
115
115
  if (entries === undefined) {
116
116
  entries = new Map();
@@ -130,20 +130,20 @@ function hasSymlinkLeadingPath(toplevel, relativePath) {
130
130
  });
131
131
  }
132
132
  function quotePath(relativePath) {
133
- let quoted = '"';
133
+ let quotedPath = '"';
134
134
  for (const character of relativePath) {
135
135
  const codePoint = character.codePointAt(0) ?? 0;
136
136
  if (character === '"' || character === '\\') {
137
- quoted += `\\${character}`;
137
+ quotedPath += `\\${character}`;
138
138
  }
139
139
  else if (codePoint < 0x20 || codePoint === 0x7f) {
140
- quoted += `\\${codePoint.toString(8).padStart(3, '0')}`;
140
+ quotedPath += `\\${codePoint.toString(8).padStart(3, '0')}`;
141
141
  }
142
142
  else {
143
- quoted += character;
143
+ quotedPath += character;
144
144
  }
145
145
  }
146
- return `${quoted}"`;
146
+ return `${quotedPath}"`;
147
147
  }
148
148
  function readChangedEntries(toplevel, paths, format) {
149
149
  const changes = new Map();
@@ -191,8 +191,8 @@ function readChangedEntries(toplevel, paths, format) {
191
191
  }
192
192
  function readHeadTrees(options) {
193
193
  const { directories, format, headSha, headTreeId, toplevel } = options;
194
- const ordered = [...directories];
195
- const input = ordered
194
+ const orderedDirectories = [...directories];
195
+ const input = orderedDirectories
196
196
  .map((directory) => (directory === '' ? `${headTreeId}\0` : `${headSha}:${directory}\0`))
197
197
  .join('');
198
198
  const batchResult = runGitForBytes(['cat-file', '--batch', '-z'], toplevel, Buffer.from(input, 'latin1'));
@@ -200,33 +200,33 @@ function readHeadTrees(options) {
200
200
  return { ok: false, reason: `git cat-file failed: ${batchResult.error}` };
201
201
  }
202
202
  const output = batchResult.stdout;
203
- const malformed = { ok: false, reason: 'git cat-file reported a malformed object' };
203
+ const malformedResult = { ok: false, reason: 'git cat-file reported a malformed object' };
204
204
  const trees = new Map();
205
205
  let offset = 0;
206
- for (const directory of ordered) {
207
- const lineEnd = output.indexOf(0x0a, offset);
208
- if (lineEnd === -1) {
209
- return malformed;
206
+ for (const directory of orderedDirectories) {
207
+ const lineEndOffset = output.indexOf(0x0a, offset);
208
+ if (lineEndOffset === -1) {
209
+ return malformedResult;
210
210
  }
211
- const header = output.toString('latin1', offset, lineEnd);
212
- offset = lineEnd + 1;
211
+ const header = output.toString('latin1', offset, lineEndOffset);
212
+ offset = lineEndOffset + 1;
213
213
  if (header.endsWith(' missing')) {
214
214
  trees.set(directory, new Map());
215
215
  continue;
216
216
  }
217
217
  const [, type, sizeText] = header.split(' ', 3);
218
218
  if (sizeText === undefined) {
219
- return malformed;
219
+ return malformedResult;
220
220
  }
221
- const size = Number(sizeText);
222
- if (!Number.isSafeInteger(size) || offset + size > output.length) {
223
- return malformed;
221
+ const sizeBytes = Number(sizeText);
222
+ if (!Number.isSafeInteger(sizeBytes) || offset + sizeBytes > output.length) {
223
+ return malformedResult;
224
224
  }
225
- const content = output.subarray(offset, offset + size);
226
- offset += size + 1;
225
+ const content = output.subarray(offset, offset + sizeBytes);
226
+ offset += sizeBytes + 1;
227
227
  const entries = type === 'tree' ? parseTreeObject(format, content) : [];
228
228
  if (entries === undefined) {
229
- return malformed;
229
+ return malformedResult;
230
230
  }
231
231
  trees.set(directory, new Map(entries.map((entry) => [entry.name, entry])));
232
232
  }
@@ -252,8 +252,8 @@ function readPathState(toplevel, relativePath, format) {
252
252
  }
253
253
  if (stats.isSymbolicLink()) {
254
254
  try {
255
- const target = readlinkSync(absolutePath, { encoding: 'buffer' });
256
- return { ok: true, kind: 'link', id: hashGitObject(format, 'blob', target) };
255
+ const targetPath = readlinkSync(absolutePath, { encoding: 'buffer' });
256
+ return { ok: true, kind: 'link', id: hashGitObject(format, 'blob', targetPath) };
257
257
  }
258
258
  catch (error) {
259
259
  return { ok: false, reason: `could not read ${relativePath}: ${describeError(error)}` };
@@ -262,8 +262,8 @@ function readPathState(toplevel, relativePath, format) {
262
262
  return { ok: false, reason: `${relativePath} is neither a file nor a symlink, so its content is not hashable` };
263
263
  }
264
264
  function splitPath(fullPath) {
265
- const separator = fullPath.lastIndexOf('/');
266
- return separator === -1
265
+ const separatorIndex = fullPath.lastIndexOf('/');
266
+ return separatorIndex === -1
267
267
  ? { name: fullPath, parent: '' }
268
- : { name: fullPath.slice(separator + 1), parent: fullPath.slice(0, separator) };
268
+ : { name: fullPath.slice(separatorIndex + 1), parent: fullPath.slice(0, separatorIndex) };
269
269
  }
@@ -1,11 +1,11 @@
1
1
  import { globSync } from 'node:fs';
2
2
  import path from 'node:path';
3
- const MANIFEST = 'package.json';
4
- const ALWAYS_EXCLUDED = ['**/node_modules/**'];
3
+ const MANIFEST_FILENAME = 'package.json';
4
+ const ALWAYS_EXCLUDED_PATTERNS = ['**/node_modules/**'];
5
5
  export function matchPackageDirs(monorepoRoot, includedPatterns, excludedPatterns) {
6
6
  const options = {
7
7
  cwd: monorepoRoot,
8
- exclude: [...excludedPatterns, ...ALWAYS_EXCLUDED],
8
+ exclude: [...excludedPatterns, ...ALWAYS_EXCLUDED_PATTERNS],
9
9
  followSymlinks: true,
10
10
  };
11
11
  const matches = globSync([...includedPatterns], options);
@@ -26,11 +26,11 @@ export function splitWorkspacePatterns(patterns) {
26
26
  if (pattern.trim() === '')
27
27
  continue;
28
28
  const isNegated = pattern.startsWith('!');
29
- const target = isNegated ? excludedPatterns : includedPatterns;
30
- target.push(buildManifestPattern(isNegated ? pattern.slice(1) : pattern));
29
+ const targetPatterns = isNegated ? excludedPatterns : includedPatterns;
30
+ targetPatterns.push(buildManifestPattern(isNegated ? pattern.slice(1) : pattern));
31
31
  }
32
32
  return { excludedPatterns, includedPatterns };
33
33
  }
34
34
  function buildManifestPattern(pattern) {
35
- return `${pattern.replace(/\/?$/, '')}/${MANIFEST}`;
35
+ return `${pattern.replace(/\/?$/, '')}/${MANIFEST_FILENAME}`;
36
36
  }
@@ -1,7 +1,7 @@
1
1
  export declare const PACKAGE_NAME = "@williamthorsen/nmr-core";
2
2
  export type { CacheDirRef, CacheEntryRef } from './cache-store.js';
3
- export { readCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, } from './cache-store.js';
4
- export { GIT_OUTPUT_LIMIT } from './gitOutputLimit.js';
3
+ export { readCacheEntry, readGuardedCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, writeGuardedCacheEntry, } from './cache-store.js';
4
+ export { GIT_OUTPUT_LIMIT_BYTES } from './gitOutputLimit.js';
5
5
  export { hasErrnoCode } from './hasErrnoCode.js';
6
6
  export type { WorkingTreeHashResult } from './hashWorkingTree.js';
7
7
  export { hashWorkingTree, readHeadSha } from './hashWorkingTree.js';
@@ -9,6 +9,7 @@ export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFl
9
9
  export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
10
10
  export type { GlyphSet, InvalidOutputStyle, OutputStyle, ResolveStreamStylesOptions, StatusGlyphName, StreamStyleResolution, StreamStyles, TruncateToWidthOptions, } from './terminal.js';
11
11
  export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
12
+ export { startTimer } from './timer.js';
12
13
  export type { ManagedFileOutcome, ManagedFileResult } from './updateManagedFile.js';
13
14
  export { updateManagedFile } from './updateManagedFile.js';
14
15
  export type { WriteOutcome, WriteResult } from './writeFileWithCheck.js';
package/dist/esm/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  export const PACKAGE_NAME = '@williamthorsen/nmr-core';
2
- export { readCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, } from "./cache-store.js";
3
- export { GIT_OUTPUT_LIMIT } from "./gitOutputLimit.js";
2
+ export { readCacheEntry, readGuardedCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, writeGuardedCacheEntry, } from "./cache-store.js";
3
+ export { GIT_OUTPUT_LIMIT_BYTES } from "./gitOutputLimit.js";
4
4
  export { hasErrnoCode } from "./hasErrnoCode.js";
5
5
  export { hashWorkingTree, readHeadSha } from "./hashWorkingTree.js";
6
6
  export { parseArgs, parseArgsOrExit, ParseError } from "./parseArgs.js";
7
7
  export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
8
+ export { startTimer } from "./timer.js";
8
9
  export { updateManagedFile } from "./updateManagedFile.js";
9
10
  export { writeFileWithCheck } from "./writeFileWithCheck.js";
10
11
  export { findPackageRoot, resolveSelfVersion } from '@williamthorsen/toolbelt.packaging/candidate';
@@ -14,14 +14,16 @@ export class ParseError extends Error {
14
14
  }
15
15
  export function parseArgs(argv, schema, options = {}) {
16
16
  const nodeOptions = {};
17
- const byName = new Map();
17
+ const entriesByName = new Map();
18
18
  const flags = {};
19
- for (const [key, def] of Object.entries(schema)) {
20
- const name = def.long.replace(/^--/, '');
19
+ for (const [key, definition] of Object.entries(schema)) {
20
+ const name = definition.long.replace(/^--/, '');
21
21
  nodeOptions[name] =
22
- def.short === undefined ? { type: def.type } : { type: def.type, short: def.short.replace(/^-/, '') };
23
- byName.set(name, { key, def });
24
- flags[key] = initialFlagValues[def.type];
22
+ definition.short === undefined
23
+ ? { type: definition.type }
24
+ : { type: definition.type, short: definition.short.replace(/^-/, '') };
25
+ entriesByName.set(name, { key, definition });
26
+ flags[key] = initialFlagValues[definition.type];
25
27
  }
26
28
  const { tokens } = nodeParseArgs({
27
29
  args: argv,
@@ -42,11 +44,11 @@ export function parseArgs(argv, schema, options = {}) {
42
44
  if (token.kind !== 'option') {
43
45
  continue;
44
46
  }
45
- const entry = byName.get(token.name);
47
+ const entry = entriesByName.get(token.name);
46
48
  if (entry === undefined) {
47
49
  throw new ParseError('unknown-flag', token.rawName);
48
50
  }
49
- if (entry.def.type === 'boolean') {
51
+ if (entry.definition.type === 'boolean') {
50
52
  if (token.value !== undefined) {
51
53
  throw new ParseError('unexpected-value', token.rawName);
52
54
  }
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { GIT_OUTPUT_LIMIT } from "./gitOutputLimit.js";
2
+ import { GIT_OUTPUT_LIMIT_BYTES } from "./gitOutputLimit.js";
3
3
  export function runGit(args, cwd, input) {
4
4
  const result = runGitForBytes(args, cwd, input === undefined ? undefined : Buffer.from(input, 'utf8'));
5
5
  return result.ok ? { ok: true, stdout: result.stdout.toString('utf8') } : result;
@@ -9,7 +9,7 @@ export function runGitForBytes(args, cwd, input) {
9
9
  cwd,
10
10
  env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
11
11
  input,
12
- maxBuffer: GIT_OUTPUT_LIMIT,
12
+ maxBuffer: GIT_OUTPUT_LIMIT_BYTES,
13
13
  });
14
14
  if (result.error) {
15
15
  return { ok: false, error: result.error.message };
@@ -47,13 +47,13 @@ export declare function reportError(message: string, stream?: Writable): void;
47
47
  * Prints a status line for a managed-file result, followed by its diff indented beneath it: a failure to stderr,
48
48
  * every other outcome to stdout.
49
49
  */
50
- export declare function reportTemplateUpdate(result: ManagedFileResult, dryRun: boolean, styles?: StreamStyles): void;
50
+ export declare function reportTemplateUpdate(result: ManagedFileResult, isDryRun: boolean, styles?: StreamStyles): void;
51
51
  /**
52
52
  * Prints a terminal message for a write result based on its outcome: a failure to stderr, every
53
53
  * other outcome to stdout. Each message takes its own stream's style from `styles`; without
54
54
  * `styles`, it takes the style detected for that stream.
55
55
  */
56
- export declare function reportWriteResult(result: WriteResult, dryRun: boolean, styles?: StreamStyles): void;
56
+ export declare function reportWriteResult(result: WriteResult, isDryRun: boolean, styles?: StreamStyles): void;
57
57
  /**
58
58
  * Resolves the style of each output stream: the flag when one is named, else the named environment
59
59
  * variable, else detection from `CI`, the stream's terminal state, and `TERM`. Never throws; a value
@@ -29,14 +29,14 @@ export function printSuccess(message, style = detectStreamStyle(process.stdout))
29
29
  export function reportError(message, stream = process.stderr) {
30
30
  stream.write(`${formatErrorLine(message)}\n`);
31
31
  }
32
- export function reportTemplateUpdate(result, dryRun, styles) {
32
+ export function reportTemplateUpdate(result, isDryRun, styles) {
33
33
  const style = styles?.stdout;
34
34
  switch (result.outcome) {
35
35
  case 'created':
36
- printSuccess(dryRun ? `[dry-run] Would create ${result.filePath}` : `Created ${result.filePath}`, style);
36
+ printSuccess(isDryRun ? `[dry-run] Would create ${result.filePath}` : `Created ${result.filePath}`, style);
37
37
  break;
38
38
  case 'updated':
39
- printSuccess(dryRun ? `[dry-run] Would update ${result.filePath}` : `Updated ${result.filePath}`, style);
39
+ printSuccess(isDryRun ? `[dry-run] Would update ${result.filePath}` : `Updated ${result.filePath}`, style);
40
40
  if (result.diff !== undefined && result.diff !== '') {
41
41
  console.info(indentLines(result.diff, ' '.repeat(4)));
42
42
  }
@@ -51,11 +51,11 @@ export function reportTemplateUpdate(result, dryRun, styles) {
51
51
  }
52
52
  }
53
53
  }
54
- export function reportWriteResult(result, dryRun, styles) {
54
+ export function reportWriteResult(result, isDryRun, styles) {
55
55
  const style = styles?.stdout;
56
56
  switch (result.outcome) {
57
57
  case 'created':
58
- if (dryRun) {
58
+ if (isDryRun) {
59
59
  printSuccess(`[dry-run] Would create ${result.filePath}`, style);
60
60
  }
61
61
  else {
@@ -63,7 +63,7 @@ export function reportWriteResult(result, dryRun, styles) {
63
63
  }
64
64
  break;
65
65
  case 'overwritten':
66
- if (dryRun) {
66
+ if (isDryRun) {
67
67
  printSuccess(`[dry-run] Would overwrite ${result.filePath}`, style);
68
68
  }
69
69
  else {
@@ -93,10 +93,10 @@ export function reportWriteResult(result, dryRun, styles) {
93
93
  }
94
94
  export function resolveStreamStyles(options) {
95
95
  const { argv = [], env, envVar, flag, stderrIsTty, stdoutIsTty } = options;
96
- const stderr = resolveOutputStyle({ argv, env, envVar, flag, isTty: stderrIsTty });
97
- const stdout = resolveOutputStyle({ argv, env, envVar, flag, isTty: stdoutIsTty });
98
- const styles = { stderr: stderr.style, stdout: stdout.style };
99
- return stdout.invalid === undefined ? { styles } : { invalid: stdout.invalid, styles };
96
+ const stderrResolution = resolveOutputStyle({ argv, env, envVar, flag, isTty: stderrIsTty });
97
+ const stdoutResolution = resolveOutputStyle({ argv, env, envVar, flag, isTty: stdoutIsTty });
98
+ const styles = { stderr: stderrResolution.style, stdout: stdoutResolution.style };
99
+ return stdoutResolution.invalid === undefined ? { styles } : { invalid: stdoutResolution.invalid, styles };
100
100
  }
101
101
  function detectStreamStyle(stream) {
102
102
  return detectOutputStyle({ env: process.env, isTty: stream.isTTY === true });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Starts a timer on the monotonic clock and returns a function reporting the whole milliseconds elapsed since this
3
+ * call, which a wall-clock adjustment during the span cannot shorten or make negative.
4
+ */
5
+ export declare function startTimer(): () => number;
@@ -0,0 +1,4 @@
1
+ import { startTimer as startMonotonicTimer } from '@williamthorsen/toolbelt.datetime/proposed';
2
+ export function startTimer() {
3
+ return startMonotonicTimer();
4
+ }
@@ -11,9 +11,9 @@ export interface ManagedFileResult {
11
11
  /**
12
12
  * Writes `content` to a file that a package renders from a template, when the file is missing or its bytes differ.
13
13
  *
14
- * With `dryRun`, returns the outcome and diff without writing. Returns a filesystem error in the result rather than
14
+ * With `isDryRun`, returns the outcome and diff without writing. Returns a filesystem error in the result rather than
15
15
  * throwing it.
16
16
  */
17
17
  export declare function updateManagedFile(filePath: string, content: string, options: {
18
- dryRun: boolean;
18
+ isDryRun: boolean;
19
19
  }): ManagedFileResult;
@@ -3,22 +3,22 @@ import { dirname } from 'node:path';
3
3
  import { describeError } from '@williamthorsen/toolbelt.errors';
4
4
  import { structuredPatch } from 'diff';
5
5
  export function updateManagedFile(filePath, content, options) {
6
- let existing;
6
+ let existingContent;
7
7
  if (existsSync(filePath)) {
8
8
  try {
9
- existing = readFileSync(filePath, 'utf8');
9
+ existingContent = readFileSync(filePath, 'utf8');
10
10
  }
11
11
  catch (error) {
12
12
  return { filePath, outcome: 'failed', error: describeError(error) };
13
13
  }
14
- if (existing === content) {
14
+ if (existingContent === content) {
15
15
  return { filePath, outcome: 'up-to-date' };
16
16
  }
17
17
  }
18
- const result = existing === undefined
18
+ const result = existingContent === undefined
19
19
  ? { filePath, outcome: 'created' }
20
- : { filePath, outcome: 'updated', diff: formatHunks(existing, content) };
21
- if (options.dryRun) {
20
+ : { filePath, outcome: 'updated', diff: formatHunks(existingContent, content) };
21
+ if (options.isDryRun) {
22
22
  return result;
23
23
  }
24
24
  try {
@@ -30,8 +30,8 @@ export function updateManagedFile(filePath, content, options) {
30
30
  }
31
31
  return result;
32
32
  }
33
- function formatHunks(before, after) {
34
- const { hunks } = structuredPatch('', '', before, after, undefined, undefined, { context: 3 });
33
+ function formatHunks(oldContent, newContent) {
34
+ const { hunks } = structuredPatch('', '', oldContent, newContent, undefined, undefined, { context: 3 });
35
35
  return hunks
36
36
  .flatMap((hunk) => [
37
37
  `@@ -${String(hunk.oldStart)},${String(hunk.oldLines)} +${String(hunk.newStart)},${String(hunk.newLines)} @@`,
@@ -3,20 +3,20 @@ import path from 'node:path';
3
3
  import { findDirectoryChainMatch } from '@williamthorsen/toolbelt.filesystem';
4
4
  import { parse } from 'yaml';
5
5
  import { matchPackageDirs, resolvePackageDirs, splitWorkspacePatterns } from "./helpers/workspace-patterns.js";
6
- const PACKAGE_MANIFEST = 'package.json';
7
- const WORKSPACE_MANIFEST = 'pnpm-workspace.yaml';
6
+ const PACKAGE_MANIFEST_FILENAME = 'package.json';
7
+ const WORKSPACE_MANIFEST_FILENAME = 'pnpm-workspace.yaml';
8
8
  export function findMonorepoRoot(startDir) {
9
- return findDirectoryChainMatch(startDir ?? process.cwd(), [WORKSPACE_MANIFEST])?.dir;
9
+ return findDirectoryChainMatch(startDir ?? process.cwd(), [WORKSPACE_MANIFEST_FILENAME])?.dir;
10
10
  }
11
11
  export function isMonorepoRoot(dir) {
12
- return existsSync(path.join(dir, WORKSPACE_MANIFEST));
12
+ return existsSync(path.join(dir, WORKSPACE_MANIFEST_FILENAME));
13
13
  }
14
14
  export function readWorkspaceOverrides(monorepoRoot) {
15
- const manifestRead = readWorkspaceManifest(monorepoRoot);
16
- if (manifestRead.kind !== 'parsed' || !isObject(manifestRead.value)) {
15
+ const manifestReadResult = readWorkspaceManifest(monorepoRoot);
16
+ if (manifestReadResult.kind !== 'parsed' || !isObject(manifestReadResult.value)) {
17
17
  return undefined;
18
18
  }
19
- const overrides = manifestRead.value['overrides'];
19
+ const overrides = manifestReadResult.value['overrides'];
20
20
  return isObject(overrides) ? readStringValues(overrides) : undefined;
21
21
  }
22
22
  export function readWorkspacePackageNames(packageDirs) {
@@ -24,7 +24,7 @@ export function readWorkspacePackageNames(packageDirs) {
24
24
  for (const dir of packageDirs) {
25
25
  let parsedManifest;
26
26
  try {
27
- parsedManifest = JSON.parse(readFileSync(path.join(dir, PACKAGE_MANIFEST), 'utf8'));
27
+ parsedManifest = JSON.parse(readFileSync(path.join(dir, PACKAGE_MANIFEST_FILENAME), 'utf8'));
28
28
  }
29
29
  catch {
30
30
  continue;
@@ -36,19 +36,19 @@ export function readWorkspacePackageNames(packageDirs) {
36
36
  return names;
37
37
  }
38
38
  export function resolveWorkspace(monorepoRoot) {
39
- const manifestRead = readWorkspaceManifest(monorepoRoot);
40
- if (manifestRead.kind === 'absent') {
39
+ const manifestReadResult = readWorkspaceManifest(monorepoRoot);
40
+ if (manifestReadResult.kind === 'absent') {
41
41
  return { kind: 'not-a-workspace' };
42
42
  }
43
- if (manifestRead.kind === 'unreadable') {
43
+ if (manifestReadResult.kind === 'unreadable') {
44
44
  return { cause: 'unreadable-manifest', kind: 'empty', patterns: [] };
45
45
  }
46
- const packagesRead = readDeclaredPackages(manifestRead.value);
47
- if (packagesRead.kind !== 'patterns') {
48
- const cause = packagesRead.kind === 'absent' ? 'no-packages-list' : 'unreadable-packages';
46
+ const packagesReadResult = readDeclaredPackages(manifestReadResult.value);
47
+ if (packagesReadResult.kind !== 'patterns') {
48
+ const cause = packagesReadResult.kind === 'absent' ? 'no-packages-list' : 'unreadable-packages';
49
49
  return { cause, kind: 'empty', patterns: [] };
50
50
  }
51
- const { patterns } = packagesRead;
51
+ const { patterns } = packagesReadResult;
52
52
  const packageDirs = resolvePackageDirs(monorepoRoot, patterns);
53
53
  if (packageDirs.length > 0) {
54
54
  return { kind: 'packages', packageDirs, patterns };
@@ -89,12 +89,12 @@ function readStringValues(record) {
89
89
  return result;
90
90
  }
91
91
  function readWorkspaceManifest(monorepoRoot) {
92
- const workspaceFile = path.join(monorepoRoot, WORKSPACE_MANIFEST);
93
- if (!existsSync(workspaceFile)) {
92
+ const workspaceManifestPath = path.join(monorepoRoot, WORKSPACE_MANIFEST_FILENAME);
93
+ if (!existsSync(workspaceManifestPath)) {
94
94
  return { kind: 'absent' };
95
95
  }
96
96
  try {
97
- return { kind: 'parsed', value: parse(readFileSync(workspaceFile, 'utf8')) };
97
+ return { kind: 'parsed', value: parse(readFileSync(workspaceManifestPath, 'utf8')) };
98
98
  }
99
99
  catch {
100
100
  return { kind: 'unreadable' };
@@ -9,11 +9,11 @@ export interface WriteResult {
9
9
  /**
10
10
  * Writes a file with existence and content checks, creating parent directories as needed.
11
11
  *
12
- * Without `overwrite`, leaves an existing file alone and reports it `up-to-date` when its content matches up to
13
- * trailing whitespace. With `dryRun`, returns the outcome without writing. Returns a filesystem error in the
12
+ * Without `shouldOverwrite`, leaves an existing file alone and reports it `up-to-date` when its content matches up to
13
+ * trailing whitespace. With `isDryRun`, returns the outcome without writing. Returns a filesystem error in the
14
14
  * result rather than throwing it: `skipped` when the existing file cannot be read, `failed` when the write fails.
15
15
  */
16
16
  export declare function writeFileWithCheck(filePath: string, content: string, options: {
17
- dryRun: boolean;
18
- overwrite: boolean;
17
+ isDryRun: boolean;
18
+ shouldOverwrite: boolean;
19
19
  }): WriteResult;
@@ -9,12 +9,12 @@ function normalizeTrailingWhitespace(content) {
9
9
  .trimEnd();
10
10
  }
11
11
  export function writeFileWithCheck(filePath, content, options) {
12
- const { dryRun, overwrite } = options;
13
- const fileExists = existsSync(filePath);
14
- if (fileExists && !overwrite) {
12
+ const { isDryRun, shouldOverwrite } = options;
13
+ const doesFileExist = existsSync(filePath);
14
+ if (doesFileExist && !shouldOverwrite) {
15
15
  try {
16
- const existing = readFileSync(filePath, 'utf8');
17
- if (normalizeTrailingWhitespace(existing) === normalizeTrailingWhitespace(content)) {
16
+ const existingContent = readFileSync(filePath, 'utf8');
17
+ if (normalizeTrailingWhitespace(existingContent) === normalizeTrailingWhitespace(content)) {
18
18
  return { filePath, outcome: 'up-to-date' };
19
19
  }
20
20
  }
@@ -24,8 +24,8 @@ export function writeFileWithCheck(filePath, content, options) {
24
24
  }
25
25
  return { filePath, outcome: 'skipped' };
26
26
  }
27
- const outcome = fileExists ? 'overwritten' : 'created';
28
- if (dryRun) {
27
+ const outcome = doesFileExist ? 'overwritten' : 'created';
28
+ if (isDryRun) {
29
29
  return { filePath, outcome };
30
30
  }
31
31
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@williamthorsen/nmr-core",
3
- "version": "0.13.5",
3
+ "version": "0.14.0",
4
4
  "private": false,
5
5
  "description": "Shared utilities for node-monorepo-tools packages",
6
6
  "keywords": [
@@ -39,17 +39,18 @@
39
39
  "dist"
40
40
  ],
41
41
  "dependencies": {
42
- "@williamthorsen/toolbelt.errors": "0.8.3",
43
- "@williamthorsen/toolbelt.filesystem": "0.9.3",
44
- "@williamthorsen/toolbelt.packaging": "0.6.3",
45
- "@williamthorsen/toolbelt.terminal": "0.2.1",
42
+ "@williamthorsen/toolbelt.datetime": "4.1.0",
43
+ "@williamthorsen/toolbelt.errors": "0.9.0",
44
+ "@williamthorsen/toolbelt.filesystem": "0.10.0",
45
+ "@williamthorsen/toolbelt.packaging": "0.7.0",
46
+ "@williamthorsen/toolbelt.terminal": "0.3.0",
46
47
  "diff": "9.0.0",
47
48
  "yaml": "2.9.1"
48
49
  },
49
50
  "devDependencies": {
50
- "@williamthorsen/toolbelt.testing": "0.6.3",
51
- "@williamthorsen/toolbelt.vitest": "0.10.3",
52
- "vitest": "4.1.11"
51
+ "@williamthorsen/toolbelt.testing": "0.8.0",
52
+ "@williamthorsen/toolbelt.vitest": "0.13.0",
53
+ "vitest": "5.0.5"
53
54
  },
54
55
  "engines": {
55
56
  "node": ">=24.16.0"