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. contract 在 node 22 · linux…

sha256:46db1a293f2908c9c69fa38cb1ad5f3a906097f03e33048c8436cd63445a9b23

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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.');

原始种子者

匿名