CodeSampleX

示例

p-limit 7.3.1

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

sha256:f5d58d0179ad13ebaa65cfa72909dc74718dd536be55c5cda2c19a7e3c770f6a

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

执行证据

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

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
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@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-23
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-08

案例

HOW
目标
verify pkg:npm/p-limit@7.3.1
包
环境
node 22.23.2
创建时间
2026-08-23T05:57:47Z

契约

  1. pLimit restricts concurrent execution of async tasks to the specified concurrency limit
  2. limit tracks activeCount and pendingCount reflecting real-time queue state
  3. limit passes through arguments to the wrapped async function and resolves with return value
  4. limit.clearQueue discards pending tasks while allowing active tasks to complete
  5. limit.clearQueue with rejectOnClear rejects pending tasks with an AbortError
  6. limit.concurrency getter and setter dynamically adjust active task capacity
  7. limit.map concurrently maps iterable items with the concurrency limit
  8. limitFunction wraps a function with a shared concurrency limiter
  9. pLimit throws a TypeError when given invalid concurrency or rejectOnClear options

文件

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

Use EXACTLY these public packages and versions:
  - pkg:npm/p-limit@7.3.1

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:92ed1fbdb58ffd134e19c64339c663a3eba6d41a95abeb92493e6d3ca098eca8","contract":["pLimit restricts concurrent execution of async tasks to the specified concurrency limit","limit tracks activeCount and pendingCount reflecting real-time queue state","limit passes through arguments to the wrapped async function and resolves with return value","limit.clearQueue discards pending tasks while allowing active tasks to complete","limit.clearQueue with rejectOnClear rejects pending tasks with an AbortError","limit.concurrency getter and setter dynamically adjust active task capacity","limit.map concurrently maps iterable items with the concurrency limit","limitFunction wraps a function with a shared concurrency limiter","pLimit throws a TypeError when given invalid concurrency or rejectOnClear options"],"goal":"verify pkg:npm/p-limit@7.3.1","kind":"HOW","packages":["pkg:npm/p-limit@7.3.1"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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@7.3.1"],"schemaVersion":1,"subject":"pkg:npm/p-limit@7.3.1","verifierAdapter":"node-typescript@1"}
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": "7.3.1"
      }
    },
    "node_modules/p-limit": {
      "version": "7.3.1",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-7.3.1.tgz",
      "integrity": "sha512-0trZaiG7Y7kN/Egy9a8j47t9osC0Tch4PaIWd9yGF6bvmlk7muExRvGNYb8sXBwEKMoNKsbNN9P8EefuQekE4Q==",
      "license": "MIT",
      "dependencies": {
        "yocto-queue": "^1.2.1"
      },
      "engines": {
        "node": ">=20"
      }
    },
    "node_modules/yocto-queue": {
      "version": "1.2.2",
      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz",
      "integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==",
      "license": "MIT",
      "engines": {
        "node": ">=12.20"
      }
    }
  }
}
package.json
{
  "name": "sample-p-limit",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "p-limit": "7.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/p-limit@7.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-limit@7.3.1"
  ]
}
src/index.mjs
import pLimit, { limitFunction } from 'p-limit';

/**
 * Creates a concurrency limiter function.
 * @param {number|object} options Concurrency count or options object.
 * @returns {Function} Limiter function.
 */
export function createLimiter(options) {
  return pLimit(options);
}

/**
 * Concurrently maps an iterable through an async mapper with a specified concurrency limit.
 * @param {Iterable} iterable Input items.
 * @param {Function} mapper Async mapper function (item, index).
 * @param {number|object} [options=2] Concurrency or options.
 * @returns {Promise<Array>} Resolved array of results.
 */
export async function mapWithLimit(iterable, mapper, options = 2) {
  const limit = pLimit(options);
  return limit.map(iterable, mapper);
}

/**
 * Wraps a function with limited concurrency across all calls.
 * @param {Function} fn Async function to wrap.
 * @param {number|object} options Concurrency or options.
 * @returns {Function} Wrapped rate-limited function.
 */
export function wrapLimitedFunction(fn, options) {
  return limitFunction(fn, options);
}

export { pLimit, limitFunction };
export default pLimit;
test/contract.mjs
import assert from 'node:assert/strict';
import pLimit, { limitFunction } from 'p-limit';
import { createLimiter, mapWithLimit, wrapLimitedFunction } from '../src/index.mjs';

// 1. pLimit restricts concurrent execution of async tasks to the specified concurrency limit
{
  const limit = pLimit(2);
  let active = 0;
  let maxActive = 0;

  const runTask = (val) => limit(async () => {
    active++;
    maxActive = Math.max(maxActive, active);
    await new Promise(resolve => setTimeout(resolve, 25));
    active--;
    return val * 2;
  });

  const results = await Promise.all([runTask(1), runTask(2), runTask(3), runTask(4)]);
  assert.deepEqual(results, [2, 4, 6, 8]);
  assert.equal(maxActive, 2);
}

// 2. limit tracks activeCount and pendingCount reflecting real-time queue state
{
  const limit = pLimit(1);
  let release;
  const p1 = limit(async () => {
    await new Promise(resolve => { release = resolve; });
    return 'first';
  });
  const p2 = limit(async () => 'second');

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(limit.activeCount, 1);
  assert.equal(limit.pendingCount, 1);

  release();
  const res = await Promise.all([p1, p2]);
  assert.deepEqual(res, ['first', 'second']);
  assert.equal(limit.activeCount, 0);
  assert.equal(limit.pendingCount, 0);
}

// 3. limit passes through arguments to the wrapped async function and resolves with return value
{
  const limit = pLimit(2);
  const result = await limit((a, b, c) => a + b + c, 'foo', '-', 'bar');
  assert.equal(result, 'foo-bar');
}

// 4. limit.clearQueue discards pending tasks while allowing active tasks to complete
{
  const limit = pLimit(1);
  let release;
  let secondRan = false;

  const activeTask = limit(async () => {
    await new Promise(resolve => { release = resolve; });
    return 'active-done';
  });
  const pendingTask = limit(async () => {
    secondRan = true;
    return 'pending-done';
  });

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(limit.pendingCount, 1);

  limit.clearQueue();
  assert.equal(limit.pendingCount, 0);

  release();
  const activeRes = await activeTask;
  assert.equal(activeRes, 'active-done');

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(secondRan, false);
}

// 5. limit.clearQueue with rejectOnClear rejects pending tasks with an AbortError
{
  const limit = pLimit({ concurrency: 1, rejectOnClear: true });
  let release;
  let rejectedError;

  const activeTask = limit(async () => {
    await new Promise(resolve => { release = resolve; });
    return 'done';
  });

  const pendingTask = limit(async () => 'never').catch(err => {
    rejectedError = err;
  });

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(limit.pendingCount, 1);

  limit.clearQueue();
  assert.equal(limit.pendingCount, 0);

  release();
  await activeTask;
  await pendingTask;

  assert.equal(rejectedError?.name, 'AbortError');
}

// 6. limit.concurrency getter and setter dynamically adjust active task capacity
{
  const limit = pLimit(1);
  assert.equal(limit.concurrency, 1);

  let release1;
  let release2;
  let startedCount = 0;

  const t1 = limit(async () => {
    startedCount++;
    await new Promise(resolve => { release1 = resolve; });
  });
  const t2 = limit(async () => {
    startedCount++;
    await new Promise(resolve => { release2 = resolve; });
  });

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(startedCount, 1);

  limit.concurrency = 2;
  assert.equal(limit.concurrency, 2);

  await new Promise(resolve => setImmediate(resolve));
  assert.equal(startedCount, 2);

  release1();
  release2();
  await Promise.all([t1, t2]);
}

// 7. limit.map concurrently maps iterable items with the concurrency limit
{
  const limit = pLimit(2);
  const items = [10, 20, 30, 40];
  const mapped = await limit.map(items, async (item, index) => {
    await new Promise(resolve => setTimeout(resolve, 10));
    return item + index;
  });
  assert.deepEqual(mapped, [10, 21, 32, 43]);

  // Helper mapWithLimit
  const helperMapped = await mapWithLimit([1, 2, 3], async (x) => x * 10, 2);
  assert.deepEqual(helperMapped, [10, 20, 30]);
}

// 8. limitFunction wraps a function with a shared concurrency limiter
{
  let concurrentExecutions = 0;
  let peakExecutions = 0;

  const limitedFn = limitFunction(async (x) => {
    concurrentExecutions++;
    peakExecutions = Math.max(peakExecutions, concurrentExecutions);
    await new Promise(resolve => setTimeout(resolve, 20));
    concurrentExecutions--;
    return x * 10;
  }, 2);

  const results = await Promise.all([limitedFn(1), limitedFn(2), limitedFn(3), limitedFn(4)]);
  assert.deepEqual(results, [10, 20, 30, 40]);
  assert.equal(peakExecutions, 2);

  // Helper wrapLimitedFunction
  const wrapped = wrapLimitedFunction(async (x) => x + 5, 2);
  assert.equal(await wrapped(10), 15);
}

// 9. pLimit throws a TypeError when given invalid concurrency or rejectOnClear options
{
  assert.throws(() => pLimit(0), TypeError);
  assert.throws(() => pLimit(-1), TypeError);
  assert.throws(() => pLimit(1.5), TypeError);
  assert.throws(() => pLimit('invalid'), TypeError);
  assert.throws(() => pLimit({ concurrency: 1, rejectOnClear: 'not-a-bool' }), TypeError);
  assert.throws(() => createLimiter(0), TypeError);
}

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

原始种子者

匿名