CodeSampleX

示例

tinyexec 1.3.0: execSync

已验证示例 — npm tinyexec 1.3.0: execSync. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: execSync is exported as a function that synchronously executes a…

sha256:14c4f1d48dc2de39c863efe7b5e13eecb0503bb341feefe1df1fb86b6350fbab

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-06

案例

HOW
目标
verify tinyexec.execSync in pkg:npm/tinyexec@1.3.0
包
符号
  • tinyexec.execSync
创建时间
2026-09-06T15:47:22Z

契约

  1. execSync is exported as a function that synchronously executes a command and returns a SyncResult
  2. execSync returns an output object containing stdout, stderr, exitCode, signalCode, pid, and killed
  3. execSync passes command arguments and custom environment variables via nodeOptions
  4. execSync implements synchronous iteration over combined stdout and stderr lines via Symbol.iterator
  5. execSync captures signal termination setting signalCode and killed on the result object
  6. execSync returns non-zero exitCode without throwing when throwOnError is false or omitted
  7. execSync throws NonZeroExitError when throwOnError is enabled and command exits with non-zero code
  8. execSync throws ETIMEDOUT error when execution duration exceeds the configured timeout option
  9. execSync throws spawn errors directly when executable does not exist

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Notes: Tinyexec Synchronous Execution

## Search Result
`search_known_solution` returned `NO_SAFE_MATCH` for `tinyexec.execSync` in `tinyexec@1.3.0`. Existing samples for `tinyexec` cover earlier version `0.3.2` primitives (`ExecProcess`, `NonZeroExitError`, and async `exec`), but lack contract verification for the synchronous execution API `execSync` (and its alias `xSync`) added in newer releases.

## Naive Model Assumption
Models and developers frequently assume:
1. `execSync` returns a Promise like `exec` or shares `Symbol.asyncIterator`, rather than executing synchronously and returning a synchronous iterable (`Symbol.iterator`).
2. Like async `exec` which handles timeouts by aborting via `AbortSignal` and resolving with `aborted: true` / `killed: true`, developers often assume synchronous `execSync` with `{ timeout }` returns a result object with `killed: true` instead of throwing an `ETIMEDOUT` error.
3. Synchronous execution throws on non-zero exit codes by default, rather than requiring `{ throwOnError: true }` to throw `NonZeroExitError`.

## Failure Mode
1. `execSync` executes synchronously and returns `SyncResult` directly; iterating over its output is synchronous via `Symbol.iterator`.
2. When the `timeout` option expires during `execSync`, the underlying `spawnSync` reports an `ETIMEDOUT` error, which `xSync` throws as an `Error` (`code: 'ETIMEDOUT'`).
3. For commands terminating via POSIX signals (e.g. `SIGTERM`), `result.exitCode` is `undefined`, `result.signalCode` is set to the signal name (e.g. `'SIGTERM'`), and `result.killed` is `true`.
4. When `throwOnError: true` is configured and the process exits with a non-zero exit code or signal, `execSync` throws `NonZeroExitError` exposing `err.exitCode` and `err.output` properties.
5. Nonexistent binaries throw an `Error` with `code: 'ENOENT'`.
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 tinyexec.execSync in pkg:npm/tinyexec@1.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tinyexec@1.3.0
Demonstrate these symbols/APIs:
  - tinyexec.execSync

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:88f2129a3cf1658fc52e35966da4e93d5f24bfc8ef43d9f8a996d479473db933","contract":["execSync is exported as a function that synchronously executes a command and returns a SyncResult","execSync returns an output object containing stdout, stderr, exitCode, signalCode, pid, and killed","execSync passes command arguments and custom environment variables via nodeOptions","execSync implements synchronous iteration over combined stdout and stderr lines via Symbol.iterator","execSync captures signal termination setting signalCode and killed on the result object","execSync returns non-zero exitCode without throwing when throwOnError is false or omitted","execSync throws NonZeroExitError when throwOnError is enabled and command exits with non-zero code","execSync throws ETIMEDOUT error when execution duration exceeds the configured timeout option","execSync throws spawn errors directly when executable does not exist"],"goal":"verify tinyexec.execSync in pkg:npm/tinyexec@1.3.0","kind":"HOW","packages":["pkg:npm/tinyexec@1.3.0"],"schemaVersion":1,"symbols":["tinyexec.execSync"]},"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/tinyexec@1.3.0"],"schemaVersion":1,"subject":"pkg:npm/tinyexec@1.3.0","symbols":["tinyexec.execSync"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tinyexec-execsync",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tinyexec-execsync",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tinyexec": "1.3.0"
      }
    },
    "node_modules/tinyexec": {
      "version": "1.3.0",
      "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",
      "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",
      "license": "MIT",
      "engines": {
        "node": ">=18"
      }
    }
  }
}
package.json
{
  "name": "sample-tinyexec-execsync",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "tinyexec": "1.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tinyexec.execSync in pkg:npm/tinyexec@1.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tinyexec@1.3.0"
  ],
  "symbols": [
    "tinyexec.execSync"
  ]
}
src/index.js
import { execSync, xSync, NonZeroExitError } from 'tinyexec';

/**
 * Synchronously executes a command with arguments and options.
 * @param {string} command - Executable or command name
 * @param {string[]} [args] - Arguments
 * @param {import('tinyexec').SyncOptions} [options] - Synchronous execution options
 * @returns {import('tinyexec').SyncResult}
 */
export function executeSync(command, args, options) {
  return execSync(command, args, options);
}

/**
 * Synchronously executes a command with throwOnError: true.
 * @param {string} command - Executable or command name
 * @param {string[]} [args] - Arguments
 * @param {import('tinyexec').SyncOptions} [options] - Synchronous execution options
 * @returns {import('tinyexec').SyncResult}
 */
export function executeStrictSync(command, args, options) {
  return execSync(command, args, {
    ...options,
    throwOnError: true
  });
}

/**
 * Collects all lines emitted by iterating over the SyncResult.
 * @param {import('tinyexec').SyncResult} result
 * @returns {string[]}
 */
export function collectSyncLines(result) {
  return [...result];
}

export {
  execSync,
  xSync,
  NonZeroExitError
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  execSync,
  xSync,
  NonZeroExitError,
  executeSync,
  executeStrictSync,
  collectSyncLines
} from '../src/index.js';

// ---------------------------------------------------------------------------
// 1. execSync is exported as a function that synchronously executes a command and returns a SyncResult
// ---------------------------------------------------------------------------
assert.equal(typeof execSync, 'function', 'execSync must be exported as a function');
assert.equal(typeof xSync, 'function', 'xSync must be exported as a function');
assert.equal(execSync, xSync, 'execSync must be identical to xSync');
assert.equal(typeof executeSync, 'function', 'executeSync helper must be exported');
assert.equal(typeof executeStrictSync, 'function', 'executeStrictSync helper must be exported');
assert.equal(typeof collectSyncLines, 'function', 'collectSyncLines helper must be exported');

// ---------------------------------------------------------------------------
// 2. execSync returns an output object containing stdout, stderr, exitCode, signalCode, pid, and killed
// ---------------------------------------------------------------------------
{
  const result = execSync(process.execPath, [
    '-e',
    'process.stdout.write("sync stdout output"); process.stderr.write("sync stderr output");'
  ]);

  assert.equal(result.stdout, 'sync stdout output', 'stdout must match expected output');
  assert.equal(result.stderr, 'sync stderr output', 'stderr must match expected output');
  assert.equal(result.exitCode, 0, 'exitCode must be 0 for successful execution');
  assert.equal(result.signalCode, null, 'signalCode must be null on clean exit');
  assert.equal(typeof result.pid, 'number', 'pid must be a number');
  assert(result.pid > 0, 'pid must be a positive integer');
  assert.equal(result.killed, false, 'killed must be false for normal process completion');
}

// ---------------------------------------------------------------------------
// 3. execSync passes command arguments and custom environment variables via nodeOptions
// ---------------------------------------------------------------------------
{
  const result = executeSync(
    process.execPath,
    ['-e', 'process.stdout.write(process.argv[1] + ":" + process.env.CSX_TEST_SYNC_VAR);', 'ARG_VAL'],
    {
      nodeOptions: {
        env: {
          ...process.env,
          CSX_TEST_SYNC_VAR: 'SYNC_VAR_SET'
        }
      }
    }
  );

  assert.equal(result.stdout, 'ARG_VAL:SYNC_VAR_SET', 'arguments and environment variables must be passed through');
  assert.equal(result.exitCode, 0);
}

// ---------------------------------------------------------------------------
// 4. execSync implements synchronous iteration over combined stdout and stderr lines via Symbol.iterator
// ---------------------------------------------------------------------------
{
  const result = execSync(process.execPath, [
    '-e',
    'console.log("line-1"); console.log("line-2"); console.error("err-line-3");'
  ]);

  const lines = collectSyncLines(result);
  assert.deepEqual(lines, ['line-1', 'line-2', 'err-line-3'], 'synchronous iterator must yield stdout followed by stderr lines');
}

// ---------------------------------------------------------------------------
// 5. execSync captures signal termination setting signalCode and killed on the result object
// ---------------------------------------------------------------------------
{
  const result = execSync(process.execPath, [
    '-e',
    'process.kill(process.pid, "SIGTERM");'
  ]);

  assert.equal(result.killed, true, 'killed must be true when terminated by signal');
  assert.equal(result.signalCode, 'SIGTERM', 'signalCode must be SIGTERM');
  assert.equal(result.exitCode, undefined, 'exitCode must be undefined when terminated by signal');
}

// ---------------------------------------------------------------------------
// 6. execSync returns non-zero exitCode without throwing when throwOnError is false or omitted
// ---------------------------------------------------------------------------
{
  const result = execSync(process.execPath, [
    '-e',
    'process.stderr.write("non-fatal error notice"); process.exit(7);'
  ]);

  assert.equal(result.exitCode, 7, 'exitCode must match exit status');
  assert.equal(result.stderr, 'non-fatal error notice', 'stderr must be captured');
  assert.equal(result.signalCode, null);
}

// ---------------------------------------------------------------------------
// 7. execSync throws NonZeroExitError when throwOnError is enabled and command exits with non-zero code
// ---------------------------------------------------------------------------
{
  assert.throws(
    () => {
      executeStrictSync(process.execPath, [
        '-e',
        'process.stderr.write("fatal error encounter"); process.exit(42);'
      ]);
    },
    (err) => {
      assert(err instanceof NonZeroExitError, 'thrown error must be an instance of NonZeroExitError');
      assert.equal(err.exitCode, 42, 'NonZeroExitError must expose the process exitCode');
      assert.equal(err.output?.stderr, 'fatal error encounter', 'output property must contain stderr');
      assert.equal(err.result?.exitCode, 42, 'result property must contain exitCode');
      return true;
    }
  );
}

// ---------------------------------------------------------------------------
// 8. execSync throws ETIMEDOUT error when execution duration exceeds the configured timeout option
// ---------------------------------------------------------------------------
{
  assert.throws(
    () => {
      execSync(process.execPath, ['-e', 'while(true){}'], {
        timeout: 100
      });
    },
    (err) => {
      assert(err instanceof Error, 'must throw an Error when timeout is exceeded');
      assert.equal(err.code, 'ETIMEDOUT', 'error code must be ETIMEDOUT');
      return true;
    }
  );
}

// ---------------------------------------------------------------------------
// 9. execSync throws spawn errors directly when executable does not exist
// ---------------------------------------------------------------------------
{
  assert.throws(
    () => {
      execSync('definitely_nonexistent_binary_for_tinyexec_contract_check');
    },
    (err) => {
      assert(err instanceof Error, 'must throw Error on spawn failure');
      assert.equal(err.code, 'ENOENT', 'error code must be ENOENT');
      return true;
    }
  );
}

console.log('All tinyexec.execSync contract assertions passed successfully.');

原始种子者

匿名