CodeSampleX

Пример

minimatch 10.1.1: Filter array pathnames using minimatch glob predicates, proving root-only versus matchBase basename matching, dotfile filtering, negation handling, and scoped defaults

Проверенный пример — npm minimatch 10.1.1: Filter array pathnames using minimatch glob predicates, proving root-only versus matchBase basename matching…

sha256:4d7c0d2763c2de4390c58168cd07dabcf9855ad43ceccb6d4682d673df5f82a3

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда node linux x64 node node npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Кейс

HOW
Цель
Filter array pathnames using minimatch glob predicates, proving root-only versus matchBase basename matching, dotfile filtering, negation handling, and scoped defaults
Пакеты
Символы
  • minimatch.filter
Окружение
node
Создан
2026-08-18T01:25:55Z

Контракт

  1. minimatch.filter generates a curried predicate function for Array.prototype.filter where slashless patterns match root paths by default and match base filenames across directories when matchBase is enabled
  2. assert globstar pattern matches nested files across arbitrary directory depths
  3. assert dotfiles are excluded by default wildcard filters and included when dot is set to true
  4. assert negated patterns filter out matches unless nonegate is enabled to treat exclamation marks literally
  5. assert nocase enables case-insensitive pattern matching against file paths
  6. assert minimatch.defaults binds configuration options to subsequent filter calls

Файлы

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Minimatch 10.1.1 Filter Behavior

## Search and Prior Art

Querying known network solutions returned sample `sha256:585ab2a8ea43909cb7e47145ba967133e7da688e33baa7e055319539c3675105`, which demonstrated general glob matching features across brace expansion, partial matching, and Windows path escaping. This sample targets the behavior, options, and edge cases of `minimatch.filter`.

## Pinned Release

- Package: `minimatch`
- Version: `10.1.1`

## Observed Behavior

`minimatch.filter(pattern, options)` returns a curried predicate function `(p) => boolean` designed to be passed directly to `Array.prototype.filter()`.

1. **Root Matching vs Basename Matching (`matchBase`)**:
   - A pattern without slashes (such as `*.css`) only matches filenames located at the root level (e.g. `styles.css`).
   - If a caller expects a slashless pattern to match nested paths like `src/styles.css`, filtering will silently omit those paths.
   - Enabling `{ matchBase: true }` allows slashless patterns to match against the base filename of nested paths.

2. **Recursive Globstar Matching**:
   - Multi-level directory paths match recursive globstar patterns (such as `**/*.tsx`).

3. **Dotfile Handling (`dot`)**:
   - By default (`dot: false`), wildcard patterns like `*` ignore dotfiles (such as `.env` or `.eslintrc.json`).
   - Specifying `{ dot: true }` includes dotfiles in matching results.

4. **Negation Patterns (`nonegate`)**:
   - Patterns prefixed with `!` act as negations, excluding paths that match the underlying pattern.
   - Setting `{ nonegate: true }` suppresses negation logic and matches literal leading exclamation marks.

5. **Case Sensitivity (`nocase`)**:
   - Glob matching is case-sensitive by default.
   - Passing `{ nocase: true }` enables case-insensitive comparisons against pathnames.

6. **Scoped Defaults (`minimatch.defaults`)**:
   - `minimatch.defaults(options)` creates a scoped instance that applies preset options to all derived `filter()` invocations.
csx.json
{"case":{"believed":"slashless glob patterns match file basenames at any directory depth when filtering path arrays","caseId":"case:sha256:f140cbddfada225a44acae5f9e199245adea3be25039618a3893a140bb0e9040","contract":["minimatch.filter generates a curried predicate function for Array.prototype.filter where slashless patterns match root paths by default and match base filenames across directories when matchBase is enabled","assert globstar pattern matches nested files across arbitrary directory depths","assert dotfiles are excluded by default wildcard filters and included when dot is set to true","assert negated patterns filter out matches unless nonegate is enabled to treat exclamation marks literally","assert nocase enables case-insensitive pattern matching against file paths","assert minimatch.defaults binds configuration options to subsequent filter calls"],"goal":"Filter array pathnames using minimatch glob predicates, proving root-only versus matchBase basename matching, dotfile filtering, negation handling, and scoped defaults","kind":"HOW","packages":["pkg:npm/minimatch@10.1.1"],"schemaVersion":1,"symbols":["minimatch.filter"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/minimatch@10.1.1"],"schemaVersion":1,"symbols":["minimatch.filter"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "minimatch-filter-contract",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "minimatch-filter-contract",
      "version": "1.0.0",
      "dependencies": {
        "minimatch": "10.1.1"
      }
    },
    "node_modules/@isaacs/balanced-match": {
      "version": "4.0.1",
      "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz",
      "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==",
      "license": "MIT",
      "engines": {
        "node": "20 || >=22"
      }
    },
    "node_modules/@isaacs/brace-expansion": {
      "version": "5.0.1",
      "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.1.tgz",
      "integrity": "sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==",
      "license": "MIT",
      "dependencies": {
        "@isaacs/balanced-match": "^4.0.1"
      },
      "engines": {
        "node": "20 || >=22"
      }
    },
    "node_modules/minimatch": {
      "version": "10.1.1",
      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.1.1.tgz",
      "integrity": "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==",
      "license": "BlueOak-1.0.0",
      "dependencies": {
        "@isaacs/brace-expansion": "^5.0.0"
      },
      "engines": {
        "node": "20 || >=22"
      },
      "funding": {
        "url": "https://github.com/sponsors/isaacs"
      }
    }
  }
}
package.json
{
  "name": "minimatch-filter-contract",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "minimatch": "10.1.1"
  }
}
src/index.mjs
import { minimatch, filter, defaults } from 'minimatch';

/**
 * Creates a reusable filter predicate for array filtering.
 * @param {string} pattern Glob pattern
 * @param {import('minimatch').MinimatchOptions} [options]
 * @returns {(p: string) => boolean}
 */
export function createGlobFilter(pattern, options) {
  return minimatch.filter(pattern, options);
}

/**
 * Filters a list of file paths using a minimatch glob pattern.
 * @param {string[]} paths
 * @param {string} pattern
 * @param {import('minimatch').MinimatchOptions} [options]
 * @returns {string[]}
 */
export function filterPaths(paths, pattern, options) {
  return paths.filter(filter(pattern, options));
}

/**
 * Creates a scoped minimatch instance with default options and filters paths.
 * @param {string[]} paths
 * @param {import('minimatch').MinimatchOptions} defaultOpts
 * @param {string} pattern
 * @param {import('minimatch').MinimatchOptions} [options]
 * @returns {string[]}
 */
export function filterWithDefaults(paths, defaultOpts, pattern, options) {
  const scopedMinimatch = defaults(defaultOpts);
  return paths.filter(scopedMinimatch.filter(pattern, options));
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { minimatch, filter } from 'minimatch';
import { createGlobFilter, filterPaths, filterWithDefaults } from '../src/index.mjs';

const samplePaths = [
  'config.json',
  'styles.css',
  'src/app.js',
  'src/app.test.js',
  'src/styles.css',
  'src/components/button.tsx',
  '.env',
  '.eslintrc.json',
  '!special.txt'
];

// 1. Export identity and curried predicate function
assert.strictEqual(typeof minimatch.filter, 'function');
assert.strictEqual(filter, minimatch.filter);

const isCssPredicate = createGlobFilter('*.css');
assert.strictEqual(typeof isCssPredicate, 'function');

// 2. Slashless pattern: matches root-level files only by default, matches nested basenames with matchBase: true
const rootCssOnly = filterPaths(samplePaths, '*.css');
assert.deepStrictEqual(rootCssOnly, ['styles.css']);

const allCssWithMatchBase = filterPaths(samplePaths, '*.css', { matchBase: true });
assert.deepStrictEqual(allCssWithMatchBase, ['styles.css', 'src/styles.css']);

// 3. Globstar matching across arbitrary directory depths
const tsxFiles = filterPaths(samplePaths, '**/*.tsx');
assert.deepStrictEqual(tsxFiles, ['src/components/button.tsx']);

// 4. Dotfile handling: dot: false excludes hidden files; dot: true includes them
const nonDotFiles = filterPaths(samplePaths, '*');
assert.deepStrictEqual(nonDotFiles, ['config.json', 'styles.css', '!special.txt']);

const allFilesWithDot = filterPaths(samplePaths, '*', { dot: true });
assert.deepStrictEqual(allFilesWithDot, ['config.json', 'styles.css', '.env', '.eslintrc.json', '!special.txt']);

// 5. Negation and nonegate option
const nonTestFiles = filterPaths(samplePaths, '!*.test.js', { matchBase: true });
assert.deepStrictEqual(nonTestFiles, [
  'config.json',
  'styles.css',
  'src/app.js',
  'src/styles.css',
  'src/components/button.tsx',
  '.env',
  '.eslintrc.json',
  '!special.txt'
]);

const literalExclamation = filterPaths(samplePaths, '!*.txt', { nonegate: true });
assert.deepStrictEqual(literalExclamation, ['!special.txt']);

// 6. Case sensitivity: case-sensitive by default, case-insensitive with nocase: true
const upperCaseMiss = filterPaths(samplePaths, '*.JSON');
assert.deepStrictEqual(upperCaseMiss, []);

const upperCaseHit = filterPaths(samplePaths, '*.JSON', { nocase: true });
assert.deepStrictEqual(upperCaseHit, ['config.json']);

// 7. Scoped minimatch defaults
const scopedResults = filterWithDefaults(
  samplePaths,
  { matchBase: true, nocase: true },
  '*.TSX'
);
assert.deepStrictEqual(scopedResults, ['src/components/button.tsx']);

console.log('CONTRACT PASS: minimatch.filter proved correct glob filtering behavior');

Исходный сидер

csx-seed