CodeSampleX

Exemplo

is-generator-fn 2.1.0: is-generator-fn

Amostra verificada para npm is-generator-fn 2.1.0: is-generator-fn. O contrato rodou em node 22 · linux alpine/x64 · docker e passou.

sha256:cdef6f26fa7339441355aed5d11a18daa1386fcfd0986b2e35c1ab6488d31017

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-29

Caso

HOW
Objetivo
verify is-generator-fn in pkg:npm/is-generator-fn@2.1.0
Pacotes
Símbolos
  • is-generator-fn
Ambiente
node 22.23.2
Criado
2026-08-29T05:35:46Z

Contrato

  1. isGeneratorFn returns true for generator function declarations, expressions, and generator methods
  2. isGeneratorFn returns false for standard synchronous functions, arrow functions, async functions, and async generator functions
  3. isGeneratorFn returns false for generator iterator instances produced by calling generator functions
  4. isGeneratorFn safely returns false for non-function primitives, null, undefined, arrays, and objects

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# CSX Sample Notes: is-generator-fn contract verification

## 1. Search Result
`search_known_solution` returned NO_SAFE_MATCH for `pkg:npm/is-generator-fn@2.1.0` verifying `is-generator-fn`. This sample proves exact runtime semantics for generator function detection in modern Node.js and ESM environments.

## 2. What a Model Would Have Written
A naive model would:
1. Confuse generator functions (`function* () {}`) with generator iterator instances (`(function* () {})()`) and expect `isGeneratorFn` to return `true` for both.
2. Expect `async function* () {}` (async generator functions) to return `true`, even though in `is-generator-fn@2.1.0` their constructor name is `AsyncGeneratorFunction` and `toString` tag is `[object AsyncGeneratorFunction]`, making `is-generator-fn` return `false`.
3. Try to check `fn.constructor.name === 'GeneratorFunction'` without guarding against `typeof value !== 'function'` or missing `constructor` properties (e.g. `Object.create(null)` or prototypes stripped).
4. Rely on TypeScript or Babel transpilation instead of validating native Node.js ESM runtime behavior.

## 3. How the Wrong Version Fails
1. Passing a generator instance `const gen = (function* () { yield 1; })();` to `isGeneratorFn(gen)` returns `false` because `typeof gen === 'object'`, causing assertions expecting `true` to fail with `AssertionError: expected false to equal true`.
2. Expecting `isGeneratorFn(async function* () {})` to return `true` fails because `is-generator-fn@2.1.0` specifically targets synchronous generator functions.
3. Accessing properties directly without function type checks throws `TypeError: Cannot read properties of undefined` or `null`.
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 is-generator-fn in pkg:npm/is-generator-fn@2.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/is-generator-fn@2.1.0
Demonstrate these symbols/APIs:
  - is-generator-fn
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.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:87e18c64681df0757b5378e837dde60738cfa1d58cd2245ed4cbc2d483ad33e8","constraints":{"executionContext":"node"},"contract":["isGeneratorFn returns true for generator function declarations, expressions, and generator methods","isGeneratorFn returns false for standard synchronous functions, arrow functions, async functions, and async generator functions","isGeneratorFn returns false for generator iterator instances produced by calling generator functions","isGeneratorFn safely returns false for non-function primitives, null, undefined, arrays, and objects"],"goal":"verify is-generator-fn in pkg:npm/is-generator-fn@2.1.0","kind":"HOW","packages":["pkg:npm/is-generator-fn@2.1.0"],"schemaVersion":1,"symbols":["is-generator-fn"]},"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/is-generator-fn@2.1.0"],"schemaVersion":1,"subject":"pkg:npm/is-generator-fn@2.1.0","symbols":["is-generator-fn"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-is-generator-fn",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-is-generator-fn",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "is-generator-fn": "2.1.0"
      }
    },
    "node_modules/is-generator-fn": {
      "version": "2.1.0",
      "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz",
      "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-is-generator-fn",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "is-generator-fn": "2.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify is-generator-fn in pkg:npm/is-generator-fn@2.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/is-generator-fn@2.1.0"
  ],
  "symbols": [
    "is-generator-fn"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
src/index.mjs
import isGeneratorFn from 'is-generator-fn';

/**
 * Validates whether the given input is a generator function.
 * @param {unknown} value
 * @returns {boolean}
 */
export function isGeneratorFunction(value) {
  return isGeneratorFn(value);
}

/**
 * Filters an array of values, returning only those that are generator functions.
 * @param {Array<unknown>} items
 * @returns {Array<Function>}
 */
export function filterGeneratorFunctions(items) {
  if (!Array.isArray(items)) {
    return [];
  }
  return items.filter(isGeneratorFn);
}

/**
 * Distinguishes between generator functions and generator iterator objects.
 * @param {unknown} value
 * @returns {'generator-function' | 'generator-iterator' | 'other'}
 */
export function classifyGeneratorEntity(value) {
  if (isGeneratorFn(value)) {
    return 'generator-function';
  }
  if (
    value !== null &&
    typeof value === 'object' &&
    typeof value[Symbol.iterator] === 'function' &&
    typeof value.next === 'function' &&
    typeof value.throw === 'function'
  ) {
    return 'generator-iterator';
  }
  return 'other';
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import isGeneratorFn from 'is-generator-fn';
import {
  isGeneratorFunction,
  filterGeneratorFunctions,
  classifyGeneratorEntity
} from '../src/index.mjs';

// --- Part 1: Generator function declarations, expressions, and methods ---
function* sampleDeclaration() {
  yield 1;
}
const sampleExpression = function* () {
  yield 2;
};
const obj = {
  *sampleMethod() {
    yield 3;
  }
};
class SampleClass {
  *classMethod() {
    yield 4;
  }
}
const instance = new SampleClass();

assert.equal(isGeneratorFn(sampleDeclaration), true, 'Generator declaration must return true');
assert.equal(isGeneratorFn(sampleExpression), true, 'Generator expression must return true');
assert.equal(isGeneratorFn(obj.sampleMethod), true, 'Object generator method must return true');
assert.equal(isGeneratorFn(instance.classMethod), true, 'Class generator method must return true');
assert.equal(isGeneratorFunction(sampleDeclaration), true, 'Wrapper function must return true');

// --- Part 2: Non-generator functions (sync regular, arrow, async, async generator) ---
function regularFn() {
  return 1;
}
const arrowFn = () => 2;
async function asyncFn() {
  return 3;
}
async function* asyncGenFn() {
  yield 4;
}

assert.equal(isGeneratorFn(regularFn), false, 'Regular function must return false');
assert.equal(isGeneratorFn(arrowFn), false, 'Arrow function must return false');
assert.equal(isGeneratorFn(asyncFn), false, 'Async function must return false');
assert.equal(isGeneratorFn(asyncGenFn), false, 'Async generator function must return false in 2.1.0');
assert.equal(isGeneratorFunction(regularFn), false, 'Wrapper function must return false for regular function');

// --- Part 3: Generator iterator instances (objects) vs Generator functions ---
const iteratorInstance = sampleDeclaration();
assert.equal(isGeneratorFn(iteratorInstance), false, 'Generator iterator instance must return false');
assert.equal(classifyGeneratorEntity(sampleDeclaration), 'generator-function');
assert.equal(classifyGeneratorEntity(iteratorInstance), 'generator-iterator');
assert.equal(classifyGeneratorEntity(regularFn), 'other');

// --- Part 4: Primitives, null, undefined, arrays, and plain objects ---
assert.equal(isGeneratorFn(null), false, 'null must return false');
assert.equal(isGeneratorFn(undefined), false, 'undefined must return false');
assert.equal(isGeneratorFn(42), false, 'number must return false');
assert.equal(isGeneratorFn('function* () {}'), false, 'string must return false');
assert.equal(isGeneratorFn(true), false, 'boolean must return false');
assert.equal(isGeneratorFn(Symbol('gen')), false, 'symbol must return false');
assert.equal(isGeneratorFn({}), false, 'plain object must return false');
assert.equal(isGeneratorFn([]), false, 'array must return false');

// --- Part 5: Batch filtering utility ---
const mixed = [sampleDeclaration, regularFn, arrowFn, sampleExpression, null, 123, iteratorInstance];
const filtered = filterGeneratorFunctions(mixed);
assert.equal(filtered.length, 2, 'Filtered array must contain exactly 2 generator functions');
assert.equal(filtered[0], sampleDeclaration);
assert.equal(filtered[1], sampleExpression);

// --- Part 6: Default export property compatibility ---
assert.equal(typeof isGeneratorFn.default, 'function', 'Default export property must be a function');
assert.equal(isGeneratorFn.default, isGeneratorFn, 'Default export must reference isGeneratorFn');

console.log('CONTRACT PASS: is-generator-fn 2.1.0 contract verified');

Seeder de origem

anônimo