CodeSampleX

샘플

p-limit 3.1.0

검증된 샘플 — npm p-limit 3.1.0. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: pLimit restricts concurrent execution of async tasks to the specified…

sha256:a81faa3901abd508cdbe0aef5e5b377ade2af965f7ae7aada76631446914ecf9

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19

케이스

HOW
목표
verify pkg:npm/p-limit@3.1.0
패키지
환경
node 22.23.2
생성일
2026-08-19T22:10:40Z

컨트랙트

  1. pLimit restricts concurrent execution of async tasks to the specified concurrency threshold
  2. limit exposes activeCount and pendingCount properties reflecting real-time queue state
  3. limit.clearQueue empties pending queued tasks while allowing active tasks to complete
  4. limit passes through arguments to the wrapped async function and resolves with the return value
  5. pLimit throws a TypeError when initialized with invalid concurrency values

파일

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

Use EXACTLY these public packages and versions:
  - pkg:npm/p-limit@3.1.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:ce26529a57ef02aeb2cc7ac7c31df35cbc3679f23e2636cbc82878976bf70ac2","constraints":{"executionContext":"node"},"contract":["pLimit restricts concurrent execution of async tasks to the specified concurrency threshold","limit exposes activeCount and pendingCount properties reflecting real-time queue state","limit.clearQueue empties pending queued tasks while allowing active tasks to complete","limit passes through arguments to the wrapped async function and resolves with the return value","pLimit throws a TypeError when initialized with invalid concurrency values"],"goal":"verify pkg:npm/p-limit@3.1.0","kind":"HOW","packages":["pkg:npm/p-limit@3.1.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@3.1.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "p-limit-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "p-limit-sample",
      "version": "1.0.0",
      "dependencies": {
        "p-limit": "3.1.0"
      }
    },
    "node_modules/p-limit": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
      "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
      "license": "MIT",
      "dependencies": {
        "yocto-queue": "^0.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/yocto-queue": {
      "version": "0.1.0",
      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
      "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    }
  }
}
package.json
{
  "name": "p-limit-sample",
  "version": "1.0.0",
  "dependencies": {
    "p-limit": "3.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/p-limit@3.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-limit@3.1.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const pLimit = require('p-limit');

/**
 * Creates a concurrency limiter function.
 *
 * @param {number} concurrency - Maximum number of concurrent tasks.
 * @returns {import('p-limit').Limit}
 */
function createLimiter(concurrency) {
  return pLimit(concurrency);
}

/**
 * Executes an async task through a concurrency limiter.
 *
 * @param {import('p-limit').Limit} limiter
 * @param {(...args: any[]) => Promise<any>} fn
 * @param {...any} args
 * @returns {Promise<any>}
 */
function runWithLimit(limiter, fn, ...args) {
  return limiter(fn, ...args);
}

/**
 * Retrieves the current active and pending counts for a limiter.
 *
 * @param {import('p-limit').Limit} limiter
 * @returns {{ activeCount: number, pendingCount: number }}
 */
function getLimiterState(limiter) {
  return {
    activeCount: limiter.activeCount,
    pendingCount: limiter.pendingCount,
  };
}

/**
 * Clears any pending tasks waiting in the limiter queue.
 *
 * @param {import('p-limit').Limit} limiter
 */
function clearLimiterQueue(limiter) {
  limiter.clearQueue();
}

module.exports = {
  createLimiter,
  runWithLimit,
  getLimiterState,
  clearLimiterQueue,
  pLimit,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  createLimiter,
  runWithLimit,
  getLimiterState,
  clearLimiterQueue,
} = require('../src/index.js');

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

async function main() {
  // Contract 1: pLimit restricts concurrent execution of async tasks to the specified concurrency threshold
  {
    const limit = createLimiter(2);
    let active = 0;
    let maxActive = 0;

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

    const results = await Promise.all([
      runWithLimit(limit, task),
      runWithLimit(limit, task),
      runWithLimit(limit, task),
      runWithLimit(limit, task),
      runWithLimit(limit, task),
    ]);

    assert.strictEqual(results.length, 5);
    assert.strictEqual(results.every(r => r === 'done'), true);
    assert.strictEqual(maxActive, 2, 'Max concurrent executions should not exceed concurrency limit');
  }

  // Contract 2: limit exposes activeCount and pendingCount properties reflecting real-time queue state
  {
    const limit = createLimiter(1);
    let release;
    const blocker = new Promise(resolve => {
      release = resolve;
    });

    const p1 = limit(() => blocker);
    const p2 = limit(() => delay(10));
    const p3 = limit(() => delay(10));

    await delay(5);

    const state = getLimiterState(limit);
    assert.strictEqual(state.activeCount, 1, 'activeCount should be 1');
    assert.strictEqual(state.pendingCount, 2, 'pendingCount should be 2');

    release();
    await Promise.all([p1, p2, p3]);

    const finalState = getLimiterState(limit);
    assert.strictEqual(finalState.activeCount, 0, 'activeCount should be 0 after completion');
    assert.strictEqual(finalState.pendingCount, 0, 'pendingCount should be 0 after completion');
  }

  // Contract 3: limit.clearQueue empties pending queued tasks while allowing active tasks to complete
  {
    const limit = createLimiter(1);
    let task1Started = false;
    let task1Finished = false;
    let task2Ran = false;
    let release1;
    const blocker = new Promise(resolve => {
      release1 = resolve;
    });

    const p1 = limit(async () => {
      task1Started = true;
      await blocker;
      task1Finished = true;
      return 'task1';
    });

    const p2 = limit(async () => {
      task2Ran = true;
      return 'task2';
    });

    await delay(5);
    assert.strictEqual(task1Started, true);
    assert.strictEqual(limit.pendingCount, 1);

    clearLimiterQueue(limit);
    assert.strictEqual(limit.pendingCount, 0, 'pendingCount should be 0 after clearQueue');

    release1();
    const res1 = await p1;
    assert.strictEqual(res1, 'task1');
    assert.strictEqual(task1Finished, true);
    assert.strictEqual(task2Ran, false, 'Cleared task should not run');
  }

  // Contract 4: limit passes through arguments to the wrapped async function and resolves with the return value
  {
    const limit = createLimiter(2);
    const multiply = async (a, b) => {
      await delay(5);
      return a * b;
    };

    const res = await runWithLimit(limit, multiply, 6, 7);
    assert.strictEqual(res, 42, 'Limiter should pass arguments and resolve with return value');
  }

  // Contract 5: pLimit throws a TypeError when initialized with invalid concurrency values
  {
    assert.throws(
      () => createLimiter(0),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
    assert.throws(
      () => createLimiter(-1),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
    assert.throws(
      () => createLimiter(1.5),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
    assert.throws(
      () => createLimiter('invalid'),
      {
        name: 'TypeError',
        message: 'Expected `concurrency` to be a number from 1 and up',
      }
    );
  }

  console.log('All pkg:npm/p-limit@3.1.0 contracts passed successfully.');
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});

오리진 시더

익명