CodeSampleX

示例

yaml 2.9.0: Asynchronously traverse and modify YAML AST with visitAsync

已验证示例 — npm yaml 2.9.0: Asynchronously traverse and modify YAML AST with visitAsync. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:1252c8c3eb7dd04c41fbf774e291102f99ad969814cd1b8997c64f4665dc6309

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

执行证据

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

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm 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
目标
Asynchronously traverse and modify YAML AST with visitAsync
包
符号
  • visitAsync
创建时间
2026-08-19T12:01:59Z

契约

  1. assert visitAsync asynchronously traverses YAML AST nodes including Document, Map, Seq, Pair, and Scalar
  2. assert visitAsync modifies Scalar node values and replaces nodes during async traversal
  3. assert visitAsync removes nodes and key-value pairs when visitor returns visitAsync.REMOVE
  4. assert visitAsync halts traversal immediately when visitor returns visitAsync.BREAK
  5. assert visitAsync skips child node inspection when visitor returns visitAsync.SKIP

文件

  • 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: Asynchronously traverse and modify YAML AST with visitAsync
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/yaml@2.9.0
Demonstrate these symbols/APIs:
  - visitAsync

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:584503da0c90f459f86c9923c29d6e386e004018b44de84f0f0273026e62757a","contract":["assert visitAsync asynchronously traverses YAML AST nodes including Document, Map, Seq, Pair, and Scalar","assert visitAsync modifies Scalar node values and replaces nodes during async traversal","assert visitAsync removes nodes and key-value pairs when visitor returns visitAsync.REMOVE","assert visitAsync halts traversal immediately when visitor returns visitAsync.BREAK","assert visitAsync skips child node inspection when visitor returns visitAsync.SKIP"],"goal":"Asynchronously traverse and modify YAML AST with visitAsync","kind":"HOW","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["visitAsync"]},"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,"virtualization":"wsl"},"license":"MIT-0","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["visitAsync"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { visitAsync, isScalar, isPair, isMap, isSeq, isDocument, Scalar } from 'yaml';

/**
 * Asynchronously updates all Scalar values matching the predicate.
 */
export async function transformScalarsAsync(doc, transformFn) {
  await visitAsync(doc, {
    async Scalar(key, node, path) {
      const updated = await transformFn(node.value, key, path);
      if (updated !== undefined) {
        node.value = updated;
      }
    }
  });
  return doc;
}

/**
 * Asynchronously removes pairs matching the filter condition.
 */
export async function filterPairsAsync(doc, shouldRemoveFn) {
  await visitAsync(doc, {
    async Pair(key, node, path) {
      const shouldRemove = await shouldRemoveFn(node.key?.value, node.value, path);
      if (shouldRemove) {
        return visitAsync.REMOVE;
      }
    }
  });
  return doc;
}

/**
 * Asynchronously collects visited node types.
 */
export async function collectNodeTypesAsync(doc) {
  const types = [];
  await visitAsync(doc, {
    async Map() { types.push('Map'); },
    async Seq() { types.push('Seq'); },
    async Pair() { types.push('Pair'); },
    async Scalar() { types.push('Scalar'); }
  });
  return types;
}

export { visitAsync, isScalar, isPair, isMap, isSeq, isDocument, Scalar };
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=="
    }
  }
}
package.json
{
  "name": "sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "yaml": "2.9.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Asynchronously traverse and modify YAML AST with visitAsync",
  "kind": "HOW",
  "packages": [
    "pkg:npm/yaml@2.9.0"
  ],
  "symbols": [
    "visitAsync"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { parseDocument, Scalar } from 'yaml';
import {
  visitAsync,
  transformScalarsAsync,
  filterPairsAsync,
  collectNodeTypesAsync
} from '../index.mjs';

// 1. assert visitAsync asynchronously traverses YAML AST nodes including Document, Map, Seq, Pair, and Scalar
{
  const yamlText = `
service: gateway
endpoints:
  - /health
  - /metrics
retries: 5
`;
  const doc = parseDocument(yamlText);
  const types = await collectNodeTypesAsync(doc);

  assert.ok(types.includes('Map'), 'Must visit Map nodes');
  assert.ok(types.includes('Seq'), 'Must visit Seq nodes');
  assert.ok(types.includes('Pair'), 'Must visit Pair nodes');
  assert.ok(types.includes('Scalar'), 'Must visit Scalar nodes');

  const visitedValues = [];
  await visitAsync(doc, {
    async Scalar(key, node) {
      visitedValues.push(node.value);
    }
  });

  assert.ok(visitedValues.includes('gateway'));
  assert.ok(visitedValues.includes('/health'));
  assert.ok(visitedValues.includes('/metrics'));
  assert.ok(visitedValues.includes(5));
}

// 2. assert visitAsync modifies Scalar node values and replaces nodes during async traversal
{
  const yamlText = `
user: alice
endpoint: /v1/api
`;
  const doc = parseDocument(yamlText);

  await transformScalarsAsync(doc, async (value) => {
    if (value === 'alice') {
      return Promise.resolve('bob');
    }
    return undefined;
  });

  // Replace a Scalar node with a new Scalar node
  await visitAsync(doc, {
    async Scalar(key, node) {
      if (node.value === '/v1/api') {
        return new Scalar('/v2/api');
      }
    }
  });

  const js = doc.toJS();
  assert.equal(js.user, 'bob');
  assert.equal(js.endpoint, '/v2/api');
}

// 3. assert visitAsync removes nodes and key-value pairs when visitor returns visitAsync.REMOVE
{
  const yamlText = `
environment: production
debugMode: true
tags:
  - legacy
  - stable
`;
  const doc = parseDocument(yamlText);

  await filterPairsAsync(doc, async (key) => {
    return Promise.resolve(key === 'debugMode');
  });

  await visitAsync(doc, {
    async Scalar(key, node) {
      if (node.value === 'legacy') {
        return visitAsync.REMOVE;
      }
    }
  });

  const js = doc.toJS();
  assert.equal(js.debugMode, undefined);
  assert.equal(js.environment, 'production');
  assert.deepEqual(js.tags, ['stable']);
}

// 4. assert visitAsync halts traversal immediately when visitor returns visitAsync.BREAK
{
  const yamlText = `
first: 10
second: 20
third: 30
fourth: 40
`;
  const doc = parseDocument(yamlText);
  const seenScalars = [];

  await visitAsync(doc, {
    async Scalar(key, node) {
      seenScalars.push(node.value);
      if (node.value === 20) {
        return visitAsync.BREAK;
      }
    }
  });

  assert.ok(seenScalars.includes('first'));
  assert.ok(seenScalars.includes(10));
  assert.ok(seenScalars.includes('second'));
  assert.ok(seenScalars.includes(20));
  assert.ok(!seenScalars.includes('third'), 'Should break before third');
  assert.ok(!seenScalars.includes(30), 'Should break before 30');
  assert.ok(!seenScalars.includes('fourth'), 'Should break before fourth');
  assert.ok(!seenScalars.includes(40), 'Should break before 40');
}

// 5. assert visitAsync skips child node inspection when visitor returns visitAsync.SKIP
{
  const yamlText = `
metadata:
  nestedField1: skipMe
  nestedField2: skipMeToo
keepField: processMe
`;
  const doc = parseDocument(yamlText);
  const processed = [];

  await visitAsync(doc, {
    async Map(key, node, path) {
      if (path.length > 0 && path[path.length - 1].key?.value === 'metadata') {
        return visitAsync.SKIP;
      }
    },
    async Scalar(key, node) {
      processed.push(node.value);
    }
  });

  assert.ok(processed.includes('metadata'));
  assert.ok(!processed.includes('nestedField1'), 'nestedField1 must be skipped');
  assert.ok(!processed.includes('skipMe'), 'skipMe must be skipped');
  assert.ok(!processed.includes('nestedField2'), 'nestedField2 must be skipped');
  assert.ok(!processed.includes('skipMeToo'), 'skipMeToo must be skipped');
  assert.ok(processed.includes('keepField'));
  assert.ok(processed.includes('processMe'));
}

console.log('PASS: All visitAsync contract assertions passed successfully');

原始种子者

匿名