CodeSampleX

Пример

@csstools/css-parser-algorithms 4.0.0: parse CSS component values with parseListOfComponentValues and tokenize

Проверенный пример — npm @csstools/css-parser-algorithms 4.0.0: parse CSS component values with parseListOfComponentValues and tokenize. Контракт выполнен на…

sha256:46db1a293f2908c9c69fa38cb1ad5f3a906097f03e33048c8436cd63445a9b23

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

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

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

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

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

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

Кейс

HOW
Цель
parse CSS component values with parseListOfComponentValues and tokenize
Пакеты
Символы
  • parseListOfComponentValues
Создан
2026-08-28T10:09:30Z

Контракт

  1. parseListOfComponentValues parses CSS token stream into AST component values
  2. FunctionNode identifies CSS function syntax with getName and toString
  3. SimpleBlockNode parses bracketed and parenthesized CSS blocks
  4. walk traverses component values AST hierarchically
  5. parseCommaSeparatedListOfComponentValues parses comma-delimited component value lists
  6. normalize restores missing closing delimiters for unclosed functions and blocks
  7. sourceIndices calculates start and end offsets in source

Файлы

  • 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: parse CSS component values with parseListOfComponentValues and tokenize
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40csstools/css-parser-algorithms@4.0.0
Demonstrate these symbols/APIs:
  - parseListOfComponentValues

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:81149500c2cc715019afb11637998af37fdd40a0807d5d0b4e0cad840bea087c","contract":["parseListOfComponentValues parses CSS token stream into AST component values","FunctionNode identifies CSS function syntax with getName and toString","SimpleBlockNode parses bracketed and parenthesized CSS blocks","walk traverses component values AST hierarchically","parseCommaSeparatedListOfComponentValues parses comma-delimited component value lists","normalize restores missing closing delimiters for unclosed functions and blocks","sourceIndices calculates start and end offsets in source"],"goal":"parse CSS component values with parseListOfComponentValues and tokenize","kind":"HOW","packages":["pkg:npm/%40csstools/css-parser-algorithms@4.0.0"],"schemaVersion":1,"symbols":["parseListOfComponentValues"]},"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/%40csstools/css-parser-algorithms@4.0.0"],"schemaVersion":1,"subject":"pkg:npm/%40csstools/css-parser-algorithms@4.0.0","symbols":["parseListOfComponentValues"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-css-parser-algorithms",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-css-parser-algorithms",
      "version": "1.0.0",
      "dependencies": {
        "@csstools/css-parser-algorithms": "4.0.0",
        "@csstools/css-tokenizer": "4.0.0"
      }
    },
    "node_modules/@csstools/css-parser-algorithms": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",
      "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=20.19.0"
      },
      "peerDependencies": {
        "@csstools/css-tokenizer": "^4.0.0"
      }
    },
    "node_modules/@csstools/css-tokenizer": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",
      "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=20.19.0"
      }
    }
  }
}
package.json
{
  "name": "sample-css-parser-algorithms",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @csstools/css-parser-algorithms",
  "main": "src/index.js",
  "dependencies": {
    "@csstools/css-parser-algorithms": "4.0.0",
    "@csstools/css-tokenizer": "4.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "parse CSS component values with parseListOfComponentValues and tokenize",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40csstools/css-parser-algorithms@4.0.0"
  ],
  "symbols": [
    "parseListOfComponentValues"
  ]
}
src/index.js
const { tokenize } = require('@csstools/css-tokenizer');
const {
  parseListOfComponentValues,
  parseCommaSeparatedListOfComponentValues,
  parseComponentValue,
  isFunctionNode,
  isSimpleBlockNode,
  isTokenNode,
  isWhitespaceNode,
  isCommentNode,
  sourceIndices,
  stringify,
  walk
} = require('@csstools/css-parser-algorithms');

/**
 * Parse CSS string into a list of component values.
 * @param {string} css - CSS string to parse.
 * @returns {Array<object>} Array of parsed component value AST nodes.
 */
function parseValues(css) {
  const tokens = tokenize({ css });
  return parseListOfComponentValues(tokens);
}

/**
 * Parse CSS string into a comma-separated list of component value lists.
 * @param {string} css - CSS string to parse.
 * @returns {Array<Array<object>>} Comma-separated list of component value lists.
 */
function parseCommaSeparatedValues(css) {
  const tokens = tokenize({ css });
  return parseCommaSeparatedListOfComponentValues(tokens);
}

/**
 * Collect all function nodes and their names from a CSS string.
 * @param {string} css - CSS string to analyze.
 * @returns {Array<{name: string, value: string}>} Array of function information objects.
 */
function findFunctions(css) {
  const values = parseValues(css);
  const functions = [];
  walk(values, (entry) => {
    if (isFunctionNode(entry.node)) {
      functions.push({
        name: entry.node.getName(),
        value: entry.node.toString()
      });
    }
  });
  return functions;
}

/**
 * Stringify component values back to CSS text.
 * @param {Array<Array<object>>} lists - Array of component value lists.
 * @returns {string} Stringified CSS representation.
 */
function serializeComponentValues(lists) {
  return stringify(lists);
}

module.exports = {
  tokenize,
  parseListOfComponentValues,
  parseCommaSeparatedListOfComponentValues,
  parseComponentValue,
  isFunctionNode,
  isSimpleBlockNode,
  isTokenNode,
  isWhitespaceNode,
  isCommentNode,
  sourceIndices,
  stringify,
  walk,
  parseValues,
  parseCommaSeparatedValues,
  findFunctions,
  serializeComponentValues
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  tokenize,
  parseListOfComponentValues,
  parseCommaSeparatedListOfComponentValues,
  parseComponentValue,
  isFunctionNode,
  isSimpleBlockNode,
  isTokenNode,
  isWhitespaceNode,
  isCommentNode,
  sourceIndices,
  stringify,
  walk,
  parseValues,
  parseCommaSeparatedValues,
  findFunctions,
  serializeComponentValues
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof parseListOfComponentValues, 'function', 'parseListOfComponentValues must be a function');
assert.strictEqual(typeof parseCommaSeparatedListOfComponentValues, 'function', 'parseCommaSeparatedListOfComponentValues must be a function');
assert.strictEqual(typeof parseComponentValue, 'function', 'parseComponentValue must be a function');
assert.strictEqual(typeof isFunctionNode, 'function', 'isFunctionNode must be a function');
assert.strictEqual(typeof isSimpleBlockNode, 'function', 'isSimpleBlockNode must be a function');
assert.strictEqual(typeof walk, 'function', 'walk must be a function');

// 2. parseListOfComponentValues parses CSS token stream into AST component values
const cssInput = 'calc(100% - 20px) [data-theme="dark"] /* note */';
const tokens = tokenize({ css: cssInput });
const nodes = parseListOfComponentValues(tokens);

assert.strictEqual(nodes.length, 5, 'Should parse 5 top-level component values');
assert.strictEqual(nodes[0].type, 'function');
assert.strictEqual(nodes[1].type, 'whitespace');
assert.strictEqual(nodes[2].type, 'simple-block');
assert.strictEqual(nodes[3].type, 'whitespace');
assert.strictEqual(nodes[4].type, 'comment');

assert.ok(isFunctionNode(nodes[0]), 'First node should be a FunctionNode');
assert.ok(isWhitespaceNode(nodes[1]), 'Second node should be a WhitespaceNode');
assert.ok(isSimpleBlockNode(nodes[2]), 'Third node should be a SimpleBlockNode');
assert.ok(isCommentNode(nodes[4]), 'Fifth node should be a CommentNode');

// 3. FunctionNode identifies CSS function syntax with getName and toString
const funcNode = nodes[0];
assert.strictEqual(funcNode.getName(), 'calc');
assert.strictEqual(funcNode.toString(), 'calc(100% - 20px)');
assert.strictEqual(typeof funcNode.tokens, 'function');
assert.ok(Array.isArray(funcNode.tokens()));

// 4. SimpleBlockNode parses bracketed and parenthesized CSS blocks
const blockNode = nodes[2];
assert.strictEqual(blockNode.toString(), '[data-theme="dark"]');
assert.ok(Array.isArray(blockNode.value));

// 5. walk traverses component values AST hierarchically
const visitedTypes = [];
walk(nodes, (entry) => {
  visitedTypes.push(entry.node.type);
});
assert.ok(visitedTypes.includes('function'));
assert.ok(visitedTypes.includes('token'));
assert.ok(visitedTypes.includes('simple-block'));
assert.ok(visitedTypes.includes('comment'));

const functions = findFunctions('rgb(255 0 0) linear-gradient(to right, red, blue)');
assert.strictEqual(functions.length, 2);
assert.strictEqual(functions[0].name, 'rgb');
assert.strictEqual(functions[1].name, 'linear-gradient');

// 6. parseCommaSeparatedListOfComponentValues parses comma-delimited component value lists
const commaTokens = tokenize({ css: '10px 20px, 30px 40px, auto' });
const commaLists = parseCommaSeparatedListOfComponentValues(commaTokens);
assert.strictEqual(commaLists.length, 3, 'Should split into 3 comma-separated lists');
assert.strictEqual(serializeComponentValues(commaLists), '10px 20px, 30px 40px, auto');

// 7. normalize restores missing closing delimiters for unclosed functions and blocks
const unclosedFunc = parseComponentValue(tokenize({ css: 'min(10px, 20px' }));
assert.strictEqual(unclosedFunc.toString(), 'min(10px, 20px');
unclosedFunc.normalize();
assert.strictEqual(unclosedFunc.toString(), 'min(10px, 20px)');

const unclosedBlock = parseComponentValue(tokenize({ css: '[aria-hidden="true"' }));
assert.strictEqual(unclosedBlock.toString(), '[aria-hidden="true"');
unclosedBlock.normalize();
assert.strictEqual(unclosedBlock.toString(), '[aria-hidden="true"]');

// 8. sourceIndices calculates start and end offsets in source
const indices = sourceIndices(nodes[0]);
assert.strictEqual(indices[0], 0);
assert.strictEqual(indices[1], 16);

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

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

аноним