CodeSampleX

Exemplo

postcss 8.5.26: Container#index

Amostra verificada para npm postcss 8.5.26: Container#index. O contrato rodou em node 22 · linux alpine/x64 · docker e passou.

sha256:c66d33ecd6ced22f89a95eca12a3f620163c8981d2ac74b33dfacb334d6c66cf

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 linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Caso

HOW
Objetivo
verify Container#index in pkg:npm/postcss@8.5.26
Pacotes
Símbolos
  • Container#index
Criado
2026-08-27T01:53:31Z

Contrato

  1. assert Container#index returns 0-based index of child Node in Root container
  2. assert Container#index returns 0-based index of Declaration or Comment in Rule container
  3. assert Container#index returns numeric argument as-is when number is passed
  4. assert Container#index returns -1 when target node does not belong to the container
  5. assert Container#index resolves index correctly for proxy-wrapped nodes and parsed AST children

Arquivos

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

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

Código-fonte

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 Container#index in pkg:npm/postcss@8.5.26
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/postcss@8.5.26
Demonstrate these symbols/APIs:
  - Container#index

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:f9ad5933b41936cc323db281744168d77814b763bc44c358f284c85338ebc92e","contract":["assert Container#index returns 0-based index of child Node in Root container","assert Container#index returns 0-based index of Declaration or Comment in Rule container","assert Container#index returns numeric argument as-is when number is passed","assert Container#index returns -1 when target node does not belong to the container","assert Container#index resolves index correctly for proxy-wrapped nodes and parsed AST children"],"goal":"verify Container#index in pkg:npm/postcss@8.5.26","kind":"HOW","packages":["pkg:npm/postcss@8.5.26"],"schemaVersion":1,"symbols":["Container#index"]},"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/postcss@8.5.26"],"schemaVersion":1,"subject":"pkg:npm/postcss@8.5.26","symbols":["Container#index"],"verifierAdapter":"node-typescript@1"}
index.js
import postcss from 'postcss';

/**
 * Returns the index of a child node or numerical position within a PostCSS container.
 *
 * @param {import('postcss').Container} container
 * @param {import('postcss').Node|number} child
 * @returns {number} 0-based index of the child, or -1 if not found
 */
export function getNodeIndex(container, child) {
  if (!container || typeof container.index !== 'function') {
    throw new TypeError('Expected a PostCSS Container instance');
  }
  return container.index(child);
}

/**
 * Finds the index and node of the first declaration matching the given property name.
 *
 * @param {import('postcss').Container} container
 * @param {string} propertyName
 * @returns {{ index: number, decl: import('postcss').Declaration | null }}
 */
export function findDeclarationIndex(container, propertyName) {
  if (!container || !Array.isArray(container.nodes)) {
    return { index: -1, decl: null };
  }

  for (const node of container.nodes) {
    if (node.type === 'decl' && node.prop === propertyName) {
      const idx = container.index(node);
      return { index: idx, decl: node };
    }
  }

  return { index: -1, decl: null };
}

/**
 * Inserts a new declaration immediately after an existing declaration identified by property name.
 *
 * @param {import('postcss').Container} container
 * @param {string} targetProp
 * @param {{ prop: string, value: string }} newDeclProps
 * @returns {import('postcss').Declaration | null}
 */
export function insertDeclarationAfter(container, targetProp, newDeclProps) {
  const { index, decl } = findDeclarationIndex(container, targetProp);
  if (index === -1 || !decl) {
    return null;
  }

  const newDecl = postcss.decl(newDeclProps);
  container.insertAfter(index, newDecl);
  return newDecl;
}

/**
 * Swaps positions of two child nodes at the specified indices in a container.
 *
 * @param {import('postcss').Container} container
 * @param {number} indexA
 * @param {number} indexB
 * @returns {boolean} true if swap succeeded
 */
export function swapNodes(container, indexA, indexB) {
  if (!container || !Array.isArray(container.nodes)) {
    return false;
  }

  const total = container.nodes.length;
  if (indexA < 0 || indexA >= total || indexB < 0 || indexB >= total || indexA === indexB) {
    return false;
  }

  const nodeA = container.nodes[indexA];
  const nodeB = container.nodes[indexB];

  const firstIdx = Math.min(indexA, indexB);
  const secondIdx = Math.max(indexA, indexB);

  // Remove higher index first to preserve lower index
  container.removeChild(secondIdx);
  container.removeChild(firstIdx);

  if (indexA < indexB) {
    container.insertBefore(firstIdx, nodeB);
    container.insertBefore(secondIdx, nodeA);
  } else {
    container.insertBefore(firstIdx, nodeA);
    container.insertBefore(secondIdx, nodeB);
  }

  return true;
}
package-lock.json
{
  "name": "sample-postcss-container-index",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-postcss-container-index",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "postcss": "8.5.26"
      }
    },
    "node_modules/nanoid": {
      "version": "3.3.18",
      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
      "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "bin": {
        "nanoid": "bin/nanoid.cjs"
      },
      "engines": {
        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
      }
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    },
    "node_modules/postcss": {
      "version": "8.5.26",
      "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
      "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
      "funding": [
        {
          "type": "opencollective",
          "url": "https://opencollective.com/postcss/"
        },
        {
          "type": "tidelift",
          "url": "https://tidelift.com/funding/github/npm/postcss"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "nanoid": "^3.3.17",
        "picocolors": "^1.1.1",
        "source-map-js": "^1.2.1"
      },
      "engines": {
        "node": "^10 || ^12 || >=14"
      }
    },
    "node_modules/source-map-js": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
      "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-postcss-container-index",
  "version": "1.0.0",
  "description": "Clean-room sample verifying Container#index in postcss",
  "main": "index.js",
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "postcss": "8.5.26"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Container#index in pkg:npm/postcss@8.5.26",
  "kind": "HOW",
  "packages": [
    "pkg:npm/postcss@8.5.26"
  ],
  "symbols": [
    "Container#index"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import postcss from 'postcss';
import { getNodeIndex, findDeclarationIndex, insertDeclarationAfter, swapNodes } from '../index.js';

// 1. assert Container#index returns 0-based index of child Node in Root container
{
  const css = `
    @charset "UTF-8";
    @import "base.css";
    .card { color: black; }
    /* footer comment */
  `;
  const root = postcss.parse(css);

  const charsetAtRule = root.nodes[0];
  const importAtRule = root.nodes[1];
  const cardRule = root.nodes[2];
  const footerComment = root.nodes[3];

  assert.equal(root.index(charsetAtRule), 0, 'First at-rule in root must be index 0');
  assert.equal(root.index(importAtRule), 1, 'Second at-rule in root must be index 1');
  assert.equal(root.index(cardRule), 2, 'Rule in root must be index 2');
  assert.equal(root.index(footerComment), 3, 'Comment in root must be index 3');
  assert.equal(getNodeIndex(root, cardRule), 2, 'getNodeIndex helper must return 2 for rule in root');
}

// 2. assert Container#index returns 0-based index of Declaration or Comment in Rule container
{
  const root = postcss.parse(`
    .button {
      display: inline-block;
      /* layout properties */
      margin: 8px;
      padding: 4px 12px;
      color: #333;
    }
  `);

  const rule = root.first;
  assert.ok(rule && rule.type === 'rule', 'Root first child must be a Rule');

  const displayDecl = rule.nodes[0];
  const commentNode = rule.nodes[1];
  const marginDecl = rule.nodes[2];
  const paddingDecl = rule.nodes[3];
  const colorDecl = rule.nodes[4];

  assert.equal(rule.index(displayDecl), 0, 'display declaration must be index 0 in rule');
  assert.equal(rule.index(commentNode), 1, 'comment must be index 1 in rule');
  assert.equal(rule.index(marginDecl), 2, 'margin declaration must be index 2 in rule');
  assert.equal(rule.index(paddingDecl), 3, 'padding declaration must be index 3 in rule');
  assert.equal(rule.index(colorDecl), 4, 'color declaration must be index 4 in rule');

  const found = findDeclarationIndex(rule, 'margin');
  assert.equal(found.index, 2, 'findDeclarationIndex must find margin at index 2');
  assert.equal(found.decl, marginDecl, 'found declaration reference must match');
}

// 3. assert Container#index returns numeric argument as-is when number is passed
{
  const root = postcss.parse('a { color: red; }');
  const rule = root.first;

  assert.equal(root.index(0), 0, 'root.index(0) must return 0');
  assert.equal(root.index(42), 42, 'root.index(42) must return 42');
  assert.equal(root.index(-1), -1, 'root.index(-1) must return -1');
  assert.equal(rule.index(3), 3, 'rule.index(3) must return 3');
  assert.equal(getNodeIndex(rule, 7), 7, 'getNodeIndex(rule, 7) must return 7');
}

// 4. assert Container#index returns -1 when target node does not belong to the container
{
  const rootA = postcss.parse('.container-a { color: blue; }');
  const rootB = postcss.parse('.container-b { font-size: 16px; }');

  const ruleA = rootA.first;
  const ruleB = rootB.first;
  const declA = ruleA.first;
  const declB = ruleB.first;

  const standaloneDecl = postcss.decl({ prop: 'opacity', value: '0.8' });

  assert.equal(ruleA.index(declB), -1, 'Node belonging to ruleB must return -1 in ruleA');
  assert.equal(ruleB.index(declA), -1, 'Node belonging to ruleA must return -1 in ruleB');
  assert.equal(rootA.index(declA), -1, 'Declaration inside ruleA is not a direct child of rootA and must return -1');
  assert.equal(ruleA.index(standaloneDecl), -1, 'Unattached node must return -1 in ruleA');
  assert.equal(rootA.index(standaloneDecl), -1, 'Unattached node must return -1 in rootA');
}

// 5. assert Container#index resolves index correctly for proxy-wrapped nodes and parsed AST children
{
  const root = postcss.parse(`
    .nav {
      top: 0;
      left: 0;
      position: fixed;
    }
  `);
  const rule = root.first;

  // Verify proxyOf unwrapping inside index()
  const topDecl = rule.nodes[0];
  const proxyDecl = topDecl.toProxy ? topDecl.toProxy() : topDecl;
  assert.equal(rule.index(proxyDecl), 0, 'index() on proxy wrapped child must return 0');

  // Verify container mutations with indexing helpers
  const inserted = insertDeclarationAfter(rule, 'top', { prop: 'right', value: '0' });
  assert.ok(inserted, 'insertDeclarationAfter must succeed');
  assert.equal(rule.index(inserted), 1, 'Newly inserted node must be placed at index 1');
  assert.equal(rule.nodes[1].prop, 'right');

  // Verify swap operation using container index positions
  const swapResult = swapNodes(rule, 0, 3);
  assert.equal(swapResult, true, 'swapNodes must return true');
  assert.equal(rule.nodes[0].prop, 'position', 'Element from index 3 must now be at index 0');
  assert.equal(rule.nodes[3].prop, 'top', 'Element from index 0 must now be at index 3');
}

console.log('All Container#index contract assertions passed successfully.');

Seeder de origem

anônimo