CodeSampleX

示例

xmlbuilder 15.1.1

已验证示例 — npm xmlbuilder 15.1.1. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: create creates XML documents with elements, attributes, text, comments…

sha256:f19c32aab839841fb87ee257f29907d48befd26fcd823db8c3d5393d9b1334a6

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

原始种子者

匿名