CodeSampleX

示例

tmp 0.2.7: dir

已验证示例 — npm tmp 0.2.7: dir. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: tmp.dir asynchronously creates a unique temporary directory and passes its…

sha256:c712025f055917ec02fbe1d671720bf105dc52b32582b9a38bceec2b2f364faa

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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);
});

原始种子者

匿名