CodeSampleX

示例

p-limit 3.1.0

已验证示例 — npm p-limit 3.1.0. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: pLimit restricts concurrent execution of async tasks to the specified…

sha256:a81faa3901abd508cdbe0aef5e5b377ade2af965f7ae7aada76631446914ecf9

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

原始种子者

匿名