CodeSampleX

示例

yaml 2.9.0: visit, visitAsync

已验证示例 — npm yaml 2.9.0: visit, visitAsync. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: assert visit traverses AST nodes and mutates scalar values…

sha256:0ea3da29c86f3b4496bf8b8cddba68e1994caa00092ba00c08debed428bed8af

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.22 linux 24 · ubuntu · glibc 2.39 x64 node 22.22 javascript npm 11 wsl

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19

案例

HOW
目标
verify pkg:npm/yaml@2.9.0
包
符号
  • yaml.visit
  • yaml.visitAsync
环境
node 22.22.2
创建时间
2026-08-19T12:51:57Z

契约

  1. assert visit traverses AST nodes and mutates scalar values in-place within a YAML Document
  2. assert visit removes mapping pairs and sequence items when returning visit.REMOVE
  3. assert visit replaces AST nodes when returning a new Scalar from visitor callback
  4. assert visit stops further traversal immediately when returning visit.BREAK
  5. assert visit skips child node traversal when returning visit.SKIP
  6. assert visitAsync asynchronously traverses and mutates Document AST nodes with async visitor callbacks

文件

  • PROMPT.md
  • csx.json
  • index.mjs
  • 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/yaml@2.9.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/yaml@2.9.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@11.8.0
  - runtime: node@22.22.2

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:c364dd243b5cecbd867c1066b749a08c7803c549c992fbaed3b59e89b189e7c6","constraints":{"executionContext":"node"},"contract":["assert visit traverses AST nodes and mutates scalar values in-place within a YAML Document","assert visit removes mapping pairs and sequence items when returning visit.REMOVE","assert visit replaces AST nodes when returning a new Scalar from visitor callback","assert visit stops further traversal immediately when returning visit.BREAK","assert visit skips child node traversal when returning visit.SKIP","assert visitAsync asynchronously traverses and mutates Document AST nodes with async visitor callbacks"],"goal":"verify pkg:npm/yaml@2.9.0","kind":"HOW","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["yaml.visit","yaml.visitAsync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"11.8.0","runtime":"node","runtimeVersion":"22.22.2","schemaVersion":1,"virtualization":"wsl"},"license":"MIT-0","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["yaml.visit","yaml.visitAsync"],"verifierAdapter":"node-typescript@1"}
index.mjs
import YAML, { parseDocument, visit, visitAsync, Scalar } from 'yaml';

/**
 * Traverse and modify a YAML Document AST using visit.
 */
export function walkDocument(doc, visitor) {
  visit(doc, visitor);
  return doc;
}

/**
 * Remove nodes matching a predicate by returning visit.REMOVE.
 */
export function removeMatchingNodes(doc, predicate) {
  visit(doc, {
    Pair(key, pair) {
      if (predicate('Pair', pair)) {
        return visit.REMOVE;
      }
    },
    Seq(key, seq) {
      if (predicate('Seq', seq)) {
        return visit.REMOVE;
      }
    },
    Scalar(key, scalar) {
      if (predicate('Scalar', scalar)) {
        return visit.REMOVE;
      }
    }
  });
  return doc;
}

/**
 * Replace scalar values in AST using visitor return values.
 */
export function replaceScalarValues(doc, replacer) {
  visit(doc, {
    Scalar(key, scalar) {
      const replacement = replacer(scalar.value, key);
      if (replacement !== undefined && replacement !== scalar.value) {
        return new Scalar(replacement);
      }
    }
  });
  return doc;
}

/**
 * Asynchronously traverse and modify a YAML Document AST using visitAsync.
 */
export async function walkDocumentAsync(doc, asyncVisitor) {
  await visitAsync(doc, asyncVisitor);
  return doc;
}
package-lock.json
{
  "name": "sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample",
      "version": "1.0.0",
      "dependencies": {
        "yaml": "2.9.0"
      }
    },
    "node_modules/yaml": {
      "version": "2.9.0",
      "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
      "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
      "license": "ISC",
      "bin": {
        "yaml": "bin.mjs"
      },
      "engines": {
        "node": ">= 14.6"
      },
      "funding": {
        "url": "https://github.com/sponsors/eemeli"
      }
    }
  }
}
package.json
{
  "name": "sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "yaml": "2.9.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/yaml@2.9.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/yaml@2.9.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@11.8.0",
    "runtime": "node@22.22.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import YAML, { parseDocument, visit, visitAsync, Scalar } from 'yaml';
import {
  walkDocument,
  removeMatchingNodes,
  replaceScalarValues,
  walkDocumentAsync
} from '../index.mjs';

// 1. assert visit traverses AST nodes and mutates scalar values in-place within a YAML Document
{
  const yamlSource = `
app:
  name: demo-service
  environment: staging
  port: 3000
`;
  const doc = parseDocument(yamlSource);
  walkDocument(doc, {
    Scalar(key, node) {
      if (node.value === 'staging') {
        node.value = 'production';
      }
      if (node.value === 3000) {
        node.value = 8080;
      }
    }
  });

  const js = doc.toJS();
  assert.equal(js.app.name, 'demo-service');
  assert.equal(js.app.environment, 'production');
  assert.equal(js.app.port, 8080);
}

// 2. assert visit removes mapping pairs and sequence items when returning visit.REMOVE
{
  const yamlSource = `
service:
  name: web-api
  secretKey: confidential-token
tags:
  - public
  - internal-only
  - release
`;
  const doc = parseDocument(yamlSource);
  removeMatchingNodes(doc, (type, node) => {
    if (type === 'Pair' && node.key && node.key.value === 'secretKey') {
      return true;
    }
    if (type === 'Scalar' && node.value === 'internal-only') {
      return true;
    }
    return false;
  });

  const js = doc.toJS();
  assert.equal(js.service.name, 'web-api');
  assert.equal(js.service.secretKey, undefined);
  assert.deepEqual(js.tags, ['public', 'release']);
}

// 3. assert visit replaces AST nodes when returning a new Scalar from visitor callback
{
  const yamlSource = `
database:
  host: localhost
  timeout: 5
`;
  const doc = parseDocument(yamlSource);
  replaceScalarValues(doc, (val, key) => {
    if (val === 'localhost') {
      return 'db.internal';
    }
    if (val === 5) {
      return 30;
    }
    return val;
  });

  const js = doc.toJS();
  assert.equal(js.database.host, 'db.internal');
  assert.equal(js.database.timeout, 30);
}

// 4. assert visit stops further traversal immediately when returning visit.BREAK
{
  const yamlSource = `
step1: alpha
step2: beta
step3: gamma
step4: delta
`;
  const doc = parseDocument(yamlSource);
  const visitedValues = [];
  visit(doc, {
    Scalar(key, node) {
      visitedValues.push(node.value);
      if (node.value === 'beta') {
        return visit.BREAK;
      }
    }
  });

  assert.ok(visitedValues.includes('step1'));
  assert.ok(visitedValues.includes('alpha'));
  assert.ok(visitedValues.includes('step2'));
  assert.ok(visitedValues.includes('beta'));
  assert.equal(visitedValues.includes('step3'), false);
  assert.equal(visitedValues.includes('gamma'), false);
  assert.equal(visitedValues.includes('step4'), false);
  assert.equal(visitedValues.includes('delta'), false);
}

// 5. assert visit skips child node traversal when returning visit.SKIP
{
  const yamlSource = `
included:
  nestedKey: nestedVal
skippedSection:
  nestedKey: secretVal
`;
  const doc = parseDocument(yamlSource);
  const visitedKeys = [];
  visit(doc, {
    Pair(key, pair) {
      if (pair.key && pair.key.value === 'skippedSection') {
        return visit.SKIP;
      }
    },
    Scalar(key, node) {
      visitedKeys.push(node.value);
    }
  });

  assert.deepEqual(visitedKeys, ['included', 'nestedKey', 'nestedVal']);
}

// 6. assert visitAsync asynchronously traverses and mutates Document AST nodes with async visitor callbacks
{
  const yamlSource = `
metrics:
  cpu: 10
  memory: 20
  disk: 30
`;
  const doc = parseDocument(yamlSource);
  await walkDocumentAsync(doc, {
    async Scalar(key, node) {
      if (typeof node.value === 'number') {
        await new Promise((resolve) => setTimeout(resolve, 5));
        node.value = node.value * 2;
      }
    }
  });

  const js = doc.toJS();
  assert.equal(js.metrics.cpu, 20);
  assert.equal(js.metrics.memory, 40);
  assert.equal(js.metrics.disk, 60);
}

console.log('PASS: all contract assertions satisfied');

原始种子者

匿名