CodeSampleX

示例

exponential-backoff 3.1.3: backOff

已验证示例 — npm exponential-backoff 3.1.3: backOff. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: backOff executes an async function and resolves with…

sha256:5c54bec84008dd91d29a76ff3e26944d833a70bc3ac30ebfb200437c5bdadf65

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-26
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-07

案例

HOW
目标
verify pkg:npm/exponential-backoff@3.1.3
包
符号
  • backOff
环境
node 22.23.2
创建时间
2026-08-26T07:35:16Z

契约

  1. backOff executes an async function and resolves with its return value on the first attempt without delay
  2. backOff retries a failing async function with exponential delay and resolves when a subsequent attempt succeeds
  3. backOff rejects with the last encountered error when numOfAttempts is exceeded
  4. backOff invokes the retry callback with the error and attempt index and stops retrying when retry returns false
  5. backOff supports asynchronous retry callbacks to determine whether to continue reattempts
  6. retryWithBackoff wraps backOff and passes custom options including startingDelay, numOfAttempts, and jitter

文件

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

Use EXACTLY these public packages and versions:
  - pkg:npm/exponential-backoff@3.1.3
Demonstrate these symbols/APIs:
  - backOff

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:ab9ad279ebfd7943324a14414bb38576327fdf583a5aa42ebf15440fc3416f1e","contract":["backOff executes an async function and resolves with its return value on the first attempt without delay","backOff retries a failing async function with exponential delay and resolves when a subsequent attempt succeeds","backOff rejects with the last encountered error when numOfAttempts is exceeded","backOff invokes the retry callback with the error and attempt index and stops retrying when retry returns false","backOff supports asynchronous retry callbacks to determine whether to continue reattempts","retryWithBackoff wraps backOff and passes custom options including startingDelay, numOfAttempts, and jitter"],"goal":"verify pkg:npm/exponential-backoff@3.1.3","kind":"HOW","packages":["pkg:npm/exponential-backoff@3.1.3"],"schemaVersion":1,"symbols":["backOff"]},"contractCommand":["node","test/contract.mjs"],"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/exponential-backoff@3.1.3"],"schemaVersion":1,"subject":"pkg:npm/exponential-backoff@3.1.3","symbols":["backOff"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-exponential-backoff",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-exponential-backoff",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "exponential-backoff": "3.1.3"
      }
    },
    "node_modules/exponential-backoff": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
      "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==",
      "license": "Apache-2.0"
    }
  }
}
package.json
{
  "name": "sample-exponential-backoff",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for exponential-backoff@3.1.3",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "exponential-backoff": "3.1.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/exponential-backoff@3.1.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/exponential-backoff@3.1.3"
  ],
  "symbols": [
    "backOff"
  ]
}
src/index.js
'use strict';

const { backOff } = require('exponential-backoff');

/**
 * Retries an asynchronous operation with exponential backoff.
 *
 * @template T
 * @param {() => Promise<T>} fn - The asynchronous operation to execute.
 * @param {import('exponential-backoff').BackoffOptions} [options] - Backoff configuration options.
 * @returns {Promise<T>} Result of the operation.
 */
async function retryWithBackoff(fn, options = {}) {
  return backOff(fn, options);
}

module.exports = {
  backOff,
  retryWithBackoff
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { backOff, retryWithBackoff } = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof backOff, 'function', 'backOff export must be a function');
  assert.equal(typeof retryWithBackoff, 'function', 'retryWithBackoff export must be a function');

  // 2. Immediate success without retry
  let callCount1 = 0;
  const result1 = await backOff(async () => {
    callCount1++;
    return 'immediate-success';
  });
  assert.equal(result1, 'immediate-success');
  assert.equal(callCount1, 1, 'should only be called once on immediate success');

  // 3. Retries on failure and succeeds
  let callCount2 = 0;
  const attemptsSeen = [];
  const result2 = await backOff(async () => {
    callCount2++;
    if (callCount2 < 3) {
      throw new Error(`fail ${callCount2}`);
    }
    return 'recovered';
  }, {
    numOfAttempts: 5,
    startingDelay: 5,
    timeMultiple: 1.5,
    retry: (err, attemptNumber) => {
      assert(err instanceof Error);
      attemptsSeen.push(attemptNumber);
      return true;
    }
  });
  assert.equal(result2, 'recovered');
  assert.equal(callCount2, 3);
  assert.deepEqual(attemptsSeen, [1, 2], 'retry callback receives the 1-based attempt number that failed');

  // 4. Max attempts exceeded throws last error
  let callCount3 = 0;
  await assert.rejects(
    async () => {
      await backOff(async () => {
        callCount3++;
        throw new Error(`persistent error ${callCount3}`);
      }, {
        numOfAttempts: 3,
        startingDelay: 5
      });
    },
    {
      name: 'Error',
      message: 'persistent error 3'
    },
    'should reject with the last error when numOfAttempts is exhausted'
  );
  assert.equal(callCount3, 3);

  // 5. Abort early when retry callback returns false
  let callCount4 = 0;
  await assert.rejects(
    async () => {
      await backOff(async () => {
        callCount4++;
        const error = new Error('non-retryable error');
        error.code = 'UNRECOVERABLE';
        throw error;
      }, {
        numOfAttempts: 5,
        startingDelay: 5,
        retry: (err) => {
          return err.code !== 'UNRECOVERABLE';
        }
      });
    },
    (err) => {
      return err.message === 'non-retryable error' && err.code === 'UNRECOVERABLE';
    },
    'should stop retrying immediately when retry returns false'
  );
  assert.equal(callCount4, 1, 'should not retry after retry returns false');

  // 6. Async retry callback support
  let callCount5 = 0;
  const asyncResult = await backOff(async () => {
    callCount5++;
    if (callCount5 === 1) {
      throw new Error('transient error');
    }
    return 'async-recovered';
  }, {
    numOfAttempts: 3,
    startingDelay: 5,
    retry: async (err, attemptNumber) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return attemptNumber < 2;
    }
  });
  assert.equal(asyncResult, 'async-recovered');
  assert.equal(callCount5, 2);

  // 7. Custom options and retryWithBackoff wrapper
  let wrapperCount = 0;
  const wrapperResult = await retryWithBackoff(async () => {
    wrapperCount++;
    if (wrapperCount < 2) {
      throw new Error('first try fail');
    }
    return 42;
  }, {
    numOfAttempts: 4,
    startingDelay: 5,
    delayFirstAttempt: false,
    jitter: 'none',
    maxDelay: 50
  });
  assert.equal(wrapperResult, 42);
  assert.equal(wrapperCount, 2);

  console.log('All exponential-backoff contract tests passed successfully.');
}

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

原始种子者

匿名