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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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');

오리진 시더

익명