CodeSampleX

示例

pend 1.2.0

已验证示例 — npm pend 1.2.0. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: Pend exports constructor and helper functions

sha256:5d1ea91f2ecc3b5922c4fe8019ebb5c7ac2f410b498fd774bdb8999f058a0645

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-23

案例

HOW
目标
verify pkg:npm/pend@1.2.0
包
创建时间
2026-08-23T14:05:41Z

契约

  1. Pend exports constructor and helper functions
  2. Pend initializes with zero pending tasks, infinite max concurrency, and empty wait queue
  3. createPend helper initializes Pend with specified maximum concurrency limit
  4. go executes tasks asynchronously and wait invokes callback when all tasks finish
  5. max concurrency setting throttles concurrent execution and queues pending tasks until capacity opens
  6. wait receives the first error passed to a task callback
  7. hold manually increments pending count and returns a callback to release the slot
  8. invoking a release callback more than once throws an error
  9. wait on empty pend invokes callback synchronously
  10. runParallel executes tasks concurrently within max concurrency limit and returns ordered results
  11. runParallel rejects when any task yields an error
  12. runSeries executes tasks sequentially in order and collects results

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 pkg:npm/pend@1.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/pend@1.2.0

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:9df674a09b931a5b2c3cf96246b1893bf39c99b76eb080e0ce02b37b8a109c9b","contract":["Pend exports constructor and helper functions","Pend initializes with zero pending tasks, infinite max concurrency, and empty wait queue","createPend helper initializes Pend with specified maximum concurrency limit","go executes tasks asynchronously and wait invokes callback when all tasks finish","max concurrency setting throttles concurrent execution and queues pending tasks until capacity opens","wait receives the first error passed to a task callback","hold manually increments pending count and returns a callback to release the slot","invoking a release callback more than once throws an error","wait on empty pend invokes callback synchronously","runParallel executes tasks concurrently within max concurrency limit and returns ordered results","runParallel rejects when any task yields an error","runSeries executes tasks sequentially in order and collects results"],"goal":"verify pkg:npm/pend@1.2.0","kind":"HOW","packages":["pkg:npm/pend@1.2.0"],"schemaVersion":1},"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/pend@1.2.0"],"schemaVersion":1,"subject":"pkg:npm/pend@1.2.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-pend",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pend",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "pend": "1.2.0"
      }
    },
    "node_modules/pend": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
      "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-pend",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for pend@1.2.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "pend": "1.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/pend@1.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pend@1.2.0"
  ]
}
src/index.js
const Pend = require('pend');

/**
 * Creates a new Pend instance with optional maximum concurrency.
 *
 * @param {number} [max=Infinity] - Maximum number of concurrent tasks.
 * @returns {Pend} A new Pend instance.
 */
function createPend(max = Infinity) {
  const p = new Pend();
  p.max = max;
  return p;
}

/**
 * Runs an array of asynchronous task functions with bounded concurrency.
 * Each task function is called with a callback (err, result).
 *
 * @param {Array<Function>} tasks - Array of functions of form fn(done).
 * @param {number} [maxConcurrency=Infinity] - Maximum concurrency limit.
 * @returns {Promise<Array<*>>} Resolves with array of results in task order, or rejects with first error.
 */
function runParallel(tasks, maxConcurrency = Infinity) {
  return new Promise((resolve, reject) => {
    const pend = new Pend();
    pend.max = maxConcurrency;
    const results = new Array(tasks.length);

    tasks.forEach((task, index) => {
      pend.go((done) => {
        task((err, result) => {
          if (err) {
            done(err);
            return;
          }
          results[index] = result;
          done();
        });
      });
    });

    pend.wait((err) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
}

/**
 * Runs an array of asynchronous task functions sequentially (concurrency = 1).
 *
 * @param {Array<Function>} tasks - Array of functions of form fn(done).
 * @returns {Promise<Array<*>>} Resolves with array of results in task order.
 */
function runSeries(tasks) {
  return runParallel(tasks, 1);
}

module.exports = {
  Pend,
  createPend,
  runParallel,
  runSeries
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  Pend,
  createPend,
  runParallel,
  runSeries
} = require('../src/index.js');

async function testAll() {
  // 1. Pend exports constructor and helper functions
  assert.equal(typeof Pend, 'function', 'Pend must be a constructor function');
  assert.equal(typeof createPend, 'function', 'createPend helper must be a function');
  assert.equal(typeof runParallel, 'function', 'runParallel helper must be a function');
  assert.equal(typeof runSeries, 'function', 'runSeries helper must be a function');

  // 2. Pend initial state defaults
  const p1 = new Pend();
  assert.equal(p1.pending, 0, 'pending should start at 0');
  assert.equal(p1.max, Infinity, 'max should default to Infinity');
  assert.equal(p1.error, null, 'error should start null');
  assert.ok(Array.isArray(p1.listeners), 'listeners should be an array');
  assert.ok(Array.isArray(p1.waiting), 'waiting should be an array');

  // 3. createPend configures max concurrency
  const pBounded = createPend(2);
  assert.equal(pBounded.max, 2, 'createPend should set max concurrency');

  // 4. go executes tasks and wait calls callback when all finish
  const results = [];
  const p2 = new Pend();
  p2.go((cb) => {
    setTimeout(() => {
      results.push('a');
      cb();
    }, 20);
  });
  p2.go((cb) => {
    setTimeout(() => {
      results.push('b');
      cb();
    }, 10);
  });

  const waitPromise1 = new Promise((resolve, reject) => {
    p2.wait((err) => {
      if (err) reject(err);
      else resolve();
    });
  });
  await waitPromise1;
  assert.equal(results.length, 2, 'all tasks should complete');
  assert.equal(p2.pending, 0, 'pending should be 0 after completion');

  // 5. max concurrency queues tasks until slots open
  const p3 = new Pend();
  p3.max = 2;
  let activeCount = 0;
  let maxObservedActive = 0;
  const executionOrder = [];

  for (let i = 0; i < 5; i++) {
    const taskIndex = i;
    p3.go((cb) => {
      activeCount++;
      if (activeCount > maxObservedActive) {
        maxObservedActive = activeCount;
      }
      setTimeout(() => {
        executionOrder.push(taskIndex);
        activeCount--;
        cb();
      }, 15);
    });
  }

  await new Promise((resolve, reject) => {
    p3.wait((err) => {
      if (err) reject(err);
      else resolve();
    });
  });

  assert.equal(maxObservedActive, 2, 'active concurrent tasks should not exceed max limit of 2');
  assert.equal(executionOrder.length, 5, 'all 5 tasks should execute');

  // 6. error propagation: wait receives first error from any task
  const p4 = new Pend();
  const testError = new Error('task failure');
  p4.go((cb) => {
    setTimeout(() => cb(testError), 10);
  });
  p4.go((cb) => {
    setTimeout(() => cb(), 20);
  });

  const capturedErr = await new Promise((resolve) => {
    p4.wait((err) => resolve(err));
  });
  assert.equal(capturedErr, testError, 'wait should receive the error returned by task');

  // 7. hold manually increments pending and returns a release callback
  const p5 = new Pend();
  const release1 = p5.hold();
  const release2 = p5.hold();
  assert.equal(p5.pending, 2, 'pending count should reflect held slots');
  release1();
  assert.equal(p5.pending, 1, 'pending count should decrement on release');
  release2();
  assert.equal(p5.pending, 0, 'pending count should be 0 when all releases called');

  // 8. invoking a release callback twice throws an error
  const p6 = new Pend();
  const releaseOnce = p6.hold();
  releaseOnce();
  assert.throws(
    () => {
      releaseOnce();
    },
    {
      name: 'Error',
      message: 'callback called twice'
    },
    'calling release callback twice should throw'
  );

  // 9. wait on empty pend invokes callback synchronously
  let syncCalled = false;
  const p7 = new Pend();
  p7.wait((err) => {
    assert.equal(err, null, 'error should be null');
    syncCalled = true;
  });
  assert.equal(syncCalled, true, 'wait on empty pend must execute callback immediately');

  // 10. runParallel helper executes tasks with bounded concurrency and returns results
  const parallelResults = await runParallel([
    (cb) => setTimeout(() => cb(null, 10), 15),
    (cb) => setTimeout(() => cb(null, 20), 5),
    (cb) => setTimeout(() => cb(null, 30), 10)
  ], 2);
  assert.deepEqual(parallelResults, [10, 20, 30], 'runParallel should return ordered results');

  // 11. runParallel rejects on task error
  await assert.rejects(
    async () => {
      await runParallel([
        (cb) => setTimeout(() => cb(null, 'ok'), 10),
        (cb) => setTimeout(() => cb(new Error('parallel failed')), 5)
      ]);
    },
    {
      name: 'Error',
      message: 'parallel failed'
    },
    'runParallel should reject on task error'
  );

  // 12. runSeries executes tasks in sequential order
  const seriesOrder = [];
  const seriesResults = await runSeries([
    (cb) => {
      seriesOrder.push('step1');
      setTimeout(() => cb(null, 'first'), 15);
    },
    (cb) => {
      seriesOrder.push('step2');
      setTimeout(() => cb(null, 'second'), 5);
    }
  ]);
  assert.deepEqual(seriesOrder, ['step1', 'step2'], 'runSeries should execute steps sequentially');
  assert.deepEqual(seriesResults, ['first', 'second'], 'runSeries should collect results in order');

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

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

原始种子者

匿名