CodeSampleX

Пример

istanbul-lib-report 3.0.1: create report context with custom watermarks and check classForPercent

Проверенный пример — npm istanbul-lib-report 3.0.1: create report context with custom watermarks and check classForPercent. Контракт выполнен на node 22 …

sha256:27b7c655ddaa34dcead744ae50c60912232b0e30b26e8858a8feada9dd56db77

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
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-27

Кейс

HOW
Цель
create report context with custom watermarks and check classForPercent
Пакеты
Символы
  • createContext
  • getDefaultWatermarks
Окружение
node 22.23.2
Создан
2026-08-27T16:33:46Z

Контракт

  1. getDefaultWatermarks returns default percentage thresholds of 50 and 80 for statements, functions, branches, and lines
  2. createContext initializes a Context instance with default directory and normalized watermarks when custom values are omitted
  3. createContext accepts custom reporting directory and watermark thresholds overriding specific coverage metric bounds
  4. Context.classForPercent classifies percentage values into low, medium, or high buckets based on configured watermark thresholds
  5. Context.classForPercent returns unknown for unrecognized coverage metric types
  6. Context.getSource retrieves file source code using custom sourceFinder function

Файлы

  • 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: create report context with custom watermarks and check classForPercent
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/istanbul-lib-report@3.0.1
Demonstrate these symbols/APIs:
  - createContext
  - getDefaultWatermarks

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:235ef04ec064d4dc3b1b867840f0783c191efefc084bb0b03b115fe9c3585349","contract":["getDefaultWatermarks returns default percentage thresholds of 50 and 80 for statements, functions, branches, and lines","createContext initializes a Context instance with default directory and normalized watermarks when custom values are omitted","createContext accepts custom reporting directory and watermark thresholds overriding specific coverage metric bounds","Context.classForPercent classifies percentage values into low, medium, or high buckets based on configured watermark thresholds","Context.classForPercent returns unknown for unrecognized coverage metric types","Context.getSource retrieves file source code using custom sourceFinder function"],"goal":"create report context with custom watermarks and check classForPercent","kind":"HOW","packages":["pkg:npm/istanbul-lib-report@3.0.1"],"schemaVersion":1,"symbols":["createContext","getDefaultWatermarks"]},"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/istanbul-lib-report@3.0.1"],"schemaVersion":1,"subject":"pkg:npm/istanbul-lib-report@3.0.1","symbols":["createContext","getDefaultWatermarks"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-istanbul-lib-report",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-istanbul-lib-report",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "istanbul-lib-report": "3.0.1"
      }
    },
    "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/istanbul-lib-coverage": {
      "version": "3.2.2",
      "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
      "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/istanbul-lib-report": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
      "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "istanbul-lib-coverage": "^3.0.0",
        "make-dir": "^4.0.0",
        "supports-color": "^7.1.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/make-dir": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
      "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
      "license": "MIT",
      "dependencies": {
        "semver": "^7.5.3"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/semver": {
      "version": "7.8.5",
      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
      "license": "ISC",
      "bin": {
        "semver": "bin/semver.js"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/supports-color": {
      "version": "7.2.0",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
      "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    }
  }
}
package.json
{
  "name": "sample-istanbul-lib-report",
  "version": "1.0.0",
  "description": "Clean-room verification sample for istanbul-lib-report",
  "main": "src/index.js",
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "istanbul-lib-report": "3.0.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "create report context with custom watermarks and check classForPercent",
  "kind": "HOW",
  "packages": [
    "pkg:npm/istanbul-lib-report@3.0.1"
  ],
  "symbols": [
    "createContext",
    "getDefaultWatermarks"
  ]
}
src/index.js
import libReport from 'istanbul-lib-report';

const { createContext: createReportContext, getDefaultWatermarks: getReportDefaultWatermarks } = libReport;

/**
 * Returns standard default watermarks for coverage metrics.
 *
 * @returns {Record<string, [number, number]>} Default watermark thresholds.
 */
export function getDefaultWatermarks() {
  return getReportDefaultWatermarks();
}

/**
 * Creates an Istanbul reporting context with optional customized settings.
 *
 * @param {object} [options={}] - Configuration options for the reporting context.
 * @param {string} [options.dir] - Base directory for report generation.
 * @param {object} [options.watermarks] - Custom watermark thresholds for metrics.
 * @param {Function} [options.sourceFinder] - Custom source lookup function.
 * @param {object} [options.coverageMap] - Coverage map instance or mock.
 * @returns {object} Istanbul Context instance.
 */
export function createCoverageReportContext(options = {}) {
  const coverageMap = options.coverageMap || {
    files: () => [],
    fileCoverageFor: () => null
  };

  return createReportContext({
    dir: options.dir,
    watermarks: options.watermarks,
    sourceFinder: options.sourceFinder,
    coverageMap
  });
}

/**
 * Evaluates coverage classification ('low', 'medium', 'high', or 'unknown') for a percentage.
 *
 * @param {object} context - Istanbul Context instance.
 * @param {string} metricType - Coverage metric ('statements', 'functions', 'branches', 'lines').
 * @param {number} percent - Coverage percentage value.
 * @returns {string} Severity class name.
 */
export function evaluateCoverageClass(context, metricType, percent) {
  return context.classForPercent(metricType, percent);
}
test/contract.mjs
import assert from 'node:assert/strict';
import libReport from 'istanbul-lib-report';
import {
  getDefaultWatermarks,
  createCoverageReportContext,
  evaluateCoverageClass
} from '../src/index.js';

const { createContext, getDefaultWatermarks: getDirectDefaultWatermarks } = libReport;

// 1. getDefaultWatermarks returns default percentage thresholds of 50 and 80 for statements, functions, branches, and lines
{
  const directDefaults = getDirectDefaultWatermarks();
  const helperDefaults = getDefaultWatermarks();

  assert.deepEqual(
    directDefaults,
    {
      statements: [50, 80],
      functions: [50, 80],
      branches: [50, 80],
      lines: [50, 80]
    },
    'Direct getDefaultWatermarks must return expected 50/80 boundaries'
  );

  assert.deepEqual(
    helperDefaults,
    directDefaults,
    'Helper getDefaultWatermarks must match direct package export'
  );
}

// 2. createContext initializes a Context instance with default directory and normalized watermarks when custom values are omitted
{
  const emptyMap = {
    files: () => [],
    fileCoverageFor: () => null
  };

  const context = createContext({ coverageMap: emptyMap });
  const helperContext = createCoverageReportContext();

  assert.equal(context.dir, 'coverage', 'Default reporting directory must be "coverage"');
  assert.equal(helperContext.dir, 'coverage', 'Helper default reporting directory must be "coverage"');

  assert.deepEqual(
    context.watermarks,
    {
      statements: [50, 80],
      functions: [50, 80],
      branches: [50, 80],
      lines: [50, 80]
    },
    'Context watermarks must default to standard boundaries'
  );
}

// 3. createContext accepts custom reporting directory and watermark thresholds overriding specific coverage metric bounds
{
  const customWatermarks = {
    statements: [65, 90],
    branches: [45, 75]
  };

  const context = createCoverageReportContext({
    dir: 'custom-reports',
    watermarks: customWatermarks
  });

  assert.equal(context.dir, 'custom-reports', 'Context must use configured directory');
  assert.deepEqual(
    context.watermarks.statements,
    [65, 90],
    'Statements watermark must reflect custom configuration'
  );
  assert.deepEqual(
    context.watermarks.branches,
    [45, 75],
    'Branches watermark must reflect custom configuration'
  );
  assert.deepEqual(
    context.watermarks.functions,
    [50, 80],
    'Unspecified functions watermark must keep default boundaries'
  );
  assert.deepEqual(
    context.watermarks.lines,
    [50, 80],
    'Unspecified lines watermark must keep default boundaries'
  );
}

// 4. Context.classForPercent classifies percentage values into low, medium, or high buckets based on configured watermark thresholds
{
  const context = createCoverageReportContext({
    watermarks: {
      statements: [60, 85]
    }
  });

  // Below low watermark ( < 60 ) -> 'low'
  assert.equal(context.classForPercent('statements', 0), 'low');
  assert.equal(context.classForPercent('statements', 59.9), 'low');
  assert.equal(evaluateCoverageClass(context, 'statements', 50), 'low');

  // Between low and high watermark ( >= 60 and < 85 ) -> 'medium'
  assert.equal(context.classForPercent('statements', 60), 'medium');
  assert.equal(context.classForPercent('statements', 75), 'medium');
  assert.equal(context.classForPercent('statements', 84.99), 'medium');
  assert.equal(evaluateCoverageClass(context, 'statements', 70), 'medium');

  // At or above high watermark ( >= 85 ) -> 'high'
  assert.equal(context.classForPercent('statements', 85), 'high');
  assert.equal(context.classForPercent('statements', 100), 'high');
  assert.equal(evaluateCoverageClass(context, 'statements', 95), 'high');
}

// 5. Context.classForPercent returns unknown for unrecognized coverage metric types
{
  const context = createCoverageReportContext();

  assert.equal(
    context.classForPercent('nonexistent_metric', 75),
    'unknown',
    'classForPercent must return "unknown" for unrecognized metric types'
  );
  assert.equal(
    evaluateCoverageClass(context, 'invalid_key', 100),
    'unknown',
    'Helper evaluateCoverageClass must return "unknown" for unrecognized metric types'
  );
}

// 6. Context.getSource retrieves file source code using custom sourceFinder function
{
  const sourceStore = {
    'lib/sample.js': 'export const answer = 42;'
  };

  const context = createCoverageReportContext({
    sourceFinder: (filePath) => {
      if (sourceStore[filePath]) {
        return sourceStore[filePath];
      }
      throw new Error(`Source not found: ${filePath}`);
    }
  });

  assert.equal(
    context.getSource('lib/sample.js'),
    'export const answer = 42;',
    'getSource must return content from sourceFinder'
  );

  assert.throws(
    () => context.getSource('missing/file.js'),
    /Source not found/,
    'getSource must propagate error from sourceFinder when file is absent'
  );
}

console.log('All contract assertions passed.');

Исходный сидер

аноним