@williamthorsen/nmr-core 0.12.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,85 @@
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
+ },
46
+ {
47
+ "version": "0.13.0",
48
+ "date": "2026-09-22",
49
+ "sections": [
50
+ {
51
+ "title": "🎉 Features",
52
+ "audience": "all",
53
+ "items": [
54
+ {
55
+ "description": "Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)",
56
+ "body": "- 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.\n- 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.\n- Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.\n\nMigration: 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.",
57
+ "breaking": true,
58
+ "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.",
59
+ "hash": "3196b84c9d5f037ead0e98ee8547fe71e80fb5c6"
60
+ },
61
+ {
62
+ "description": "Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)",
63
+ "body": "- 🚨 **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`.\n- 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.\n- 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.\n- 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.\n- 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.\n\nMigration: 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.",
64
+ "breaking": true,
65
+ "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.",
66
+ "hash": "b1126866159402b8f027a9b82f2a19591a6e9e1b"
67
+ }
68
+ ]
69
+ },
70
+ {
71
+ "title": "🐛 Bug fixes",
72
+ "audience": "all",
73
+ "items": [
74
+ {
75
+ "description": "Truncate release-kit commit subjects by display column (#840)",
76
+ "body": "- 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.\n- Replaces the `...` marker on a truncated subject with `…`, the default of the width-aware truncation that now does the cutting.\n- Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.",
77
+ "hash": "f75d9b4abd9fbda264d5dd40ca5b7abb64f5a3f3"
78
+ }
79
+ ]
80
+ }
81
+ ]
82
+ },
2
83
  {
3
84
  "version": "0.12.0",
4
85
  "date": "2026-09-18",
@@ -131,7 +212,7 @@
131
212
  },
132
213
  {
133
214
  "description": "Adopt `isError` and consolidate errno narrowing on a shared helper (#697)",
134
- "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.",
135
216
  "hash": "c5e8e8a5e006b451e8c5aeea75d35772926d503c"
136
217
  }
137
218
  ]
package/CHANGELOG.md CHANGED
@@ -2,6 +2,51 @@
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
+
20
+ ## 0.13.0 — 2026-09-22
21
+
22
+ ### 🎉 Features
23
+
24
+ - 🚨 **Breaking:** Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)
25
+
26
+ - 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.
27
+ - 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.
28
+ - Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.
29
+
30
+ 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.
31
+
32
+ - 🚨 **Breaking:** Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)
33
+
34
+ - 🚨 **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`.
35
+ - 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.
36
+ - 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.
37
+ - 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.
38
+ - 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.
39
+
40
+ 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.
41
+
42
+ ### 🐛 Bug fixes
43
+
44
+ - Truncate release-kit commit subjects by display column (#840)
45
+
46
+ - 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.
47
+ - Replaces the `...` marker on a truncated subject with `…`, the default of the width-aware truncation that now does the cutting.
48
+ - Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.
49
+
5
50
  ## 0.12.0 — 2026-09-18
6
51
 
7
52
  ### 🎉 Features
package/README.md CHANGED
@@ -1,33 +1,12 @@
1
+ <!-- readme-type: library -->
2
+
1
3
  # @williamthorsen/nmr-core
2
4
 
3
5
  Shared utilities for node-monorepo-tools packages.
4
6
 
5
7
  This package serves as the shared library foundation for the monorepo. For the nmr CLI tool, see [`@williamthorsen/nmr`](../nmr).
6
8
 
7
- <!-- section:release-notes -->
8
- ## Release notes — v0.12.0 (2026-09-18)
9
-
10
- ### 🎉 Features
11
-
12
- - Give nmr-core's print helpers plain output in pipes and CI logs (#834)
13
-
14
- - Stops `printError`, `printSkip`, `printSuccess`, and `reportWriteResult` in `@williamthorsen/nmr-core` from printing emoji into a pipe or a CI log: Each helper now detects a plain or rich style from `CI` and the terminal state of its own stream (stderr for `printError`, stdout for the others), and accepts an optional trailing `OutputStyle` that outranks detection.
15
- - Adds `resolveStreamStyles`, which resolves a `plain` or `rich` output style separately for stdout and stderr, reading a caller-named flag first, then a caller-named environment variable (`auto`, `plain`, or `rich`), then `CI`, the stream's terminal state, and `TERM`, and which returns a setting that it does not recognize in `invalid` instead of throwing.
16
- - Re-exports `defineGlyphSet`, `STATUS_GLYPHS`, `wrapToWidth`, `measureGlyphColumn`, and `describeInvalidOutputStyle` from the experimental `/candidate` API of `@williamthorsen/toolbelt.terminal`, so that a package that depends on `@williamthorsen/nmr-core` builds glyph sets and wraps text without declaring that dependency itself.
17
- - Changes the rich marker of `printSkip` from ⚠️ to 🟠, the `warning` glyph in `STATUS_GLYPHS`; rich `printError` and `printSuccess` output is unchanged.
18
-
19
- - Give release-kit plain output in pipes and CI logs (#835)
20
-
21
- - Adds the `RELEASE_KIT_OUTPUT_STYLE` environment variable, which accepts `auto`, `plain`, or `rich` and outranks the detection from `CI`, the stream's terminal state, and `TERM`; any other value is a usage error that exits with code 1.
22
- - Changes the emoji in rich output so that none has a different meaning from the one that it has in `nmr`: warnings from ⚠️ to 🟠, skips from ⏭️ to ⏩, the errors of `show-tag-prefixes` from ⛔ to ❌, and the tag marker from 🏷️ to 🔖.
23
- - Adds a required `style` parameter to `formatValidateOverridesResult`, which the package root exports.
24
-
25
- - Give nmr plain output in pipes and CI logs (#838)
26
-
27
- - Stops `nmr` from printing emoji to a pipe or a CI log: When the output stream is not a terminal or `CI` is set, a verdict reads `PASS`, `FAIL`, `SKIP`, or `NOOP` and a command icon is omitted, so that a log can be searched for a verdict.
28
- - Adds `--output-style <auto|plain|rich>` to `nmr` and the `NMR_OUTPUT_STYLE` variable, each forcing either style; the flag outranks the variable, a value that names no style exits 1 with a usage error, and neither enters a check-cache key: A rich run and a plain run share a recorded pass.
29
- - Replaces several rich glyphs, taking the status markers from the set that release-kit and v11y-check print so that one status has one glyph across the three tools: a recalled pass shows ⏩ in place of ⏭️, a skipped empty override shows ⚪ in place of ⛔, a warning and the `--log` refusal show 🟠 in place of ⚠️ and 📭, the `--log` header shows 💾 in place of 📼, and `nmr-ensure-prepublish-hooks` reports ✅ and ❌ in place of ✓ and ✗.
30
- <!-- /section:release-notes -->
9
+ <!-- section:release-notes --><!-- /section:release-notes -->
31
10
 
32
11
  ## Installation
33
12
 
@@ -37,12 +16,23 @@ Requires Node.js 24 or later.
37
16
  pnpm add -D @williamthorsen/nmr-core
38
17
  ```
39
18
 
19
+ ## Workspace introspection
20
+
21
+ The `./workspace` entry publishes the pnpm-workspace lookups that nmr and release-kit share. Every one of them
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
24
+ from pnpm.
25
+
26
+ The entry stays out of the root export, which keeps `yaml` out of the module closure of every other importer,
27
+ the build bootstrap's included.
28
+
40
29
  ## The `nmr-source` export condition
41
30
 
42
- Alongside the usual entry, the package declares an `nmr-source` export condition resolving to its TypeScript
43
- source. It exists for one caller: the compiler that builds this package. That compiler imports this package, so
44
- on a tree with no build output it has to reach the source, which is what the condition gives it.
31
+ Both entries declare an `nmr-source` export condition resolving to their TypeScript source. It exists for one
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.
45
34
 
46
- Nothing else should pass `--conditions nmr-source`. The published package ships `dist` alone, so the condition
47
- resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without the flag
48
- is unaffected: an unmatched condition is skipped, and the 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
  }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The manifest patterns that a declared `packages` list resolves to, split by what each entry asks of the matcher.
3
+ *
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
+ */
7
+ export interface WorkspacePatternSplit {
8
+ excludedPatterns: string[];
9
+ includedPatterns: string[];
10
+ }
11
+ /**
12
+ * Matches manifest patterns against a monorepo root, returning the absolute directories that contain a matched
13
+ * manifest, sorted and free of duplicates.
14
+ */
15
+ export declare function matchPackageDirs(monorepoRoot: string, includedPatterns: readonly string[], excludedPatterns: readonly string[]): string[];
16
+ /**
17
+ * Resolves pnpm workspace patterns to absolute package directories.
18
+ *
19
+ * Applies pnpm's algorithm: every pattern is rewritten to match a manifest, `!`-prefixed patterns become
20
+ * exclusions, and the matcher decides the rest. Exclusions filter the entire positive match set
21
+ * irrespective of declaration order.
22
+ */
23
+ export declare function resolvePackageDirs(monorepoRoot: string, patterns: readonly string[]): string[];
24
+ /**
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.
27
+ */
28
+ export declare function splitWorkspacePatterns(patterns: readonly string[]): WorkspacePatternSplit;
@@ -0,0 +1,36 @@
1
+ import { globSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ const MANIFEST = 'package.json';
4
+ const ALWAYS_EXCLUDED = ['**/node_modules/**'];
5
+ export function matchPackageDirs(monorepoRoot, includedPatterns, excludedPatterns) {
6
+ const options = {
7
+ cwd: monorepoRoot,
8
+ exclude: [...excludedPatterns, ...ALWAYS_EXCLUDED],
9
+ followSymlinks: true,
10
+ };
11
+ const matches = globSync([...includedPatterns], options);
12
+ const dirs = matches.map((match) => path.dirname(path.resolve(monorepoRoot, match)));
13
+ return [...new Set(dirs)].toSorted();
14
+ }
15
+ export function resolvePackageDirs(monorepoRoot, patterns) {
16
+ const { excludedPatterns, includedPatterns } = splitWorkspacePatterns(patterns);
17
+ if (includedPatterns.length === 0) {
18
+ return [];
19
+ }
20
+ return matchPackageDirs(monorepoRoot, includedPatterns, excludedPatterns);
21
+ }
22
+ export function splitWorkspacePatterns(patterns) {
23
+ const includedPatterns = [];
24
+ const excludedPatterns = [];
25
+ for (const pattern of patterns) {
26
+ if (pattern.trim() === '')
27
+ continue;
28
+ const isNegated = pattern.startsWith('!');
29
+ const target = isNegated ? excludedPatterns : includedPatterns;
30
+ target.push(buildManifestPattern(isNegated ? pattern.slice(1) : pattern));
31
+ }
32
+ return { excludedPatterns, includedPatterns };
33
+ }
34
+ function buildManifestPattern(pattern) {
35
+ return `${pattern.replace(/\/?$/, '')}/${MANIFEST}`;
36
+ }
@@ -9,7 +9,9 @@ export { hashWorkingTree, readHeadSha } from './hashWorkingTree.js';
9
9
  export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFlags, ParseErrorKind, } from './parseArgs.js';
10
10
  export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
11
11
  export { readPackageVersion } from './readPackageVersion.js';
12
- export type { GlyphSet, InvalidOutputStyle, OutputStyle, ResolveStreamStylesOptions, StatusGlyphName, StreamStyleResolution, StreamStyles, } from './terminal.js';
13
- export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, wrapToWidth, } from './terminal.js';
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, 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, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, 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,13 +1,14 @@
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
- export type { GlyphSet, InvalidOutputStyle, OutputStyle, StatusGlyphName, } from '@williamthorsen/toolbelt.terminal/candidate';
5
- export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, STATUS_GLYPHS, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
5
+ export type { GlyphSet, InvalidOutputStyle, OutputStyle, StatusGlyphName, TruncateToWidthOptions, } from '@williamthorsen/toolbelt.terminal/candidate';
6
+ export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
6
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;
@@ -1,6 +1,6 @@
1
1
  import process from 'node:process';
2
2
  import { detectOutputStyle, measureGlyphColumn, resolveOutputStyle, STATUS_GLYPHS, } from '@williamthorsen/toolbelt.terminal/candidate';
3
- export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, STATUS_GLYPHS, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
3
+ export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
4
4
  export function formatErrorLine(message) {
5
5
  return `Error: ${message}`;
6
6
  }
@@ -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
+ }
@@ -0,0 +1,58 @@
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
+ */
12
+ export type EmptyWorkspaceCause = 'all-excluded' | 'no-package' | 'no-packages-list' | 'no-pattern' | 'unreadable-manifest' | 'unreadable-packages';
13
+ /**
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.
16
+ *
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.
19
+ */
20
+ export type WorkspaceResolution = {
21
+ kind: 'empty';
22
+ cause: EmptyWorkspaceCause;
23
+ patterns: string[];
24
+ } | {
25
+ kind: 'not-a-workspace';
26
+ } | {
27
+ kind: 'packages';
28
+ packageDirs: string[];
29
+ patterns: string[];
30
+ };
31
+ /**
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.
34
+ */
35
+ export declare function findMonorepoRoot(startDir?: string): string | undefined;
36
+ /** Reports whether a directory is the monorepo root, which the workspace manifest's presence marks. */
37
+ export declare function isMonorepoRoot(dir: string): boolean;
38
+ /**
39
+ * Reads the `overrides` block from the monorepo root's `pnpm-workspace.yaml`, the site from which pnpm reads an
40
+ * override.
41
+ *
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.
44
+ */
45
+ export declare function readWorkspaceOverrides(monorepoRoot: string): Record<string, string> | undefined;
46
+ /**
47
+ * Reads the manifest `name` that each of the given package directories declares, skipping a directory whose
48
+ * manifest is missing, unparseable, or nameless.
49
+ */
50
+ export declare function readWorkspacePackageNames(packageDirs: readonly string[]): string[];
51
+ /**
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.
54
+ *
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`.
57
+ */
58
+ export declare function resolveWorkspace(monorepoRoot: string): WorkspaceResolution;
@@ -0,0 +1,111 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { matchPackageDirs, resolvePackageDirs, splitWorkspacePatterns } from "./helpers/workspace-patterns.js";
5
+ const PACKAGE_MANIFEST = 'package.json';
6
+ const WORKSPACE_MANIFEST = 'pnpm-workspace.yaml';
7
+ export function findMonorepoRoot(startDir) {
8
+ let dir = path.resolve(startDir ?? process.cwd());
9
+ for (;;) {
10
+ if (isMonorepoRoot(dir)) {
11
+ return dir;
12
+ }
13
+ const parent = path.dirname(dir);
14
+ if (parent === dir) {
15
+ return undefined;
16
+ }
17
+ dir = parent;
18
+ }
19
+ }
20
+ export function isMonorepoRoot(dir) {
21
+ return existsSync(path.join(dir, WORKSPACE_MANIFEST));
22
+ }
23
+ export function readWorkspaceOverrides(monorepoRoot) {
24
+ const manifestRead = readWorkspaceManifest(monorepoRoot);
25
+ if (manifestRead.kind !== 'parsed' || !isObject(manifestRead.value)) {
26
+ return undefined;
27
+ }
28
+ const overrides = manifestRead.value['overrides'];
29
+ return isObject(overrides) ? readStringValues(overrides) : undefined;
30
+ }
31
+ export function readWorkspacePackageNames(packageDirs) {
32
+ const names = [];
33
+ for (const dir of packageDirs) {
34
+ let parsedManifest;
35
+ try {
36
+ parsedManifest = JSON.parse(readFileSync(path.join(dir, PACKAGE_MANIFEST), 'utf8'));
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ if (isObject(parsedManifest) && typeof parsedManifest['name'] === 'string') {
42
+ names.push(parsedManifest['name']);
43
+ }
44
+ }
45
+ return names;
46
+ }
47
+ export function resolveWorkspace(monorepoRoot) {
48
+ const manifestRead = readWorkspaceManifest(monorepoRoot);
49
+ if (manifestRead.kind === 'absent') {
50
+ return { kind: 'not-a-workspace' };
51
+ }
52
+ if (manifestRead.kind === 'unreadable') {
53
+ return { cause: 'unreadable-manifest', kind: 'empty', patterns: [] };
54
+ }
55
+ const packagesRead = readDeclaredPackages(manifestRead.value);
56
+ if (packagesRead.kind !== 'patterns') {
57
+ const cause = packagesRead.kind === 'absent' ? 'no-packages-list' : 'unreadable-packages';
58
+ return { cause, kind: 'empty', patterns: [] };
59
+ }
60
+ const { patterns } = packagesRead;
61
+ const packageDirs = resolvePackageDirs(monorepoRoot, patterns);
62
+ if (packageDirs.length > 0) {
63
+ return { kind: 'packages', packageDirs, patterns };
64
+ }
65
+ return { cause: diagnoseEmptyCause(monorepoRoot, patterns), kind: 'empty', patterns };
66
+ }
67
+ function diagnoseEmptyCause(monorepoRoot, patterns) {
68
+ const { excludedPatterns, includedPatterns } = splitWorkspacePatterns(patterns);
69
+ if (includedPatterns.length === 0) {
70
+ return 'no-pattern';
71
+ }
72
+ if (excludedPatterns.length > 0 && matchPackageDirs(monorepoRoot, includedPatterns, []).length > 0) {
73
+ return 'all-excluded';
74
+ }
75
+ return 'no-package';
76
+ }
77
+ function readDeclaredPackages(parsedManifest) {
78
+ if (!isObject(parsedManifest))
79
+ return { kind: 'absent' };
80
+ const packages = parsedManifest['packages'];
81
+ if (packages === undefined || packages === null)
82
+ return { kind: 'absent' };
83
+ if (!Array.isArray(packages))
84
+ return { kind: 'unreadable' };
85
+ if (!packages.every((entry) => typeof entry === 'string'))
86
+ return { kind: 'unreadable' };
87
+ return packages.length === 0 ? { kind: 'absent' } : { kind: 'patterns', patterns: packages };
88
+ }
89
+ function isObject(value) {
90
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
91
+ }
92
+ function readStringValues(record) {
93
+ const result = {};
94
+ for (const [key, value] of Object.entries(record)) {
95
+ if (typeof value === 'string')
96
+ result[key] = value;
97
+ }
98
+ return result;
99
+ }
100
+ function readWorkspaceManifest(monorepoRoot) {
101
+ const workspaceFile = path.join(monorepoRoot, WORKSPACE_MANIFEST);
102
+ if (!existsSync(workspaceFile)) {
103
+ return { kind: 'absent' };
104
+ }
105
+ try {
106
+ return { kind: 'parsed', value: parse(readFileSync(workspaceFile, 'utf8')) };
107
+ }
108
+ catch {
109
+ return { kind: 'unreadable' };
110
+ }
111
+ }
@@ -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.12.0",
3
+ "version": "0.13.1",
4
4
  "private": false,
5
5
  "description": "Shared utilities for node-monorepo-tools packages",
6
6
  "keywords": [
@@ -26,6 +26,11 @@
26
26
  "nmr-source": "./src/index.ts",
27
27
  "types": "./dist/esm/index.d.ts",
28
28
  "default": "./dist/esm/index.js"
29
+ },
30
+ "./workspace": {
31
+ "nmr-source": "./src/workspace.ts",
32
+ "types": "./dist/esm/workspace.d.ts",
33
+ "default": "./dist/esm/workspace.js"
29
34
  }
30
35
  },
31
36
  "files": [
@@ -35,7 +40,9 @@
35
40
  ],
36
41
  "dependencies": {
37
42
  "@williamthorsen/toolbelt.errors": "0.8.1",
38
- "@williamthorsen/toolbelt.terminal": "0.2.0"
43
+ "@williamthorsen/toolbelt.terminal": "0.2.0",
44
+ "diff": "9.0.0",
45
+ "yaml": "2.9.1"
39
46
  },
40
47
  "devDependencies": {
41
48
  "@williamthorsen/toolbelt.filesystem": "0.9.1",
@@ -44,7 +51,7 @@
44
51
  "vitest": "4.1.11"
45
52
  },
46
53
  "engines": {
47
- "node": ">=24"
54
+ "node": ">=24.16.0"
48
55
  },
49
56
  "publishConfig": {
50
57
  "access": "public"