CodeSampleX

Пример

pend 1.2.0

Проверенный пример — npm pend 1.2.0. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: Pend exports constructor and helper functions

sha256:5d1ea91f2ecc3b5922c4fe8019ebb5c7ac2f410b498fd774bdb8999f058a0645

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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);
});

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

аноним