@williamthorsen/nmr-core 0.13.0 → 0.13.1

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,48 @@
1
1
  [
2
+ {
3
+ "version": "0.13.1",
4
+ "date": "2026-10-01",
5
+ "sections": [
6
+ {
7
+ "title": "♻️ Refactoring",
8
+ "audience": "dev",
9
+ "items": [
10
+ {
11
+ "description": "Replaces every `.sort()` call that suppressed `unicorn/no-array-sort` with `toSorted()` and drops the spread copy wherever the source was already an array. (#925)",
12
+ "hash": "4680fb4e865ffce0bd135fac20d49b766b156992",
13
+ "entry": 1
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "title": "🧪 Tests",
19
+ "audience": "dev",
20
+ "items": [
21
+ {
22
+ "description": "Stubs `GIT_CEILING_DIRECTORIES` to the fixture's parent in every test that expects git to find no repository, so that a repository above the temp directory can no longer change the test's result. (#923)",
23
+ "hash": "71d8c3dfb45aca872ca897ee589aae6351a1f516",
24
+ "entry": 2
25
+ }
26
+ ]
27
+ },
28
+ {
29
+ "title": "📚 Documentation",
30
+ "audience": "dev",
31
+ "items": [
32
+ {
33
+ "description": "Revises the comments in `packages/nmr-core/src` against the comment-discipline rules, correcting the `writeFileWithCheck` description, which omitted the `skipped` outcome for an unreadable existing file, and the `WorkspaceResolution` description, which named `unreadable-manifest` as the only cause with no patterns. (#920)",
34
+ "hash": "72b361c63e67e58ee5ebfb4dae10d9b144517a85",
35
+ "entry": 1
36
+ },
37
+ {
38
+ "description": "Revises the README, doc comments, inline comments, and test titles in `packages/nmr-core` to align with the plain-speech doctrine and the writing conventions, including four failure `reason` strings returned by `hashWorkingTree`. (#934)",
39
+ "hash": "f084ddcecec9be602a97cdf3158eabd5aaebbe09",
40
+ "entry": 1
41
+ }
42
+ ]
43
+ }
44
+ ]
45
+ },
2
46
  {
3
47
  "version": "0.13.0",
4
48
  "date": "2026-09-22",
@@ -168,7 +212,7 @@
168
212
  },
169
213
  {
170
214
  "description": "Adopt `isError` and consolidate errno narrowing on a shared helper (#697)",
171
- "body": "Replaces every hand-rolled `instanceof Error` narrowing with `hasErrnoCode`, a new predicate exported from `@williamthorsen/nmr-core`, or with `isError` from `@williamthorsen/toolbelt.errors`. Previously the errno question was answered by inline copies alongside two private helpers of differing shape; both helpers are removed.\r\n\r\nSeparately, `eslint.config.ts` now bans `instanceof Error` in every position rather than in a ternary alone.",
215
+ "body": "Replaces every hand-rolled `instanceof Error` narrowing with `hasErrnoCode`, a new predicate exported from `@williamthorsen/nmr-core`, or with `isError` from `@williamthorsen/toolbelt.errors`. Previously the errno question was answered by inline copies alongside two private helpers of differing shape; both helpers are removed.\n\nSeparately, `eslint.config.ts` now bans `instanceof Error` in every position rather than in a ternary alone.",
172
216
  "hash": "c5e8e8a5e006b451e8c5aeea75d35772926d503c"
173
217
  }
174
218
  ]
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## 0.13.1 — 2026-10-01
6
+
7
+ ### ♻️ Refactoring
8
+
9
+ - Replaces every `.sort()` call that suppressed `unicorn/no-array-sort` with `toSorted()` and drops the spread copy wherever the source was already an array. (#925)
10
+
11
+ ### 🧪 Tests
12
+
13
+ - Stubs `GIT_CEILING_DIRECTORIES` to the fixture's parent in every test that expects git to find no repository, so that a repository above the temp directory can no longer change the test's result. (#923)
14
+
15
+ ### 📚 Documentation
16
+
17
+ - Revises the comments in `packages/nmr-core/src` against the comment-discipline rules, correcting the `writeFileWithCheck` description, which omitted the `skipped` outcome for an unreadable existing file, and the `WorkspaceResolution` description, which named `unreadable-manifest` as the only cause with no patterns. (#920)
18
+ - Revises the README, doc comments, inline comments, and test titles in `packages/nmr-core` to align with the plain-speech doctrine and the writing conventions, including four failure `reason` strings returned by `hashWorkingTree`. (#934)
19
+
5
20
  ## 0.13.0 — 2026-09-22
6
21
 
7
22
  ### 🎉 Features
package/README.md CHANGED
@@ -6,37 +6,7 @@ Shared utilities for node-monorepo-tools packages.
6
6
 
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
- <!-- section:release-notes -->
10
- ## Release notes — v0.13.0 (2026-09-22)
11
-
12
- ### 🎉 Features
13
-
14
- - 🚨 **Breaking:** Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)
15
-
16
- - Adds a `./workspace` subpath export to `@williamthorsen/nmr-core`, whose `resolveWorkspace` returns a pnpm workspace's package directories, or the cause of an empty result, as a value rather than as a thrown error.
17
- - Reports a `pnpm-workspace.yaml` that the YAML parser rejects under a cause of its own, `unreadable-manifest`, so `nmr -R build` names the syntax error and its remedy in place of failing with the parser's own error.
18
- - Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.
19
-
20
- Migration: Replace each `diagnoseEmptyWorkspace` call with `resolveWorkspace`, which reports the cause on the empty result it already returns, and rename the `no-manifest` cause to `no-package`. `EmptyWorkspaceCause` also gains `unreadable-manifest`, so an exhaustive switch over it stops compiling until it handles the new member; every other export of `@williamthorsen/nmr/workspace` keeps its signature and its `UserError` throws.
21
-
22
- - 🚨 **Breaking:** Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)
23
-
24
- - 🚨 **Breaking:** Narrows `no-pattern` in `@williamthorsen/nmr-core`'s `EmptyWorkspaceCause`, moving an absent or empty `packages` list onto `no-packages-list` and a value that is not a list of strings onto `unreadable-packages`.
25
- - Stops `release-kit` from tagging, publishing, and label-syncing a package that a `!` entry in `pnpm-workspace.yaml` excludes, which its previous `glob`-based resolution could not remove from the match.
26
- - Replaces the release of the root package alone with a failure naming the condition that emptied the workspace, when `pnpm-workspace.yaml` does not hold valid YAML or declares a workspace that does not resolve to a package.
27
- - Replaces the `no-pattern` remedy that `nmr` printed for a `pnpm-workspace.yaml` declaring no `packages` list, and for one declaring a `packages` value that is not a list of strings.
28
- - Raises `engines.node` to `>=24.16.0` in `@williamthorsen/nmr-core` and `@williamthorsen/release-kit`, because Node 24.0 through 24.15 ignores the `followSymlinks` option that the workspace matcher passes to `globSync` and drops a symlinked package directory from the resolution without reporting it.
29
-
30
- Migration: Add a `no-packages-list` arm and an `unreadable-packages` arm to any `switch` that covers `EmptyWorkspaceCause` exhaustively. `no-pattern` now names only a list that the resolver read in full and whose entries all failed to become a positive pattern, so move the handling of an absent `packages` key, an empty list, and a value that is not a list of strings out of the `no-pattern` arm into the two new ones. Route `no-packages-list` to single-package behavior rather than to a failure path: pnpm resolves such a manifest to the root package alone.
31
-
32
- ### 🐛 Bug fixes
33
-
34
- - Truncate release-kit commit subjects by display column (#840)
35
-
36
- - Fixes the issue that the `release-kit` prepare report cut a commit subject at 69 UTF-16 code units instead of at display columns, so a subject of CJK characters printed about twice the intended 72-column width and a cut inside an emoji left a broken character that a terminal drew as a replacement glyph.
37
- - Replaces the `...` marker on a truncated subject with `…`, the default of the width-aware truncation that now does the cutting.
38
- - Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.
39
- <!-- /section:release-notes -->
9
+ <!-- section:release-notes --><!-- /section:release-notes -->
40
10
 
41
11
  ## Installation
42
12
 
@@ -49,8 +19,8 @@ pnpm add -D @williamthorsen/nmr-core
49
19
  ## Workspace introspection
50
20
 
51
21
  The `./workspace` entry publishes the pnpm-workspace lookups that nmr and release-kit share. Every one of them
52
- is total: it returns a value rather than throwing, so each CLI keeps its own error boundary.
53
- [Workspace introspection](../nmr/docs/workspace.md) documents what each lookup returns and where it diverges
22
+ is total: It returns a value rather than throwing, so each CLI keeps its own error boundary.
23
+ [Workspace introspection](../nmr/docs/workspace.md) documents what each lookup returns and how it diverges
54
24
  from pnpm.
55
25
 
56
26
  The entry stays out of the root export, which keeps `yaml` out of the module closure of every other importer,
@@ -59,9 +29,10 @@ the build bootstrap's included.
59
29
  ## The `nmr-source` export condition
60
30
 
61
31
  Both entries declare an `nmr-source` export condition resolving to their TypeScript source. It exists for one
62
- caller: the compiler that builds this package. That compiler imports this package, so on a tree with no build
63
- output it has to reach the source, which is what the condition gives it.
32
+ caller: the compiler that builds this package. That compiler imports this package, so on a tree without build
33
+ output it has to import the source, and the condition resolves the import to that source.
64
34
 
65
- Nothing else should pass `--conditions nmr-source`. The published package ships `dist` alone, so the condition
66
- resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without the flag
67
- is unaffected: an unmatched condition is skipped, and each entry resolves to the build output as it always has.
35
+ Nothing else should pass `--conditions nmr-source`. Because the published package contains only `dist`, the
36
+ condition resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without
37
+ the flag is unaffected: An unmatched condition is skipped, and each entry resolves to the build output as it always
38
+ has.
@@ -1,8 +1,8 @@
1
- /** Names the cache directory a tool's entries live in: `{home}/node_modules/.cache/{tool}/`. */
1
+ /** Names the cache directory that contains a tool's entries: `{home}/node_modules/.cache/{tool}/`. */
2
2
  export interface CacheDirRef {
3
- /** The tool the cache belongs to, e.g. `nmr-compile`. Becomes the directory name. */
3
+ /** The tool to which the cache belongs, e.g. `nmr-compile`. Becomes the directory name. */
4
4
  tool: string;
5
- /** The directory the cache serves; its nearest `node_modules` ancestor hosts the cache. */
5
+ /** The directory that the cache serves; its nearest `node_modules` ancestor contains the cache. */
6
6
  scopeDir: string;
7
7
  }
8
8
  /** Locates a single entry within a tool's cache directory. */
@@ -12,44 +12,44 @@ export interface CacheEntryRef extends CacheDirRef {
12
12
  /** Filename extension, including the leading dot. */
13
13
  extension: string;
14
14
  /**
15
- * Strings folded into the filename digest alongside the absolute scope directory, so that one scope can hold
16
- * several entries. Two refs differing only in `slug` would collide were the slug all that separated them.
15
+ * Strings folded into the filename digest alongside the absolute scope directory, so that one scope can have
16
+ * several entries.
17
17
  */
18
18
  discriminators?: string[];
19
19
  }
20
20
  /**
21
21
  * Reads an entry's raw text, or `undefined` when it is absent or unreadable. A cache that cannot be read is a
22
- * miss, never an error: the caller's fallback is to do the work again, which is always correct.
22
+ * miss, never an error: The caller's fallback is to do the work again, which is always correct.
23
23
  */
24
24
  export declare function readCacheEntry(entryPath: string): Promise<string | undefined>;
25
25
  /**
26
26
  * Reads a JSON entry and narrows it with `isValidEntry`, returning `undefined` when the entry is missing,
27
- * unparseable, or of the wrong shape. Content written by an older format therefore reads as a miss rather than
28
- * reaching the caller as a value it cannot trust.
27
+ * unparseable, or of the wrong shape. Content written in an older format therefore reads as a miss rather than
28
+ * being returned to the caller as a value that it cannot trust.
29
29
  */
30
30
  export declare function readJsonCacheEntry<T>(entryPath: string, isValidEntry: (value: unknown) => value is T): Promise<T | undefined>;
31
- /** Removes a tool's entire cache directory. Idempotent: an absent directory is a silent no-op. */
31
+ /** Removes a tool's entire cache directory. Idempotent: An absent directory is a silent no-op. */
32
32
  export declare function removeCacheDir(ref: CacheDirRef): Promise<void>;
33
- /** Removes a single entry. Idempotent: an absent entry is a silent no-op, as is an absent cache directory. */
33
+ /** Removes a single entry. Idempotent: An absent entry is a silent no-op, as is an absent cache directory. */
34
34
  export declare function removeCacheEntry(entryPath: string): Promise<void>;
35
35
  /**
36
36
  * Resolves the absolute path of a tool's cache directory. The conventional `node_modules/.cache/{tool}/` home is
37
- * git-ignored and outside any `files` convention, so an entry never reaches a published tarball. The home is the
38
- * nearest enclosing directory that already has a `node_modules`: the scope's own when it has one, otherwise a
39
- * hoisted ancestor, such as the workspace root for a zero-dependency package. No `node_modules` is ever
40
- * materialized solely to hold the cache.
37
+ * git-ignored and outside any `files` convention, so an entry is never included in a published tarball. The home
38
+ * is the nearest enclosing directory that already has a `node_modules`: the scope's own when it has one, otherwise
39
+ * a hoisted ancestor, such as the workspace root for a zero-dependency package. The function never materializes a
40
+ * `node_modules` solely to store the cache.
41
41
  */
42
42
  export declare function resolveCacheDir(ref: CacheDirRef): string;
43
43
  /**
44
- * Resolves the absolute path of a single cache entry. The file name folds a digest of the absolute scope
45
- * directory (and any discriminators) into a readable base name, so scopes sharing a hoisted `node_modules`
46
- * never collide while the path stays stable across runs for the same scope.
44
+ * Resolves the absolute path of a single cache entry. The function folds a digest of the absolute scope directory
45
+ * (and any discriminators) into a readable base name, so scopes sharing a hoisted `node_modules` never collide
46
+ * while the path stays stable across runs for the same scope.
47
47
  */
48
48
  export declare function resolveCacheEntryPath(ref: CacheEntryRef): string;
49
49
  /**
50
- * Writes an entry, creating the cache directory as needed. The write lands in a uniquely named temporary file
51
- * and is renamed into place, so a concurrent reader sees either the previous entry or the new one and never a
52
- * half-written file. Throws when the write cannot be completed; a caller for whom a failed cache write is not
53
- * worth failing over catches it.
50
+ * Writes an entry, creating the cache directory as needed. Because the function writes to a uniquely named
51
+ * temporary file and renames it into place, a concurrent reader sees either the previous entry or the new one and
52
+ * never a half-written file. Throws when the write cannot be completed; a caller for whom a failed cache write is
53
+ * not worth failing over catches it.
54
54
  */
55
55
  export declare function writeCacheEntry(entryPath: string, content: string): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Find the nearest ancestor directory containing `package.json`, starting from
2
+ * Finds the nearest ancestor directory containing `package.json`, starting from
3
3
  * the directory of the given `import.meta.url`.
4
4
  *
5
5
  * Useful for resolving bundled assets (presets, templates) relative to the
@@ -1,10 +1,8 @@
1
1
  /**
2
- * The `maxBuffer` every git invocation that pipes stdout should declare, raised well above Node's 1 MiB default
3
- * so a tree with thousands of untracked files still reports a status and a long-lived repo still lists its tags.
2
+ * The `maxBuffer` for every git invocation that pipes stdout, raised well above Node's 1 MiB default so that a
3
+ * tree with thousands of untracked files still reports a status and a long-lived repo still lists its tags.
4
4
  *
5
- * Node enforces the cap on the parent side: it kills the child and reports `ENOBUFS` once the pipe accumulates
6
- * past the limit, so the child never learns why it died and the error names the spawned program rather than the
7
- * output that overflowed. A call site that omits the option inherits the default silently and fails only once
8
- * the repo it runs against has grown enough, which is why the value is shared rather than chosen per site.
5
+ * Past the limit, Node kills the child and reports `ENOBUFS`, an error that names the spawned program rather than
6
+ * the output that overflowed. A call site that omits the option fails this way only once its repo has grown enough.
9
7
  */
10
8
  export declare const GIT_OUTPUT_LIMIT: number;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Narrows a thrown value to an `Error` carrying the given Node errno code.
2
+ * Narrows a thrown value to an `Error` with the given Node errno code.
3
3
  *
4
4
  * `isError` recognizes an `Error` crossing a realm boundary, which a bare `instanceof` test reports as false.
5
5
  */
@@ -1,7 +1,7 @@
1
1
  /**
2
- * A whole-repo content hash, or the reason one could not be produced. Every degraded condition (no repository,
3
- * no commit, a git failure, a tree this hash cannot describe) reports `ok: false` rather than a hash a caller
4
- * might act on. A caller that gates work on the hash therefore does the work whenever the hash is unavailable.
2
+ * A whole-repo content hash, or the reason one could not be produced. For every degraded condition (no repository,
3
+ * no commit, a git failure, a tree that this hash cannot describe), the result is `ok: false` rather than a hash on
4
+ * which a caller might act.
5
5
  */
6
6
  export type WorkingTreeHashResult = {
7
7
  ok: true;
@@ -14,21 +14,21 @@ export type WorkingTreeHashResult = {
14
14
  };
15
15
  /**
16
16
  * Produces a content hash of the entire working tree at `cwd`: the commit's tree object folded with the current
17
- * content of every path git reports as changed or untracked. Two trees holding the same content hash alike, so
18
- * a `touch` that changes no bytes leaves the hash where it was, while any edit, addition, or deletion moves it.
17
+ * content of every path that git reports as changed or untracked. Two trees with the same content hash alike, so a
18
+ * `touch` that does not change any bytes leaves the hash unchanged, while any edit, addition, or deletion moves it.
19
19
  *
20
- * The hash is taken from git's own status rather than by walking the filesystem, which keeps it proportional to
21
- * what has changed rather than to the size of the repository, and inherits git's ignore rules for free. Nothing
22
- * here writes to the object database or the index: a hash is an observation, and a repository must look exactly
23
- * the same after taking one.
20
+ * Reading git's own status keeps the running time proportional to what has changed rather than to the size of the
21
+ * repository, and applies git's ignore rules. Nothing here writes to the object database or the index: A hash is
22
+ * an observation, and a repository must look exactly the same after taking one.
24
23
  *
25
24
  * Because the commit's tree object is the base of the fold, committing an already-hashed tree moves the hash
26
- * even though no content changed. The reverse holds too, and usefully: a rebase or an amended message that
27
- * preserves content leaves the hash alone, as does checking out a branch whose tree is identical.
25
+ * even though the content did not change. The reverse holds too, and usefully: A rebase or an amended message
26
+ * that preserves content leaves the hash alone, as does checking out a branch whose tree is identical.
28
27
  */
29
28
  export declare function hashWorkingTree(cwd: string): WorkingTreeHashResult;
30
29
  /**
31
- * Returns the commit `HEAD` names, or `undefined` when git cannot say. Cheap next to a full hash, so a caller
32
- * holding an observation of a tree can ask whether the commit still stands where it did without retaking it.
30
+ * Returns the commit that `HEAD` names, or `undefined` when git cannot say. Because it is cheap next to a full
31
+ * hash, a caller that has observed a tree can check whether `HEAD` still names the same commit without hashing the
32
+ * tree again.
33
33
  */
34
34
  export declare function readHeadSha(cwd: string): string | undefined;
@@ -20,7 +20,7 @@ export function hashWorkingTree(cwd) {
20
20
  }
21
21
  const toplevel = toplevelResult.stdout.trim();
22
22
  if (toplevel === '') {
23
- return { ok: false, reason: 'git reported no repository toplevel' };
23
+ return { ok: false, reason: 'git did not report a repository toplevel' };
24
24
  }
25
25
  if (existsSync(path.join(toplevel, '.gitmodules'))) {
26
26
  return { ok: false, reason: 'the repository declares submodules, whose content this hash does not cover' };
@@ -31,7 +31,7 @@ export function hashWorkingTree(cwd) {
31
31
  }
32
32
  const [headSha, headTreeSha] = revisionResult.stdout.trim().split('\n', 2);
33
33
  if (headSha === undefined || headTreeSha === undefined) {
34
- return { ok: false, reason: 'git reported no HEAD commit and tree' };
34
+ return { ok: false, reason: 'git did not report a HEAD commit and tree' };
35
35
  }
36
36
  const statusResult = runGit(['status', '--porcelain=v2', '-z', '--untracked-files=all'], cwd);
37
37
  if (!statusResult.ok) {
@@ -46,7 +46,7 @@ export function hashWorkingTree(cwd) {
46
46
  hash.update('\0');
47
47
  hash.update(headTreeSha);
48
48
  hash.update('\0');
49
- for (const relativePath of [...pathsResult.paths].sort()) {
49
+ for (const relativePath of [...pathsResult.paths].toSorted()) {
50
50
  const content = digestPathContent(toplevel, relativePath);
51
51
  if (!content.ok) {
52
52
  return content;
@@ -81,7 +81,7 @@ function collectChangedPaths(statusOutput) {
81
81
  continue;
82
82
  }
83
83
  if (SUBMODULE_BEARING_TYPES.has(type) && extractField(record, 2)?.startsWith('S') === true) {
84
- return { ok: false, reason: 'the working tree holds a submodule, whose content this hash does not cover' };
84
+ return { ok: false, reason: 'the working tree contains a submodule, whose content this hash does not cover' };
85
85
  }
86
86
  const precedingFieldCount = PRECEDING_FIELD_COUNTS[type];
87
87
  if (precedingFieldCount === undefined) {
@@ -96,7 +96,7 @@ function collectChangedPaths(statusOutput) {
96
96
  index++;
97
97
  const originalPath = records[index];
98
98
  if (originalPath === undefined || originalPath === '') {
99
- return { ok: false, reason: 'git status reported a rename with no original path' };
99
+ return { ok: false, reason: 'git status reported a rename without an original path' };
100
100
  }
101
101
  paths.add(originalPath);
102
102
  }
@@ -1,19 +1,16 @@
1
1
  /**
2
- * The manifest patterns a declared `packages` list resolves to, split by what each entry asks of the matcher.
2
+ * The manifest patterns that a declared `packages` list resolves to, split by what each entry asks of the matcher.
3
3
  *
4
- * Held as manifest patterns rather than as the entries themselves, so a caller re-matching a subset spends the
5
- * same rewriting a full resolution does.
4
+ * Each entry is already rewritten to match a manifest, so that a caller re-matching a subset applies the same
5
+ * rewriting as a full resolution.
6
6
  */
7
7
  export interface WorkspacePatternSplit {
8
8
  excludedPatterns: string[];
9
9
  includedPatterns: string[];
10
10
  }
11
11
  /**
12
- * Matches manifest patterns against a monorepo root, returning the absolute directories that hold a matched
12
+ * Matches manifest patterns against a monorepo root, returning the absolute directories that contain a matched
13
13
  * manifest, sorted and free of duplicates.
14
- *
15
- * Takes the exclusion set as an argument of its own, so a caller diagnosing an empty resolution can re-match
16
- * the positive patterns alone and learn whether the exclusions are what emptied it.
17
14
  */
18
15
  export declare function matchPackageDirs(monorepoRoot: string, includedPatterns: readonly string[], excludedPatterns: readonly string[]): string[];
19
16
  /**
@@ -25,9 +22,7 @@ export declare function matchPackageDirs(monorepoRoot: string, includedPatterns:
25
22
  */
26
23
  export declare function resolvePackageDirs(monorepoRoot: string, patterns: readonly string[]): string[];
27
24
  /**
28
- * Splits a declared `packages` list into the manifest patterns the matcher includes and the ones it excludes.
29
- *
30
- * The sole reader of what counts as a positive pattern, shared by a resolution and by a diagnosis of its empty
31
- * result: two readers classifying entries separately could disagree about which condition a manifest is in.
25
+ * Splits a declared `packages` list into the manifest patterns that the matcher includes and the ones that it
26
+ * excludes. A resolution and the diagnosis of its empty result both classify entries here, so that they agree.
32
27
  */
33
28
  export declare function splitWorkspacePatterns(patterns: readonly string[]): WorkspacePatternSplit;
@@ -10,6 +10,8 @@ export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFl
10
10
  export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
11
11
  export { readPackageVersion } from './readPackageVersion.js';
12
12
  export type { GlyphSet, InvalidOutputStyle, OutputStyle, ResolveStreamStylesOptions, StatusGlyphName, StreamStyleResolution, StreamStyles, TruncateToWidthOptions, } from './terminal.js';
13
- export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
13
+ export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
14
+ export type { ManagedFileOutcome, ManagedFileResult } from './updateManagedFile.js';
15
+ export { updateManagedFile } from './updateManagedFile.js';
14
16
  export type { WriteOutcome, WriteResult } from './writeFileWithCheck.js';
15
17
  export { writeFileWithCheck } from './writeFileWithCheck.js';
package/dist/esm/index.js CHANGED
@@ -6,5 +6,6 @@ export { hasErrnoCode } from "./hasErrnoCode.js";
6
6
  export { hashWorkingTree, readHeadSha } from "./hashWorkingTree.js";
7
7
  export { parseArgs, parseArgsOrExit, ParseError } from "./parseArgs.js";
8
8
  export { readPackageVersion } from "./readPackageVersion.js";
9
- export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
9
+ export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
10
+ export { updateManagedFile } from "./updateManagedFile.js";
10
11
  export { writeFileWithCheck } from "./writeFileWithCheck.js";
@@ -6,7 +6,7 @@ export interface FlagDefinition {
6
6
  }
7
7
  /** Map of camelCase property names to their flag definitions. */
8
8
  export type FlagSchema = Record<string, FlagDefinition>;
9
- /** Infer the result type from a flag schema: booleans become `boolean`, strings become `string | undefined`. */
9
+ /** Infers the result type from a flag schema: booleans become `boolean`, strings become `string | undefined`. */
10
10
  export type ParsedFlags<S extends FlagSchema> = {
11
11
  [K in keyof S]: S[K]['type'] extends 'boolean' ? boolean : string | undefined;
12
12
  };
@@ -20,12 +20,12 @@ export interface ParseArgsOptions {
20
20
  /** When true, positionals are collected; otherwise an unexpected positional throws. Defaults to false. */
21
21
  allowPositionals?: boolean;
22
22
  }
23
- /** Discriminates the failure modes `parseArgs` reports. */
23
+ /** Discriminates the failure modes that `parseArgs` reports. */
24
24
  export type ParseErrorKind = 'unknown-flag' | 'missing-value' | 'unexpected-value' | 'unexpected-positional';
25
25
  /**
26
26
  * Error thrown by `parseArgs` on invalid input.
27
27
  *
28
- * Carries the failure `kind` and the offending token in `flag` — a flag as the user typed it, or the
28
+ * Carries the failure `kind` and the offending token in `flag`: a flag as the user typed it, or the
29
29
  * positional value for `'unexpected-positional'`. Its `message` is composed from those fields, so error
30
30
  * wording is uniform across every kind.
31
31
  */
@@ -35,17 +35,13 @@ export declare class ParseError extends Error {
35
35
  constructor(kind: ParseErrorKind, flag: string);
36
36
  }
37
37
  /**
38
- * Parse a pre-sliced argv array against a flag schema.
38
+ * Parses a pre-sliced argv array against a flag schema.
39
39
  *
40
40
  * Delegates tokenizing to `node:util.parseArgs` (non-strict, with tokens) and validates the token
41
41
  * stream against the schema. Throws `ParseError` on an unknown flag, a missing string-flag value, a
42
- * value supplied to a boolean flag, or — unless `options.allowPositionals` is set — an unexpected
42
+ * value supplied to a boolean flag, or (unless `options.allowPositionals` is set) an unexpected
43
43
  * positional argument. Does not write output or exit.
44
44
  */
45
45
  export declare function parseArgs<S extends FlagSchema>(argv: string[], schema: S, options?: ParseArgsOptions): ParsedArgs<S>;
46
- /**
47
- * Parse argv, or print a usage error to stderr and exit non-zero.
48
- *
49
- * The canonical "parse or die" entry point for CLI commands that terminate on invalid input.
50
- */
46
+ /** Parses argv, or prints a usage error to stderr and exits non-zero. */
51
47
  export declare function parseArgsOrExit<S extends FlagSchema>(argv: string[], schema: S, options?: ParseArgsOptions): ParsedArgs<S>;
@@ -1,14 +1,9 @@
1
1
  /**
2
- * Read the `version` field from the nearest ancestor `package.json`, starting
2
+ * Reads the `version` field from the nearest ancestor `package.json`, starting
3
3
  * from the directory of the given `import.meta.url`.
4
4
  *
5
- * Composes `findPackageRoot` with a `package.json` read so callers get a
6
- * depth-agnostic version lookup that works in source layouts (`src/...`),
7
- * compiled layouts (`dist/esm/...`), and consumer layouts (npm-installed,
8
- * `npx`).
9
- *
10
5
  * Throws if the located `package.json` lacks a string `version` field.
11
- * Propagates `findPackageRoot`'s own error when no ancestor `package.json`
12
- * exists.
6
+ * Propagates `findPackageRoot`'s own error when it does not find an ancestor
7
+ * `package.json`.
13
8
  */
14
9
  export declare function readPackageVersion(fromUrl: string): string;
@@ -1,5 +1,6 @@
1
1
  import type { Writable } from 'node:stream';
2
2
  import { type GlyphSet, type InvalidOutputStyle, type OutputStyle, type StatusGlyphName } from '@williamthorsen/toolbelt.terminal/candidate';
3
+ import type { ManagedFileResult } from './updateManagedFile.js';
3
4
  import type { WriteResult } from './writeFileWithCheck.js';
4
5
  export type { GlyphSet, InvalidOutputStyle, OutputStyle, StatusGlyphName, TruncateToWidthOptions, } from '@williamthorsen/toolbelt.terminal/candidate';
5
6
  export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
@@ -7,7 +8,7 @@ export interface ResolveStreamStylesOptions {
7
8
  /** Raw arguments in which to find `flag`; read only when `flag` is given. */
8
9
  readonly argv?: readonly string[] | undefined;
9
10
  readonly env: Readonly<Record<string, string | undefined>>;
10
- /** The environment variable holding the caller's standing preference: `auto`, `plain`, or `rich`. */
11
+ /** The environment variable containing the caller's standing preference: `auto`, `plain`, or `rich`. */
11
12
  readonly envVar: string;
12
13
  /** The flag naming a style for one invocation, leading dashes included; it outranks `envVar`. */
13
14
  readonly flag?: string | undefined;
@@ -15,7 +16,7 @@ export interface ResolveStreamStylesOptions {
15
16
  readonly stdoutIsTty: boolean;
16
17
  }
17
18
  export interface StreamStyleResolution {
18
- /** The first value of `flag` or `envVar` that names no setting; resolution continues with the next source. */
19
+ /** The first value of `flag` or `envVar` that does not name a setting; resolution continues with the next source. */
19
20
  readonly invalid?: InvalidOutputStyle | undefined;
20
21
  readonly styles: StreamStyles;
21
22
  }
@@ -23,11 +24,7 @@ export interface StreamStyles {
23
24
  readonly stderr: OutputStyle;
24
25
  readonly stdout: OutputStyle;
25
26
  }
26
- /**
27
- * Renders the canonical `Error: <message>` line (without a trailing newline) — the single
28
- * definition of this shape. Use it where the line is a value rather than a write target,
29
- * e.g. a command that returns its message for the caller to print.
30
- */
27
+ /** Renders the canonical `Error: <message>` line, without a trailing newline, for a caller that needs it as a value. */
31
28
  export declare function formatErrorLine(message: string): string;
32
29
  /**
33
30
  * Renders a glyph from `glyphs` and a message, omitting the separating space when the glyph's variant is
@@ -44,12 +41,13 @@ export declare function printSkip(message: string, style?: OutputStyle): void;
44
41
  export declare function printStep(message: string): void;
45
42
  /** Prints a success message to stdout, in the style detected for stdout unless one is given. */
46
43
  export declare function printSuccess(message: string, style?: OutputStyle): void;
44
+ /** Writes the canonical `Error: <message>` line to `stream`, which an in-process CLI sets to its own `Writable`. */
45
+ export declare function reportError(message: string, stream?: Writable): void;
47
46
  /**
48
- * Writes the canonical `Error: <message>` line to a stream (stderr by default) — the single
49
- * sanctioned door for this output shape. Pass an injected stream for in-process CLIs that
50
- * route output through a `Writable` rather than touching `process.stderr` directly.
47
+ * Prints a status line for a managed-file result, followed by its diff indented beneath it: a failure to stderr,
48
+ * every other outcome to stdout.
51
49
  */
52
- export declare function reportError(message: string, stream?: Writable): void;
50
+ export declare function reportTemplateUpdate(result: ManagedFileResult, dryRun: boolean, styles?: StreamStyles): void;
53
51
  /**
54
52
  * Prints a terminal message for a write result based on its outcome: a failure to stderr, every
55
53
  * other outcome to stdout. Each message takes its own stream's style from `styles`; without
@@ -59,7 +57,7 @@ export declare function reportWriteResult(result: WriteResult, dryRun: boolean,
59
57
  /**
60
58
  * Resolves the style of each output stream: the flag when one is named, else the named environment
61
59
  * variable, else detection from `CI`, the stream's terminal state, and `TERM`. Never throws; a value
62
- * that names no setting is returned in `invalid`, for the caller to report with
60
+ * that does not name a setting is returned in `invalid`, for the caller to report with
63
61
  * `describeInvalidOutputStyle`.
64
62
  */
65
63
  export declare function resolveStreamStyles(options: ResolveStreamStylesOptions): StreamStyleResolution;
@@ -29,6 +29,28 @@ 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) {
33
+ const style = styles?.stdout;
34
+ switch (result.outcome) {
35
+ case 'created':
36
+ printSuccess(dryRun ? `[dry-run] Would create ${result.filePath}` : `Created ${result.filePath}`, style);
37
+ break;
38
+ case 'updated':
39
+ printSuccess(dryRun ? `[dry-run] Would update ${result.filePath}` : `Updated ${result.filePath}`, style);
40
+ if (result.diff !== undefined && result.diff !== '') {
41
+ console.info(indentLines(result.diff, ' '.repeat(4)));
42
+ }
43
+ break;
44
+ case 'up-to-date':
45
+ printSuccess(`${result.filePath} (up to date)`, style);
46
+ break;
47
+ case 'failed': {
48
+ const detail = result.error === undefined ? '' : `: ${result.error}`;
49
+ printError(`Failed to update ${result.filePath}${detail}`, styles?.stderr);
50
+ break;
51
+ }
52
+ }
53
+ }
32
54
  export function reportWriteResult(result, dryRun, styles) {
33
55
  const style = styles?.stdout;
34
56
  switch (result.outcome) {
@@ -79,3 +101,9 @@ export function resolveStreamStyles(options) {
79
101
  function detectStreamStyle(stream) {
80
102
  return detectOutputStyle({ env: process.env, isTty: stream.isTTY === true });
81
103
  }
104
+ function indentLines(text, indent) {
105
+ return text
106
+ .split('\n')
107
+ .map((line) => `${indent}${line}`)
108
+ .join('\n');
109
+ }
@@ -0,0 +1,19 @@
1
+ /** Outcome of an `updateManagedFile` call. */
2
+ export type ManagedFileOutcome = 'created' | 'updated' | 'up-to-date' | 'failed';
3
+ /** Result returned by `updateManagedFile`. */
4
+ export interface ManagedFileResult {
5
+ filePath: string;
6
+ outcome: ManagedFileOutcome;
7
+ /** Hunks of a unified diff from the existing file to the rendered content; present only for `updated`. */
8
+ diff?: string;
9
+ error?: string;
10
+ }
11
+ /**
12
+ * Writes `content` to a file that a package renders from a template, when the file is missing or its bytes differ.
13
+ *
14
+ * With `dryRun`, returns the outcome and diff without writing. Returns a filesystem error in the result rather than
15
+ * throwing it.
16
+ */
17
+ export declare function updateManagedFile(filePath: string, content: string, options: {
18
+ dryRun: boolean;
19
+ }): ManagedFileResult;
@@ -0,0 +1,41 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { describeError } from '@williamthorsen/toolbelt.errors';
4
+ import { structuredPatch } from 'diff';
5
+ export function updateManagedFile(filePath, content, options) {
6
+ let existing;
7
+ if (existsSync(filePath)) {
8
+ try {
9
+ existing = readFileSync(filePath, 'utf8');
10
+ }
11
+ catch (error) {
12
+ return { filePath, outcome: 'failed', error: describeError(error) };
13
+ }
14
+ if (existing === content) {
15
+ return { filePath, outcome: 'up-to-date' };
16
+ }
17
+ }
18
+ const result = existing === undefined
19
+ ? { filePath, outcome: 'created' }
20
+ : { filePath, outcome: 'updated', diff: formatHunks(existing, content) };
21
+ if (options.dryRun) {
22
+ return result;
23
+ }
24
+ try {
25
+ mkdirSync(dirname(filePath), { recursive: true });
26
+ writeFileSync(filePath, content, 'utf8');
27
+ }
28
+ catch (error) {
29
+ return { filePath, outcome: 'failed', error: describeError(error) };
30
+ }
31
+ return result;
32
+ }
33
+ function formatHunks(before, after) {
34
+ const { hunks } = structuredPatch('', '', before, after, undefined, undefined, { context: 3 });
35
+ return hunks
36
+ .flatMap((hunk) => [
37
+ `@@ -${String(hunk.oldStart)},${String(hunk.oldLines)} +${String(hunk.newStart)},${String(hunk.newLines)} @@`,
38
+ ...hunk.lines.filter((line) => !line.startsWith('\\')),
39
+ ])
40
+ .join('\n');
41
+ }
@@ -1,12 +1,21 @@
1
- /** Which of six conditions left a workspace resolving to no package directory. */
1
+ /**
2
+ * The condition under which a workspace resolves to an empty set of package directories. Each calls for a
3
+ * different remedy:
4
+ *
5
+ * - `all-excluded`: The positive patterns match packages, and the exclusions remove every one.
6
+ * - `no-package`: The positive patterns do not match any package.
7
+ * - `no-packages-list`: The manifest does not declare a pattern list, which pnpm resolves to the root package alone.
8
+ * - `no-pattern`: The list does not contain a positive pattern, as with `!` entries and entries that YAML emptied.
9
+ * - `unreadable-manifest`: The manifest cannot be read or parsed, whatever patterns it may declare.
10
+ * - `unreadable-packages`: The `packages` value is not a list of strings.
11
+ */
2
12
  export type EmptyWorkspaceCause = 'all-excluded' | 'no-package' | 'no-packages-list' | 'no-pattern' | 'unreadable-manifest' | 'unreadable-packages';
3
13
  /**
4
- * What resolving a directory's workspace patterns produced: the directory declares no workspace, it resolves
5
- * to a set of package directories, or it resolves to none and the cause says which condition emptied it.
14
+ * What resolving a directory's workspace patterns produced: The directory does not declare a workspace, it
15
+ * resolves to a set of package directories, or it resolves to none and the cause says which condition emptied it.
6
16
  *
7
- * The declared patterns travel with the last two because a message composed from one quotes them back to the
8
- * reader. They are empty under `unreadable-manifest`, the one cause whose manifest declares nothing the reader
9
- * can see.
17
+ * The last two include the declared patterns because a message composed from one quotes them back to the reader.
18
+ * The patterns are empty when the manifest does not yield a pattern list.
10
19
  */
11
20
  export type WorkspaceResolution = {
12
21
  kind: 'empty';
@@ -20,49 +29,30 @@ export type WorkspaceResolution = {
20
29
  patterns: string[];
21
30
  };
22
31
  /**
23
- * Finds the monorepo root by walking up from `startDir`, defaulting to `process.cwd()`, until it reaches a
24
- * directory holding `pnpm-workspace.yaml`.
25
- *
26
- * Returns nothing where the walk runs out of parent directories, which a CLI turns into whichever failure its
27
- * own error boundary calls for.
32
+ * Finds the monorepo root by walking up from `startDir`, defaulting to `process.cwd()`, to the first directory
33
+ * containing `pnpm-workspace.yaml`, or returns `undefined` when the walk does not find one.
28
34
  */
29
35
  export declare function findMonorepoRoot(startDir?: string): string | undefined;
30
36
  /** Reports whether a directory is the monorepo root, which the workspace manifest's presence marks. */
31
37
  export declare function isMonorepoRoot(dir: string): boolean;
32
38
  /**
33
- * Reads the `overrides` block from the monorepo root's `pnpm-workspace.yaml`, the site pnpm reads an override
34
- * from.
39
+ * Reads the `overrides` block from the monorepo root's `pnpm-workspace.yaml`, the site from which pnpm reads an
40
+ * override.
35
41
  *
36
- * Returns nothing when the manifest is missing, unreadable, unparseable, or declares no block, and drops an
37
- * entry whose value is not a string.
42
+ * Returns nothing when the manifest is missing, unreadable, unparseable, or does not declare the block, and drops
43
+ * an entry whose value is not a string.
38
44
  */
39
45
  export declare function readWorkspaceOverrides(monorepoRoot: string): Record<string, string> | undefined;
40
46
  /**
41
- * Reads the manifest `name` each of the given package directories declares, which is what a `-F` pattern
42
- * matches.
43
- *
44
- * A directory whose manifest is missing, unparseable, or nameless contributes nothing. The sweep runs for a
45
- * diagnostic's sake, so one malformed manifest elsewhere in the workspace must not replace the diagnostic the
46
- * reader asked for with a failure of its own.
47
+ * Reads the manifest `name` that each of the given package directories declares, skipping a directory whose
48
+ * manifest is missing, unparseable, or nameless.
47
49
  */
48
50
  export declare function readWorkspacePackageNames(packageDirs: readonly string[]): string[];
49
51
  /**
50
- * Resolves the workspace a directory declares, applying pnpm's pattern semantics — including `!`-prefixed
51
- * exclusions — and reporting which condition left the result empty.
52
- *
53
- * Reaches the filesystem a second time for `all-excluded` alone, re-matching the positive patterns without the
54
- * exclusion set. That runs only where a resolution has already come back empty.
55
- *
56
- * Three causes separate what a manifest declares from what the reader could make of it, because one remedy
57
- * does not answer them all. `no-packages-list` is a manifest declaring nothing, an absent `packages` key or an
58
- * empty list, which pnpm resolves to the root package alone; `unreadable-packages` is a `packages` value that
59
- * is not a list of strings, which declares something the reader refused; and `no-pattern` is a list whose
60
- * entries all fail to become a positive pattern, `!` entries and entries YAML emptied. A caller treating an
61
- * empty resolution as a failure needs the first held apart from the other two, and a caller composing a
62
- * message needs all three.
52
+ * Resolves the workspace declared by a directory, applying pnpm's pattern semantics (including `!`-prefixed
53
+ * exclusions) and reporting which condition left the result empty.
63
54
  *
64
- * A manifest that the reader cannot parse at all is `unreadable-manifest`. It declares whatever it declares,
65
- * and the remedy the pattern causes share — declare a positive pattern — repairs nothing for a reader who has
66
- * one and a syntax error above it.
55
+ * Reaches the filesystem a second time only when the resolution is empty, re-matching the positive patterns
56
+ * without the exclusions to tell `all-excluded` from `no-package`.
67
57
  */
68
58
  export declare function resolveWorkspace(monorepoRoot: string): WorkspaceResolution;
@@ -7,12 +7,11 @@ export interface WriteResult {
7
7
  error?: string;
8
8
  }
9
9
  /**
10
- * Write a file with existence and content checks.
10
+ * Writes a file with existence and content checks, creating parent directories as needed.
11
11
  *
12
- * Creates parent directories as needed. Compares content using whitespace-normalized comparison
13
- * to determine whether an existing file is up to date. In dry-run mode, returns the outcome
14
- * that would happen without performing writes. Filesystem errors are caught and returned as
15
- * `{ outcome: 'failed' }` rather than thrown.
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
14
+ * result rather than throwing it: `skipped` when the existing file cannot be read, `failed` when the write fails.
16
15
  */
17
16
  export declare function writeFileWithCheck(filePath: string, content: string, options: {
18
17
  dryRun: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@williamthorsen/nmr-core",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "private": false,
5
5
  "description": "Shared utilities for node-monorepo-tools packages",
6
6
  "keywords": [
@@ -41,6 +41,7 @@
41
41
  "dependencies": {
42
42
  "@williamthorsen/toolbelt.errors": "0.8.1",
43
43
  "@williamthorsen/toolbelt.terminal": "0.2.0",
44
+ "diff": "9.0.0",
44
45
  "yaml": "2.9.1"
45
46
  },
46
47
  "devDependencies": {