CodeSampleX

Exemplo

minimatch 10.1.1: Match file paths using glob patterns with minimatch

Amostra verificada para npm minimatch 10.1.1: Match file paths using glob patterns with minimatch. O contrato rodou em node 22 · linux alpine/x64 · docker e…

sha256:1c7f0ddd7b6df1f79f1d2956e72a8b519747b695745a34fb956234062291ae1d

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Caso

HOW
Objetivo
Match file paths using glob patterns with minimatch
Pacotes
Símbolos
  • minimatch
Ambiente
node 22.23.2
Criado
2026-08-20T12:00:01Z

Contrato

  1. minimatch matches file paths against glob patterns with standard wildcard, globstar, and negation support
  2. minimatch match filters an array of file paths matching glob patterns and supports nonull fallback
  3. minimatch filter generates a predicate function for Array.prototype.filter with options
  4. minimatch braceExpand expands brace pattern expressions into individual glob strings
  5. minimatch escape and unescape handle special glob characters for literal matching
  6. minimatch Minimatch instance compiles and tests glob patterns and exposes AST and makeRe regex generation

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.js

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Match file paths using glob patterns with minimatch
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/minimatch@10.1.1
Demonstrate these symbols/APIs:
  - minimatch
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:64956892d83cc2055d4fb4e4a0c8ddb8121f5e4362c324f00039bb8cf9401667","constraints":{"executionContext":"node"},"contract":["minimatch matches file paths against glob patterns with standard wildcard, globstar, and negation support","minimatch match filters an array of file paths matching glob patterns and supports nonull fallback","minimatch filter generates a predicate function for Array.prototype.filter with options","minimatch braceExpand expands brace pattern expressions into individual glob strings","minimatch escape and unescape handle special glob characters for literal matching","minimatch Minimatch instance compiles and tests glob patterns and exposes AST and makeRe regex generation"],"goal":"Match file paths using glob patterns with minimatch","kind":"HOW","packages":["pkg:npm/minimatch@10.1.1"],"schemaVersion":1,"symbols":["minimatch"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/minimatch@10.1.1"],"schemaVersion":1,"symbols":["minimatch"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "minimatch-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "minimatch-sample",
      "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"
      }
    }
  }
}
package.json
{
  "name": "minimatch-sample",
  "version": "1.0.0",
  "dependencies": {
    "minimatch": "10.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Match file paths using glob patterns with minimatch",
  "kind": "HOW",
  "packages": [
    "pkg:npm/minimatch@10.1.1"
  ],
  "symbols": [
    "minimatch"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const {
  minimatch,
  Minimatch,
  filter,
  match,
  braceExpand,
  makeRe,
  escape,
  unescape,
} = require('minimatch');

/**
 * Tests whether a given file path matches a glob pattern.
 *
 * @param {string} p - File path to test.
 * @param {string} pattern - Glob pattern.
 * @param {object} [options] - Minimatch options.
 * @returns {boolean} True if the path matches the pattern.
 */
function matchPath(p, pattern, options) {
  return minimatch(p, pattern, options);
}

/**
 * Filters an array of file paths returning only those that match the pattern.
 *
 * @param {string[]} list - List of paths.
 * @param {string} pattern - Glob pattern.
 * @param {object} [options] - Minimatch options.
 * @returns {string[]} Filtered matching paths.
 */
function matchPaths(list, pattern, options) {
  return match(list, pattern, options);
}

/**
 * Creates a filter predicate function for Array.prototype.filter.
 *
 * @param {string} pattern - Glob pattern.
 * @param {object} [options] - Minimatch options.
 * @returns {Function} Predicate function.
 */
function createPathFilter(pattern, options) {
  return filter(pattern, options);
}

/**
 * Expands brace expressions in a glob pattern into an array of distinct patterns.
 *
 * @param {string} pattern - Glob pattern with braces.
 * @param {object} [options] - Minimatch options.
 * @returns {string[]} Array of expanded pattern strings.
 */
function expandBracePattern(pattern, options) {
  return braceExpand(pattern, options);
}

/**
 * Escapes special glob characters in a path for literal pattern matching.
 *
 * @param {string} str - String to escape.
 * @returns {string} Escaped string.
 */
function escapeGlob(str) {
  return escape(str);
}

/**
 * Unescapes glob characters escaped by escapeGlob.
 *
 * @param {string} str - Escaped string to restore.
 * @returns {string} Unescaped string.
 */
function unescapeGlob(str) {
  return unescape(str);
}

/**
 * Compiles a glob pattern into a regular expression.
 *
 * @param {string} pattern - Glob pattern.
 * @param {object} [options] - Minimatch options.
 * @returns {RegExp|false} Generated regular expression.
 */
function patternToRegExp(pattern, options) {
  return makeRe(pattern, options);
}

/**
 * Creates a Minimatch instance for compiled pattern matching.
 *
 * @param {string} pattern - Glob pattern.
 * @param {object} [options] - Minimatch options.
 * @returns {Minimatch} Minimatch compiled instance.
 */
function createMinimatch(pattern, options) {
  return new Minimatch(pattern, options);
}

module.exports = {
  matchPath,
  matchPaths,
  createPathFilter,
  expandBracePattern,
  escapeGlob,
  unescapeGlob,
  patternToRegExp,
  createMinimatch,
  minimatch,
  Minimatch,
  filter,
  match,
  braceExpand,
  makeRe,
  escape,
  unescape,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  matchPath,
  matchPaths,
  createPathFilter,
  expandBracePattern,
  escapeGlob,
  unescapeGlob,
  patternToRegExp,
  createMinimatch,
  minimatch,
  Minimatch,
  filter,
  match,
  braceExpand,
  makeRe,
  escape,
  unescape,
} = require('../src/index.js');

// Contract 1: minimatch matches file paths against glob patterns with standard wildcard, globstar, and negation support
{
  assert.strictEqual(matchPath('src/index.js', '*.js'), false, 'Direct wildcard does not cross directory separators without globstar');
  assert.strictEqual(matchPath('index.js', '*.js'), true, 'Direct wildcard matches root filename');
  assert.strictEqual(matchPath('src/utils/helper.js', 'src/**/*.js'), true, 'Globstar matches arbitrary nested subdirectories');
  assert.strictEqual(matchPath('src/utils/helper.ts', 'src/**/*.js'), false, 'Rejects files with non-matching extensions');
  assert.strictEqual(matchPath('config/app.json', '!config/**/*.yaml'), true, 'Negation pattern accepts non-matching negative target');
  assert.strictEqual(matchPath('config/app.yaml', '!config/**/*.yaml'), false, 'Negation pattern rejects matching negative target');
  assert.strictEqual(matchPath('src/components/Button.jsx', '*.jsx', { matchBase: true }), true, 'matchBase enables basename matching without path prefix');
}

// Contract 2: minimatch match filters an array of file paths matching glob patterns and supports nonull fallback
{
  const fileList = ['server.js', 'client.ts', 'helper.js', 'style.css'];
  const jsFiles = matchPaths(fileList, '*.js');
  assert.deepStrictEqual(jsFiles, ['server.js', 'helper.js'], 'Filters only matching javascript files');

  const emptyMatches = matchPaths(fileList, '*.vue', { nonull: false });
  assert.deepStrictEqual(emptyMatches, [], 'Returns empty array when no files match and nonull is false');

  const nonullMatches = matchPaths(fileList, '*.vue', { nonull: true });
  assert.deepStrictEqual(nonullMatches, ['*.vue'], 'Returns pattern string in array when nonull is true and no match exists');
}

// Contract 3: minimatch filter generates a predicate function for Array.prototype.filter with options
{
  const files = ['INDEX.JS', 'main.js', 'style.CSS', 'readme.MD'];
  const jsFilter = createPathFilter('*.js', { nocase: true });
  const matched = files.filter(jsFilter);
  assert.deepStrictEqual(matched, ['INDEX.JS', 'main.js'], 'Case-insensitive filter matches both uppercase and lowercase extensions');

  const dotFiles = ['.env', '.gitignore', 'app.config.js'];
  const dotFilter = createPathFilter('.*', { dot: true });
  assert.deepStrictEqual(dotFiles.filter(dotFilter), ['.env', '.gitignore'], 'dot option matches filenames starting with dot');
}

// Contract 4: minimatch braceExpand expands brace pattern expressions into individual glob strings
{
  const expanded = expandBracePattern('src/{controllers,models}/*.{js,ts}');
  assert.deepStrictEqual(
    expanded,
    [
      'src/controllers/*.js',
      'src/controllers/*.ts',
      'src/models/*.js',
      'src/models/*.ts',
    ],
    'Expands permutations of nested brace groups'
  );

  const rangeExpanded = expandBracePattern('build/chunk-{1..3}.js');
  assert.deepStrictEqual(
    rangeExpanded,
    ['build/chunk-1.js', 'build/chunk-2.js', 'build/chunk-3.js'],
    'Expands numeric range sequence in braces'
  );
}

// Contract 5: minimatch escape and unescape handle special glob characters for literal matching
{
  const specialPath = 'lib/[special]/+core.js';
  const escaped = escapeGlob('[special]');
  assert.strictEqual(escaped, '\\[special\\]', 'Escapes brackets in glob pattern');

  const unescaped = unescapeGlob(escaped);
  assert.strictEqual(unescaped, '[special]', 'Restores escaped pattern to original literal string');

  const pattern = `lib/${escaped}/*.js`;
  assert.strictEqual(matchPath(specialPath, pattern), true, 'Escaped pattern matches directory with literal brackets');
  assert.strictEqual(matchPath('lib/s/core.js', pattern), false, 'Escaped pattern does not treat brackets as character class');
}

// Contract 6: minimatch Minimatch instance compiles and tests glob patterns and exposes AST and makeRe regex generation
{
  const compiled = createMinimatch('src/**/*.spec.js', { dot: false });
  assert.strictEqual(compiled.match('src/auth/login.spec.js'), true, 'Compiled Minimatch tests valid path successfully');
  assert.strictEqual(compiled.match('src/auth/login.js'), false, 'Compiled Minimatch rejects non-matching path');

  const regex = patternToRegExp('*.{png,jpg}');
  assert.ok(regex instanceof RegExp, 'makeRe returns a RegExp instance');
  assert.strictEqual(regex.test('image.png'), true, 'Generated RegExp tests true for png extension');
  assert.strictEqual(regex.test('image.jpg'), true, 'Generated RegExp tests true for jpg extension');
  assert.strictEqual(regex.test('image.svg'), false, 'Generated RegExp tests false for svg extension');
}

console.log('All pkg:npm/minimatch@10.1.1 contracts passed successfully.');

Seeder de origem

anônimo