CodeSampleX

Пример

p-limit 2.3.0

Проверенный пример — npm p-limit 2.3.0. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: limits concurrent execution of async tasks to…

sha256:03f4389da922c77317c4f55b5a324002f475d2d32fc501dd1aa10a206c48e574

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-21

Кейс

HOW
Цель
verify pkg:npm/p-limit@2.3.0
Пакеты
Окружение
node 22.23.2
Создан
2026-08-21T04:00:42Z

Контракт

  1. limits concurrent execution of async tasks to specified limit (concurrency=2)
  2. tracks activeCount and pendingCount accurately during queued execution
  3. passes arguments to limited async functions and returns resolved values
  4. clears queued tasks when clearQueue() is called
  5. maps items concurrently with a given limit

Файлы

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

Скачать артефакт с исходным кодом (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/p-limit@2.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/p-limit@2.3.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:dafbb235ebe32f86b9791392355d46b69dc5478fec82237b34e5dc73ad57e32b","constraints":{"executionContext":"node"},"contract":["limits concurrent execution of async tasks to specified limit (concurrency=2)","tracks activeCount and pendingCount accurately during queued execution","passes arguments to limited async functions and returns resolved values","clears queued tasks when clearQueue() is called","maps items concurrently with a given limit"],"goal":"verify pkg:npm/p-limit@2.3.0","kind":"HOW","packages":["pkg:npm/p-limit@2.3.0"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/p-limit@2.3.0"],"schemaVersion":1,"subject":"pkg:npm/p-limit@2.3.0","verifierAdapter":"node-typescript@1"}
index.js
const pLimit = require('p-limit');

function mapWithLimit(items, limitCount, asyncFn) {
  const limit = pLimit(limitCount);
  return Promise.all(items.map((item, index) => limit(() => asyncFn(item, index))));
}

module.exports = {
  mapWithLimit,
  pLimit,
};
package-lock.json
{
  "name": "sample-p-limit",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-p-limit",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "p-limit": "2.3.0"
      }
    },
    "node_modules/p-limit": {
      "version": "2.3.0",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
      "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
      "license": "MIT",
      "dependencies": {
        "p-try": "^2.0.0"
      },
      "engines": {
        "node": ">=6"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/p-try": {
      "version": "2.2.0",
      "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
      "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    }
  }
}
package.json
{
  "name": "sample-p-limit",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for p-limit",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "license": "MIT-0",
  "dependencies": {
    "p-limit": "2.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/p-limit@2.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-limit@2.3.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
const assert = require('assert');
const pLimit = require('p-limit');
const { mapWithLimit } = require('../index.js');

async function runTests() {
  // Test 1: limits concurrency to specified limit
  {
    const limit = pLimit(2);
    let active = 0;
    let maxActive = 0;

    const delay = (ms, value) =>
      new Promise((resolve) => {
        setTimeout(() => resolve(value), ms);
      });

    const task = async (id, ms) => {
      active++;
      maxActive = Math.max(maxActive, active);
      await delay(ms);
      active--;
      return id;
    };

    const promises = [
      limit(() => task(1, 50)),
      limit(() => task(2, 50)),
      limit(() => task(3, 50)),
      limit(() => task(4, 50)),
    ];

    const results = await Promise.all(promises);
    assert.deepStrictEqual(results, [1, 2, 3, 4], 'all results returned');
    assert.strictEqual(maxActive, 2, 'concurrency never exceeded limit of 2');
    assert.strictEqual(limit.activeCount, 0, 'activeCount is 0 after completion');
    assert.strictEqual(limit.pendingCount, 0, 'pendingCount is 0 after completion');
  }

  // Test 2: tracks activeCount and pendingCount correctly
  {
    const limit = pLimit(1);
    let resolveFirst;
    const firstPromise = new Promise((resolve) => {
      resolveFirst = resolve;
    });

    const p1 = limit(() => firstPromise);
    const p2 = limit(() => Promise.resolve('second'));
    const p3 = limit(() => Promise.resolve('third'));

    assert.strictEqual(limit.activeCount, 1, '1 task is active');
    assert.strictEqual(limit.pendingCount, 2, '2 tasks are pending');

    resolveFirst('first');
    const res = await Promise.all([p1, p2, p3]);
    assert.deepStrictEqual(res, ['first', 'second', 'third']);
    assert.strictEqual(limit.activeCount, 0);
    assert.strictEqual(limit.pendingCount, 0);
  }

  // Test 3: arguments passing to async function
  {
    const limit = pLimit(2);
    const fn = async (a, b) => a + b;
    const res = await limit(fn, 10, 20);
    assert.strictEqual(res, 30, 'arguments forwarded correctly');
  }

  // Test 4: clearQueue discards pending tasks
  {
    const limit = pLimit(1);
    let resolveFirst;
    const firstPromise = new Promise((resolve) => {
      resolveFirst = resolve;
    });

    let executed2 = false;
    let executed3 = false;

    const p1 = limit(() => firstPromise);
    const p2 = limit(async () => {
      executed2 = true;
      return 'two';
    });
    const p3 = limit(async () => {
      executed3 = true;
      return 'three';
    });

    assert.strictEqual(limit.pendingCount, 2);
    limit.clearQueue();
    assert.strictEqual(limit.pendingCount, 0);

    resolveFirst('done');
    await p1;

    await new Promise((r) => setTimeout(r, 20));
    assert.strictEqual(executed2, false, 'cleared task 2 did not execute');
    assert.strictEqual(executed3, false, 'cleared task 3 did not execute');
  }

  // Test 5: helper mapWithLimit
  {
    const items = [1, 2, 3, 4, 5];
    const double = async (x) => x * 2;
    const mapped = await mapWithLimit(items, 2, double);
    assert.deepStrictEqual(mapped, [2, 4, 6, 8, 10]);
  }

  console.log('Contract tests passed successfully.');
}

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

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

аноним