CodeSampleX

示例

async 3.2.6

已验证示例 — npm async 3.2.6. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: async.waterfall runs an array of dependent tasks in series passing results to…

sha256:92370558a32c665d4a2a380abc344480bc1e60ee97346291fe36b77ef527ec35

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-26

案例

HOW
目标
verify pkg:npm/async@3.2.6
包
环境
node 22.23.2
创建时间
2026-08-26T09:24:05Z

契约

  1. async.waterfall runs an array of dependent tasks in series passing results to next tasks
  2. async.parallel executes async tasks in parallel and collects results
  3. async.eachLimit iterates over items with a concurrency limit
  4. async.map transforms an array asynchronously and preserves result ordering
  5. async.filter filters items based on asynchronous predicate test
  6. async.reduce reduces an array to a single value using an async reducer function
  7. async.queue processes tasks with concurrency control and drain handling
  8. async.retry executes an operation repeatedly until it succeeds or reaches attempt limit

文件

  • 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/async@3.2.6
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/async@3.2.6

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:cf5d053c455bb1ee18b6313d12fd9a6ca34fdaa101e9d58941be8c60a1e121bf","contract":["async.waterfall runs an array of dependent tasks in series passing results to next tasks","async.parallel executes async tasks in parallel and collects results","async.eachLimit iterates over items with a concurrency limit","async.map transforms an array asynchronously and preserves result ordering","async.filter filters items based on asynchronous predicate test","async.reduce reduces an array to a single value using an async reducer function","async.queue processes tasks with concurrency control and drain handling","async.retry executes an operation repeatedly until it succeeds or reaches attempt limit"],"goal":"verify pkg:npm/async@3.2.6","kind":"HOW","packages":["pkg:npm/async@3.2.6"],"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/async@3.2.6"],"schemaVersion":1,"subject":"pkg:npm/async@3.2.6","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-async",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-async",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "async": "3.2.6"
      }
    },
    "node_modules/async": {
      "version": "3.2.6",
      "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
      "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-async",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "async": "3.2.6"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/async@3.2.6",
  "kind": "HOW",
  "packages": [
    "pkg:npm/async@3.2.6"
  ]
}
src/index.mjs
import async from 'async';

/**
 * Runs an array of dependent functions in series, each passing its results to the next.
 * @param {Array<Function>} tasks Array of functions to run.
 * @returns {Promise<any>} Resolves with the result of the final task.
 */
export function runWaterfall(tasks) {
  return async.waterfall(tasks);
}

/**
 * Runs multiple asynchronous tasks in parallel and returns their results.
 * @param {Array<Function>|Object} tasks Tasks to execute.
 * @returns {Promise<any>} Resolves with the collected results.
 */
export function runParallel(tasks) {
  return async.parallel(tasks);
}

/**
 * Iterates over an array with a specified concurrency limit.
 * @param {Array} items Collection to iterate over.
 * @param {number} limit Concurrency limit.
 * @param {Function} iteratee Async iteratee function.
 * @returns {Promise<void>} Resolves when all items are processed.
 */
export function runEachLimit(items, limit, iteratee) {
  return async.eachLimit(items, limit, iteratee);
}

/**
 * Maps values through an async function in parallel.
 * @param {Array} items Collection to map.
 * @param {Function} iteratee Async mapping function.
 * @returns {Promise<Array>} Resolves with mapped results.
 */
export function runMap(items, iteratee) {
  return async.map(items, iteratee);
}

/**
 * Filters items using an asynchronous predicate.
 * @param {Array} items Collection to filter.
 * @param {Function} predicate Async predicate returning boolean.
 * @returns {Promise<Array>} Resolves with filtered elements.
 */
export function runFilter(items, predicate) {
  return async.filter(items, predicate);
}

/**
 * Reduces a collection to a single value using an async reducer function.
 * @param {Array} items Collection to reduce.
 * @param {*} initialMemo Initial accumulator value.
 * @param {Function} reducer Async reducer (memo, item, callback).
 * @returns {Promise<*>} Resolves with the reduced value.
 */
export function runReduce(items, initialMemo, reducer) {
  return async.reduce(items, initialMemo, reducer);
}

/**
 * Creates a QueueObject with the specified concurrency.
 * @param {Function} worker Task processor function.
 * @param {number} concurrency Max tasks processed simultaneously.
 * @returns {Object} Async queue instance.
 */
export function createTaskQueue(worker, concurrency) {
  return async.queue(worker, concurrency);
}

/**
 * Retries an asynchronous task until it succeeds or attempts are exhausted.
 * @param {number|Object} opts Retry options or max attempts.
 * @param {Function} task Task function to execute.
 * @returns {Promise<any>} Resolves with task result.
 */
export function runRetry(opts, task) {
  return async.retry(opts, task);
}

export { async };
export default async;
test/contract.mjs
import assert from 'node:assert/strict';
import async from 'async';
import {
  runWaterfall,
  runParallel,
  runEachLimit,
  runMap,
  runFilter,
  runReduce,
  createTaskQueue,
  runRetry
} from '../src/index.mjs';

// 1. async.waterfall runs an array of dependent tasks in series passing results to next tasks
{
  const result = await async.waterfall([
    (callback) => {
      callback(null, 'step1', 10);
    },
    (arg1, arg2, callback) => {
      callback(null, `${arg1}-${arg2 + 5}`);
    },
    (arg3, callback) => {
      callback(null, `result:${arg3}`);
    }
  ]);
  assert.equal(result, 'result:step1-15');

  const helperResult = await runWaterfall([
    (callback) => callback(null, 100),
    (val, callback) => callback(null, val * 2)
  ]);
  assert.equal(helperResult, 200);
}

// 2. async.parallel executes async tasks in parallel and collects results
{
  let order = [];
  const results = await async.parallel([
    async () => {
      await new Promise((resolve) => setTimeout(resolve, 20));
      order.push('t1');
      return 1;
    },
    async () => {
      await new Promise((resolve) => setTimeout(resolve, 10));
      order.push('t2');
      return 2;
    }
  ]);
  assert.deepEqual(results, [1, 2]);
  assert.deepEqual(order, ['t2', 't1']);

  const objResult = await runParallel({
    a: (cb) => cb(null, 'apple'),
    b: (cb) => cb(null, 'banana')
  });
  assert.deepEqual(objResult, { a: 'apple', b: 'banana' });
}

// 3. async.eachLimit iterates over items with a concurrency limit
{
  let active = 0;
  let maxActive = 0;
  const items = [1, 2, 3, 4, 5, 6];
  const processed = [];

  await async.eachLimit(items, 2, async (item) => {
    active++;
    maxActive = Math.max(maxActive, active);
    await new Promise((resolve) => setTimeout(resolve, 15));
    processed.push(item);
    active--;
  });

  assert.equal(maxActive, 2);
  assert.equal(processed.length, 6);

  let helperActive = 0;
  let helperMaxActive = 0;
  await runEachLimit([10, 20, 30], 1, async (x) => {
    helperActive++;
    helperMaxActive = Math.max(helperMaxActive, helperActive);
    await new Promise((resolve) => setTimeout(resolve, 10));
    helperActive--;
  });
  assert.equal(helperMaxActive, 1);
}

// 4. async.map transforms an array asynchronously and preserves result ordering
{
  const input = [10, 20, 30];
  const mapped = await async.map(input, async (val) => {
    await new Promise((resolve) => setTimeout(resolve, 10));
    return val * 2;
  });
  assert.deepEqual(mapped, [20, 40, 60]);

  const helperMapped = await runMap(['a', 'b'], async (str) => str.toUpperCase());
  assert.deepEqual(helperMapped, ['A', 'B']);
}

// 5. async.filter filters items based on asynchronous predicate test
{
  const numbers = [1, 2, 3, 4, 5, 6];
  const evens = await async.filter(numbers, async (n) => {
    return n % 2 === 0;
  });
  assert.deepEqual(evens, [2, 4, 6]);

  const helperFiltered = await runFilter(['apple', 'kiwi', 'pear'], async (fruit) => fruit.length > 4);
  assert.deepEqual(helperFiltered, ['apple']);
}

// 6. async.reduce reduces an array to a single value using an async reducer function
{
  const numbers = [1, 2, 3, 4];
  const sum = await async.reduce(numbers, 0, async (memo, item) => {
    return memo + item;
  });
  assert.equal(sum, 10);

  const helperReduced = await runReduce(['a', 'b', 'c'], 'start', async (memo, item) => `${memo}-${item}`);
  assert.equal(helperReduced, 'start-a-b-c');
}

// 7. async.queue processes tasks with concurrency control and drain handling
{
  let activeCount = 0;
  let peakActive = 0;
  const completed = [];

  const q = async.queue(async (task) => {
    activeCount++;
    peakActive = Math.max(peakActive, activeCount);
    await new Promise((resolve) => setTimeout(resolve, 15));
    completed.push(task.id);
    activeCount--;
    return task.id;
  }, 2);

  assert.equal(q.concurrency, 2);

  let drained = false;
  q.drain(() => {
    drained = true;
  });

  q.push([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }]);
  await q.drain();

  assert.equal(drained, true);
  assert.equal(peakActive, 2);
  assert.equal(completed.length, 4);

  const helperQueue = createTaskQueue(async (data) => data * 2, 1);
  assert.equal(helperQueue.concurrency, 1);
}

// 8. async.retry executes an operation repeatedly until it succeeds or reaches attempt limit
{
  let attempts = 0;
  const result = await async.retry(3, (callback) => {
    attempts++;
    if (attempts < 3) {
      callback(new Error('transient error'));
    } else {
      callback(null, 'success');
    }
  });

  assert.equal(result, 'success');
  assert.equal(attempts, 3);

  let failed = false;
  try {
    await runRetry(2, (cb) => cb(new Error('always fails')));
  } catch (err) {
    failed = true;
    assert.equal(err.message, 'always fails');
  }
  assert.equal(failed, true);
}

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

原始种子者

匿名