CodeSampleX

Пример

tmp 0.2.7: dir

Проверенный пример — npm tmp 0.2.7: dir. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: tmp.dir asynchronously creates a unique…

sha256:c712025f055917ec02fbe1d671720bf105dc52b32582b9a38bceec2b2f364faa

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

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

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

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

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

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

Кейс

HOW
Цель
verify tmp.dir in pkg:npm/tmp@0.2.7
Пакеты
Символы
  • tmp.dir
Создан
2026-09-01T20:37:56Z

Контракт

  1. tmp.dir asynchronously creates a unique temporary directory and passes its path and a cleanup callback
  2. tmp.dir supports prefix and postfix options to customize the directory name
  3. tmp.dir supports mode option to set directory permissions
  4. tmp.dir with unsafeCleanup removes the directory and all contained files upon invoking the cleanup callback
  5. tmp.dir supports template option for custom directory naming patterns

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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: verify tmp.dir in pkg:npm/tmp@0.2.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tmp@0.2.7
Demonstrate these symbols/APIs:
  - tmp.dir

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:653b35aaeabee2438761985159b0ee2fd840204260e1f249ab10803810f1f6d2","contract":["tmp.dir asynchronously creates a unique temporary directory and passes its path and a cleanup callback","tmp.dir supports prefix and postfix options to customize the directory name","tmp.dir supports mode option to set directory permissions","tmp.dir with unsafeCleanup removes the directory and all contained files upon invoking the cleanup callback","tmp.dir supports template option for custom directory naming patterns"],"goal":"verify tmp.dir in pkg:npm/tmp@0.2.7","kind":"HOW","packages":["pkg:npm/tmp@0.2.7"],"schemaVersion":1,"symbols":["tmp.dir"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tmp@0.2.7"],"schemaVersion":1,"subject":"pkg:npm/tmp@0.2.7","symbols":["tmp.dir"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tmp-dir",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tmp-dir",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tmp": "0.2.7"
      }
    },
    "node_modules/tmp": {
      "version": "0.2.7",
      "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
      "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",
      "license": "MIT",
      "engines": {
        "node": ">=14.14"
      }
    }
  }
}
package.json
{
  "name": "sample-tmp-dir",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "tmp": "0.2.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tmp.dir in pkg:npm/tmp@0.2.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tmp@0.2.7"
  ],
  "symbols": [
    "tmp.dir"
  ]
}
src/index.mjs
import tmp from 'tmp';

/**
 * Create a temporary directory asynchronously using tmp.dir.
 * @param {object|Function} optionsOrCb Options object or callback function
 * @param {Function} [cb] Callback function (err, path, cleanupCallback)
 */
export function createTempDir(optionsOrCb, cb) {
  if (typeof optionsOrCb === 'function') {
    return tmp.dir(optionsOrCb);
  }
  return tmp.dir(optionsOrCb, cb);
}

/**
 * Create a temporary directory returning a Promise with path and async cleanup function.
 * @param {object} [options] Options for tmp.dir
 * @returns {Promise<{ path: string, cleanup: () => Promise<void>, rawCleanup: Function }>}
 */
export function createTempDirPromise(options = {}) {
  return new Promise((resolve, reject) => {
    tmp.dir(options, (err, dirPath, cleanupCallback) => {
      if (err) {
        return reject(err);
      }
      const cleanup = () =>
        new Promise((res, rej) => {
          cleanupCallback((cErr) => {
            if (cErr) return rej(cErr);
            res();
          });
        });
      resolve({ path: dirPath, cleanup, rawCleanup: cleanupCallback });
    });
  });
}

export { tmp };
export default tmp;
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import tmp, { createTempDir, createTempDirPromise } from '../src/index.mjs';

async function runTests() {
  // 1. tmp.dir creates a temporary directory and passes dirPath and async cleanupCallback
  await new Promise((resolve, reject) => {
    tmp.dir((err, dirPath, cleanupCallback) => {
      if (err) return reject(err);
      try {
        assert.ok(typeof dirPath === 'string', 'dirPath must be a string');
        assert.ok(fs.existsSync(dirPath), 'directory must exist on filesystem');
        const stat = fs.statSync(dirPath);
        assert.ok(stat.isDirectory(), 'created path must be a directory');
        assert.ok(typeof cleanupCallback === 'function', 'cleanupCallback must be a function');

        cleanupCallback((cleanupErr) => {
          if (cleanupErr) return reject(cleanupErr);
          try {
            assert.strictEqual(fs.existsSync(dirPath), false, 'cleanupCallback must remove the directory');
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  });

  // 2. tmp.dir supports prefix and postfix options
  await new Promise((resolve, reject) => {
    tmp.dir({ prefix: 'customPrefix_', postfix: '_customPostfix' }, (err, dirPath, cleanupCallback) => {
      if (err) return reject(err);
      try {
        const baseName = path.basename(dirPath);
        assert.ok(baseName.startsWith('customPrefix_'), 'directory name must start with prefix');
        assert.ok(baseName.endsWith('_customPostfix'), 'directory name must end with postfix');
        assert.ok(fs.existsSync(dirPath), 'directory must exist');

        cleanupCallback((cleanupErr) => {
          if (cleanupErr) return reject(cleanupErr);
          try {
            assert.strictEqual(fs.existsSync(dirPath), false, 'directory must be removed after cleanup');
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  });

  // 3. tmp.dir supports mode option to set directory permissions
  await new Promise((resolve, reject) => {
    const desiredMode = 0o700;
    tmp.dir({ mode: desiredMode }, (err, dirPath, cleanupCallback) => {
      if (err) return reject(err);
      try {
        const stat = fs.statSync(dirPath);
        const actualMode = stat.mode & 0o777;
        assert.strictEqual(actualMode, desiredMode, 'directory mode must match configured mode');

        cleanupCallback((cleanupErr) => {
          if (cleanupErr) return reject(cleanupErr);
          try {
            assert.strictEqual(fs.existsSync(dirPath), false);
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  });

  // 4. tmp.dir with unsafeCleanup removes directory containing files on cleanup
  await new Promise((resolve, reject) => {
    tmp.dir({ unsafeCleanup: true }, (err, dirPath, cleanupCallback) => {
      if (err) return reject(err);
      try {
        const nestedFile = path.join(dirPath, 'nested-file.txt');
        fs.writeFileSync(nestedFile, 'sample content', 'utf8');
        assert.ok(fs.existsSync(nestedFile), 'nested file must exist before cleanup');

        cleanupCallback((cleanupErr) => {
          if (cleanupErr) return reject(cleanupErr);
          try {
            assert.strictEqual(fs.existsSync(dirPath), false, 'unsafeCleanup must remove directory with files');
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  });

  // 5. tmp.dir supports template option
  await new Promise((resolve, reject) => {
    tmp.dir({ template: 'tmpl-XXXXXX' }, (err, dirPath, cleanupCallback) => {
      if (err) return reject(err);
      try {
        const baseName = path.basename(dirPath);
        assert.ok(baseName.startsWith('tmpl-'), 'directory name must follow template prefix');
        assert.ok(fs.existsSync(dirPath), 'directory must exist');

        cleanupCallback((cleanupErr) => {
          if (cleanupErr) return reject(cleanupErr);
          try {
            assert.strictEqual(fs.existsSync(dirPath), false);
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  });

  // 6. createTempDir helper works with callback
  await new Promise((resolve, reject) => {
    createTempDir((err, dirPath, cleanupCallback) => {
      if (err) return reject(err);
      try {
        assert.ok(fs.existsSync(dirPath), 'directory from createTempDir must exist');
        cleanupCallback((cleanupErr) => {
          if (cleanupErr) return reject(cleanupErr);
          try {
            assert.strictEqual(fs.existsSync(dirPath), false);
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  });

  // 7. createTempDirPromise returns promise resolving to path and cleanup function
  {
    const { path: dirPath, cleanup } = await createTempDirPromise({ prefix: 'prom-' });
    assert.ok(typeof dirPath === 'string', 'resolved path must be string');
    assert.ok(path.basename(dirPath).startsWith('prom-'), 'prefix must match');
    assert.ok(fs.existsSync(dirPath), 'directory must exist');

    await cleanup();
    assert.strictEqual(fs.existsSync(dirPath), false, 'cleanup must remove directory');
  }

  console.log('All contract assertions passed.');
}

runTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

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

аноним