CodeSampleX

Sample

jest-worker 27.5.1: execute exported worker functions in parallel with Worker pool and shut down

Verified sample for npm jest-worker 27.5.1: execute exported worker functions in parallel with Worker pool and shut down. The contract ran on node 22 · linux…

sha256:98f59ba510be78133f81990262a4b0c1bde5959243ec82052e7499080d666f78

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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-27

Case

HOW
Goal
execute exported worker functions in parallel with Worker pool and shut down
Packages
Symbols
  • Worker
  • Worker.end
Created
2026-08-27T23:15:51Z

Contract

  1. Worker initializes worker pool with worker_threads and executes synchronous exported functions
  2. Worker executes asynchronous exported functions and resolves returned Promises
  3. Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end
  4. Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises
  5. Worker executes setup lifecycle hook with setupArgs during worker initialization
  6. Worker supports forked child process mode and terminates with Worker.end

Files

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • src/worker.cjs
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

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: execute exported worker functions in parallel with Worker pool and shut down
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jest-worker@27.5.1
Demonstrate these symbols/APIs:
  - Worker
  - Worker.end

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:8c8c9c25377cae62468ee59eda236d0d23b6efd867403de2a5644a68498f15eb","contract":["Worker initializes worker pool with worker_threads and executes synchronous exported functions","Worker executes asynchronous exported functions and resolves returned Promises","Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end","Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises","Worker executes setup lifecycle hook with setupArgs during worker initialization","Worker supports forked child process mode and terminates with Worker.end"],"goal":"execute exported worker functions in parallel with Worker pool and shut down","kind":"HOW","packages":["pkg:npm/jest-worker@27.5.1"],"schemaVersion":1,"symbols":["Worker","Worker.end"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jest-worker@27.5.1"],"schemaVersion":1,"subject":"pkg:npm/jest-worker@27.5.1","symbols":["Worker","Worker.end"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jest-worker",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-worker",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "jest-worker": "27.5.1"
      }
    },
    "node_modules/@types/node": {
      "version": "26.4.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
      "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/has-flag": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
      "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/jest-worker": {
      "version": "27.5.1",
      "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
      "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*",
        "merge-stream": "^2.0.0",
        "supports-color": "^8.0.0"
      },
      "engines": {
        "node": ">= 10.13.0"
      }
    },
    "node_modules/merge-stream": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
      "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
      "license": "MIT"
    },
    "node_modules/supports-color": {
      "version": "8.1.1",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
      "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/supports-color?sponsor=1"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-jest-worker",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "jest-worker": "27.5.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "execute exported worker functions in parallel with Worker pool and shut down",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jest-worker@27.5.1"
  ],
  "symbols": [
    "Worker",
    "Worker.end"
  ]
}
src/index.mjs
import { Worker } from 'jest-worker';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const __dirname = dirname(fileURLToPath(import.meta.url));
export const DEFAULT_WORKER_PATH = join(__dirname, 'worker.cjs');

/**
 * Creates a jest-worker pool pointing to the specified worker file.
 * @param {string} [workerPath] Absolute path to worker module.
 * @param {object} [options] Worker options (numWorkers, enableWorkerThreads, etc.).
 * @returns {Worker} Worker instance.
 */
export function createWorkerPool(workerPath = DEFAULT_WORKER_PATH, options = {}) {
  return new Worker(workerPath, {
    numWorkers: options.numWorkers ?? 2,
    enableWorkerThreads: options.enableWorkerThreads ?? true,
    ...options
  });
}

/**
 * Runs a batch of tasks concurrently across worker threads and terminates the pool.
 * @param {Array<{ id: number, payload: number }>} items Items to process.
 * @param {object} [options] Worker options.
 * @returns {Promise<Array<any>>} Results of batch execution.
 */
export async function runBatchAndClose(items, options = {}) {
  const worker = createWorkerPool(DEFAULT_WORKER_PATH, options);
  try {
    const promises = items.map(item => worker.processTask(item.id, item.payload));
    return await Promise.all(promises);
  } finally {
    await worker.end();
  }
}

export { Worker };
export default Worker;
src/worker.cjs
/**
 * Worker module providing compute tasks for jest-worker pool.
 */

let initializedState = null;

function setup(initVal) {
  initializedState = initVal || 'ready';
}

function teardown() {
  initializedState = null;
}

function getStatus() {
  return initializedState;
}

function computeSum(a, b) {
  return a + b;
}

async function transformText(text) {
  return text.toUpperCase();
}

function processTask(id, payload) {
  return {
    taskId: id,
    processed: true,
    result: payload * 2
  };
}

function failingTask(msg) {
  throw new Error(msg || 'task failed');
}

module.exports = {
  setup,
  teardown,
  getStatus,
  computeSum,
  transformText,
  processTask,
  failingTask
};
test/contract.mjs
import assert from 'node:assert/strict';
import { Worker } from 'jest-worker';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { createWorkerPool, runBatchAndClose, DEFAULT_WORKER_PATH } from '../src/index.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const workerPath = join(__dirname, '../src/worker.cjs');

// 1. Worker initializes worker pool with worker_threads and executes synchronous exported functions
{
  const worker = new Worker(workerPath, {
    numWorkers: 2,
    enableWorkerThreads: true
  });

  const sum = await worker.computeSum(15, 27);
  assert.equal(sum, 42);

  const endResult = await worker.end();
  assert.equal(endResult.forceExited, false);
}

// 2. Worker executes asynchronous exported functions and resolves returned Promises
{
  const worker = new Worker(workerPath, {
    numWorkers: 2,
    enableWorkerThreads: true
  });

  const res = await worker.transformText('hello jest worker');
  assert.equal(res, 'HELLO JEST WORKER');

  const endResult = await worker.end();
  assert.equal(endResult.forceExited, false);
}

// 3. Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end
{
  const items = [
    { id: 1, payload: 10 },
    { id: 2, payload: 20 },
    { id: 3, payload: 30 },
    { id: 4, payload: 40 }
  ];

  const results = await runBatchAndClose(items, { numWorkers: 2 });
  assert.deepEqual(results, [
    { taskId: 1, processed: true, result: 20 },
    { taskId: 2, processed: true, result: 40 },
    { taskId: 3, processed: true, result: 60 },
    { taskId: 4, processed: true, result: 80 }
  ]);
}

// 4. Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises
{
  const worker = new Worker(workerPath, {
    numWorkers: 1,
    enableWorkerThreads: true
  });

  let caughtError = null;
  try {
    await worker.failingTask('invalid payload input');
  } catch (err) {
    caughtError = err;
  }

  assert.ok(caughtError instanceof Error);
  assert.match(caughtError.message, /invalid payload input/);

  await worker.end();
}

// 5. Worker executes setup lifecycle hook with setupArgs during worker initialization
{
  const worker = new Worker(workerPath, {
    numWorkers: 1,
    enableWorkerThreads: true,
    setupArgs: ['custom-init-state']
  });

  const status = await worker.getStatus();
  assert.equal(status, 'custom-init-state');

  await worker.end();
}

// 6. Worker supports forked child process mode and terminates with Worker.end
{
  const worker = new Worker(workerPath, {
    numWorkers: 2,
    enableWorkerThreads: false
  });

  const res = await worker.computeSum(100, 200);
  assert.equal(res, 300);

  const endResult = await worker.end();
  assert.equal(endResult.forceExited, false);
}

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

Origin Seeder

anonymous