CodeSampleX

Exemplo

xmlbuilder 15.1.1: create

Amostra verificada para npm xmlbuilder 15.1.1: create. O contrato rodou em node 22 · linux debian/x64 · docker e passou: create instantiates an XML document…

sha256:38b89b354b6df90b567b9befa4513278f6fa2a96911c9d5d36a249a158da73de

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-01

Caso

HOW
Objetivo
verify xmlbuilder.create in pkg:npm/xmlbuilder@15.1.1
Pacotes
Símbolos
  • xmlbuilder.create
Ambiente
node 22.23.2
Criado
2026-09-01T11:46:11Z

Contrato

  1. create instantiates an XML document tree with root name and XML declaration
  2. create supports nested element chaining with attributes, text, CDATA, comments, and processing instructions
  3. create converts JavaScript object hierarchy into XML document tree
  4. create supports XML namespaces and prefixed elements and attributes
  5. create supports node traversal, attribute mutation, and unescaped raw markup injection
  6. end serializes document created with create to formatted or compact XML string

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 xmlbuilder.create in pkg:npm/xmlbuilder@15.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/xmlbuilder@15.1.1
Demonstrate these symbols/APIs:
  - xmlbuilder.create

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:ba5e816b33acd61dabf2ba4a7d795183c83400dde3f30b7bf78029ffdb0501c6","contract":["create instantiates an XML document tree with root name and XML declaration","create supports nested element chaining with attributes, text, CDATA, comments, and processing instructions","create converts JavaScript object hierarchy into XML document tree","create supports XML namespaces and prefixed elements and attributes","create supports node traversal, attribute mutation, and unescaped raw markup injection","end serializes document created with create to formatted or compact XML string"],"goal":"verify xmlbuilder.create in pkg:npm/xmlbuilder@15.1.1","kind":"HOW","packages":["pkg:npm/xmlbuilder@15.1.1"],"schemaVersion":1,"symbols":["xmlbuilder.create"]},"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","symbols":["xmlbuilder.create"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-xmlbuilder-create",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-xmlbuilder-create",
      "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-create",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of xmlbuilder.create in pkg:npm/xmlbuilder@15.1.1",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "xmlbuilder": "15.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify xmlbuilder.create in pkg:npm/xmlbuilder@15.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/xmlbuilder@15.1.1"
  ],
  "symbols": [
    "xmlbuilder.create"
  ]
}
src/index.js
const xmlbuilder = require('xmlbuilder');

/**
 * Creates an XML document rooted at rootName with optional XML declaration, doctype, and options.
 *
 * @param {string} rootName - The name of the root element.
 * @param {object} [xmldec] - XML declaration settings (e.g., { version: '1.0', encoding: 'UTF-8', standalone: true }).
 * @param {object} [doctype] - Document type definition settings.
 * @param {object} [options] - Builder and writer options.
 * @returns {object} Root XMLElement.
 */
function createXmlDocument(rootName, xmldec, doctype, options) {
  return xmlbuilder.create(rootName, xmldec, doctype, options);
}

/**
 * Creates an XML document directly from a JavaScript object hierarchy.
 *
 * @param {object} obj - The object tree representing elements, attributes (@key), text (#text), and CDATA (#cdata).
 * @param {object} [options] - Builder options.
 * @returns {object} Root XMLElement.
 */
function createXmlFromObject(obj, options) {
  return xmlbuilder.create(obj, options);
}

/**
 * Creates and serializes a fully structured XML document with elements, attributes, CDATA, comments, and instructions.
 *
 * @param {object} config - Configuration containing root name, declaration, attributes, and child entries.
 * @returns {string} Serialized XML string.
 */
function buildStructuredDocument(config) {
  const root = xmlbuilder.create(
    config.rootName || 'root',
    config.xmldec || { version: '1.0', encoding: 'UTF-8' },
    config.doctype,
    config.options
  );

  if (config.attributes) {
    for (const [key, value] of Object.entries(config.attributes)) {
      root.att(key, value);
    }
  }

  if (Array.isArray(config.children)) {
    for (const child of config.children) {
      const el = root.ele(child.name, child.attributes || {});
      if (child.text) el.txt(child.text);
      if (child.cdata) el.cdata(child.cdata);
      if (child.comment) el.comment(child.comment);
      if (child.instruction) el.instruction(child.instruction.target, child.instruction.content);
      if (child.raw) el.raw(child.raw);
    }
  }

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

module.exports = {
  xmlbuilder,
  createXmlDocument,
  createXmlFromObject,
  buildStructuredDocument
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  xmlbuilder,
  createXmlDocument,
  createXmlFromObject,
  buildStructuredDocument
} = require('../src/index.js');

// 1. create instantiates an XML document tree with root name and XML declaration
{
  const root = createXmlDocument('feed', { version: '1.0', encoding: 'UTF-8', standalone: true });
  assert.strictEqual(root.name, 'feed');
  assert.strictEqual(typeof root.ele, 'function');
  assert.strictEqual(typeof root.att, 'function');
  assert.strictEqual(typeof root.end, 'function');

  const xml = root.end({ pretty: false });
  assert.strictEqual(xml.includes('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'), true);
  assert.strictEqual(xml.includes('<feed/>'), true);
}

// 2. create supports nested element chaining with attributes, text, CDATA, comments, and processing instructions
{
  const root = xmlbuilder.create('project', { version: '1.0', encoding: 'UTF-8' })
    .att('id', 'proj-01')
    .ele('metadata')
      .ele('title', 'Sample Project').up()
      .ele('description').cdata('Contains <special> & characters').up()
      .comment('project status comment')
      .instruction('xml-stylesheet', 'type="text/xsl" href="style.xsl"')
    .up()
    .ele('item', { order: '1' })
      .txt('Item Content')
    .up();

  const xml = root.end({ pretty: false });
  assert.strictEqual(xml.includes('<project id="proj-01">'), true);
  assert.strictEqual(xml.includes('<title>Sample Project</title>'), true);
  assert.strictEqual(xml.includes('<![CDATA[Contains <special> & characters]]>'), true);
  assert.strictEqual(xml.includes('<!-- project status comment -->'), true);
  assert.strictEqual(xml.includes('<?xml-stylesheet type="text/xsl" href="style.xsl"?>'), true);
  assert.strictEqual(xml.includes('<item order="1">Item Content</item>'), true);
}

// 3. create converts JavaScript object hierarchy into XML document tree
{
  const jsObject = {
    inventory: {
      '@status': 'active',
      product: [
        { '@id': 'p100', name: 'Widget A', price: '19.99' },
        { '@id': 'p200', name: 'Widget B', price: '29.99' }
      ]
    }
  };

  const doc = createXmlFromObject(jsObject);
  const xml = doc.end({ pretty: false });

  assert.strictEqual(xml.includes('<inventory status="active">'), true);
  assert.strictEqual(xml.includes('<product id="p100"><name>Widget A</name><price>19.99</price></product>'), true);
  assert.strictEqual(xml.includes('<product id="p200"><name>Widget B</name><price>29.99</price></product>'), true);
}

// 4. create supports XML namespaces and prefixed elements and attributes
{
  const root = xmlbuilder.create('root', { version: '1.0' })
    .att('xmlns', 'http://example.com/default')
    .att('xmlns:custom', 'http://example.com/custom')
    .ele('custom:entry', { 'custom:code': 'ABC' }, 'Namespaced value');

  const xml = root.end({ pretty: false });
  assert.strictEqual(xml.includes('xmlns="http://example.com/default"'), true);
  assert.strictEqual(xml.includes('xmlns:custom="http://example.com/custom"'), true);
  assert.strictEqual(xml.includes('<custom:entry custom:code="ABC">Namespaced value</custom:entry>'), true);
}

// 5. create supports node traversal, attribute mutation, and unescaped raw markup injection
{
  const root = xmlbuilder.create('container');
  root.att('initial', 'first-val');
  assert.strictEqual(root.getAttribute('initial'), 'first-val');

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

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

  const child = root.ele('child', { index: '0' });
  assert.strictEqual(child.doc(), root.doc());
  assert.strictEqual(child.up(), root);

  root.raw('<rawElement id="raw-1">payload &amp; test</rawElement>');
  const xml = root.end({ pretty: false });
  assert.strictEqual(xml.includes('<rawElement id="raw-1">payload &amp; test</rawElement>'), true);
}

// 6. end serializes document created with create to formatted or compact XML string
{
  const output = buildStructuredDocument({
    rootName: 'report',
    attributes: { version: '1.0' },
    children: [
      { name: 'summary', text: 'All systems operational' },
      { name: 'details', cdata: 'Line 1\nLine 2' }
    ]
  });

  const lines = output.split('\n');
  assert.strictEqual(lines.length >= 4, true, 'Formatted output should contain multiple lines');
  assert.strictEqual(lines[0].startsWith('<?xml'), true);
  assert.strictEqual(output.includes('<report version="1.0">'), true);
  assert.strictEqual(output.includes('<summary>All systems operational</summary>'), true);
  assert.strictEqual(output.includes('<![CDATA[Line 1\nLine 2]]>'), true);
}

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

Seeder de origem

anônimo