CodeSampleX

サンプル

yaml 2.9.0: visit, visitAsync

検証済みサンプル — npm yaml 2.9.0: visit, visitAsync. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: assert visit traverses AST nodes and mutates scalar…

sha256:0ea3da29c86f3b4496bf8b8cddba68e1994caa00092ba00c08debed428bed8af

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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');

オリジンシーダー

匿名