diff --git a/.changeset/node-22-support.md b/.changeset/node-22-support.md new file mode 100644 index 0000000..fa961a5 --- /dev/null +++ b/.changeset/node-22-support.md @@ -0,0 +1,5 @@ +--- +'code-inventory': minor +--- + +Support Node.js 22.12 and newer, down from Node.js 26. diff --git a/.changeset/picomatch-globs.md b/.changeset/picomatch-globs.md new file mode 100644 index 0000000..37bf1f9 --- /dev/null +++ b/.changeset/picomatch-globs.md @@ -0,0 +1,11 @@ +--- +'code-inventory': minor +--- + +Match glob options and npm workspace patterns with [picomatch](https://github.com/micromatch/picomatch), a new dependency, instead of Node's `path.matchesGlob`, so neither the CLI nor the library prints an experimental-feature warning on Node.js versions before 22.20 and 24.8. Most patterns select the same files as before. The differences: + +- `--workspace-entries` and `workspaceEntries()` select member folders as npm does. An exclusion such as `!packages/b` applies wherever it is listed, unless a later pattern that it matches lists the folder again; `!packages/b/**` also excludes `packages/b`; exclusions also apply to dot folders; and `packages/**` also selects `packages` when it has a manifest. +- Glob options (`--exclude`, `--test`, `--tooling`, `--production`, `--entry-glob` and the matching library options) are case-sensitive on every platform. On macOS and Windows, path segments with wildcards or character classes used to ignore case. +- `--exclude`, `--test`, `--tooling` and `--production` accept a leading `./`, as `--entry-glob` already did. +- A pattern also matches a path spelled exactly like it, so `app/[id]/route.ts` selects that file as well as `app/i/route.ts`, and a pattern ending in `/**` also matches the path before it. +- A `!(…)` extglob also rejects names that begin with one of its alternatives, so `src/!(a).ts` no longer matches `src/ab.ts`, and it can match dot files. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11fd5cb..c09c769 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,68 @@ jobs: - run: npm run check - run: npm pack --dry-run --ignore-scripts + # The supported Node.js lines. The checks job above uses the development version in .node-version. + test: + name: Test (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + node: [22, 24, 26] + env: + NODE_OPTIONS: --max-old-space-size=2048 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ matrix.node }} + package-manager-cache: false + - run: npm ci --ignore-scripts --no-audit --fund=false + - run: npm run typecheck + - run: npm run build + - run: npm test + + oldest-node: + name: Tests and packed CLI on Node 22.12.0 + runs-on: ubuntu-latest + timeout-minutes: 10 + env: + NODE_OPTIONS: --max-old-space-size=2048 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # ESLint needs a newer Node.js, so the package is installed, built and packed with the development version. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .node-version + package-manager-cache: false + - run: npm ci --ignore-scripts --no-audit --fund=false + - run: npm run build + - run: npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22.12.0 + package-manager-cache: false + - run: npm test + # The package under test is installed from its tarball, as a user installs it, so no lockfile applies. + - name: Use the packed CLI and library + working-directory: ${{ runner.temp }} + run: | # zizmor: ignore[adhoc-packages] + mkdir app && cd app + npm init --yes > /dev/null + npm install --no-audit --no-fund --ignore-scripts ../code-inventory-*.tgz + printf 'export function normalize(value: string) {\n return value.trim();\n}\n' > text.ts + printf "import { normalize } from './text';\nnormalize(' order ');\n" > app.ts + npx code-inventory . --symbol normalize --format json --exclude 'node_modules/**' > usage.json 2> stderr.txt + if [ -s stderr.txt ]; then cat stderr.txt; exit 1; fi + node -e "const r = require('./usage.json'); process.exit(r.completeness === 'complete' && r.usage.counts.directCallSites === 1 ? 0 : 1)" + node --input-type=module -e "import { scan, usages } from 'code-inventory'; const n = usages(scan('.', { exclude: ['node_modules/**'], scopes: { test: ['**/*.test.ts'] } }), 'normalize').counts.directCallSites; if (n !== 1) process.exit(1); console.log(n)" 2> stderr.txt + if [ -s stderr.txt ]; then cat stderr.txt; exit 1; fi + # actionlint checks the workflow syntax and the shell in each step; zizmor checks them for security problems. workflows: runs-on: ubuntu-latest @@ -62,7 +124,7 @@ jobs: # in `needs`. ci: if: always() - needs: [workflows, checks] + needs: [workflows, checks, test, oldest-node] runs-on: ubuntu-latest timeout-minutes: 5 permissions: diff --git a/AGENTS.md b/AGENTS.md index a727a42..93e37b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,8 +33,8 @@ Notes for coding agents working in this repository. People should read CONTRIBUT exit code 2. Don't throw for them; errors are for invalid options and inputs the scan can't use at all. - Relative imports in `src/` end in `.ts`; the build rewrites them. Type-only imports use `import type`. - `no-console` is on; the CLI writes with `process.stdout.write`. -- The only runtime dependency is the TypeScript 6 compiler under the `typescript` alias. Every dependency is pinned to - an exact version. Ask before adding one, and list it in `THIRD_PARTY.md`. +- The runtime dependencies are the TypeScript 6 compiler under the `typescript` alias and `picomatch`, which matches + glob options. Every dependency is pinned to an exact version. Ask before adding one, and list it in `THIRD_PARTY.md`. - A change users can see updates `README.md` and the matching page in `docs/` in the same pull request. - Changesets: a change that affects users carries one (`npx changeset`). Breaking changes are `minor` before 1.0; never `major`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aec5bc7..46f72bd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -104,8 +104,8 @@ publishes nothing. ## Dependencies Every dependency in `package.json` is pinned to an exact version, so a version changes only in a pull request. Update -them after reading their changelogs, with `npm install --save-exact --ignore-scripts`, and run `npm audit`. The only runtime -dependency is the TypeScript 6 compiler, installed as an npm alias; ask before adding another one. +them after reading their changelogs, with `npm install --save-exact --ignore-scripts`, and run `npm audit`. The runtime +dependencies are the TypeScript 6 compiler, installed as an npm alias, and picomatch; ask before adding another one. When a dependency is added, add it to [THIRD_PARTY.md](THIRD_PARTY.md) with its license. diff --git a/README.md b/README.md index ff39338..6456157 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,14 @@ Find where JavaScript and TypeScript declarations are used. The CLI and library ## Run your first scan -In a JavaScript or TypeScript project with Node.js 26 or newer: +In a JavaScript or TypeScript project with Node.js 22.12 or newer: ```sh npm install --save-dev code-inventory npx code-inventory . ``` -For a checkout of this repository, use the fixture to check how calls are counted. CI uses the version in [.node-version](.node-version). +For a checkout of this repository, use the fixture to check how calls are counted. Development and CI use the version in [.node-version](.node-version); CI also tests Node.js 22.12.0 and the latest 22, 24 and 26. ```sh npm ci --ignore-scripts --no-audit diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index d63fd6c..af64105 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -3,7 +3,8 @@ | Package | License | Source | | -------------------------------------------------- | ---------- | ---------------------------------------------------------------------------------------- | | @typescript/typescript6; its typescript dependency | Apache-2.0 | https://github.com/microsoft/TypeScript | -| @types/node | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped | +| picomatch | MIT | https://github.com/micromatch/picomatch | +| @types/node, @types/picomatch | MIT | https://github.com/DefinitelyTyped/DefinitelyTyped | | undici-types (Node type dependency) | MIT | https://github.com/nodejs/undici | | vitest and its workspace packages | MIT | https://github.com/vitest-dev/vitest | | prettier | MIT | https://github.com/prettier/prettier | @@ -13,6 +14,9 @@ The lockfile records exact versions, integrity hashes and licenses for transitive dependencies. Installation uses `--ignore-scripts`. The optional macOS-only fsevents package declares an install script and is not installed on Linux. +The runtime dependencies are the compiler and picomatch 4.0.7, which matches glob options and has no dependencies of +its own. + The compiler dependency is an npm alias to `@typescript/typescript6@6.0.2`, as documented by Microsoft for tooling that requires the compiler API. That package resolves `typescript@6.0.3` internally. diff --git a/docs/guide.html b/docs/guide.html index 8e8a34f..1e66b2a 100644 --- a/docs/guide.html +++ b/docs/guide.html @@ -44,7 +44,8 @@

Your first scan

Build from source

Clone the code-inventory repository and open its root - directory. The examples use the compiled files in your checkout. Use Node.js 26 or newer. CI pins 26.13.1. + directory. The examples use the compiled files in your checkout. Use Node.js 22.12 or newer. Development and + the full set of checks use the version in .node-version, 26.13.1.

npm ci --ignore-scripts --no-audit
 npm run build
diff --git a/docs/reference.html b/docs/reference.html index e7cc52f..90931aa 100644 --- a/docs/reference.html +++ b/docs/reference.html @@ -43,7 +43,11 @@

CLI options

node dist/cli.js [directory] [options]

The directory defaults to the current working directory. Quote globs so the scanner receives the pattern - directly. + directly. Globs match slash-separated paths relative to the scan root, case-sensitively on every platform. + * and ** skip dot files and folders unless the pattern names them, as in + .config/**. Braces such as {a,b}, extglobs such as @(a|b) and character + classes work; other parentheses are literal, so 'app/(marketing)/**' selects a Next.js route + group.

--project config
@@ -76,8 +80,10 @@

CLI options

--workspace-entries
- Read the root and member manifests matched by the root npm workspaces array. Each entry origin lists the - manifest, field and analyzed file. Use --project for any required compiler output mapping. + Read the root and member manifests matched by the root npm workspaces array, selecting member folders as npm + does: * and ** skip dot folders unless a pattern names them, and a pattern + starting with ! excludes the folders it matches. Each entry origin lists the manifest, field + and analyzed file. Use --project for any required compiler output mapping.
--next-routes
diff --git a/package-lock.json b/package-lock.json index a253bf1..de13809 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.4.0", "license": "MIT", "dependencies": { + "picomatch": "4.0.7", "typescript": "npm:@typescript/typescript6@6.0.2" }, "bin": { @@ -17,7 +18,8 @@ "devDependencies": { "@changesets/changelog-github": "2.0.0", "@changesets/cli": "3.1.0", - "@types/node": "26.6.11", + "@types/node": "22.12.0", + "@types/picomatch": "4.0.3", "ajv": "8.20.0", "eslint": "10.16.0", "prettier": "3.10.1", @@ -25,7 +27,7 @@ "vitest": "5.1.2" }, "engines": { - "node": ">=26" + "node": ">=22.12" } }, "node_modules/@cacheable/memory": { @@ -1080,15 +1082,22 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.6.11", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", - "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==", + "version": "22.12.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.12.0.tgz", + "integrity": "sha512-Fll2FZ1riMjNmlmJOdAyY5pUbkftXslB5DgEzlIuNaiWhXd00FhWxVC/r4yV/4wBb9JfImTu+jiSvXTkJ7F/gA==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~8.9.0" + "undici-types": "~6.20.0" } }, + "node_modules/@types/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-iG0T6+nYJ9FAPmx9SsUlnwcq1ZVRuCXcVEvWnntoPlrOpwtSTKNDC9uVAxTsC3PUvJ+99n4RpAcNgBbHX3JSnQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.74.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.74.0.tgz", @@ -2537,7 +2546,6 @@ "version": "4.0.7", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -2865,9 +2873,9 @@ } }, "node_modules/undici-types": { - "version": "8.9.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", - "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", "dev": true, "license": "MIT" }, diff --git a/package.json b/package.json index 78f7745..cc04860 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "cli" ], "engines": { - "node": ">=26" + "node": ">=22.12" }, "exports": { ".": { @@ -51,12 +51,14 @@ "changeset": "changeset" }, "dependencies": { + "picomatch": "4.0.7", "typescript": "npm:@typescript/typescript6@6.0.2" }, "devDependencies": { "@changesets/changelog-github": "2.0.0", "@changesets/cli": "3.1.0", - "@types/node": "26.6.11", + "@types/node": "22.12.0", + "@types/picomatch": "4.0.3", "ajv": "8.20.0", "eslint": "10.16.0", "prettier": "3.10.1", diff --git a/src/globs.ts b/src/globs.ts new file mode 100644 index 0000000..b2c53f8 --- /dev/null +++ b/src/globs.ts @@ -0,0 +1,37 @@ +import { posix } from 'node:path'; +import picomatch from 'picomatch/posix.js'; + +/** + * Rewrite a glob option for picomatch so that it keeps the syntax the options have always had: a backslash separates + * path segments like a slash, `.` and `..` segments and repeated slashes are normalized, and parentheses, `|` and + * double quotes are literal characters except in extglobs such as `@(a|b)`. + */ +function picomatchGlob(pattern: string): string { + const normalized = posix.normalize(pattern.replaceAll('\\', '/')); + const groups: boolean[] = []; + let glob = ''; + for (let index = 0; index < normalized.length; index++) { + const character = normalized[index]!; + if (character === '(') { + const extglob = index > 0 && '@!+*?'.includes(normalized[index - 1]!); + groups.push(extglob); + glob += extglob ? character : '\\('; + } else if (character === ')') glob += groups.pop() ? character : '\\)'; + else if (character === '|') glob += groups.at(-1) ? character : '\\|'; + else if (character === '"') glob += '\\"'; + else glob += character; + } + return glob; +} + +/** + * Match slash-separated paths relative to the scan root against glob options. Matching is case-sensitive on every + * platform, `*` and `**` skip dot files and folders unless the pattern names them, and a leading `!` is part of the + * name rather than a negation. An empty pattern matches nothing. + */ +export function globMatcher(patterns: readonly string[]): (path: string) => boolean { + const globs = patterns.filter((pattern) => pattern !== '').map(picomatchGlob); + if (!globs.length) return () => false; + const isMatch = picomatch(globs, { nonegate: true, posix: true }); + return (path) => isMatch(path); +} diff --git a/src/package-entries.ts b/src/package-entries.ts index f6784e2..6855357 100644 --- a/src/package-entries.ts +++ b/src/package-entries.ts @@ -4,6 +4,7 @@ import { loadProjects } from './projects.ts'; import { discover, portablePath } from './discovery.ts'; import { readFileSync } from 'node:fs'; import { resolve, posix } from 'node:path'; +import picomatch from 'picomatch/posix.js'; /** Node substitutes the same nonempty subpath for every star in a target, including across directories. */ function capture(parts: string[], path: string): string | null { @@ -61,18 +62,11 @@ export function workspaceEntries(directory: string, inventory: Inventory): Entry } const entries = manifestEntries(directory, inventory, '', true); const manifests = discover(directory, (name) => name === 'package.json').map((path) => portablePath(directory, path)); + const selected = workspaceMatcher(patterns); for (const manifest of manifests) { if (manifest === 'package.json') continue; const member = posix.dirname(manifest); - const selected = patterns.reduce((included: boolean, pattern: string) => { - const prefix = pattern.match(/^!*/)?.[0].length ?? 0; - const glob = pattern - .slice(prefix) - .replace(/^\.?\/+/, '') - .replace(/\/+$/, ''); - return posix.matchesGlob(member, glob) ? prefix % 2 === 0 : included; - }, false); - if (selected) { + if (selected(member)) { entries.push(...manifestEntries(directory, inventory, member, true)); } } @@ -80,6 +74,37 @@ export function workspaceEntries(directory: string, inventory: Inventory): Entry return entries; } +/** + * Select workspace folders as npm does (@npmcli/map-workspaces). A pattern with an odd number of leading `!` excludes + * the folders it matches, including dot folders. An including pattern cancels the exclusions listed before it that + * match the pattern itself. Including patterns match folders, and their `*` and `**` skip dot folders unless the + * pattern names them. + */ +function workspaceMatcher(patterns: readonly string[]): (member: string) => boolean { + let excluded: string[] = []; + let included: string[] = []; + for (const entry of patterns) { + const bangs = entry.length - entry.replace(/^!+/, '').length; + const pattern = entry.slice(bangs).replace(/^\.?\/+/, ''); + if (!pattern) continue; + if (bangs % 2 === 1) excluded.push(pattern); + else { + excluded = excluded.filter((exclusion) => !picomatch(exclusion, { posix: true })(pattern)); + included.push(pattern); + } + } + for (const exclusion of excluded) { + included = included.filter((pattern) => !picomatch(exclusion, { posix: true })(pattern)); + } + if (!included.length) return () => false; + const include = picomatch( + included.map((pattern) => pattern.replaceAll('\\', '/').replace(/\/+$/, '')), + { posix: true }, + ); + const exclude = excluded.length ? picomatch(excluded, { dot: true, posix: true }) : () => false; + return (member) => include(member) && !exclude(member) && !exclude(member + '/'); +} + function manifestEntries(directory: string, inventory: Inventory, member: string, allowEmpty: boolean): EntryOrigin[] { const manifestPath = posix.join(member, 'package.json'); const manifest = JSON.parse(readFileSync(resolve(directory, manifestPath), 'utf8')); diff --git a/src/projects.ts b/src/projects.ts index e8cff99..7e05bb3 100644 --- a/src/projects.ts +++ b/src/projects.ts @@ -1,7 +1,8 @@ import ts from 'typescript'; import { existsSync } from 'node:fs'; -import { dirname, posix, resolve } from 'node:path'; +import { dirname, resolve } from 'node:path'; import { compare, hashFile, portablePath, scopeOf } from './discovery.ts'; +import { globMatcher } from './globs.ts'; import type { Scope } from './model.ts'; export interface ScanOptions { @@ -18,13 +19,15 @@ export interface Project { } export function fileRules(options: ScanOptions) { - const matches = (file: string, patterns: readonly string[] = []) => - patterns.some((pattern) => posix.matchesGlob(file, pattern)); + const excluded = globMatcher(options.exclude ?? []); + const scopes = (['test', 'tooling', 'production'] as const).map( + (scope) => [scope, globMatcher(options.scopes?.[scope] ?? [])] as const, + ); return { - excluded: (file: string) => matches(file, options.exclude), + excluded, scope(file: string): Scope { - for (const scope of ['test', 'tooling', 'production'] as const) { - if (matches(file, options.scopes?.[scope])) return scope; + for (const [scope, matches] of scopes) { + if (matches(file)) return scope; } return scopeOf(file); }, diff --git a/src/reachability.ts b/src/reachability.ts index 00ed918..01ea5ba 100644 --- a/src/reachability.ts +++ b/src/reachability.ts @@ -1,4 +1,5 @@ import { posix } from 'node:path'; +import { globMatcher } from './globs.ts'; import type { EntryOrigin } from './package-entries.ts'; import { selectSymbol } from './query.ts'; import type { CodeSymbol, Inventory, Location, ModuleReference } from './model.ts'; @@ -33,8 +34,7 @@ export function reachability( const selected = new Set(files.map((file) => posix.normalize(file))); const analyzed = new Set(inventory.files.filter((file) => file.status === 'analyzed').map((file) => file.path)); for (const glob of options.entryGlobs ?? []) { - const pattern = glob.replace(/^\.\//, ''); - const matches = [...analyzed].filter((file) => posix.matchesGlob(file, pattern)); + const matches = [...analyzed].filter(globMatcher([glob])); if (!matches.length) throw new Error('No analyzed entry files match: ' + glob); for (const file of matches) selected.add(file); } diff --git a/test/entry-discovery.test.ts b/test/entry-discovery.test.ts index 7a18709..3c0b92e 100644 --- a/test/entry-discovery.test.ts +++ b/test/entry-discovery.test.ts @@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { expect, it, onTestFinished } from 'vitest'; +import { scan, workspaceEntries } from '../src/index.ts'; it('reports workspace manifest origins and scopes HTTP handler invocations to each route', () => { const root = mkdtempSync(join(tmpdir(), 'workspace-entries-')); @@ -46,3 +47,35 @@ it('reports workspace manifest origins and scopes HTTP handler invocations to ea .sort(), ).toEqual(['GET', 'GET', 'one', 'serve', 'two']); }); + +it('selects workspace folders as npm does, including dot folders and exclusions', () => { + const root = mkdtempSync(join(tmpdir(), 'workspace-globs-')); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + for (const member of ['packages/a', 'packages/b', 'packages/b/nested', 'packages/.hidden']) { + mkdirSync(join(root, member), { recursive: true }); + writeFileSync(join(root, member, 'package.json'), JSON.stringify({ main: './index.ts' })); + writeFileSync(join(root, member, 'index.ts'), 'export const value = 1;\n'); + } + writeFileSync(join(root, 'root.ts'), 'export const value = 1;\n'); + const inventory = scan(root); + const members = (workspaces: string[]) => { + writeFileSync(join(root, 'package.json'), JSON.stringify({ main: './root.ts', workspaces })); + return workspaceEntries(root, inventory) + .map((origin) => dirname(origin.manifest)) + .filter((member) => member !== '.') + .sort(); + }; + expect(members(['packages/*'])).toEqual(['packages/a', 'packages/b']); + expect(members(['packages/**'])).toEqual(['packages/a', 'packages/b', 'packages/b/nested']); + expect(members(['packages/.*'])).toEqual(['packages/.hidden']); + expect(members(['packages/{a,b}', '!!packages/.hidden'])).toEqual(['packages/.hidden', 'packages/a', 'packages/b']); + expect(members(['./packages/*/', '!/packages/b'])).toEqual(['packages/a']); + expect(members(['packages/**', '!packages/b'])).toEqual(['packages/a', 'packages/b/nested']); + // A later pattern that an exclusion matches cancels the exclusion. + expect(members(['packages/*', '!packages/b', 'packages/b'])).toEqual(['packages/a', 'packages/b']); + expect(members(['packages/*', '!packages/*', 'packages/a'])).toEqual(['packages/a', 'packages/b']); + // Otherwise an exclusion applies wherever it is listed, and to dot folders too. + expect(members(['!packages/b', 'packages/*'])).toEqual(['packages/a']); + expect(members(['packages/**', '!packages/b/**'])).toEqual(['packages/a']); + expect(members(['packages/.*', '!packages/*'])).toEqual([]); +}); diff --git a/test/globs.test.ts b/test/globs.test.ts new file mode 100644 index 0000000..1bc4f06 --- /dev/null +++ b/test/globs.test.ts @@ -0,0 +1,131 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { afterAll, expect, it, onTestFinished } from 'vitest'; +import { reachability, scan, workspaceEntries } from '../src/index.ts'; + +function project(prefix: string, files: Record): string { + const root = mkdtempSync(join(tmpdir(), prefix)); + for (const [path, content] of Object.entries(files)) { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), content); + } + return root; +} + +const sources = [ + '.eslintrc.ts', + '.config/c.ts', + 'app/(marketing)/page/route.ts', + 'app/[id]/route.ts', + 'src/.hidden/h.ts', + 'src/a.test.ts', + 'src/a.ts', + 'src/b.ts', + 'src/deep/x/d.ts', +]; +const root = project( + 'globs-', + Object.fromEntries(sources.map((path, index) => [path, `export function f${index}() {}\n`])), +); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +const excluded = (...exclude: string[]) => + scan(root, { exclude }) + .files.filter((file) => file.reason === 'scan-exclude') + .map((file) => file.path) + .sort(); + +it('skips dot files and folders in glob options unless the pattern names them', () => { + const visible = [ + 'app/(marketing)/page/route.ts', + 'app/[id]/route.ts', + 'src/a.test.ts', + 'src/a.ts', + 'src/b.ts', + 'src/deep/x/d.ts', + ]; + expect(excluded('**')).toEqual(visible); + expect(excluded('**/*.ts')).toEqual(visible); + expect(excluded('*')).toEqual([]); + expect(excluded('src/**')).toEqual(['src/a.test.ts', 'src/a.ts', 'src/b.ts', 'src/deep/x/d.ts']); + expect(excluded('src/.hidden/**', '.config/*')).toEqual(['.config/c.ts', 'src/.hidden/h.ts']); + expect(excluded('**/.*')).toEqual(['.eslintrc.ts']); + expect(excluded('**/.*/**')).toEqual(['.config/c.ts', 'src/.hidden/h.ts']); + expect(excluded('.*.ts', 'src/{a,.hidden/h}.ts')).toEqual(['.eslintrc.ts', 'src/.hidden/h.ts', 'src/a.ts']); +}); + +it('supports globstars, braces, extglobs and character classes in glob options', () => { + expect(excluded('src/**/*.ts')).toEqual(['src/a.test.ts', 'src/a.ts', 'src/b.ts', 'src/deep/x/d.ts']); + expect(excluded('src/deep/**/d.ts', '**/x/*')).toEqual(['src/deep/x/d.ts']); + expect(excluded('src/{a,b}.ts')).toEqual(['src/a.ts', 'src/b.ts']); + expect(excluded('src/*.{test,spec}.ts')).toEqual(['src/a.test.ts']); + expect(excluded('src/@(a|b).ts')).toEqual(['src/a.ts', 'src/b.ts']); + expect(excluded('src/!(*.test).ts')).toEqual(['src/a.ts', 'src/b.ts']); + expect(excluded('src/[!a].ts', 'src/?.test.ts')).toEqual(['src/a.test.ts', 'src/b.ts']); +}); + +it('reads parentheses, pipes, backslashes and a leading ! in glob options literally', () => { + expect(excluded('app/(marketing)/**')).toEqual(['app/(marketing)/page/route.ts']); + expect(excluded('app/[[]id]/route.ts')).toEqual(['app/[id]/route.ts']); + expect(excluded('src/a.ts|src/b.ts')).toEqual([]); + expect(excluded('!src/a.ts')).toEqual([]); + expect(excluded('src\\a.ts', 'src//b.ts', 'src/./deep/../a.test.ts')).toEqual([ + 'src/a.test.ts', + 'src/a.ts', + 'src/b.ts', + ]); + expect(excluded('')).toEqual([]); +}); + +it('matches glob options case-sensitively and accepts a leading ./', () => { + expect(excluded('SRC/*.ts', 'src/[A-B].ts', 'src/@(A).ts')).toEqual([]); + expect(excluded('./src/*.ts')).toEqual(['src/a.test.ts', 'src/a.ts', 'src/b.ts']); +}); + +it('assigns scopes and entry files with glob options', () => { + const inventory = scan(root, { scopes: { test: ['.config/**'], tooling: ['src/**/*.test.ts'] } }); + const scopes = Object.fromEntries(inventory.symbols.map((symbol) => [symbol.location.file, symbol.scope])); + expect(scopes['.config/c.ts']).toBe('test'); + expect(scopes['src/a.test.ts']).toBe('tooling'); + expect(scopes['src/a.ts']).toBe('production'); + const report = reachability(inventory, [], { entryGlobs: ['app/(marketing)/**/route.ts', './src/{a,b}.ts'] }); + expect(report.entries).toEqual(['app/(marketing)/page/route.ts', 'src/a.ts', 'src/b.ts']); + expect(() => reachability(inventory, [], { entryGlobs: ['src/**/.*.ts'] })).toThrow( + 'No analyzed entry files match: src/**/.*.ts', + ); +}); + +it('prints no warnings from the library or the CLI when glob options are used', () => { + const workspaces = project('globs-workspaces-', { + 'package.json': JSON.stringify({ private: true, workspaces: ['packages/*', '!packages/b'] }), + 'packages/a/package.json': JSON.stringify({ main: './index.ts' }), + 'packages/a/index.ts': 'export function a() {}\n', + 'packages/b/package.json': JSON.stringify({ main: './index.ts' }), + 'packages/b/index.ts': 'export function b() {}\n', + }); + onTestFinished(() => rmSync(workspaces, { recursive: true, force: true })); + const library = resolve(import.meta.dirname, '../dist/index.js'); + const script = ` + import { reachability, scan, workspaceEntries } from ${JSON.stringify(library)}; + const inventory = scan(process.argv[1], { exclude: ['src/b.ts'], scopes: { test: ['**/*.test.ts'] } }); + reachability(inventory, [], { entryGlobs: ['src/*.ts'] }); + const entries = workspaceEntries(process.argv[2], scan(process.argv[2])).map((origin) => origin.file); + process.stdout.write(JSON.stringify(entries)); + `; + const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, root, workspaces], { + encoding: 'utf8', + }); + expect(result.stderr).toBe(''); + expect(JSON.parse(result.stdout)).toEqual(['packages/a/index.ts']); + expect(workspaceEntries(workspaces, scan(workspaces)).map((origin) => origin.file)).toEqual(['packages/a/index.ts']); + + const cli = spawnSync( + process.execPath, + [resolve(import.meta.dirname, '../dist/cli.js'), root, '--exclude', 'src/b.ts', '--entry-glob', 'src/*.ts'], + { encoding: 'utf8' }, + ); + expect(cli.stderr).toBe(''); + expect(cli.status).toBe(0); +});