CodeSampleX

샘플

xmlbuilder 15.1.1

검증된 샘플 — npm xmlbuilder 15.1.1. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: create creates XML documents with elements, attributes, text…

sha256:f19c32aab839841fb87ee257f29907d48befd26fcd823db8c3d5393d9b1334a6

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

케이스

HOW
목표
verify pkg:npm/xmlbuilder@15.1.1
패키지
환경
node 22.23.2
생성일
2026-08-28T05:04:19Z

컨트랙트

  1. create creates XML documents with elements, attributes, text, comments, CDATA, and processing instructions
  2. create converts plain JavaScript objects into nested XML document structures
  3. end formats and serializes XML document tree to string with customizable formatting options
  4. raw inserts unescaped XML markup directly into the node tree
  5. node manipulation supports updating and removing attributes and inspecting element hierarchy
  6. begin creates XML fragments and builders without root declarations
  7. buildStructuredXml constructs complete XML reports from structured configuration objects

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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/xmlbuilder@15.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/xmlbuilder@15.1.1
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.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:2ed3ea82da8cef481f5dbfad2b2c29016094e608bbc51c6c6604eaaefc1438fc","constraints":{"executionContext":"node"},"contract":["create creates XML documents with elements, attributes, text, comments, CDATA, and processing instructions","create converts plain JavaScript objects into nested XML document structures","end formats and serializes XML document tree to string with customizable formatting options","raw inserts unescaped XML markup directly into the node tree","node manipulation supports updating and removing attributes and inspecting element hierarchy","begin creates XML fragments and builders without root declarations","buildStructuredXml constructs complete XML reports from structured configuration objects"],"goal":"verify pkg:npm/xmlbuilder@15.1.1","kind":"HOW","packages":["pkg:npm/xmlbuilder@15.1.1"],"schemaVersion":1},"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":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/xmlbuilder@15.1.1"],"schemaVersion":1,"subject":"pkg:npm/xmlbuilder@15.1.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-xmlbuilder",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-xmlbuilder",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "xmlbuilder": "15.1.1"
      }
    },
    "node_modules/xmlbuilder": {
      "version": "15.1.1",
      "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
      "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
      "license": "MIT",
      "engines": {
        "node": ">=8.0"
      }
    }
  }
}
package.json
{
  "name": "sample-xmlbuilder",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of pkg:npm/xmlbuilder@15.1.1",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "xmlbuilder": "15.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/xmlbuilder@15.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/xmlbuilder@15.1.1"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const xmlbuilder = require('xmlbuilder');

/**
 * Creates an XML document using fluent method chaining.
 *
 * @param {string} rootName - Name of the root element.
 * @param {object} [xmldec] - XML declaration options (e.g. { version: '1.0', encoding: 'UTF-8' }).
 * @param {object} [doctype] - Doctype options.
 * @param {object} [options] - Writer/builder options.
 * @returns {object} Root XMLElement.
 */
function createDocument(rootName, xmldec, doctype, options) {
  return xmlbuilder.create(rootName, xmldec, doctype, options);
}

/**
 * Converts a plain JavaScript object into an XML document tree.
 *
 * @param {object} obj - Object representation of the XML tree.
 * @param {object} [options] - Builder options.
 * @returns {object} Root XMLElement.
 */
function createFromObject(obj, options) {
  return xmlbuilder.create(obj, options);
}

/**
 * Starts building an XML document or fragment with begin().
 *
 * @param {object|function} [options] - Builder options or chunk writer callback.
 * @returns {object} XMLDocument or XMLWriter.
 */
function beginDocument(options) {
  return xmlbuilder.begin(options);
}

/**
 * Builds a structured XML payload with elements, attributes, CDATA, comments, and instructions.
 *
 * @param {object} data - Configuration object with rootName, attributes, and items.
 * @returns {string} Formatted XML string.
 */
function buildStructuredXml(data) {
  const root = xmlbuilder.create(data.rootName || 'root', { version: '1.0', encoding: 'UTF-8' });

  if (data.attributes) {
    for (const [k, v] of Object.entries(data.attributes)) {
      root.att(k, v);
    }
  }

  if (Array.isArray(data.items)) {
    for (const item of data.items) {
      const node = root.ele(item.tag, item.attributes || {});
      if (item.text) node.txt(item.text);
      if (item.cdata) node.cdata(item.cdata);
      if (item.comment) node.comment(item.comment);
      if (item.instruction) node.instruction(item.instruction.target, item.instruction.content);
    }
  }

  return root.end({ pretty: true, indent: '  ', newline: '\n' });
}

module.exports = {
  xmlbuilder,
  createDocument,
  createFromObject,
  beginDocument,
  buildStructuredXml
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  xmlbuilder,
  createDocument,
  createFromObject,
  beginDocument,
  buildStructuredXml
} = require('../src/index.js');

// 1. create creates XML documents with elements, attributes, text, comments, CDATA, and processing instructions
{
  const root = createDocument('catalog', { version: '1.0', encoding: 'UTF-8' })
    .att('version', '2.0')
    .ele('book', { id: 'bk101' })
      .ele('author', 'John Doe').up()
      .ele('title', 'XML Building in Node').up()
      .ele('description').cdata('Contains <markup> & entities').up()
      .comment('book catalog record')
      .instruction('renderer', 'target="html"')
    .up();

  assert.strictEqual(root.name, 'catalog', 'root element name should be catalog');
  assert.strictEqual(root.getAttribute('version'), '2.0', 'root version attribute should match');

  const xmlString = root.end({ pretty: false });
  assert.strictEqual(xmlString.includes('<?xml version="1.0" encoding="UTF-8"?>'), true);
  assert.strictEqual(xmlString.includes('<catalog version="2.0">'), true);
  assert.strictEqual(xmlString.includes('<author>John Doe</author>'), true);
  assert.strictEqual(xmlString.includes('<title>XML Building in Node</title>'), true);
  assert.strictEqual(xmlString.includes('<![CDATA[Contains <markup> & entities]]>'), true);
  assert.strictEqual(xmlString.includes('<!-- book catalog record -->'), true);
  assert.strictEqual(xmlString.includes('<?renderer target="html"?>'), true);
}

// 2. create converts plain JavaScript objects into nested XML document structures
{
  const xmlObj = {
    store: {
      '@location': 'Downtown',
      item: [
        { '@sku': 'SKU100', name: 'Keyboard', price: '49.99' },
        { '@sku': 'SKU200', name: 'Mouse', price: '29.99' }
      ]
    }
  };

  const doc = createFromObject(xmlObj);
  const xml = doc.end({ pretty: false });

  assert.strictEqual(xml.includes('<store location="Downtown">'), true);
  assert.strictEqual(xml.includes('<item sku="SKU100"><name>Keyboard</name><price>49.99</price></item>'), true);
  assert.strictEqual(xml.includes('<item sku="SKU200"><name>Mouse</name><price>29.99</price></item>'), true);
}

// 3. end formats and serializes XML document tree to string with customizable formatting options
{
  const root = xmlbuilder.create('data')
    .ele('nested', 'content')
    .up();

  const formattedXml = root.end({ pretty: true, indent: '    ', newline: '\n' });
  const lines = formattedXml.split('\n');
  assert.strictEqual(lines.length >= 4, true, 'Formatted XML should contain multiple lines');
  assert.strictEqual(lines[2].startsWith('    <nested>'), true, 'Indentation should match custom indent option');
  assert.strictEqual(lines[lines.length - 1], '</data>', 'Closing root tag should be formatted');
}

// 4. raw inserts unescaped XML markup directly into the node tree
{
  const root = xmlbuilder.create('container');
  root.raw('<unescaped id="raw1">raw &amp; payload</unescaped>');
  const output = root.end({ pretty: false });
  assert.strictEqual(output.includes('<container><unescaped id="raw1">raw &amp; payload</unescaped></container>'), true);
}

// 5. node manipulation supports updating and removing attributes and inspecting element hierarchy
{
  const root = xmlbuilder.create('node-test');
  root.att('initial', 'val1');
  assert.strictEqual(root.hasAttribute('initial'), true);
  assert.strictEqual(root.getAttribute('initial'), 'val1');

  root.att('initial', 'updated-val');
  assert.strictEqual(root.getAttribute('initial'), 'updated-val');

  root.removeAttribute('initial');
  assert.strictEqual(root.hasAttribute('initial'), false);

  const child = root.ele('child-node', { order: '1' });
  assert.strictEqual(child.doc(), root.doc());
  assert.strictEqual(child.up(), root);
}

// 6. begin creates XML fragments and builders without root declarations
{
  let chunks = [];
  const writer = beginDocument((chunk) => chunks.push(chunk));
  writer.ele('fragment').ele('sub', 'frag-text').end();

  assert.strictEqual(chunks.length > 0, true, 'Callback writer should receive chunks');
  const joined = chunks.join('');
  assert.strictEqual(joined, '<fragment><sub>frag-text</sub></fragment>');

  const staticFrag = beginDocument().ele('inline', { active: 'true' }).end({ pretty: false });
  assert.strictEqual(staticFrag, '<inline active="true"/>');
}

// 7. buildStructuredXml constructs complete XML reports from structured configuration objects
{
  const output = buildStructuredXml({
    rootName: 'report',
    attributes: { id: 'REP-001', generated: '2026-08-28' },
    items: [
      { tag: 'status', text: 'SUCCESS' },
      { tag: 'log', cdata: 'Execution OK\nExit 0' },
      { tag: 'meta', comment: 'automated test run' }
    ]
  });

  assert.strictEqual(output.includes('<report id="REP-001" generated="2026-08-28">'), true);
  assert.strictEqual(output.includes('<status>SUCCESS</status>'), true);
  assert.strictEqual(output.includes('<![CDATA[Execution OK\nExit 0]]>'), true);
  assert.strictEqual(output.includes('<!-- automated test run -->'), true);
}

console.log('Contract tests passed successfully.');

오리진 시더

익명