CodeSampleX

샘플

p-cancelable 2.1.1: create and cancel a promise with PCancelable and handle CancelError

검증된 샘플 — npm p-cancelable 2.1.1: create and cancel a promise with PCancelable and handle CancelError. node 22 · linux alpine/x64 · docker에서 contract를 실행해…

sha256:17ee1c909e67662d1697e1def90d6dc1b4d171896c9de9c94a6451e39d4d122d

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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
목표
create and cancel a promise with PCancelable and handle CancelError
패키지
심벌
  • PCancelable
  • PCancelable.CancelError
환경
node 22.23.2
생성일
2026-08-26T08:17:19Z

컨트랙트

  1. resolves normally with the expected value when not canceled
  2. canceling a pending promise synchronously sets isCanceled to true and invokes onCancel handlers
  3. canceling rejects the promise with CancelError and error.isCanceled is true
  4. custom cancellation reason is preserved in CancelError message
  5. setting onCancel.shouldReject to false prevents promise rejection upon cancellation
  6. PCancelable.fn converts a function into a cancelable promise function

파일

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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: create and cancel a promise with PCancelable and handle CancelError
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/p-cancelable@2.1.1
Demonstrate these symbols/APIs:
  - PCancelable
  - PCancelable.CancelError

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:258b2f4af3204a62a19c1e27cf6790662ee5cc8e3b445ad6635bc13ccc999af9","contract":["resolves normally with the expected value when not canceled","canceling a pending promise synchronously sets isCanceled to true and invokes onCancel handlers","canceling rejects the promise with CancelError and error.isCanceled is true","custom cancellation reason is preserved in CancelError message","setting onCancel.shouldReject to false prevents promise rejection upon cancellation","PCancelable.fn converts a function into a cancelable promise function"],"goal":"create and cancel a promise with PCancelable and handle CancelError","kind":"HOW","packages":["pkg:npm/p-cancelable@2.1.1"],"schemaVersion":1,"symbols":["PCancelable","PCancelable.CancelError"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","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-cancelable@2.1.1"],"schemaVersion":1,"subject":"pkg:npm/p-cancelable@2.1.1","symbols":["PCancelable","PCancelable.CancelError"],"verifierAdapter":"node-typescript@1"}
index.js
import PCancelable, { CancelError } from 'p-cancelable';

/**
 * Creates a delay promise that can be canceled.
 * @param {number} ms - Milliseconds to delay.
 * @param {string} [value] - Value to resolve with.
 * @returns {PCancelable<string>} Cancelable promise.
 */
export function createCancellableDelay(ms, value = 'done') {
  return new PCancelable((resolve, reject, onCancel) => {
    const timer = setTimeout(() => {
      resolve(value);
    }, ms);

    onCancel(() => {
      clearTimeout(timer);
    });
  });
}

/**
 * Creates a cancelable operation where cancellation does not reject.
 * @param {Function} cleanupFn - Cleanup callback.
 * @returns {PCancelable<string>} Cancelable promise.
 */
export function createSilentCancellable(cleanupFn) {
  return new PCancelable((resolve, reject, onCancel) => {
    onCancel.shouldReject = false;
    onCancel(() => {
      if (cleanupFn) {
        cleanupFn();
      }
    });

    const timer = setTimeout(() => {
      resolve('completed');
    }, 100);

    onCancel(() => {
      clearTimeout(timer);
    });
  });
}

export { PCancelable, CancelError };
package-lock.json
{
  "name": "sample-p-cancelable",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-p-cancelable",
      "version": "1.0.0",
      "dependencies": {
        "p-cancelable": "2.1.1"
      }
    },
    "node_modules/p-cancelable": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
      "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    }
  }
}
package.json
{
  "name": "sample-p-cancelable",
  "version": "1.0.0",
  "private": true,
  "description": "create and cancel a promise with PCancelable and handle CancelError",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "p-cancelable": "2.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "create and cancel a promise with PCancelable and handle CancelError",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-cancelable@2.1.1"
  ],
  "symbols": [
    "PCancelable",
    "PCancelable.CancelError"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import PCancelable, { CancelError } from 'p-cancelable';
import { createCancellableDelay, createSilentCancellable } from '../index.js';

// 1. resolves normally with the expected value when not canceled
{
  const result = await createCancellableDelay(10, 'success');
  assert.strictEqual(result, 'success');
}

// 2. canceling a pending promise synchronously sets isCanceled to true and invokes onCancel handlers
{
  let cleanupCalled = false;
  const p = new PCancelable((resolve, reject, onCancel) => {
    const timer = setTimeout(() => resolve('ok'), 1000);
    onCancel(() => {
      cleanupCalled = true;
      clearTimeout(timer);
    });
  });

  assert.strictEqual(p.isCanceled, false);
  p.cancel();
  assert.strictEqual(p.isCanceled, true);
  assert.strictEqual(cleanupCalled, true);

  // Catch rejection so it does not trigger unhandledRejection
  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.strictEqual(err.isCanceled, true);
      return true;
    }
  );
}

// 3. canceling rejects the promise with CancelError and error.isCanceled is true
{
  const p = createCancellableDelay(1000);
  p.cancel();

  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.ok(err instanceof PCancelable.CancelError);
      assert.strictEqual(err.name, 'CancelError');
      assert.strictEqual(err.isCanceled, true);
      assert.strictEqual(err.message, 'Promise was canceled');
      return true;
    }
  );
}

// 4. custom cancellation reason is preserved in CancelError message
{
  const p = createCancellableDelay(1000);
  p.cancel('Operation timed out by caller');
  assert.strictEqual(p.isCanceled, true);

  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.strictEqual(err.name, 'CancelError');
      assert.strictEqual(err.isCanceled, true);
      assert.strictEqual(err.message, 'Operation timed out by caller');
      return true;
    }
  );
}

// 5. setting onCancel.shouldReject to false prevents promise rejection upon cancellation
{
  let cleanedUp = false;
  const p = createSilentCancellable(() => {
    cleanedUp = true;
  });

  assert.strictEqual(p.isCanceled, false);
  p.cancel();
  assert.strictEqual(p.isCanceled, true);
  assert.strictEqual(cleanedUp, true);

  let rejected = false;
  p.catch(() => {
    rejected = true;
  });
  await new Promise((r) => setTimeout(r, 50));
  assert.strictEqual(rejected, false);
}

// 6. PCancelable.fn converts a function into a cancelable promise function
{
  let cancelled = false;
  const fn = PCancelable.fn((arg1, onCancel) => {
    return new Promise((resolve) => {
      const timer = setTimeout(() => resolve(`hello ${arg1}`), 1000);
      onCancel(() => {
        cancelled = true;
        clearTimeout(timer);
      });
    });
  });

  const p = fn('world');
  assert.strictEqual(p.isCanceled, false);
  p.cancel('custom error');
  assert.strictEqual(p.isCanceled, true);
  assert.strictEqual(cancelled, true);

  await assert.rejects(
    async () => {
      await p;
    },
    (err) => {
      assert.ok(err instanceof CancelError);
      assert.strictEqual(err.name, 'CancelError');
      assert.strictEqual(err.isCanceled, true);
      assert.strictEqual(err.message, 'custom error');
      return true;
    }
  );
}

오리진 시더

익명