CodeSampleX

샘플

fs-extra 10.1.0

검증된 샘플 — npm fs-extra 10.1.0. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: ensureDir creates nested directory structures if they do not exist

sha256:aeee8efab163cc48f0c9ce5b605150a575a12242bf464d59474ee660bd4597e4

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

케이스

HOW
목표
verify pkg:npm/fs-extra@10.1.0
패키지
환경
node 22.23.2
생성일
2026-08-20T00:51:28Z

컨트랙트

  1. ensureDir creates nested directory structures if they do not exist
  2. outputJson and readJson write and read JSON documents while automatically creating parent directories
  3. copy recursively copies directory hierarchies and supports custom filter functions
  4. emptyDir deletes all contents within a directory while leaving the directory itself intact
  5. pathExists accurately checks the existence of files and directories
  6. remove recursively removes directories and files without throwing if the target does not exist

파일

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

소스 아티팩트 내려받기 (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: verify pkg:npm/fs-extra@10.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/fs-extra@10.1.0
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:ae0ed3f3a42a723d120c0d66369dee464d0a4eb0ba30f9b2d4a1e5b72054dddc","constraints":{"executionContext":"node"},"contract":["ensureDir creates nested directory structures if they do not exist","outputJson and readJson write and read JSON documents while automatically creating parent directories","copy recursively copies directory hierarchies and supports custom filter functions","emptyDir deletes all contents within a directory while leaving the directory itself intact","pathExists accurately checks the existence of files and directories","remove recursively removes directories and files without throwing if the target does not exist"],"goal":"verify pkg:npm/fs-extra@10.1.0","kind":"HOW","packages":["pkg:npm/fs-extra@10.1.0"],"schemaVersion":1},"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/fs-extra@10.1.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "fs-extra-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "fs-extra-sample",
      "version": "1.0.0",
      "dependencies": {
        "fs-extra": "10.1.0"
      }
    },
    "node_modules/fs-extra": {
      "version": "10.1.0",
      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
      "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
      "license": "MIT",
      "dependencies": {
        "graceful-fs": "^4.2.0",
        "jsonfile": "^6.0.1",
        "universalify": "^2.0.0"
      },
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/jsonfile": {
      "version": "6.2.1",
      "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
      "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
      "license": "MIT",
      "dependencies": {
        "universalify": "^2.0.0"
      },
      "optionalDependencies": {
        "graceful-fs": "^4.1.6"
      }
    },
    "node_modules/universalify": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
      "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
      "license": "MIT",
      "engines": {
        "node": ">= 10.0.0"
      }
    }
  }
}
package.json
{
  "name": "fs-extra-sample",
  "version": "1.0.0",
  "dependencies": {
    "fs-extra": "10.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/fs-extra@10.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/fs-extra@10.1.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const fse = require('fs-extra');

/**
 * Ensures that a directory exists. If the directory structure does not exist, it is created.
 *
 * @param {string} dirPath - Directory path to ensure.
 * @returns {Promise<void>}
 */
async function ensureDirectory(dirPath) {
  await fse.ensureDir(dirPath);
}

/**
 * Writes an object to a JSON file, automatically creating parent directories if they do not exist.
 *
 * @param {string} filePath - Path of JSON file.
 * @param {any} data - Data to serialize and write.
 * @param {object} [options] - Options for writeJson (e.g. { spaces: 2 }).
 * @returns {Promise<void>}
 */
async function outputJsonFile(filePath, data, options) {
  await fse.outputJson(filePath, data, options);
}

/**
 * Reads a JSON file and parses it into a JavaScript object.
 *
 * @param {string} filePath - Path of JSON file.
 * @returns {Promise<any>}
 */
async function readJsonFile(filePath) {
  return await fse.readJson(filePath);
}

/**
 * Copies a file or directory recursively.
 *
 * @param {string} src - Source file or directory path.
 * @param {string} dest - Destination file or directory path.
 * @param {object} [options] - Copy options such as overwrite and filter.
 * @returns {Promise<void>}
 */
async function copyDirectory(src, dest, options) {
  await fse.copy(src, dest, options);
}

/**
 * Ensures that a directory is empty by deleting all items inside it while preserving the directory itself.
 *
 * @param {string} dirPath - Directory path to empty.
 * @returns {Promise<void>}
 */
async function emptyDirectory(dirPath) {
  await fse.emptyDir(dirPath);
}

/**
 * Tests whether or not the given path exists.
 *
 * @param {string} targetPath - Path to test.
 * @returns {Promise<boolean>}
 */
async function checkPathExists(targetPath) {
  return await fse.pathExists(targetPath);
}

/**
 * Removes a file or directory recursively.
 *
 * @param {string} targetPath - Path to remove.
 * @returns {Promise<void>}
 */
async function removePath(targetPath) {
  await fse.remove(targetPath);
}

module.exports = {
  ensureDirectory,
  outputJsonFile,
  readJsonFile,
  copyDirectory,
  emptyDirectory,
  checkPathExists,
  removePath,
  fse,
};
test/contract.js
const assert = require('node:assert/strict');
const path = require('node:path');
const os = require('node:os');
const fs = require('node:fs');
const {
  ensureDirectory,
  outputJsonFile,
  readJsonFile,
  copyDirectory,
  emptyDirectory,
  checkPathExists,
  removePath,
} = require('../src/index.js');

async function main() {
  const testRoot = path.join(
    os.tmpdir(),
    `fs-extra-contract-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
  );

  try {
    // Contract 1: ensureDir creates nested directory structures if they do not exist
    {
      const nestedDir = path.join(testRoot, 'a', 'b', 'c', 'nested');
      assert.strictEqual(await checkPathExists(nestedDir), false);

      await ensureDirectory(nestedDir);
      assert.strictEqual(await checkPathExists(nestedDir), true);
      assert.strictEqual(fs.statSync(nestedDir).isDirectory(), true);

      // Calling ensureDir on an already existing directory should be a no-op
      await ensureDirectory(nestedDir);
      assert.strictEqual(await checkPathExists(nestedDir), true);
    }

    // Contract 2: outputJson and readJson write and read JSON documents while automatically creating parent directories
    {
      const jsonFile = path.join(testRoot, 'nested', 'config', 'app.json');
      const payload = { name: 'csx-test', count: 42, enabled: true, tags: ['node', 'fs'] };

      assert.strictEqual(await checkPathExists(jsonFile), false);
      await outputJsonFile(jsonFile, payload, { spaces: 2 });

      assert.strictEqual(await checkPathExists(jsonFile), true);
      const readBack = await readJsonFile(jsonFile);
      assert.deepStrictEqual(readBack, payload, 'readJson output must match the written object');
    }

    // Contract 3: copy recursively copies directory hierarchies and supports custom filter functions
    {
      const srcDir = path.join(testRoot, 'src_copy');
      const destDir = path.join(testRoot, 'dest_copy');

      await outputJsonFile(path.join(srcDir, 'file1.json'), { item: 1 });
      await outputJsonFile(path.join(srcDir, 'ignore_me.txt'), { item: 'skip' });
      await outputJsonFile(path.join(srcDir, 'sub', 'file2.json'), { item: 2 });

      // Copy with filter that excludes ignore_me.txt
      await copyDirectory(srcDir, destDir, {
        filter: (src) => !src.includes('ignore_me'),
      });

      assert.strictEqual(await checkPathExists(path.join(destDir, 'file1.json')), true);
      assert.strictEqual(await checkPathExists(path.join(destDir, 'sub', 'file2.json')), true);
      assert.strictEqual(await checkPathExists(path.join(destDir, 'ignore_me.txt')), false);

      const copiedContent = await readJsonFile(path.join(destDir, 'sub', 'file2.json'));
      assert.deepStrictEqual(copiedContent, { item: 2 });
    }

    // Contract 4: emptyDir deletes all contents within a directory while leaving the directory itself intact
    {
      const targetDir = path.join(testRoot, 'to_empty');
      await outputJsonFile(path.join(targetDir, 'sub1', 'a.json'), { a: 1 });
      await outputJsonFile(path.join(targetDir, 'sub2', 'b.json'), { b: 2 });

      assert.strictEqual(await checkPathExists(targetDir), true);
      assert.ok(fs.readdirSync(targetDir).length > 0);

      await emptyDirectory(targetDir);

      assert.strictEqual(await checkPathExists(targetDir), true);
      assert.strictEqual(fs.readdirSync(targetDir).length, 0);
    }

    // Contract 5: pathExists accurately checks the existence of files and directories
    {
      const nonExistent = path.join(testRoot, 'does_not_exist_' + Date.now());
      assert.strictEqual(await checkPathExists(nonExistent), false);

      const existingFile = path.join(testRoot, 'exists.json');
      await outputJsonFile(existingFile, { ok: true });
      assert.strictEqual(await checkPathExists(existingFile), true);
    }

    // Contract 6: remove recursively removes directories and files without throwing if the target does not exist
    {
      const toRemove = path.join(testRoot, 'to_remove');
      await outputJsonFile(path.join(toRemove, 'child', 'data.json'), { removed: false });
      assert.strictEqual(await checkPathExists(toRemove), true);

      await removePath(toRemove);
      assert.strictEqual(await checkPathExists(toRemove), false);

      // Removing non-existent path should succeed silently
      await removePath(toRemove);
    }

    console.log('All pkg:npm/fs-extra@10.1.0 contracts passed successfully.');
  } finally {
    try {
      await removePath(testRoot);
    } catch (_) {}
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

오리진 시더

익명