@vibe-agent-toolkit/utils 0.2.0-rc.7 → 0.2.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/README.md +24 -4
  2. package/dist/asset-reference.js +3 -11
  3. package/dist/asset-reference.js.map +1 -1
  4. package/dist/crawl-timing.d.ts +3 -3
  5. package/dist/crawl-timing.js +3 -3
  6. package/dist/dirent-kind.d.ts +83 -0
  7. package/dist/dirent-kind.d.ts.map +1 -0
  8. package/dist/dirent-kind.js +129 -0
  9. package/dist/dirent-kind.js.map +1 -0
  10. package/dist/env-flag.d.ts +6 -1
  11. package/dist/env-flag.d.ts.map +1 -1
  12. package/dist/env-flag.js +6 -1
  13. package/dist/env-flag.js.map +1 -1
  14. package/dist/errors/errno.d.ts +51 -0
  15. package/dist/errors/errno.d.ts.map +1 -0
  16. package/dist/errors/errno.js +112 -0
  17. package/dist/errors/errno.js.map +1 -0
  18. package/dist/errors/vat-error.d.ts +60 -0
  19. package/dist/errors/vat-error.d.ts.map +1 -0
  20. package/dist/errors/vat-error.js +86 -0
  21. package/dist/errors/vat-error.js.map +1 -0
  22. package/dist/file-crawler.js +9 -9
  23. package/dist/file-crawler.js.map +1 -1
  24. package/dist/fs/file-hash.d.ts.map +1 -1
  25. package/dist/fs/file-hash.js +0 -1
  26. package/dist/fs/file-hash.js.map +1 -1
  27. package/dist/fs-utils.d.ts +16 -18
  28. package/dist/fs-utils.d.ts.map +1 -1
  29. package/dist/fs-utils.js +56 -80
  30. package/dist/fs-utils.js.map +1 -1
  31. package/dist/fs.d.ts +2 -1
  32. package/dist/fs.d.ts.map +1 -1
  33. package/dist/fs.js +2 -1
  34. package/dist/fs.js.map +1 -1
  35. package/dist/git-run.d.ts +1 -1
  36. package/dist/git-run.js +1 -1
  37. package/dist/git-snapshot.d.ts +18 -0
  38. package/dist/git-snapshot.d.ts.map +1 -1
  39. package/dist/git-snapshot.js +18 -0
  40. package/dist/git-snapshot.js.map +1 -1
  41. package/dist/git-tracker.d.ts +1 -1
  42. package/dist/git-tracker.d.ts.map +1 -1
  43. package/dist/git-tracker.js +1 -2
  44. package/dist/git-tracker.js.map +1 -1
  45. package/dist/git-utils.d.ts.map +1 -1
  46. package/dist/git-utils.js +0 -1
  47. package/dist/git-utils.js.map +1 -1
  48. package/dist/git.d.ts +1 -1
  49. package/dist/git.d.ts.map +1 -1
  50. package/dist/git.js +1 -1
  51. package/dist/git.js.map +1 -1
  52. package/dist/gitignore-checker.d.ts.map +1 -1
  53. package/dist/gitignore-checker.js +9 -3
  54. package/dist/gitignore-checker.js.map +1 -1
  55. package/dist/glob/glob-pattern.js +5 -5
  56. package/dist/glob/glob-pattern.js.map +1 -1
  57. package/dist/index.d.ts +7 -3
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +19 -4
  60. package/dist/index.js.map +1 -1
  61. package/dist/listing-refusal.d.ts +2 -1
  62. package/dist/listing-refusal.d.ts.map +1 -1
  63. package/dist/listing-refusal.js +3 -3
  64. package/dist/listing-refusal.js.map +1 -1
  65. package/dist/path-containment.d.ts +64 -0
  66. package/dist/path-containment.d.ts.map +1 -0
  67. package/dist/path-containment.js +111 -0
  68. package/dist/path-containment.js.map +1 -0
  69. package/dist/path-core.d.ts +112 -17
  70. package/dist/path-core.d.ts.map +1 -1
  71. package/dist/path-core.js +138 -22
  72. package/dist/path-core.js.map +1 -1
  73. package/dist/path-utils.d.ts.map +1 -1
  74. package/dist/path-utils.js +42 -47
  75. package/dist/path-utils.js.map +1 -1
  76. package/dist/path.d.ts +1 -1
  77. package/dist/path.d.ts.map +1 -1
  78. package/dist/path.js +1 -1
  79. package/dist/path.js.map +1 -1
  80. package/dist/project-utils.d.ts.map +1 -1
  81. package/dist/project-utils.js +9 -6
  82. package/dist/project-utils.js.map +1 -1
  83. package/dist/safe-exec.d.ts +2 -1
  84. package/dist/safe-exec.d.ts.map +1 -1
  85. package/dist/safe-exec.js +25 -7
  86. package/dist/safe-exec.js.map +1 -1
  87. package/dist/skill-targets.d.ts +2 -2
  88. package/dist/skill-targets.js +2 -2
  89. package/dist/skill-test/auth-resolver.d.ts +10 -2
  90. package/dist/skill-test/auth-resolver.d.ts.map +1 -1
  91. package/dist/skill-test/auth-resolver.js +26 -11
  92. package/dist/skill-test/auth-resolver.js.map +1 -1
  93. package/dist/skill-test/spawn-claude.d.ts +2 -1
  94. package/dist/skill-test/spawn-claude.d.ts.map +1 -1
  95. package/dist/skill-test/spawn-claude.js +20 -3
  96. package/dist/skill-test/spawn-claude.js.map +1 -1
  97. package/dist/skill-test/transcript.d.ts.map +1 -1
  98. package/dist/skill-test/transcript.js +18 -17
  99. package/dist/skill-test/transcript.js.map +1 -1
  100. package/dist/stdio-blocking.js +13 -14
  101. package/dist/stdio-blocking.js.map +1 -1
  102. package/dist/test-helpers.d.ts +47 -204
  103. package/dist/test-helpers.d.ts.map +1 -1
  104. package/dist/test-helpers.js +105 -310
  105. package/dist/test-helpers.js.map +1 -1
  106. package/dist/testing/executables.d.ts +32 -0
  107. package/dist/testing/executables.d.ts.map +1 -0
  108. package/dist/testing/executables.js +70 -0
  109. package/dist/testing/executables.js.map +1 -0
  110. package/dist/testing/hostile-tree.d.ts +79 -0
  111. package/dist/testing/hostile-tree.d.ts.map +1 -0
  112. package/dist/testing/hostile-tree.js +164 -0
  113. package/dist/testing/hostile-tree.js.map +1 -0
  114. package/dist/testing/platform-gates.d.ts +31 -0
  115. package/dist/testing/platform-gates.d.ts.map +1 -0
  116. package/dist/testing/platform-gates.js +31 -0
  117. package/dist/testing/platform-gates.js.map +1 -0
  118. package/dist/testing/temp-dir.d.ts +255 -0
  119. package/dist/testing/temp-dir.d.ts.map +1 -0
  120. package/dist/testing/temp-dir.js +363 -0
  121. package/dist/testing/temp-dir.js.map +1 -0
  122. package/dist/testing.d.ts +5 -0
  123. package/dist/testing.d.ts.map +1 -1
  124. package/dist/testing.js +10 -1
  125. package/dist/testing.js.map +1 -1
  126. package/dist/text-content.d.ts.map +1 -1
  127. package/dist/text-content.js +7 -1
  128. package/dist/text-content.js.map +1 -1
  129. package/dist/text-file.d.ts.map +1 -1
  130. package/dist/text-file.js +0 -2
  131. package/dist/text-file.js.map +1 -1
  132. package/dist/timing-dump.d.ts +1 -1
  133. package/dist/timing-dump.d.ts.map +1 -1
  134. package/dist/timing-dump.js +1 -2
  135. package/dist/timing-dump.js.map +1 -1
  136. package/dist/windows-shell.d.ts +0 -1
  137. package/dist/windows-shell.d.ts.map +1 -1
  138. package/dist/windows-shell.js +0 -1
  139. package/dist/windows-shell.js.map +1 -1
  140. package/dist/zod-introspection.js +2 -2
  141. package/dist/zod-introspection.js.map +1 -1
  142. package/eslint/README.md +126 -68
  143. package/eslint/index.cjs +111 -162
  144. package/eslint/index.d.cts +14 -17
  145. package/eslint/rules/callee-name.cjs +23 -0
  146. package/eslint/rules/commands-import-boundary.cjs +148 -0
  147. package/eslint/rules/dead-import.cjs +1 -1
  148. package/eslint/rules/dirent-type-needs-symlink-check.cjs +282 -0
  149. package/eslint/rules/eslint-rule-factory.cjs +5 -2
  150. package/eslint/rules/exempt-path-matcher.cjs +2 -1
  151. package/eslint/rules/explicit-zod-strictness.cjs +120 -0
  152. package/eslint/rules/no-bare-dynamic-import-path.cjs +5 -1
  153. package/eslint/rules/no-bare-executable-spawn.cjs +70 -0
  154. package/eslint/rules/no-bare-symlink-in-tests.cjs +16 -3
  155. package/eslint/rules/no-blind-catch.cjs +171 -0
  156. package/eslint/rules/no-child-process-execSync.cjs +8 -0
  157. package/eslint/rules/no-decaying-referent.cjs +217 -0
  158. package/eslint/rules/no-dotdot-containment.cjs +160 -0
  159. package/eslint/rules/no-file-url-string-concat.cjs +4 -1
  160. package/eslint/rules/no-fragile-entrypoint-guard.cjs +14 -1
  161. package/eslint/rules/no-fs-mkdirSync.cjs +8 -0
  162. package/eslint/rules/no-fs-promises-cp.cjs +7 -0
  163. package/eslint/rules/no-fs-realpathSync.cjs +8 -0
  164. package/eslint/rules/no-hardcoded-path-split.cjs +29 -18
  165. package/eslint/rules/no-io-in-unit-tier.cjs +129 -0
  166. package/eslint/rules/no-literal-process-exit.cjs +129 -0
  167. package/eslint/rules/no-manual-path-normalize.cjs +136 -107
  168. package/eslint/rules/no-os-tmpdir.cjs +8 -0
  169. package/eslint/rules/no-path-operations-in-comparisons.cjs +7 -2
  170. package/eslint/rules/no-path-sep-in-strings.cjs +7 -2
  171. package/eslint/rules/no-path-startswith.cjs +7 -2
  172. package/eslint/rules/no-process-exit-in-phase.cjs +12 -2
  173. package/eslint/rules/no-raw-node-path.cjs +563 -0
  174. package/eslint/rules/no-raw-text-decode.cjs +10 -1
  175. package/eslint/rules/no-registry-count-pin.cjs +255 -0
  176. package/eslint/rules/no-self-package-import.cjs +13 -2
  177. package/eslint/rules/no-test-scoped-functions.cjs +10 -3
  178. package/eslint/rules/no-unix-shell-commands.cjs +6 -2
  179. package/eslint/rules/no-unsafe-root-join.cjs +23 -2
  180. package/eslint/rules/no-url-pathname-for-fs.cjs +5 -1
  181. package/eslint/rules/no-version-literal.cjs +151 -0
  182. package/eslint/rules/prefer-startswith-over-regex.cjs +9 -0
  183. package/eslint/rules/require-justified-skip.cjs +8 -2
  184. package/eslint/rules/safe-import.cjs +1 -1
  185. package/package.json +4 -9
  186. package/eslint/rules/no-path-join.cjs +0 -14
  187. package/eslint/rules/no-path-relative.cjs +0 -14
  188. package/eslint/rules/no-path-resolve.cjs +0 -14
  189. package/eslint/rules/path-function-rule-factory.cjs +0 -496
@@ -2,10 +2,13 @@
2
2
  * ESLint rule to disallow splitting strings by hardcoded path separators
3
3
  *
4
4
  * Using .split('/') or .split('\\') on file paths breaks on Windows/Unix.
5
- * Use path.basename(), path.dirname(), or normalize with toForwardSlash() first.
5
+ * Use path.basename(), path.dirname(), or normalize first: toForwardSlash() for a
6
+ * NATIVE path (fs, path.*, the VCS — converts only where the host separator is a
7
+ * backslash), toForwardSlashAnyPlatform() for AUTHOR-WRITTEN text (hrefs, globs,
8
+ * config values, archive entries — converts every backslash on every host).
6
9
  *
7
10
  * This rule is smart enough to detect when paths are already normalized:
8
- * - Inline: toForwardSlash(path).split('/') ✅
11
+ * - Inline: toForwardSlash(path).split('/') ✅ (either converter)
9
12
  * - Variable: const normalized = toForwardSlash(path); normalized.split('/') ✅
10
13
  *
11
14
  * @example
@@ -24,6 +27,9 @@
24
27
  * // ✅ GOOD - normalize then split (variable)
25
28
  * const normalizedPath = toForwardSlash(filePath);
26
29
  * const parts = normalizedPath.split('/');
30
+ *
31
+ * // ✅ GOOD - authored text (a glob, an href) converts on every host
32
+ * const segments = toForwardSlashAnyPlatform(pattern).split('/');
27
33
  */
28
34
 
29
35
  const {
@@ -32,37 +38,46 @@ const {
32
38
  resolveSafeModule,
33
39
  } = require('./safe-import.cjs');
34
40
 
41
+ /** The converters whose result is forward-slashed, so splitting it on `/` is safe. */
42
+ const NORMALIZERS = new Set(['toForwardSlash', 'toForwardSlashAnyPlatform']);
43
+
44
+ /** A direct call to one of {@link NORMALIZERS}? */
45
+ function isNormalizerCall(node) {
46
+ return node?.type === 'CallExpression' && node.callee.type === 'Identifier' && NORMALIZERS.has(node.callee.name);
47
+ }
48
+
35
49
  module.exports = {
36
50
  meta: {
37
51
  type: 'problem',
38
52
  docs: {
39
- description: 'Disallow splitting strings by hardcoded path separators',
40
- category: 'Cross-platform compatibility',
53
+ description:
54
+ 'Disallow splitting strings by hardcoded path separators',
55
+ category: 'Path handling',
56
+ bans: "`split('/')` / `split('\\\\')` on a path",
57
+ useInstead: '`path.basename()`, or `toForwardSlash()` / `toForwardSlashAnyPlatform()` first',
58
+ subpath: '/path',
41
59
  recommended: true,
60
+ recommendedSeverity: 'error',
42
61
  },
43
62
  messages: {
44
63
  noHardcodedSplit:
45
64
  String.raw`Avoid .split('/') or .split('\') on file paths (breaks on Windows/Unix). ` +
46
- 'Use path.basename() to extract filename, or toForwardSlash() from {{safeModule}} to normalize paths first.',
65
+ 'Use path.basename() to extract filename, or normalize first with toForwardSlash() (native paths) ' +
66
+ 'or toForwardSlashAnyPlatform() (authored text such as globs and hrefs) from {{safeModule}}.',
47
67
  },
48
68
  schema: [SAFE_MODULE_ONLY_SCHEMA],
49
69
  },
50
70
 
51
71
  create(context) {
52
72
  const reportData = { safeModule: resolveSafeModule(context, SAFE_PATH_MODULE) };
53
- // Track variables that were assigned from toForwardSlash()
73
+ // Track variables that were assigned from a normalizer
54
74
  const normalizedVariables = new Set();
55
75
 
56
76
  return {
57
77
  // Track variable declarations
58
78
  VariableDeclarator(node) {
59
- // Check if this variable is assigned from toForwardSlash()
60
- if (
61
- node.init?.type === 'CallExpression' &&
62
- node.init.callee.type === 'Identifier' &&
63
- node.init.callee.name === 'toForwardSlash' &&
64
- node.id.type === 'Identifier'
65
- ) {
79
+ // Check if this variable is assigned from a normalizer
80
+ if (isNormalizerCall(node.init) && node.id.type === 'Identifier') {
66
81
  normalizedVariables.add(node.id.name);
67
82
  }
68
83
  },
@@ -102,11 +117,7 @@ module.exports = {
102
117
  const object = node.callee.object;
103
118
 
104
119
  // Case 1: Inline normalization - toForwardSlash(...).split('/')
105
- if (
106
- object.type === 'CallExpression' &&
107
- object.callee.type === 'Identifier' &&
108
- object.callee.name === 'toForwardSlash'
109
- ) {
120
+ if (isNormalizerCall(object)) {
110
121
  return; // Safe - normalized inline
111
122
  }
112
123
 
@@ -0,0 +1,129 @@
1
+ /**
2
+ * ESLint rule: no-io-in-unit-tier
3
+ *
4
+ * In a UNIT-tier test file, flags an import of `node:child_process` /
5
+ * `child_process` and any call to `mkdtemp`, `mkdtempSync`, `spawn`,
6
+ * `spawnSync`, `execSync` or `execFileSync` — bare or through a namespace.
7
+ *
8
+ * The tiers are a promise about cost and about what is being tested: a unit
9
+ * test exercises logic and finishes in milliseconds; an integration test
10
+ * wires real components; a system test runs the real binary. A `*.test.ts`
11
+ * that spawns `git` or mints a temp directory has silently moved tiers
12
+ * without moving files — it runs under the unit budget, it is coverage-
13
+ * instrumented as if it were pure, and it is the first thing to flake on a
14
+ * loaded CI runner. The audit measured the class at 93 unit files touching
15
+ * the real filesystem and 5 spawning real processes. Moving a file to the
16
+ * tier it belongs to is a rename; this rule makes the rename happen at the
17
+ * desk rather than in a 53-second package run.
18
+ *
19
+ * ## The tier boundary, as this rule reads it
20
+ *
21
+ * A file is unit-tier when it is a test file (`*.test.ts` and friends) under
22
+ * `packages/<pkg>/test/` at any depth, EXCEPT when it sits under an
23
+ * `integration/` or `system/` directory or carries the `.integration.test.`
24
+ * / `.system.test.` suffix. Helpers (`test-helpers.ts`) are not test files
25
+ * and are not checked here; a helper that spawns is caught at the unit file
26
+ * that calls it only if the call is visible there, which is a known floor.
27
+ *
28
+ * Option `allowFiles: string[]` — repo-relative paths of today's offenders,
29
+ * the ratchet. Name files, never directories.
30
+ *
31
+ * @example
32
+ * // BAD in packages/x/test/thing.test.ts — a system test wearing a unit name
33
+ * const out = spawnSync('node', [bin, '--json']);
34
+ *
35
+ * // GOOD — same code, in packages/x/test/system/thing.system.test.ts
36
+ */
37
+
38
+ 'use strict';
39
+
40
+ const { calleeName } = require('./callee-name.cjs');
41
+ const { createExemptPathMatcher, isTestFile } = require('./exempt-path-matcher.cjs');
42
+
43
+ const CHILD_PROCESS_MODULES = new Set(['node:child_process', 'child_process']);
44
+ const IO_CALLS = new Set(['mkdtemp', 'mkdtempSync', 'spawn', 'spawnSync', 'execSync', 'execFileSync']);
45
+
46
+ /** `packages/<pkg>/test/` anywhere in the path, with either separator already normalised. */
47
+ const PACKAGE_TEST_DIR = /(?:^|\/)packages\/[^/]+\/test\//u;
48
+
49
+ /** The integration and system tiers, by directory or by suffix. */
50
+ const OTHER_TIER = /\/(?:integration|system)\/|\.(?:integration|system)\.test\./u;
51
+
52
+ /** Whether `filename` is a unit-tier test file under a package's `test/`. */
53
+ function isUnitTierFile(filename) {
54
+ if (!filename) {
55
+ return false;
56
+ }
57
+ // eslint-disable-next-line local/no-manual-path-normalize -- the rule pack is standalone CommonJS and cannot import the ESM helper; config paths and linted filenames are matched separator-agnostically on purpose.
58
+ const normalized = String(filename).replaceAll('\\', '/');
59
+ return isTestFile(normalized) && PACKAGE_TEST_DIR.test(normalized) && !OTHER_TIER.test(normalized);
60
+ }
61
+
62
+ /** The banned callee name of a call, bare (`spawn(…)`) or namespaced (`cp.spawn(…)`), or null. */
63
+ function bannedCallName(call) {
64
+ const name = calleeName(call);
65
+ return name !== null && IO_CALLS.has(name) ? name : null;
66
+ }
67
+
68
+ module.exports = {
69
+ meta: {
70
+ type: 'problem',
71
+ docs: {
72
+ description:
73
+ 'Disallow child_process imports and mkdtemp/spawn/exec calls in unit-tier test files — ' +
74
+ 'a test that spawns or writes to disk belongs in the integration or system tier',
75
+ recommended: false,
76
+ recommendedSeverity: 'warn',
77
+ },
78
+ schema: [
79
+ {
80
+ type: 'object',
81
+ properties: {
82
+ allowFiles: { type: 'array', items: { type: 'string' }, uniqueItems: true },
83
+ },
84
+ additionalProperties: false,
85
+ },
86
+ ],
87
+ messages: {
88
+ childProcessImport:
89
+ "A unit-tier test imports '{{source}}': spawning a process is integration or system work. " +
90
+ 'Move the file to test/integration/ (*.integration.test.ts) or test/system/ ' +
91
+ '(*.system.test.ts), or mock the module.',
92
+ ioCall:
93
+ 'A unit-tier test calls {{name}}(): real processes and temp directories belong to the ' +
94
+ 'integration or system tier. Move the file to that tier, or test the logic without the I/O.',
95
+ },
96
+ },
97
+
98
+ create(context) {
99
+ const filename = context.filename ?? context.getFilename();
100
+ const isAllowed = createExemptPathMatcher(context.options?.[0]?.allowFiles ?? []);
101
+ if (!isUnitTierFile(filename) || isAllowed(filename)) {
102
+ return {};
103
+ }
104
+
105
+ function checkModule(node, sourceNode) {
106
+ const source = sourceNode?.type === 'Literal' ? sourceNode.value : null;
107
+ if (typeof source === 'string' && CHILD_PROCESS_MODULES.has(source)) {
108
+ context.report({ node, messageId: 'childProcessImport', data: { source } });
109
+ }
110
+ }
111
+
112
+ return {
113
+ ImportDeclaration(node) {
114
+ if (node.importKind !== 'type') {
115
+ checkModule(node, node.source);
116
+ }
117
+ },
118
+ ImportExpression(node) {
119
+ checkModule(node, node.source);
120
+ },
121
+ CallExpression(node) {
122
+ const name = bannedCallName(node);
123
+ if (name !== null) {
124
+ context.report({ node, messageId: 'ioCall', data: { name } });
125
+ }
126
+ },
127
+ };
128
+ },
129
+ };
@@ -0,0 +1,129 @@
1
+ /**
2
+ * ESLint rule: no-literal-process-exit
3
+ *
4
+ * Flags `process.exit(<number>)` and `process.exitCode = <number>`. A numeric
5
+ * exit code written at the call site re-decides the exit contract inline: one
6
+ * command exits 1 for "findings" and another exits 1 for "the config was
7
+ * unreadable", and nothing but a reader comparing two files can tell. The
8
+ * allowed shape names the meaning — `process.exit(ExitCode.FINDINGS)` — so the
9
+ * contract lives in one enum and every command shares it.
10
+ *
11
+ * The literal may hide inside an expression: `ok ? 0 : 1`, `status ?? 1`,
12
+ * `-1`. Those are flagged too, because each branch is still a number chosen at
13
+ * this site. Any non-literal argument — an identifier, a member, a call
14
+ * result — is accepted; the rule is a syntactic floor and does not chase what
15
+ * a variable holds.
16
+ *
17
+ * Option `allow: string[]` — repo-relative paths of the files permitted to
18
+ * exit with a literal (the one `bin.ts` last-resort fallback that runs when
19
+ * the enum module itself failed to load). Entries are matched at a path
20
+ * segment boundary via `exempt-path-matcher.cjs`; give the full repo-relative
21
+ * path, not a bare basename.
22
+ *
23
+ * @example
24
+ * // BAD — 1 means what, exactly?
25
+ * process.exit(1);
26
+ *
27
+ * // GOOD — the meaning is the code
28
+ * process.exit(ExitCode.FINDINGS);
29
+ */
30
+
31
+ 'use strict';
32
+
33
+ const { createExemptPathMatcher } = require('./exempt-path-matcher.cjs');
34
+
35
+ /** Whether `node` is the member expression `process.<name>` (non-computed). */
36
+ function isProcessMember(node, name) {
37
+ return (
38
+ node.type === 'MemberExpression' &&
39
+ !node.computed &&
40
+ node.object.type === 'Identifier' &&
41
+ node.object.name === 'process' &&
42
+ node.property.type === 'Identifier' &&
43
+ node.property.name === name
44
+ );
45
+ }
46
+
47
+ /**
48
+ * The first numeric literal reachable through the expression's value
49
+ * branches, or null. Walks conditionals, nullish/logical fallbacks, unary
50
+ * minus, and TypeScript wrappers — every path a number can take to become the
51
+ * exit code without passing through a name.
52
+ */
53
+ function numericLiteralLeaf(expr) {
54
+ switch (expr.type) {
55
+ case 'Literal':
56
+ return typeof expr.value === 'number' ? expr : null;
57
+ case 'UnaryExpression':
58
+ return numericLiteralLeaf(expr.argument);
59
+ case 'ConditionalExpression':
60
+ return numericLiteralLeaf(expr.consequent) ?? numericLiteralLeaf(expr.alternate);
61
+ case 'LogicalExpression':
62
+ return numericLiteralLeaf(expr.left) ?? numericLiteralLeaf(expr.right);
63
+ case 'TSAsExpression':
64
+ case 'TSNonNullExpression':
65
+ case 'TSSatisfiesExpression':
66
+ return numericLiteralLeaf(expr.expression);
67
+ default:
68
+ return null;
69
+ }
70
+ }
71
+
72
+ module.exports = {
73
+ meta: {
74
+ type: 'problem',
75
+ docs: {
76
+ description:
77
+ 'Disallow process.exit(<number>) and process.exitCode = <number> — name the meaning with ' +
78
+ 'the ExitCode enum so every command shares one exit contract',
79
+ recommended: false,
80
+ recommendedSeverity: 'warn',
81
+ },
82
+ schema: [
83
+ {
84
+ type: 'object',
85
+ properties: {
86
+ allow: { type: 'array', items: { type: 'string' }, uniqueItems: true },
87
+ },
88
+ additionalProperties: false,
89
+ },
90
+ ],
91
+ messages: {
92
+ literalExit:
93
+ 'process.exit({{literal}}) re-decides the exit contract at this call site. Use the ' +
94
+ 'ExitCode enum from @vibe-agent-toolkit/schema — process.exit(ExitCode.X) — so the code ' +
95
+ 'means the same thing in every command.',
96
+ literalExitCode:
97
+ 'process.exitCode = {{literal}} re-decides the exit contract at this site. Assign an ' +
98
+ 'ExitCode member from @vibe-agent-toolkit/schema instead.',
99
+ },
100
+ },
101
+
102
+ create(context) {
103
+ const allow = context.options?.[0]?.allow ?? [];
104
+ const filename = context.filename ?? context.getFilename();
105
+ if (createExemptPathMatcher(allow)(filename)) {
106
+ return {};
107
+ }
108
+
109
+ function reportLiteral(node, expr, messageId) {
110
+ const leaf = numericLiteralLeaf(expr);
111
+ if (leaf !== null) {
112
+ context.report({ node, messageId, data: { literal: String(leaf.raw ?? leaf.value) } });
113
+ }
114
+ }
115
+
116
+ return {
117
+ CallExpression(node) {
118
+ if (isProcessMember(node.callee, 'exit') && node.arguments.length > 0) {
119
+ reportLiteral(node, node.arguments[0], 'literalExit');
120
+ }
121
+ },
122
+ AssignmentExpression(node) {
123
+ if (isProcessMember(node.left, 'exitCode')) {
124
+ reportLiteral(node, node.right, 'literalExitCode');
125
+ }
126
+ },
127
+ };
128
+ },
129
+ };
@@ -1,16 +1,32 @@
1
1
  /**
2
- * ESLint rule to enforce using toForwardSlash() instead of manual normalization
2
+ * ESLint rule to enforce the forward-slash converters instead of hand-rolled
3
+ * normalization.
3
4
  *
4
- * Detects manual path normalization patterns and suggests using the utility function.
5
+ * Two converters, because a backslash means two different things:
6
+ *
7
+ * - `toForwardSlash(p)` — a NATIVE path (from `fs`, `path.*`, git). Converts
8
+ * only where the host's separator is a backslash; on POSIX a backslash is a
9
+ * filename character and is kept. `split(path.sep).join('/')` is exactly
10
+ * this, so it autofixes here.
11
+ * - `toForwardSlashAnyPlatform(text)` — AUTHOR-WRITTEN text (an href, a glob, a
12
+ * config value, an archive entry name). Converts every backslash on every
13
+ * host. A literal-backslash `split('\\').join('/')`, `replaceAll('\\', '/')`
14
+ * or `replace(/\\/g, '/')` is exactly this, so each autofixes here — never to
15
+ * `toForwardSlash`, which would silently stop converting on POSIX.
16
+ *
17
+ * Whether a given literal-backslash site is really author text is the author's
18
+ * call; the fix preserves behaviour, and a native-path site should then be
19
+ * switched to `toForwardSlash` by hand.
5
20
  *
6
21
  * @example
7
22
  * // ❌ BAD - manual normalization
8
- * const normalized = relativePath.split(path.sep).join('/');
9
- * const normalized = somePath.split('\\').join('/');
23
+ * const a = relativePath.split(path.sep).join('/');
24
+ * const b = href.replaceAll('\\', '/');
10
25
  *
11
- * // ✅ GOOD - use utility function
12
- * import { toForwardSlash } from '@vibe-agent-toolkit/utils/path';
13
- * const normalized = toForwardSlash(relativePath);
26
+ * // ✅ GOOD - use the utility functions
27
+ * import { toForwardSlash, toForwardSlashAnyPlatform } from '@vibe-agent-toolkit/utils/path';
28
+ * const a = toForwardSlash(relativePath);
29
+ * const b = toForwardSlashAnyPlatform(href);
14
30
  */
15
31
 
16
32
  const {
@@ -26,22 +42,85 @@ const {
26
42
  resolveSafeModule,
27
43
  } = require('./safe-import.cjs');
28
44
 
29
- const SAFE_FN = 'toForwardSlash';
45
+ const NATIVE_FN = 'toForwardSlash';
46
+ const ANY_PLATFORM_FN = 'toForwardSlashAnyPlatform';
47
+ const MESSAGE_FOR = { [NATIVE_FN]: 'useToForwardSlash', [ANY_PLATFORM_FN]: 'useToForwardSlashAnyPlatform' };
30
48
  const PATH_MODULES = new Set(['node:path', 'path']);
49
+ const BACKSLASH = '\\';
50
+
51
+ /** `.name(...)` on some receiver, with exactly `arity` arguments? */
52
+ function isMethodCall(node, name, arity) {
53
+ return (
54
+ node?.type === 'CallExpression' &&
55
+ node.callee.type === 'MemberExpression' &&
56
+ node.callee.property.name === name &&
57
+ node.arguments.length === arity
58
+ );
59
+ }
60
+
61
+ function isStringLiteral(node, value) {
62
+ return node.type === 'Literal' && node.value === value;
63
+ }
64
+
65
+ /** `/\\/g` — one literal backslash, global. */
66
+ function isGlobalBackslashRegex(node) {
67
+ return node.type === 'Literal' && node.regex?.pattern === String.raw`\\` && node.regex.flags.includes('g');
68
+ }
69
+
70
+ function isPathSep(node) {
71
+ return node.type === 'MemberExpression' && node.object.name === 'path' && node.property.name === 'sep';
72
+ }
73
+
74
+ /**
75
+ * `<x>.split(<sep>).join('/')` → the converter it is equivalent to.
76
+ *
77
+ * Splitting on a TWO-backslash SEQUENCE (e.g. collapsing a UNC server prefix)
78
+ * is a different operation that neither converter matches, so it is not
79
+ * reported.
80
+ */
81
+ function matchSplitJoin(node) {
82
+ if (!isMethodCall(node, 'join', 1) || !isStringLiteral(node.arguments[0], '/')) return undefined;
83
+ const split = node.callee.object;
84
+ if (!isMethodCall(split, 'split', 1)) return undefined;
85
+ const [separator] = split.arguments;
86
+ if (isPathSep(separator)) return { receiver: split.callee.object, fn: NATIVE_FN };
87
+ if (isStringLiteral(separator, BACKSLASH)) return { receiver: split.callee.object, fn: ANY_PLATFORM_FN };
88
+ return undefined;
89
+ }
90
+
91
+ /** `<x>.replaceAll('\\', '/')` or `<x>.replace(/\\/g, '/')` → the any-platform converter. */
92
+ function matchReplace(node) {
93
+ const isReplace = isMethodCall(node, 'replace', 2) || isMethodCall(node, 'replaceAll', 2);
94
+ if (!isReplace || !isStringLiteral(node.arguments[1], '/')) return undefined;
95
+ const [pattern] = node.arguments;
96
+ const allBackslashes =
97
+ isGlobalBackslashRegex(pattern) ||
98
+ (node.callee.property.name === 'replaceAll' && isStringLiteral(pattern, BACKSLASH));
99
+ return allBackslashes ? { receiver: node.callee.object, fn: ANY_PLATFORM_FN } : undefined;
100
+ }
31
101
 
32
102
  module.exports = {
33
103
  meta: {
34
104
  type: 'problem',
35
105
  docs: {
36
- description: 'Disallow manual path normalization patterns',
37
- category: 'Cross-platform compatibility',
106
+ description:
107
+ 'Disallow manual path normalization patterns',
108
+ category: 'Path handling',
109
+ bans: "hand-rolled `.replace(/\\\\/g, '/')` / `split(path.sep).join('/')`",
110
+ useInstead: '`toForwardSlash()` (native paths) / `toForwardSlashAnyPlatform()` (authored text)',
111
+ subpath: '/path',
38
112
  recommended: true,
113
+ recommendedSeverity: 'error',
39
114
  },
40
115
  fixable: 'code',
41
116
  messages: {
42
117
  useToForwardSlash:
43
118
  'Use toForwardSlash() from {{safeModule}} instead of manual path normalization. ' +
44
- 'Manual normalization is error-prone and less maintainable.',
119
+ 'It converts a native path only where the host separator is a backslash.',
120
+ useToForwardSlashAnyPlatform:
121
+ 'Use toForwardSlashAnyPlatform() from {{safeModule}} instead of a hand-rolled backslash replace. ' +
122
+ 'If this string is a native filesystem/git path rather than authored text, use toForwardSlash() — ' +
123
+ 'on POSIX a backslash is a filename character.',
45
124
  [DEAD_UNSAFE_IMPORT]: DEAD_UNSAFE_IMPORT_MESSAGE,
46
125
  },
47
126
  schema: [SAFE_MODULE_ONLY_SCHEMA],
@@ -50,24 +129,43 @@ module.exports = {
50
129
  create(context) {
51
130
  const sourceCode = context.getSourceCode();
52
131
  const targetModule = resolveSafeModule(context, SAFE_PATH_MODULE);
53
- // Seeded from SCOPE: a file that already imports `toForwardSlash` from the
54
- // barrel must have the call rewritten WITHOUT gaining a second binding of
55
- // the same name — that is a SyntaxError. See `safe-import.cjs`.
56
- let hasToForwardSlashImport = isNameAlreadyBound(sourceCode, SAFE_FN);
132
+ // Seeded from SCOPE: a file that already binds the name must have the call
133
+ // rewritten WITHOUT gaining a second binding of the same name — that is a
134
+ // SyntaxError. See `safe-import.cjs`.
135
+ const bound = {
136
+ [NATIVE_FN]: isNameAlreadyBound(sourceCode, NATIVE_FN),
137
+ [ANY_PLATFORM_FN]: isNameAlreadyBound(sourceCode, ANY_PLATFORM_FN),
138
+ };
57
139
  // Never mutated — the dead-import leg must not be armed by a flag that a
58
140
  // suppressed report's `fix()` can spend. See `dead-import.cjs`.
59
- const safeBoundInSource = hasToForwardSlashImport;
141
+ const safeBoundInSource = bound[NATIVE_FN];
60
142
  // The dead-import leg's OTHER gate: a `toForwardSlash(…)` call is the text
61
- // this fixer writes, and the only evidence available that it wrote it here.
62
- // Without it, any file with `toForwardSlash` in scope armed the leg — see
63
- // `dead-import.cjs`. Read from the source, never from a `fix()`.
143
+ // this fixer writes for `path.sep`, and the only evidence available that it
144
+ // wrote it here. Read from the source, never from a `fix()`.
64
145
  let safeReplacementCalled = false;
65
146
  let utilsImportNode = null;
66
147
  // `path.sep` is the last `path.*` reference in plenty of files, and
67
- // `toForwardSlash(raw)` consumes it — leaving the same dead `node:path`
68
- // binding the `safePath` rules used to leave.
148
+ // `toForwardSlash(raw)` consumes it — leaving a dead `node:path` binding.
69
149
  const pathImportNodes = [];
70
150
 
151
+ /**
152
+ * Add `fn` to the import, when nothing binds it yet.
153
+ *
154
+ * NOT latched: two reports insert identical text at the identical anchor, so
155
+ * ESLint applies one and drops the other as overlapping. Latching is not
156
+ * free — ESLint runs `fix()` for a SUPPRESSED problem before the
157
+ * `eslint-disable` filter discards it, so a latch could be spent by a report
158
+ * that is then thrown away.
159
+ */
160
+ function importFix(fixer, fn) {
161
+ if (bound[fn]) return [];
162
+ if (utilsImportNode) {
163
+ return [fixer.insertTextAfter(utilsImportNode.specifiers.at(-1), `, ${fn}`)];
164
+ }
165
+ const newImport = `import { ${fn} } from '${targetModule}';\n`;
166
+ return [insertAboveWithComments(fixer, sourceCode, sourceCode.ast.body[0], newImport)];
167
+ }
168
+
71
169
  return {
72
170
  'Program:exit'() {
73
171
  reportDeadUnsafeImports(
@@ -83,99 +181,30 @@ module.exports = {
83
181
  if (PATH_MODULES.has(node.source.value)) {
84
182
  pathImportNodes.push(node);
85
183
  }
86
- if (node.source.value === targetModule) {
87
- utilsImportNode = node;
88
- for (const spec of node.specifiers) {
89
- if (spec.type === 'ImportSpecifier' && spec.imported.name === SAFE_FN) {
90
- hasToForwardSlashImport = true;
91
- }
184
+ if (node.source.value !== targetModule) return;
185
+ utilsImportNode = node;
186
+ for (const spec of node.specifiers) {
187
+ if (spec.type === 'ImportSpecifier' && spec.imported.name in bound) {
188
+ bound[spec.imported.name] = true;
92
189
  }
93
190
  }
94
191
  },
95
192
 
96
193
  CallExpression(node) {
97
- if (node.callee.type === 'Identifier' && node.callee.name === SAFE_FN) {
194
+ if (node.callee.type === 'Identifier' && node.callee.name === NATIVE_FN) {
98
195
  safeReplacementCalled = true;
99
196
  }
100
-
101
- // Check for .split(...).join('/') pattern
102
- if (
103
- node.callee.type === 'MemberExpression' &&
104
- node.callee.property.name === 'join' &&
105
- node.arguments.length === 1 &&
106
- node.arguments[0].type === 'Literal' &&
107
- node.arguments[0].value === '/'
108
- ) {
109
- // Check if the object is a .split() call
110
- const splitCall = node.callee.object;
111
- if (
112
- splitCall.type === 'CallExpression' &&
113
- splitCall.callee.type === 'MemberExpression' &&
114
- splitCall.callee.property.name === 'split' &&
115
- splitCall.arguments.length === 1
116
- ) {
117
- const splitArg = splitCall.arguments[0];
118
-
119
- // Split on path.sep, or on a single backslash character
120
- // (source literal '\\'). Splitting on a two-backslash SEQUENCE
121
- // (source literal '\\\\', decoded value: two backslash characters)
122
- // is a different, rarer operation -- e.g. collapsing a UNC path's
123
- // leading double-backslash server prefix -- and toForwardSlash()
124
- // is not equivalent to it. Autofixing that case would silently
125
- // change program behavior, so it is deliberately excluded here.
126
- const isSplittingByPathSep =
127
- (splitArg.type === 'MemberExpression' &&
128
- splitArg.object.name === 'path' &&
129
- splitArg.property.name === 'sep') ||
130
- (splitArg.type === 'Literal' && splitArg.value === '\\');
131
-
132
- if (isSplittingByPathSep) {
133
- const variableBeingSplit = splitCall.callee.object;
134
-
135
- context.report({
136
- node,
137
- messageId: 'useToForwardSlash',
138
- data: { safeModule: targetModule },
139
- fix(fixer) {
140
- const fixes = [];
141
-
142
- // Replace the entire .split(...).join('/') with toForwardSlash(...)
143
- const originalVar = sourceCode.getText(variableBeingSplit);
144
- fixes.push(fixer.replaceText(node, `${SAFE_FN}(${originalVar})`));
145
-
146
- // Add import if needed
147
- if (!hasToForwardSlashImport) {
148
- if (utilsImportNode) {
149
- // Add to existing utils import
150
- const lastSpecifier = utilsImportNode.specifiers.at(-1);
151
- fixes.push(fixer.insertTextAfter(lastSpecifier, `, ${SAFE_FN}`));
152
- } else {
153
- // Create new import at the top
154
- const firstNode = sourceCode.ast.body[0];
155
- const newImport = `import { ${SAFE_FN} } from '${targetModule}';\n`;
156
- fixes.push(insertAboveWithComments(fixer, sourceCode, firstNode, newImport));
157
- }
158
- // NOT latched. The comment here used to claim that without a
159
- // `hasToForwardSlashImport = true` a second occurrence would
160
- // insert the import twice; an adversarial run could not
161
- // reproduce that at any occurrence count. It cannot happen:
162
- // both reports insert identical text at the identical anchor,
163
- // so the ranges coincide and ESLint applies one and drops the
164
- // other as overlapping.
165
- //
166
- // Latching it is not free, either. ESLint runs `fix()` for a
167
- // SUPPRESSED problem before the `eslint-disable` filter
168
- // discards it, so the first report could spend the flag and
169
- // then be thrown away — leaving later occurrences rewritten
170
- // to a `toForwardSlash` nothing imports.
171
- }
172
-
173
- return fixes;
174
- },
175
- });
176
- }
177
- }
178
- }
197
+ const match = matchSplitJoin(node) ?? matchReplace(node);
198
+ if (!match) return;
199
+ context.report({
200
+ node,
201
+ messageId: MESSAGE_FOR[match.fn],
202
+ data: { safeModule: targetModule },
203
+ fix(fixer) {
204
+ const receiver = sourceCode.getText(match.receiver);
205
+ return [fixer.replaceText(node, `${match.fn}(${receiver})`), ...importFix(fixer, match.fn)];
206
+ },
207
+ });
179
208
  },
180
209
  };
181
210
  },
@@ -21,4 +21,12 @@ module.exports = factory({
21
21
  // No baked-in exemption: the file that implements normalizedTmpdir() is
22
22
  // repo-specific. Consumers declare it as { exemptFiles: [...] }.
23
23
  checkMemberExpression: true, // Catch os.tmpdir() pattern
24
+ docs: {
25
+ category: 'Filesystem and process',
26
+ bans: '`os.tmpdir()` (8.3 short names on Windows)',
27
+ useInstead: '`normalizedTmpdir()`',
28
+ subpath: '/fs',
29
+ recommended: true,
30
+ recommendedSeverity: 'error',
31
+ },
24
32
  });