CodeSampleX

샘플

gensync 1.0.0-beta.2: sync and async generator execution with gensync

검증된 샘플 — npm gensync 1.0.0-beta.2: sync and async generator execution with gensync. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:f2ad7f3559b9e0001cd231479bacb25599439f845acb8a84ffaa10c612744cc2

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

컨트랙트

  1. gensync wraps sync and async function handlers into a unified dual-mode operation
  2. gensync wraps generator functions allowing unified sync and async execution via .sync and .async
  3. gensync function supports Node.js errback callback pattern via .errback
  4. gensync.all executes multiple gensync operations concurrently in async mode and sequentially in sync mode
  5. gensync.race resolves with the first completed operation across sync and async modes
  6. gensync.race throws GENSYNC_RACE_NONEMPTY when given an empty iterable
  7. gensync throws GENSYNC_OPTIONS_ERROR when invalid handler options are provided
  8. gensync throws GENSYNC_ERRBACK_NO_CALLBACK when .errback is invoked without a callback function
  9. gensync propagates errors thrown inside generator steps in both sync and async modes

파일

  • 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: sync and async generator execution with gensync
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/gensync@1.0.0-beta.2
Demonstrate these symbols/APIs:
  - gensync
  - gensync.all
  - gensync.race

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:af1bd453985aafa47f0987993694356e4b604bfd9e911d9522c1f7bd0098dfb8","contract":["gensync wraps sync and async function handlers into a unified dual-mode operation","gensync wraps generator functions allowing unified sync and async execution via .sync and .async","gensync function supports Node.js errback callback pattern via .errback","gensync.all executes multiple gensync operations concurrently in async mode and sequentially in sync mode","gensync.race resolves with the first completed operation across sync and async modes","gensync.race throws GENSYNC_RACE_NONEMPTY when given an empty iterable","gensync throws GENSYNC_OPTIONS_ERROR when invalid handler options are provided","gensync throws GENSYNC_ERRBACK_NO_CALLBACK when .errback is invoked without a callback function","gensync propagates errors thrown inside generator steps in both sync and async modes"],"goal":"sync and async generator execution with gensync","kind":"HOW","packages":["pkg:npm/gensync@1.0.0-beta.2"],"schemaVersion":1,"symbols":["gensync","gensync.all","gensync.race"]},"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/gensync@1.0.0-beta.2"],"schemaVersion":1,"subject":"pkg:npm/gensync@1.0.0-beta.2","symbols":["gensync","gensync.all","gensync.race"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-gensync",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-gensync",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "gensync": "1.0.0-beta.2"
      }
    },
    "node_modules/gensync": {
      "version": "1.0.0-beta.2",
      "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
      "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-gensync",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "gensync": "1.0.0-beta.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "sync and async generator execution with gensync",
  "kind": "HOW",
  "packages": [
    "pkg:npm/gensync@1.0.0-beta.2"
  ],
  "symbols": [
    "gensync",
    "gensync.all",
    "gensync.race"
  ]
}
src/index.mjs
import gensync from 'gensync';

/**
 * Creates a gensync operation from sync and async handlers.
 * @param {object} options Options object containing sync, async, or errback handlers.
 * @returns {Function} Gensync wrapped operation.
 */
export function createOperation(options) {
  return gensync(options);
}

/**
 * Creates a gensync workflow generator function that coordinates operations.
 * @param {GeneratorFunction} genFn Generator function using yield* for gensync operations.
 * @returns {Function} Gensync wrapped workflow.
 */
export function createWorkflow(genFn) {
  return gensync(genFn);
}

/**
 * Runs an array of gensync tasks concurrently (in async mode) or sequentially (in sync mode).
 * @param {Iterable} tasks Iterable of gensync generator calls.
 * @returns {Generator} Gensync all generator.
 */
export function runAll(tasks) {
  return gensync.all(tasks);
}

/**
 * Races an array of gensync tasks to return the first result.
 * @param {Iterable} tasks Iterable of gensync generator calls.
 * @returns {Generator} Gensync race generator.
 */
export function runRace(tasks) {
  return gensync.race(tasks);
}

export { gensync };
export default gensync;
test/contract.mjs
import assert from 'node:assert/strict';
import gensync from 'gensync';
import {
  createOperation,
  createWorkflow,
  runAll,
  runRace,
} from '../src/index.mjs';

// 1. gensync wraps sync and async function handlers into a unified dual-mode operation
{
  const readData = createOperation({
    name: 'readData',
    sync: (key) => `sync:${key}`,
    async: async (key) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return `async:${key}`;
    },
  });

  const syncResult = readData.sync('config');
  assert.equal(syncResult, 'sync:config');

  const asyncResult = await readData.async('config');
  assert.equal(asyncResult, 'async:config');
}

// 2. gensync wraps generator functions allowing unified sync and async execution via .sync and .async
{
  const fetchPart = gensync({
    sync: (part) => `part-${part}`,
    async: async (part) => `part-${part}`,
  });

  const assemble = createWorkflow(function* (id) {
    const part1 = yield* fetchPart(`${id}-A`);
    const part2 = yield* fetchPart(`${id}-B`);
    return `${part1}+${part2}`;
  });

  const syncAssembled = assemble.sync('job1');
  assert.equal(syncAssembled, 'part-job1-A+part-job1-B');

  const asyncAssembled = await assemble.async('job1');
  assert.equal(asyncAssembled, 'part-job1-A+part-job1-B');
}

// 3. gensync function supports Node.js errback callback pattern via .errback
{
  const compute = gensync({
    sync: (val) => val * 10,
    async: async (val) => val * 10,
  });

  const res = await new Promise((resolve, reject) => {
    compute.errback(5, (err, val) => {
      if (err) reject(err);
      else resolve(val);
    });
  });
  assert.equal(res, 50);
}

// 4. gensync.all executes multiple gensync operations concurrently in async mode and sequentially in sync mode
{
  const task = gensync({
    sync: (x) => `res:${x}`,
    async: async (x) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return `res:${x}`;
    },
  });

  const batch = gensync(function* (items) {
    const results = yield* runAll(items.map((item) => task(item)));
    return results;
  });

  const syncResults = batch.sync(['a', 'b', 'c']);
  assert.deepEqual(syncResults, ['res:a', 'res:b', 'res:c']);

  const asyncResults = await batch.async(['a', 'b', 'c']);
  assert.deepEqual(asyncResults, ['res:a', 'res:b', 'res:c']);

  // Empty iterable handling
  const emptyBatch = gensync(function* () {
    return yield* gensync.all([]);
  });
  assert.deepEqual(emptyBatch.sync(), []);
  assert.deepEqual(await emptyBatch.async(), []);
}

// 5. gensync.race resolves with the first completed operation across sync and async modes
{
  const fastTask = gensync({
    sync: () => 'fast-sync',
    async: async () => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return 'fast-async';
    },
  });

  const slowTask = gensync({
    sync: () => 'slow-sync',
    async: async () => {
      await new Promise((resolve) => setTimeout(resolve, 50));
      return 'slow-async';
    },
  });

  const raceWorkflow = gensync(function* () {
    return yield* runRace([fastTask(), slowTask()]);
  });

  const syncRace = raceWorkflow.sync();
  assert.equal(syncRace, 'fast-sync');

  const asyncRace = await raceWorkflow.async();
  assert.equal(asyncRace, 'fast-async');
}

// 6. gensync.race throws GENSYNC_RACE_NONEMPTY when given an empty iterable
{
  const emptyRaceSync = gensync(function* () {
    return yield* gensync.race([]);
  });

  assert.throws(
    () => emptyRaceSync.sync(),
    (err) => err.code === 'GENSYNC_RACE_NONEMPTY'
  );

  await assert.rejects(
    async () => emptyRaceSync.async(),
    (err) => err.code === 'GENSYNC_RACE_NONEMPTY'
  );
}

// 7. gensync throws GENSYNC_OPTIONS_ERROR when invalid handler options are provided
{
  assert.throws(
    () => gensync({ sync: 'not-a-function' }),
    (err) => err.code === 'GENSYNC_OPTIONS_ERROR'
  );

  assert.throws(
    () => gensync({ sync: () => {}, async: () => {}, errback: () => {} }),
    (err) => err.code === 'GENSYNC_OPTIONS_ERROR'
  );
}

// 8. gensync throws GENSYNC_ERRBACK_NO_CALLBACK when .errback is invoked without a callback function
{
  const fn = gensync({
    sync: () => 1,
    async: async () => 1,
  });

  assert.throws(
    () => fn.errback(123),
    (err) => err.code === 'GENSYNC_ERRBACK_NO_CALLBACK'
  );
}

// 9. gensync propagates errors thrown inside generator steps in both sync and async modes
{
  const failingOp = gensync({
    sync: () => {
      throw new Error('sync failure');
    },
    async: async () => {
      throw new Error('async failure');
    },
  });

  const failWorkflow = gensync(function* () {
    yield* failingOp();
  });

  assert.throws(() => failWorkflow.sync(), /sync failure/);
  await assert.rejects(async () => failWorkflow.async(), /async failure/);
}

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

오리진 시더

익명