CodeSampleX

Пример

tinyglobby 0.2.17: match files asynchronously and synchronously using glob and globSync

Проверенный пример — npm tinyglobby 0.2.17: match files asynchronously and synchronously using glob and globSync. Контракт выполнен на node 22 · linux…

sha256:02fc08892554bb3b65639edd583c74ff0e00ff0ec4c0f1cca4729ba98149ceae

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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

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

Кейс

HOW
Цель
match files asynchronously and synchronously using glob and globSync
Пакеты
Символы
  • glob
  • globSync
Окружение
node 22.23.2
Создан
2026-08-28T02:16:51Z

Контракт

  1. assert glob asynchronously matches files matching glob patterns
  2. assert globSync synchronously matches files matching glob patterns
  3. assert glob and globSync support ignore patterns and negative patterns
  4. assert glob and globSync support onlyFiles and onlyDirectories filters
  5. assert glob and globSync support custom cwd and deep options

Файлы

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

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

Исходный код

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 files asynchronously and synchronously using glob and globSync
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tinyglobby@0.2.17
Demonstrate these symbols/APIs:
  - glob
  - globSync

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:7b376a2a5a751ed77a756a67e76a0de406000cf8acb6d8d8fdd2594c3baa351c","contract":["assert glob asynchronously matches files matching glob patterns","assert globSync synchronously matches files matching glob patterns","assert glob and globSync support ignore patterns and negative patterns","assert glob and globSync support onlyFiles and onlyDirectories filters","assert glob and globSync support custom cwd and deep options"],"goal":"match files asynchronously and synchronously using glob and globSync","kind":"HOW","packages":["pkg:npm/tinyglobby@0.2.17"],"schemaVersion":1,"symbols":["glob","globSync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tinyglobby@0.2.17"],"schemaVersion":1,"subject":"pkg:npm/tinyglobby@0.2.17","symbols":["glob","globSync"],"verifierAdapter":"node-typescript@1"}
index.js
import { glob, globSync, convertPathToPattern, escapePath, isDynamicPattern } from 'tinyglobby';

/**
 * Asynchronously matches files using glob patterns.
 *
 * @param {string|string[]} patterns - Glob pattern(s) to match.
 * @param {import('tinyglobby').GlobOptions} [options] - Options for matching.
 * @returns {Promise<string[]>} Matching file paths.
 */
export async function findFiles(patterns, options = {}) {
  return glob(patterns, options);
}

/**
 * Synchronously matches files using glob patterns.
 *
 * @param {string|string[]} patterns - Glob pattern(s) to match.
 * @param {import('tinyglobby').GlobOptions} [options] - Options for matching.
 * @returns {string[]} Matching file paths.
 */
export function findFilesSync(patterns, options = {}) {
  return globSync(patterns, options);
}

export { glob, globSync, convertPathToPattern, escapePath, isDynamicPattern };
package-lock.json
{
  "name": "sample-tinyglobby",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tinyglobby",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tinyglobby": "0.2.17"
      }
    },
    "node_modules/fdir": {
      "version": "6.5.0",
      "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
      "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
      "license": "MIT",
      "engines": {
        "node": ">=12.0.0"
      },
      "peerDependencies": {
        "picomatch": "^3 || ^4"
      },
      "peerDependenciesMeta": {
        "picomatch": {
          "optional": true
        }
      }
    },
    "node_modules/picomatch": {
      "version": "4.0.7",
      "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
      "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://github.com/sponsors/jonschlinkert"
      }
    },
    "node_modules/tinyglobby": {
      "version": "0.2.17",
      "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
      "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
      "license": "MIT",
      "dependencies": {
        "fdir": "^6.5.0",
        "picomatch": "^4.0.4"
      },
      "engines": {
        "node": ">=12.0.0"
      },
      "funding": {
        "url": "https://github.com/sponsors/SuperchupuDev"
      }
    }
  }
}
package.json
{
  "name": "sample-tinyglobby",
  "version": "1.0.0",
  "description": "Clean-room sample verifying pkg:npm/tinyglobby@0.2.17 functionality",
  "type": "module",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "tinyglobby": "0.2.17"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "match files asynchronously and synchronously using glob and globSync",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tinyglobby@0.2.17"
  ],
  "symbols": [
    "glob",
    "globSync"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { glob, globSync, findFiles, findFilesSync, isDynamicPattern, escapePath } from '../index.js';

// Setup temporary directory structure for offline glob testing
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tinyglobby-test-'));

try {
  fs.writeFileSync(path.join(tmpDir, 'file1.txt'), 'content 1');
  fs.writeFileSync(path.join(tmpDir, 'file2.js'), 'console.log("hello");');
  fs.writeFileSync(path.join(tmpDir, 'file3.ts'), 'export const x = 1;');
  fs.writeFileSync(path.join(tmpDir, '.hidden.txt'), 'hidden');

  fs.mkdirSync(path.join(tmpDir, 'sub'), { recursive: true });
  fs.writeFileSync(path.join(tmpDir, 'sub', 'nested.js'), 'console.log("nested");');
  fs.writeFileSync(path.join(tmpDir, 'sub', 'nested.txt'), 'nested text');

  fs.mkdirSync(path.join(tmpDir, 'sub', 'deep'), { recursive: true });
  fs.writeFileSync(path.join(tmpDir, 'sub', 'deep', 'deep.js'), 'console.log("deep");');

  // 1. Asynchronous matching with glob and findFiles
  const asyncJsFiles = (await findFiles('**/*.js', { cwd: tmpDir })).sort();
  assert.deepStrictEqual(
    asyncJsFiles,
    ['file2.js', 'sub/deep/deep.js', 'sub/nested.js'],
    'assert glob asynchronously matches files matching glob patterns'
  );

  // 2. Synchronous matching with globSync and findFilesSync
  const syncJsFiles = findFilesSync('**/*.js', { cwd: tmpDir }).sort();
  assert.deepStrictEqual(
    syncJsFiles,
    ['file2.js', 'sub/deep/deep.js', 'sub/nested.js'],
    'assert globSync synchronously matches files matching glob patterns'
  );

  // 3. Ignore patterns and negative patterns
  const ignoredFiles = findFilesSync('**/*.{js,txt}', {
    cwd: tmpDir,
    ignore: ['**/*.txt', '**/deep/**'],
  }).sort();
  assert.deepStrictEqual(
    ignoredFiles,
    ['file2.js', 'sub/nested.js'],
    'assert glob and globSync support ignore patterns and negative patterns'
  );

  const negativeGlob = (await glob(['**/*', '!**/*.txt', '!**/deep/**'], { cwd: tmpDir })).sort();
  assert.deepStrictEqual(
    negativeGlob,
    ['file2.js', 'file3.ts', 'sub/nested.js'],
    'negative patterns filter matching results'
  );

  // 4. onlyFiles and onlyDirectories filters
  const onlyDirs = findFilesSync('*', { cwd: tmpDir, onlyDirectories: true }).sort();
  assert.deepStrictEqual(
    onlyDirs,
    ['sub/'],
    'assert glob and globSync support onlyFiles and onlyDirectories filters'
  );

  // 5. Custom cwd and deep option limiting recursion
  const shallowFiles = findFilesSync('**/*.js', { cwd: tmpDir, deep: 1 }).sort();
  assert.deepStrictEqual(
    shallowFiles,
    ['file2.js', 'sub/nested.js'],
    'assert glob and globSync support custom cwd and deep options'
  );

  // 6. Dot files matching
  const dotFiles = findFilesSync('*', { cwd: tmpDir, dot: true }).sort();
  assert.ok(
    dotFiles.includes('.hidden.txt'),
    'dot option allows matching hidden files'
  );

  // 7. Utility functions
  assert.strictEqual(isDynamicPattern('src/**/*.js'), true);
  assert.strictEqual(isDynamicPattern('src/plain/file.js'), false);
  assert.strictEqual(typeof escapePath('hello/[world]'), 'string');

  console.log('All contract assertions passed.');
} finally {
  fs.rmSync(tmpDir, { recursive: true, force: true });
}

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

аноним