CodeSampleX

サンプル

tmp 0.2.7: file

検証済みサンプル — npm tmp 0.2.7: file. node 22 · linux debian/x64 · docker で contract を実行し、成功しました: assert tmp.file is a function exported by tmp

sha256:92b767250ed01fcd62982062e58856f8485fc31607732c05891b8aca29fcec60

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

検証実行環境

環境 コントラクト ステージ 実行日
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.file in pkg:npm/tmp@0.2.7
パッケージ
シンボル
  • tmp.file
環境
node 22.23.2
作成日
2026-09-01T20:42:05Z

コントラクト

  1. assert tmp.file is a function exported by tmp
  2. assert tmp.file creates a temporary file on disk with a valid file descriptor
  3. assert tmp.file respects prefix and postfix options
  4. assert tmp.file respects discardDescriptor option by returning undefined file descriptor
  5. assert tmp.file respects mode option when creating the file
  6. assert tmp.file cleanup callback is idempotent and safely ignored on subsequent calls

ファイル

  • 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: verify tmp.file 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.file

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:6b7f036b52ba99d5833c80df9058fb2aadbcbace9ac28e17ce0364e21e43991f","contract":["assert tmp.file is a function exported by tmp","assert tmp.file creates a temporary file on disk with a valid file descriptor","assert tmp.file respects prefix and postfix options","assert tmp.file respects discardDescriptor option by returning undefined file descriptor","assert tmp.file respects mode option when creating the file","assert tmp.file cleanup callback is idempotent and safely ignored on subsequent calls"],"goal":"verify tmp.file in pkg:npm/tmp@0.2.7","kind":"HOW","packages":["pkg:npm/tmp@0.2.7"],"schemaVersion":1,"symbols":["tmp.file"]},"contractCommand":["node","test/contract.mjs"],"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/tmp@0.2.7"],"schemaVersion":1,"subject":"pkg:npm/tmp@0.2.7","symbols":["tmp.file"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const tmp = require('tmp');

/**
 * Creates a temporary file asynchronously with default or custom options.
 *
 * @param {Object|Function} [options] - Options or callback.
 * @param {Function} [callback] - Callback function (err, path, fd, cleanupCallback).
 */
function createTempFile(options, callback) {
  if (typeof options === 'function') {
    return tmp.file(options);
  }
  return tmp.file(options, callback);
}

/**
 * Promise-based helper to create a temporary file using tmp.file.
 *
 * @param {Object} [options] - Options for tmp.file.
 * @returns {Promise<{path: string, fd: number|undefined, cleanup: Function, cleanupAsync: Function}>}
 */
function createTempFileAsync(options = {}) {
  return new Promise((resolve, reject) => {
    tmp.file(options, (err, path, fd, cleanupCallback) => {
      if (err) {
        return reject(err);
      }
      const cleanupAsync = () =>
        new Promise((res, rej) => {
          cleanupCallback((cleanErr) => {
            if (cleanErr) rej(cleanErr);
            else res();
          });
        });
      resolve({ path, fd, cleanup: cleanupCallback, cleanupAsync });
    });
  });
}

module.exports = {
  tmp,
  file: tmp.file,
  createTempFile,
  createTempFileAsync,
};
package-lock.json
{
  "name": "sample-tmp-file",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tmp-file",
      "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-file",
  "version": "1.0.0",
  "description": "Clean-room sample verifying tmp.file in tmp",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "tmp": "0.2.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tmp.file in pkg:npm/tmp@0.2.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tmp@0.2.7"
  ],
  "symbols": [
    "tmp.file"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import tmpPkg from 'tmp';
import samplePkg from '../index.js';

const tmp = tmpPkg.default || tmpPkg;
const {
  file,
  createTempFile,
  createTempFileAsync,
} = samplePkg;

// 1. assert tmp.file is a function exported by tmp
assert.strictEqual(typeof tmp.file, 'function', 'tmp.file must be a function');
assert.strictEqual(typeof file, 'function', 'file exported by index.js must be a function');
assert.strictEqual(typeof createTempFile, 'function', 'createTempFile must be a function');
assert.strictEqual(typeof createTempFileAsync, 'function', 'createTempFileAsync must be a function');
assert.strictEqual(file, tmp.file, 're-exported file must match tmp.file');

// 2. assert tmp.file creates a temporary file on disk with a valid file descriptor
await new Promise((resolve, reject) => {
  tmp.file((err, filePath, fd, cleanupCallback) => {
    if (err) return reject(err);
    try {
      assert.strictEqual(typeof filePath, 'string', 'filePath must be a string');
      assert.strictEqual(typeof fd, 'number', 'fd must be a valid numeric file descriptor');
      assert.ok(fs.existsSync(filePath), 'temporary file must exist on disk');
      
      // Write data to the file descriptor to prove it is open and writable
      fs.writeSync(fd, 'tmp-file-contract-test\n');
      const content = fs.readFileSync(filePath, 'utf8');
      assert.strictEqual(content, 'tmp-file-contract-test\n', 'written content must match');

      // Asynchronously cleanup
      cleanupCallback((cleanErr) => {
        if (cleanErr) return reject(cleanErr);
        try {
          assert.strictEqual(fs.existsSync(filePath), false, 'temporary file must be removed after cleanup');
          resolve();
        } catch (assertErr) {
          reject(assertErr);
        }
      });
    } catch (e) {
      cleanupCallback(() => reject(e));
    }
  });
});

// 3. assert tmp.file respects prefix and postfix options
await new Promise((resolve, reject) => {
  tmp.file({ prefix: 'contract-prefix-', postfix: '.contract-suffix' }, (err, filePath, fd, cleanupCallback) => {
    if (err) return reject(err);
    try {
      const baseName = path.basename(filePath);
      assert.ok(baseName.startsWith('contract-prefix-'), `File basename should start with prefix: ${baseName}`);
      assert.ok(baseName.endsWith('.contract-suffix'), `File basename should end with postfix: ${baseName}`);
      assert.ok(fs.existsSync(filePath), 'temporary file with custom prefix/postfix must exist');

      cleanupCallback((cleanErr) => {
        if (cleanErr) return reject(cleanErr);
        try {
          assert.strictEqual(fs.existsSync(filePath), false, 'file must be deleted after cleanup');
          resolve();
        } catch (assertErr) {
          reject(assertErr);
        }
      });
    } catch (e) {
      cleanupCallback(() => reject(e));
    }
  });
});

// 4. assert tmp.file respects discardDescriptor option by returning undefined file descriptor
await new Promise((resolve, reject) => {
  tmp.file({ discardDescriptor: true }, (err, filePath, fd, cleanupCallback) => {
    if (err) return reject(err);
    try {
      assert.strictEqual(fd, undefined, 'fd should be undefined when discardDescriptor is true');
      assert.ok(fs.existsSync(filePath), 'file should exist even if descriptor is discarded');

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

// 5. assert tmp.file respects mode option when creating the file
await new Promise((resolve, reject) => {
  tmp.file({ mode: 0o640, discardDescriptor: true }, (err, filePath, fd, cleanupCallback) => {
    if (err) return reject(err);
    try {
      const stat = fs.statSync(filePath);
      assert.strictEqual(stat.mode & 0o777, 0o640, 'file mode should match requested mode 0o640');

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

// 6. assert tmp.file cleanup callback is idempotent and safely ignored on subsequent calls
await new Promise((resolve, reject) => {
  createTempFile((err, filePath, fd, cleanupCallback) => {
    if (err) return reject(err);
    try {
      assert.ok(fs.existsSync(filePath), 'temporary file must exist');
      cleanupCallback((cleanErr1) => {
        if (cleanErr1) return reject(cleanErr1);
        try {
          assert.strictEqual(fs.existsSync(filePath), false, 'temporary file must be removed by first cleanup');
          
          // Second invocation is a no-op and does not throw
          assert.doesNotThrow(() => {
            cleanupCallback();
          }, 'subsequent cleanupCallback invocation must not throw');
          resolve();
        } catch (assertErr) {
          reject(assertErr);
        }
      });
    } catch (e) {
      cleanupCallback(() => reject(e));
    }
  });
});

// 7. Verify async Promise helper
const asyncResult = await createTempFileAsync({ prefix: 'promise-test-' });
assert.ok(fs.existsSync(asyncResult.path), 'async created file must exist');
await asyncResult.cleanupAsync();
assert.strictEqual(fs.existsSync(asyncResult.path), false, 'async created file must be removed after cleanup');

console.log('All tmp.file contract assertions passed.');

オリジンシーダー

匿名