CodeSampleX

Пример

w3c-xmlserializer 5.0.0: Serialize DOM node to XML string using w3c-xmlserializer

Проверенный пример — npm w3c-xmlserializer 5.0.0: Serialize DOM node to XML string using w3c-xmlserializer. Контракт выполнен на node 22 · linux alpine/x64 …

sha256:ebeb0cf5b951948a8894fa3edea78b8f0a8e6e76f08a160b53f174ea252a7e55

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Кейс

HOW
Цель
Serialize DOM node to XML string using w3c-xmlserializer
Пакеты
Создан
2026-08-20T22:44:53Z

Контракт

  1. serialize(root) converts DOM Element nodes with attributes, text, comments, processing instructions, and CDATA sections into well-formed XML strings
  2. serialize(root) handles XML namespaces and namespace prefixes on elements and attributes according to W3C specification
  3. serialize(root) serializes Document, DocumentType, and DocumentFragment nodes
  4. serialize(root, { requireWellFormed: true }) throws error when encountering non-well-formed XML constructs such as illegal hyphens in comments or invalid node types

Файлы

  • 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: Serialize DOM node to XML string using w3c-xmlserializer
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/w3c-xmlserializer@5.0.0

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:97576d15c724b60c947addf65b67c58a24ad7eaebcb3bbee683642685002af6a","contract":["serialize(root) converts DOM Element nodes with attributes, text, comments, processing instructions, and CDATA sections into well-formed XML strings","serialize(root) handles XML namespaces and namespace prefixes on elements and attributes according to W3C specification","serialize(root) serializes Document, DocumentType, and DocumentFragment nodes","serialize(root, { requireWellFormed: true }) throws error when encountering non-well-formed XML constructs such as illegal hyphens in comments or invalid node types"],"goal":"Serialize DOM node to XML string using w3c-xmlserializer","kind":"HOW","packages":["pkg:npm/w3c-xmlserializer@5.0.0"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/w3c-xmlserializer@5.0.0"],"schemaVersion":1,"subject":"pkg:npm/w3c-xmlserializer@5.0.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "w3c-xmlserializer-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "w3c-xmlserializer-sample",
      "version": "1.0.0",
      "dependencies": {
        "w3c-xmlserializer": "5.0.0"
      }
    },
    "node_modules/w3c-xmlserializer": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
      "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
      "license": "MIT",
      "dependencies": {
        "xml-name-validator": "^5.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/xml-name-validator": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
      "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
      "license": "Apache-2.0",
      "engines": {
        "node": ">=18"
      }
    }
  }
}
package.json
{
  "name": "w3c-xmlserializer-sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "w3c-xmlserializer": "5.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Serialize DOM node to XML string using w3c-xmlserializer",
  "kind": "HOW",
  "packages": [
    "pkg:npm/w3c-xmlserializer@5.0.0"
  ]
}
src/index.js
import serialize from 'w3c-xmlserializer';

/**
 * Serializes a DOM node tree to an XML string according to the W3C XMLSerializer specification.
 *
 * @param {object} root - The root DOM node to serialize (Element, Document, DocumentFragment, etc.).
 * @param {object} [options] - Serialization options.
 * @param {boolean} [options.requireWellFormed=false] - Whether to enforce well-formedness constraints.
 * @returns {string} The serialized XML string.
 */
export function serializeToXml(root, options = {}) {
  return serialize(root, options);
}

/**
 * Creates a minimal DOM Element node representation compatible with W3C XMLSerializer.
 *
 * @param {string} localName - Element local name.
 * @param {object} [options]
 * @param {string|null} [options.prefix=null] - Namespace prefix.
 * @param {string|null} [options.namespaceURI=null] - Namespace URI.
 * @param {Array<{prefix?: string|null, localName: string, value: string, namespaceURI?: string|null}>} [options.attributes=[]] - Element attributes.
 * @param {Array<object>} [options.childNodes=[]] - Child nodes.
 * @returns {object} Mock DOM Element node.
 */
export function createElementNode(localName, { prefix = null, namespaceURI = null, attributes = [], childNodes = [] } = {}) {
  return {
    nodeType: 1,
    prefix,
    localName,
    namespaceURI,
    attributes: attributes.map(attr => ({
      prefix: attr.prefix ?? null,
      localName: attr.localName,
      value: attr.value,
      namespaceURI: attr.namespaceURI ?? null
    })),
    childNodes
  };
}

/**
 * Creates a minimal DOM Text node representation.
 *
 * @param {string} data - Text node character data.
 * @returns {object} Mock DOM Text node.
 */
export function createTextNode(data) {
  return {
    nodeType: 3,
    data
  };
}

/**
 * Creates a minimal DOM Comment node representation.
 *
 * @param {string} data - Comment node text.
 * @returns {object} Mock DOM Comment node.
 */
export function createCommentNode(data) {
  return {
    nodeType: 8,
    data
  };
}

/**
 * Creates a minimal DOM ProcessingInstruction node representation.
 *
 * @param {string} target - Processing instruction target name.
 * @param {string} data - Processing instruction content.
 * @returns {object} Mock DOM ProcessingInstruction node.
 */
export function createProcessingInstructionNode(target, data) {
  return {
    nodeType: 7,
    target,
    data
  };
}

/**
 * Creates a minimal DOM CDATASection node representation.
 *
 * @param {string} data - CDATA section data.
 * @returns {object} Mock DOM CDATASection node.
 */
export function createCDataSectionNode(data) {
  return {
    nodeType: 4,
    data
  };
}

/**
 * Creates a minimal DOM DocumentType node representation.
 *
 * @param {string} name - Document type name.
 * @param {string} [publicId=''] - Public identifier.
 * @param {string} [systemId=''] - System identifier.
 * @returns {object} Mock DOM DocumentType node.
 */
export function createDocumentTypeNode(name, publicId = '', systemId = '') {
  return {
    nodeType: 10,
    name,
    publicId,
    systemId
  };
}

/**
 * Creates a minimal DOM Document node representation.
 *
 * @param {Array<object>} childNodes - Document child nodes (e.g. DocumentType, root Element).
 * @returns {object} Mock DOM Document node.
 */
export function createDocumentNode(childNodes = []) {
  return {
    nodeType: 9,
    childNodes
  };
}

/**
 * Creates a minimal DOM DocumentFragment node representation.
 *
 * @param {Array<object>} childNodes - Fragment child nodes.
 * @returns {object} Mock DOM DocumentFragment node.
 */
export function createDocumentFragmentNode(childNodes = []) {
  return {
    nodeType: 11,
    childNodes
  };
}

export default serializeToXml;
test/contract.mjs
import assert from 'node:assert/strict';
import serialize, {
  serializeToXml,
  createElementNode,
  createTextNode,
  createCommentNode,
  createProcessingInstructionNode,
  createCDataSectionNode,
  createDocumentTypeNode,
  createDocumentNode,
  createDocumentFragmentNode
} from '../src/index.js';

function testElementWithChildrenSerialization() {
  // Test Element nodes with attributes, text, comment, PI, and CDATA
  const root = createElementNode('catalog', {
    attributes: [
      { localName: 'name', value: 'main' },
      { localName: 'escaped', value: 'a & b < c > "d"' }
    ],
    childNodes: [
      createCommentNode(' catalog entries '),
      createProcessingInstructionNode('xml-stylesheet', 'type="text/xsl" href="style.xsl"'),
      createElementNode('book', {
        attributes: [{ localName: 'id', value: 'bk101' }],
        childNodes: [
          createElementNode('title', {
            childNodes: [createTextNode('XML & DOM Essentials <v1>')]
          }),
          createCDataSectionNode('Code snippet: <tag attr="val"> & 100% valid')
        ]
      })
    ]
  });

  const xml = serializeToXml(root);
  assert.strictEqual(
    xml,
    '<catalog name="main" escaped="a &amp; b &lt; c &gt; &quot;d&quot;"><!-- catalog entries --><?xml-stylesheet type="text/xsl" href="style.xsl"?><book id="bk101"><title>XML &amp; DOM Essentials &lt;v1&gt;</title><![CDATA[Code snippet: <tag attr="val"> & 100% valid]]></book></catalog>'
  );
}

function testNamespaceHandling() {
  // Test XML namespace prefixes, default namespaces, and prefixed attributes
  const svg = createElementNode('svg', {
    prefix: 'svg',
    namespaceURI: 'http://www.w3.org/2000/svg',
    attributes: [
      { prefix: 'xmlns', localName: 'svg', value: 'http://www.w3.org/2000/svg', namespaceURI: 'http://www.w3.org/2000/xmlns/' },
      { prefix: null, localName: 'viewBox', value: '0 0 100 100', namespaceURI: null }
    ],
    childNodes: [
      createElementNode('circle', {
        prefix: 'svg',
        namespaceURI: 'http://www.w3.org/2000/svg',
        attributes: [
          { prefix: null, localName: 'cx', value: '50', namespaceURI: null },
          { prefix: null, localName: 'cy', value: '50', namespaceURI: null },
          { prefix: null, localName: 'r', value: '40', namespaceURI: null }
        ]
      })
    ]
  });

  const xml = serializeToXml(svg);
  assert.strictEqual(
    xml,
    '<svg:svg xmlns:svg="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><svg:circle cx="50" cy="50" r="40"/></svg:svg>'
  );
}

function testDocumentAndFragmentSerialization() {
  // Test Document node with DocumentType and HTML root
  const doc = createDocumentNode([
    createDocumentTypeNode('html'),
    createElementNode('html', {
      namespaceURI: 'http://www.w3.org/1999/xhtml',
      attributes: [
        { prefix: null, localName: 'xmlns', value: 'http://www.w3.org/1999/xhtml', namespaceURI: 'http://www.w3.org/2000/xmlns/' }
      ],
      childNodes: [
        createElementNode('body', {
          namespaceURI: 'http://www.w3.org/1999/xhtml',
          childNodes: [createTextNode('Clean-Room Verification')]
        })
      ]
    })
  ]);

  const docXml = serializeToXml(doc);
  assert.strictEqual(
    docXml,
    '<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body>Clean-Room Verification</body></html>'
  );

  // Test DocumentFragment node
  const fragment = createDocumentFragmentNode([
    createElementNode('item', { attributes: [{ localName: 'n', value: '1' }] }),
    createElementNode('item', { attributes: [{ localName: 'n', value: '2' }] })
  ]);

  const fragmentXml = serializeToXml(fragment);
  assert.strictEqual(fragmentXml, '<item n="1"/><item n="2"/>');
}

function testRequireWellFormedValidation() {
  // Test requireWellFormed throwing error on invalid comment content (double hyphen)
  const invalidComment = createCommentNode('invalid -- comment');
  assert.throws(
    () => serializeToXml(invalidComment, { requireWellFormed: true }),
    {
      name: 'Error',
      message: /Failed to serialize XML: found hyphens in illegal places in comment node data\./
    }
  );

  // Test invalid node type throws TypeError
  assert.throws(
    () => serializeToXml({ nodeType: 99 }),
    {
      name: 'TypeError',
      message: /Failed to serialize XML: only Nodes can be serialized\./
    }
  );
}

function main() {
  testElementWithChildrenSerialization();
  testNamespaceHandling();
  testDocumentAndFragmentSerialization();
  testRequireWellFormedValidation();

  console.log('All pkg:npm/w3c-xmlserializer@5.0.0 contracts passed successfully.');
}

main();

Исходный сидер

аноним