CodeSampleX

Пример

prettier 3.9.6: format, check, getFileInfo

Проверенный пример — npm prettier 3.9.6: format, check, getFileInfo. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:1324e134190052958fb119c7fa7f1aa91c16e4186ed65f124b56f21e9859d296

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-12

Кейс

HOW
Цель
verify pkg:npm/prettier@3.9.6
Пакеты
Символы
  • prettier.format
  • prettier.check
  • prettier.getFileInfo
Создан
2026-09-12T04:56:28Z

Контракт

  1. assert prettier.format formats JavaScript source code with specified options
  2. assert prettier.format supports custom indentation and formatting options
  3. assert prettier.check returns true for formatted code and false for unformatted code
  4. assert prettier.getFileInfo infers parser from filename extension

Файлы

  • 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: verify pkg:npm/prettier@3.9.6
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/prettier@3.9.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:da9a434c7265683e55f7cc29ace16f1e190b9e0ac51715b112b6e92b527620df","contract":["assert prettier.format formats JavaScript source code with specified options","assert prettier.format supports custom indentation and formatting options","assert prettier.check returns true for formatted code and false for unformatted code","assert prettier.getFileInfo infers parser from filename extension"],"goal":"verify pkg:npm/prettier@3.9.6","kind":"HOW","packages":["pkg:npm/prettier@3.9.6"],"schemaVersion":1,"symbols":["prettier.format","prettier.check","prettier.getFileInfo"]},"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/prettier@3.9.6"],"schemaVersion":1,"subject":"pkg:npm/prettier@3.9.6","symbols":["prettier.format","prettier.check","prettier.getFileInfo"],"verifierAdapter":"node-typescript@1"}
index.js
const prettier = require('prettier');

/**
 * Format source code with Prettier.
 * @param {string} source - Source code to format.
 * @param {object} [options] - Prettier format options.
 * @returns {Promise<string>} Formatted code.
 */
async function formatCode(source, options = {}) {
  return prettier.format(source, { parser: 'babel', ...options });
}

/**
 * Check if source code is formatted according to Prettier options.
 * @param {string} source - Source code to check.
 * @param {object} [options] - Prettier format options.
 * @returns {Promise<boolean>} True if formatted, false otherwise.
 */
async function checkFormatted(source, options = {}) {
  return prettier.check(source, { parser: 'babel', ...options });
}

/**
 * Get file information including inferred parser.
 * @param {string} filePath - Path to file.
 * @returns {Promise<object>} File info object.
 */
async function getFileInfo(filePath) {
  return prettier.getFileInfo(filePath);
}

module.exports = {
  formatCode,
  checkFormatted,
  getFileInfo,
  prettier,
};
package-lock.json
{
  "name": "sample-prettier",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-prettier",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "prettier": "3.9.6"
      }
    },
    "node_modules/prettier": {
      "version": "3.9.6",
      "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.6.tgz",
      "integrity": "sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==",
      "license": "MIT",
      "bin": {
        "prettier": "bin/prettier.cjs"
      },
      "engines": {
        "node": ">=14"
      },
      "funding": {
        "url": "https://github.com/prettier/prettier?sponsor=1"
      }
    }
  }
}
package.json
{
  "name": "sample-prettier",
  "version": "1.0.0",
  "description": "Clean-room sample verifying pkg:npm/prettier@3.9.6 functionality",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "prettier": "3.9.6"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/prettier@3.9.6",
  "kind": "HOW",
  "packages": [
    "pkg:npm/prettier@3.9.6"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import prettier from 'prettier';
import { formatCode, checkFormatted, getFileInfo } from '../index.js';

// 1. Verify prettier.format formats JavaScript code
const unformattedCode = 'const  a=1;\nconst b = {x: 2,y:   3};';
const formattedResult = await formatCode(unformattedCode, { semi: true, singleQuote: true });
assert.strictEqual(
  formattedResult,
  "const a = 1;\nconst b = { x: 2, y: 3 };\n",
  'prettier.format formats JavaScript source code with specified options'
);

const directFormat = await prettier.format('function test( ) { return 42; }', {
  parser: 'babel',
  semi: true,
});
assert.strictEqual(
  directFormat,
  'function test() {\n  return 42;\n}\n',
  'prettier.format directly formats code with specified parser'
);

// 2. Verify custom indentation and options
const customFormat = await formatCode('function foo() { return 1; }', {
  tabWidth: 4,
  useTabs: false,
  semi: false,
});
assert.strictEqual(
  customFormat,
  'function foo() {\n    return 1\n}\n',
  'prettier.format supports custom indentation and formatting options'
);

// 3. Verify prettier.check
const isProperlyFormatted = await checkFormatted('const a = 1;\n', { semi: true });
assert.strictEqual(
  isProperlyFormatted,
  true,
  'prettier.check returns true for formatted code and false for unformatted code'
);

const isPoorlyFormatted = await checkFormatted('const a=1;', { semi: true });
assert.strictEqual(
  isPoorlyFormatted,
  false,
  'prettier.check returns false for unformatted code'
);

const directCheck = await prettier.check('const x = 1;\n', { parser: 'babel' });
assert.strictEqual(
  directCheck,
  true,
  'prettier.check returns true directly for formatted code'
);

// 4. Verify prettier.getFileInfo
const fileInfoJs = await getFileInfo('example.js');
assert.strictEqual(
  fileInfoJs.inferredParser,
  'babel',
  'prettier.getFileInfo infers parser from filename extension'
);

const directFileInfo = await prettier.getFileInfo('data.json');
assert.strictEqual(
  directFileInfo.inferredParser,
  'json',
  'prettier.getFileInfo infers parser from filename extension'
);

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

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

аноним