AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(xml): add Create XML action (#15884)
Odai Ahmad5908109fb459
diff --git a/bun.lock b/bun.lockindex 1183d640c25..268a780215e 100644--- a/bun.lock+++ b/bun.lock@@ -10702,7 +10702,7 @@},"packages/pieces/core/xml": {"name": "@activepieces/piece-xml",- "version": "0.1.20",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/core/xml/package.json b/packages/pieces/core/xml/package.jsonindex 6f9a28325fb..e1c51d54cdb 100644--- a/packages/pieces/core/xml/package.json+++ b/packages/pieces/core/xml/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-xml",- "version": "0.1.20",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/core/xml/src/i18n/translation.json b/packages/pieces/core/xml/src/i18n/translation.jsonindex 7425d31dcf8..57c7167bf59 100644--- a/packages/pieces/core/xml/src/i18n/translation.json+++ b/packages/pieces/core/xml/src/i18n/translation.json@@ -1,9 +1,33 @@{"Extensible Markup Language for storing and transporting data": "Extensible Markup Language for storing and transporting data","Convert JSON to XML": "Convert JSON to XML",+ "Convert XML to JSON": "Convert XML to JSON",+ "Create XML": "Create XML",+ "Build an XML document from JSON, with attributes, repeated elements, CDATA and an optional XML declaration": "Build an XML document from JSON, with attributes, repeated elements, CDATA and an optional XML declaration","JSON": "JSON","Attribute field": "Attribute field","Header": "Header",+ "XML": "XML",+ "Ignore Attributes": "Ignore Attributes",+ "Root Element": "Root Element",+ "List Item Element": "List Item Element",+ "Pretty Print": "Pretty Print",+ "Include XML Declaration": "Include XML Declaration",+ "Self-Close Empty Elements": "Self-Close Empty Elements",+ "Attribute Prefix": "Attribute Prefix",+ "Text Key": "Text Key",+ "CDATA Key": "CDATA Key","Field to add your tag's attributes": "Field to add your tag's attributes",- "Add XML header": "Add XML header"+ "Add XML header": "Add XML header",+ "The XML string to convert": "The XML string to convert",+ "Ignore XML tag attributes during parsing. When unchecked, attributes are included in the output with a \"@_\" prefix (e.g. id=\"42\" becomes {\"@_id\": \"42\"}).": "Ignore XML tag attributes during parsing. When unchecked, attributes are included in the output with a \"@_\" prefix (e.g. id=\"42\" becomes {\"@_id\": \"42\"}).",+ "Each key becomes an element and each list item becomes a repeated element. Keys starting with \"@_\" become attributes, \"#text\" sets the text of an element that has attributes, and \"#cdata\" writes a CDATA section. Example: {\"book\": {\"@_id\": \"1\", \"title\": \"Dune\", \"tag\": [\"scifi\", \"classic\"]}}. The output of Convert XML to JSON can be used as-is.": "Each key becomes an element and each list item becomes a repeated element. Keys starting with \"@_\" become attributes, \"#text\" sets the text of an element that has attributes, and \"#cdata\" writes a CDATA section. Example: {\"book\": {\"@_id\": \"1\", \"title\": \"Dune\", \"tag\": [\"scifi\", \"classic\"]}}. The output of Convert XML to JSON can be used as-is.",+ "Wraps the output in one element with this name. Leave empty if your JSON already has a single top-level key. If the JSON is a list or has several top-level keys and this is empty, \"root\" is used.": "Wraps the output in one element with this name. Leave empty if your JSON already has a single top-level key. If the JSON is a list or has several top-level keys and this is empty, \"root\" is used.",+ "Element name for each item when the JSON itself is a list. Defaults to \"item\".": "Element name for each item when the JSON itself is a list. Defaults to \"item\".",+ "Put each element on its own line; text content is never changed.": "Put each element on its own line; text content is never changed.",+ "Start the output with <?xml version=\"1.0\" encoding=\"UTF-8\"?>. To use a different declaration, add a \"?xml\" key to your JSON instead, e.g. {\"?xml\": {\"@_version\": \"1.0\", \"@_standalone\": \"yes\"}}.": "Start the output with <?xml version=\"1.0\" encoding=\"UTF-8\"?>. To use a different declaration, add a \"?xml\" key to your JSON instead, e.g. {\"?xml\": {\"@_version\": \"1.0\", \"@_standalone\": \"yes\"}}.",+ "Write empty values as <tag/> instead of <tag></tag>.": "Write empty values as <tag/> instead of <tag></tag>.",+ "Keys starting with this prefix become attributes. Defaults to \"@_\", the prefix Convert XML to JSON uses.": "Keys starting with this prefix become attributes. Defaults to \"@_\", the prefix Convert XML to JSON uses.",+ "Key that holds the text of an element that also has attributes. Defaults to \"#text\".": "Key that holds the text of an element that also has attributes. Defaults to \"#text\".",+ "Key whose value is written as a CDATA section, so it is not escaped. Defaults to \"#cdata\".": "Key whose value is written as a CDATA section, so it is not escaped. Defaults to \"#cdata\"."}\ No newline at end of filediff --git a/packages/pieces/core/xml/src/index.ts b/packages/pieces/core/xml/src/index.tsindex 3de4ec090cd..bf3f076cab3 100644--- a/packages/pieces/core/xml/src/index.ts+++ b/packages/pieces/core/xml/src/index.ts@@ -2,6 +2,7 @@ import { PieceAuth, createPiece } from '@activepieces/pieces-framework';import { PieceCategory } from '@activepieces/pieces-framework';import { convertJsonToXml } from './lib/actions/convert-json-to-xml';import { convertXmlToJson } from './lib/actions/convert-xml-to-json';+import { createXml } from './lib/actions/create-xml';export const xml = createPiece({displayName: 'XML',@@ -12,6 +13,6 @@ export const xml = createPiece({categories: [PieceCategory.CORE],auth: PieceAuth.None(),authors: ["Willianwg","kishanprmr","AbdulTheActivePiecer","khaledmashaly","abuaboud"],- actions: [convertJsonToXml, convertXmlToJson],+ actions: [convertJsonToXml, convertXmlToJson, createXml],triggers: [],});diff --git a/packages/pieces/core/xml/src/lib/actions/convert-json-to-xml.ts b/packages/pieces/core/xml/src/lib/actions/convert-json-to-xml.tsindex 0fb030831ee..9800771af54 100644--- a/packages/pieces/core/xml/src/lib/actions/convert-json-to-xml.ts+++ b/packages/pieces/core/xml/src/lib/actions/convert-json-to-xml.ts@@ -8,7 +8,7 @@ export const convertJsonToXml = createAction({displayName: 'Convert JSON to XML',description: 'Convert JSON to XML',aiMetadata: {- description: 'Serializes a JSON object or array into an XML string, optionally prepending an XML declaration header and rendering the values under one designated key as tag attributes instead of child elements. Use it when a downstream system expects XML (SOAP endpoint, legacy API, RSS/sitemap body); for the opposite direction use Convert XML to JSON. Requires valid JSON input, and attributes are only emitted for the nested key named by the attribute field (defaults to "attr"); deterministic and idempotent.',+ description: 'Serializes a JSON object or array into an XML string, optionally prepending an XML declaration header and rendering the values under one designated key as tag attributes instead of child elements. Prefer Create XML for new work: this action merges list items into one element and does not read the "@_" attribute keys or "#text" that Convert XML to JSON returns. For the opposite direction use Convert XML to JSON. Requires valid JSON input, and attributes are only emitted for the nested key named by the attribute field (defaults to "attr"); deterministic and idempotent.',idempotent: true,},props: {diff --git a/packages/pieces/core/xml/src/lib/actions/convert-xml-to-json.ts b/packages/pieces/core/xml/src/lib/actions/convert-xml-to-json.tsindex ffc2ec09c41..489f28c1ef4 100644--- a/packages/pieces/core/xml/src/lib/actions/convert-xml-to-json.ts+++ b/packages/pieces/core/xml/src/lib/actions/convert-xml-to-json.ts@@ -8,7 +8,7 @@ export const convertXmlToJson = createAction({displayName: 'Convert XML to JSON',description: 'Convert XML to JSON',aiMetadata: {- description: 'Parses an XML string into a JSON structure, in either of two modes: keep tag attributes (surfaced as "@_"-prefixed keys) or ignore attributes and keep element text only. Use it to make an XML payload from an HTTP response, webhook body, or RSS/SOAP feed addressable by later steps; for the opposite direction use Convert JSON to XML. Requires a well-formed XML string passed as text, and the XML declaration is always dropped; read-only and idempotent.',+ description: 'Parses an XML string into a JSON structure, in either of two modes: keep tag attributes (surfaced as "@_"-prefixed keys) or ignore attributes and keep element text only. Use it to make an XML payload from an HTTP response, webhook body, or RSS/SOAP feed addressable by later steps; for the opposite direction use Create XML, which accepts this output as-is. Requires a well-formed XML string passed as text, and the XML declaration is always dropped; read-only and idempotent.',idempotent: true,},props: {diff --git a/packages/pieces/core/xml/src/lib/actions/create-xml.ts b/packages/pieces/core/xml/src/lib/actions/create-xml.tsnew file mode 100644index 00000000000..ce5a6927863--- /dev/null+++ b/packages/pieces/core/xml/src/lib/actions/create-xml.ts@@ -0,0 +1,327 @@+import { createAction, OutputSchema, Property, tryCatch } from '@activepieces/pieces-framework';+import { XMLBuilder, XMLValidator } from 'fast-xml-parser';++export const createXml = createAction({+ audience: 'both',+ name: 'create-xml',+ classification: 'READ',+ displayName: 'Create XML',+ description: 'Build an XML document from JSON, with attributes, repeated elements, CDATA and an optional XML declaration',+ aiMetadata: {+ description: 'Builds a well-formed XML string from a JSON object or array: each key becomes an element, each array item becomes a repeated element with the same name, keys prefixed "@_" become attributes of their parent element (including namespace declarations such as "@_xmlns:soap"), "#text" sets the text of an element that also has attributes, and "#cdata" writes a CDATA section. This is the same JSON shape that Convert XML to JSON returns, so the two actions round-trip. Use it to produce a SOAP envelope, legacy API payload, RSS feed, sitemap or file body; prefer it over Convert JSON to XML, which merges list items into one element. A top-level array or several top-level keys are wrapped in one root element ("root" unless Root Element is set). Fails with the offending key and line number when a key is not a valid XML name, and fails when the JSON is nested more than 100 levels deep. Deterministic and idempotent.',+ idempotent: true,+ },+ outputSchema: createXmlOutputSchema(),+ props: {+ json: Property.Json({+ displayName: 'JSON',+ description: 'Each key becomes an element and each list item becomes a repeated element. Keys starting with "@_" become attributes, "#text" sets the text of an element that has attributes, and "#cdata" writes a CDATA section. Example: {"book": {"@_id": "1", "title": "Dune", "tag": ["scifi", "classic"]}}. The output of Convert XML to JSON can be used as-is.',+ required: true,+ }),+ rootElement: Property.ShortText({+ displayName: 'Root Element',+ description: 'Wraps the output in one element with this name. Leave empty if your JSON already has a single top-level key. If the JSON is a list or has several top-level keys and this is empty, "root" is used.',+ required: false,+ }),+ listItemElement: Property.ShortText({+ displayName: 'List Item Element',+ description: 'Element name for each item when the JSON itself is a list. Defaults to "item".',+ required: false,+ }),+ prettyPrint: Property.Checkbox({+ displayName: 'Pretty Print',+ description: 'Put each element on its own line; text content is never changed.',+ required: false,+ defaultValue: false,+ }),+ includeDeclaration: Property.Checkbox({+ displayName: 'Include XML Declaration',+ description: 'Start the output with <?xml version="1.0" encoding="UTF-8"?>. To use a different declaration, add a "?xml" key to your JSON instead, e.g. {"?xml": {"@_version": "1.0", "@_standalone": "yes"}}.',+ required: false,+ defaultValue: false,+ }),+ selfCloseEmptyElements: Property.Checkbox({+ displayName: 'Self-Close Empty Elements',+ description: 'Write empty values as <tag/> instead of <tag></tag>.',+ required: false,+ defaultValue: false,+ }),+ attributePrefix: Property.ShortText({+ displayName: 'Attribute Prefix',+ description: 'Keys starting with this prefix become attributes. Defaults to "@_", the prefix Convert XML to JSON uses.',+ required: false,+ }),+ textKey: Property.ShortText({+ displayName: 'Text Key',+ description: 'Key that holds the text of an element that also has attributes. Defaults to "#text".',+ required: false,+ }),+ cdataKey: Property.ShortText({+ displayName: 'CDATA Key',+ description: 'Key whose value is written as a CDATA section, so it is not escaped. Defaults to "#cdata".',+ required: false,+ }),+ },+ async run(context) {+ const { json, rootElement, listItemElement, prettyPrint, includeDeclaration, selfCloseEmptyElements } = context.propsValue;+ const keys: SpecialKeys = {+ attributePrefix: context.propsValue.attributePrefix || DEFAULT_ATTRIBUTE_PREFIX,+ textKey: context.propsValue.textKey || DEFAULT_TEXT_KEY,+ cdataKey: context.propsValue.cdataKey || DEFAULT_CDATA_KEY,+ };+ const format = { keys, selfClose: selfCloseEmptyElements ?? false };+ const document = toDocument({+ json,+ rootElement: rootElement?.trim() || undefined,+ listItemElement: listItemElement?.trim() || DEFAULT_LIST_ITEM_ELEMENT,+ keys,+ });+ const { data: built, error: buildError } = await tryCatch(async () => buildDocument({ document, format, pretty: prettyPrint ?? false }));+ if (buildError) {+ throw new InvalidXmlError(+ buildError.message === MAX_DEPTH_MESSAGE+ ? `The JSON is nested more than ${MAX_DEPTH} levels deep, which is the most Create XML and Convert XML to JSON accept. Flatten the data or split it into smaller documents.`+ : `The JSON could not be turned into XML: ${buildError.message}`,+ );+ }+ const xml = built.trim();+ const validation = XMLValidator.validate(xml);+ if (validation !== true) {+ const problem = findInvalidName({ value: document, path: '', keys });+ throw new InvalidXmlError(+ `The JSON does not produce valid XML: ${problem ? `${problem} ` : ''}${validation.err.msg} (line ${validation.err.line}). Element and attribute names must start with a letter or "_" and can only contain letters, digits, "-", "_", "." and ":".`,+ );+ }+ if (!includeDeclaration || XML_DECLARATION_START.test(xml)) {+ return xml;+ }+ return `${XML_DECLARATION}${prettyPrint ? '\n' : ''}${xml}`;+ },+});++function buildDocument({ document, format, pretty }: { document: Record<string, unknown>; format: BuildFormat; pretty: boolean }): string {+ if (!pretty) {+ return String(createBuilder({ format, pretty: false, maxDepth: MAX_DEPTH }).build(document));+ }+ const token = inlineToken({ document });+ const { value, inlined } = inlineMixedChildren({ node: document, format, token, depth: 1, offset: 0 });+ const xml = String(createBuilder({ format, pretty: true, maxDepth: MAX_DEPTH }).build(value));+ return restoreInlined({ xml, token, inlined });+}++function restoreInlined({ xml, token, inlined }: { xml: string; token: string; inlined: string[] }): string {+ const [head, ...parts] = xml.split(token);+ return parts.reduce((result, part) => {+ const match = INLINED_INDEX.exec(part);+ const content = match ? inlined[Number(match[1])] : undefined;+ return match && content !== undefined ? `${result}${content}${part.slice(match[0].length)}` : `${result}${token}${part}`;+ }, head);+}++function createBuilder({ format, pretty, maxDepth }: { format: BuildFormat; pretty: boolean; maxDepth: number }): XMLBuilder {+ return new XMLBuilder({+ ignoreAttributes: false,+ attributeNamePrefix: format.keys.attributePrefix,+ textNodeName: format.keys.textKey,+ cdataPropName: format.keys.cdataKey,+ format: pretty,+ indentBy: ' ',+ suppressEmptyNode: format.selfClose,+ suppressBooleanAttributes: false,+ processEntities: true,+ maxNestedTags: maxDepth,+ });+}++function inlineMixedChildren({ node, format, token, depth, offset }: InlineParams): InlineResult {+ const entries: [string, unknown][] = [];+ const inlined: string[] = [];+ for (const [key, child] of Object.entries(node)) {+ if (!isElementKey({ key, keys: format.keys }) || key.startsWith('?')) {+ entries.push([key, child]);+ continue;+ }+ const inner = inlineElement({ name: key, value: child, format, token, depth, offset: offset + inlined.length });+ entries.push([key, inner.value]);+ appendAll({ target: inlined, items: inner.inlined });+ }+ return { value: Object.fromEntries(entries), inlined };+}++function inlineElement({ name, value, format, token, depth, offset }: InlineElementParams): { value: unknown; inlined: string[] } {+ if (Array.isArray(value)) {+ const items: unknown[] = [];+ const inlined: string[] = [];+ for (const item of value) {+ const inner = inlineElement({ name, value: item, format, token, depth, offset: offset + inlined.length });+ items.push(inner.value);+ appendAll({ target: inlined, items: inner.inlined });+ }+ return { value: items, inlined };+ }+ if (!isRecord(value) || depth > MAX_DEPTH) {+ return { value, inlined: [] };+ }+ if (!isMixedContent({ value, keys: format.keys })) {+ return inlineMixedChildren({ node: value, format, token, depth: depth + 1, offset });+ }+ const attributes = Object.fromEntries(Object.entries(value).filter(([key]) => key.startsWith(format.keys.attributePrefix)));+ const content = Object.fromEntries(Object.entries(value).filter(([key]) => !key.startsWith(format.keys.attributePrefix)));+ const element = String(createBuilder({ format, pretty: false, maxDepth: MAX_DEPTH - depth + 1 }).build({ [name]: content }));+ const open = `<${name}>`;+ const close = `</${name}>`;+ if (!element.startsWith(open) || !element.endsWith(close)) {+ return { value, inlined: [] };+ }+ return { value: { ...attributes, [format.keys.textKey]: `${token}${offset}_` }, inlined: [element.slice(open.length, element.length - close.length)] };+}++function appendAll({ target, items }: { target: string[]; items: string[] }): void {+ for (const item of items) {+ target.push(item);+ }+}++function isMixedContent({ value, keys }: { value: Record<string, unknown>; keys: SpecialKeys }): boolean {+ if (keys.cdataKey in value) {+ return true;+ }+ const text = value[keys.textKey];+ const hasText = text !== undefined && text !== null && text !== '';+ return hasText && Object.keys(value).some((key) => isElementKey({ key, keys }));+}++function inlineToken({ document }: { document: Record<string, unknown> }): string {+ const serialized = JSON.stringify(document);+ const longestRun = Array.from(serialized.matchAll(INLINE_TOKEN_PATTERN), (match) => match[1].length).reduce((longest, run) => Math.max(longest, run), -1);+ return `${INLINE_TOKEN}${'x'.repeat(longestRun + 1)}`;+}++function toDocument({ json, rootElement, listItemElement, keys }: ToDocumentParams): Record<string, unknown> {+ if (Array.isArray(json)) {+ return { [rootElement ?? DEFAULT_ROOT_ELEMENT]: { [listItemElement]: json } };+ }+ if (!isRecord(json)) {+ return { [rootElement ?? DEFAULT_ROOT_ELEMENT]: json ?? '' };+ }+ const entries = Object.entries(json).sort(([a], [b]) => Number(b === XML_DECLARATION_KEY) - Number(a === XML_DECLARATION_KEY));+ const instructions = entries.filter(([key]) => key.startsWith('?'));+ const nodes = entries.filter(([key]) => !key.startsWith('?'));+ const hasSingleRoot = nodes.length === 1 && !Array.isArray(nodes[0][1]) && isElementKey({ key: nodes[0][0], keys });+ if (!rootElement && hasSingleRoot) {+ return Object.fromEntries([...instructions, ...nodes]);+ }+ return {+ ...Object.fromEntries(instructions),+ [rootElement ?? DEFAULT_ROOT_ELEMENT]: Object.fromEntries(nodes),+ };+}++function isElementKey({ key, keys }: { key: string; keys: SpecialKeys }): boolean {+ return !key.startsWith(keys.attributePrefix) && key !== keys.textKey && key !== keys.cdataKey;+}++function findInvalidName({ value, path, keys }: { value: unknown; path: string; keys: SpecialKeys }): string | undefined {+ if (Array.isArray(value)) {+ for (const [index, item] of value.entries()) {+ const itemPath = `${path}[${index}]`;+ if (Array.isArray(item)) {+ return `The list at ${itemPath} sits directly inside another list, so it has no element name; wrap it in an object such as {"row": [...]}.`;+ }+ const found = findInvalidName({ value: item, path: itemPath, keys });+ if (found) {+ return found;+ }+ }+ return undefined;+ }+ if (!isRecord(value)) {+ return undefined;+ }+ for (const [key, child] of Object.entries(value)) {+ const childPath = path ? `${path}.${key}` : key;+ const isAttribute = key.startsWith(keys.attributePrefix);+ const name = isAttribute ? key.slice(keys.attributePrefix.length) : key.replace(/^\?/, '');+ if (key !== keys.textKey && key !== keys.cdataKey && !XML_NAME.test(name)) {+ return `"${name}" at ${childPath} is not a valid XML ${isAttribute ? 'attribute' : 'element'} name.`;+ }+ const found = isAttribute ? undefined : findInvalidName({ value: child, path: childPath, keys });+ if (found) {+ return found;+ }+ }+ return undefined;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function createXmlOutputSchema(): OutputSchema {+ return {+ fields: [{ key: 'xml', label: 'XML', value: '', description: 'The XML document built from the JSON input.' }],+ };+}++class InvalidXmlError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'InvalidXmlError';+ }+}++const DEFAULT_ATTRIBUTE_PREFIX = '@_';+const DEFAULT_TEXT_KEY = '#text';+const DEFAULT_CDATA_KEY = '#cdata';+const DEFAULT_ROOT_ELEMENT = 'root';+const DEFAULT_LIST_ITEM_ELEMENT = 'item';+const XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>';+const MAX_DEPTH = 100;+const XML_DECLARATION_KEY = '?xml';+const XML_DECLARATION_START = /^<\?xml[\s?]/;+const INLINE_TOKEN = 'apinlinexml';+const INLINE_TOKEN_PATTERN = new RegExp(`${INLINE_TOKEN}(x*)`, 'g');+const INLINED_INDEX = /^(\d+)_/;+const MAX_DEPTH_MESSAGE = 'Maximum nested tags exceeded';+const NAME_START_CHARS = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';+const XML_NAME = new RegExp(`^[${NAME_START_CHARS}][${NAME_START_CHARS}\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$`);++type SpecialKeys = {+ attributePrefix: string;+ textKey: string;+ cdataKey: string;+};++type BuildFormat = {+ keys: SpecialKeys;+ selfClose: boolean;+};++type InlineResult = {+ value: Record<string, unknown>;+ inlined: string[];+};++type InlineParams = {+ node: Record<string, unknown>;+ format: BuildFormat;+ token: string;+ depth: number;+ offset: number;+};++type InlineElementParams = {+ name: string;+ value: unknown;+ format: BuildFormat;+ token: string;+ depth: number;+ offset: number;+};++type ToDocumentParams = {+ json: unknown;+ rootElement: string | undefined;+ listItemElement: string;+ keys: SpecialKeys;+};diff --git a/packages/pieces/core/xml/test/create-xml.test.ts b/packages/pieces/core/xml/test/create-xml.test.tsnew file mode 100644index 00000000000..824dabfbb4d--- /dev/null+++ b/packages/pieces/core/xml/test/create-xml.test.ts@@ -0,0 +1,568 @@+/// <reference types="vitest/globals" />++import { createXml } from '../src/lib/actions/create-xml';+import { convertXmlToJson } from '../src/lib/actions/convert-xml-to-json';+import { convertJsonToXml } from '../src/lib/actions/convert-json-to-xml';+import { createMockActionContext } from '@activepieces/pieces-framework';++describe('createXml', () => {+ describe('lists', () => {+ test('repeats the element for each value in a list', async () => {+ expect(await buildXml({ json: { post: { tags: ['a', 'b'] } } })).toBe('<post><tags>a</tags><tags>b</tags></post>');+ });++ test('wraps a single top-level key that holds a list, so {"tags":["a","b"]} gives one tags element per item', async () => {+ expect(await buildXml({ json: { tags: ['a', 'b'] } })).toBe('<root><tags>a</tags><tags>b</tags></root>');+ expect(await buildXml({ json: { tags: ['a', 'b'] }, rootElement: 'post' })).toBe('<post><tags>a</tags><tags>b</tags></post>');+ });++ test('writes one element per object in a list', async () => {+ expect(await buildXml({ json: { root: { row: [{ c: 1 }, { c: 2, d: 'x' }] } } })).toBe(+ '<root><row><c>1</c></row><row><c>2</c><d>x</d></row></root>',+ );+ });++ test('keeps attributes on each repeated element', async () => {+ expect(await buildXml({ json: { r: { i: [{ '@_n': '1', '#text': 'a' }, { '@_n': '2', '#text': 'b' }] } } })).toBe(+ '<r><i n="1">a</i><i n="2">b</i></r>',+ );+ });++ test('omits the element for an empty list', async () => {+ expect(await buildXml({ json: { r: { items: [], o: {} } } })).toBe('<r><o></o></r>');+ });++ test('writes null items as empty repeated elements', async () => {+ expect(await buildXml({ json: { r: { c: [null, 1] } } })).toBe('<r><c/><c>1</c></r>');+ });+ });++ describe('attributes, text and CDATA', () => {+ test('writes @_ keys as attributes of their parent element', async () => {+ expect(await buildXml({ json: { book: { '@_id': '1', title: 'T' } } })).toBe('<book id="1"><title>T</title></book>');+ });++ test('writes #text next to attributes', async () => {+ expect(await buildXml({ json: { price: { '@_currency': 'USD', '#text': 9.5 } } })).toBe('<price currency="USD">9.5</price>');+ });++ test('writes boolean and number attributes with a value', async () => {+ expect(await buildXml({ json: { input: { '@_checked': true, '@_hidden': false, '@_size': 0 } } })).toBe(+ '<input checked="true" hidden="false" size="0"></input>',+ );+ });++ test('writes namespace declarations and prefixed names', async () => {+ expect(await buildXml({ json: soapEnvelope })).toBe(+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><m:GetPrice xmlns:m="https://example.com/prices"><m:Item>Apples</m:Item></m:GetPrice></soap:Body></soap:Envelope>',+ );+ });++ test('writes a default namespace', async () => {+ expect(await buildXml({ json: { feed: { '@_xmlns': 'http://www.w3.org/2005/Atom', title: 'x' } } })).toBe(+ '<feed xmlns="http://www.w3.org/2005/Atom"><title>x</title></feed>',+ );+ });++ test('writes #cdata as a CDATA section and splits an embedded ]]>', async () => {+ expect(await buildXml({ json: { a: { '#cdata': '<b>bold</b> & more' } } })).toBe('<a><![CDATA[<b>bold</b> & more]]></a>');+ expect(await buildXml({ json: { a: { '#cdata': 'x]]>y' } } })).toBe('<a><![CDATA[x]]]]><![CDATA[>y]]></a>');+ });++ test('supports a custom attribute prefix, text key and CDATA key', async () => {+ expect(+ await buildXml({ json: { price: { $currency: 'USD', _: 9.5, note: { '!c': '<x>' } } }, attributePrefix: '$', textKey: '_', cdataKey: '!c' }),+ ).toBe('<price currency="USD">9.5<note><![CDATA[<x>]]></note></price>');+ });++ test('treats @_ keys as plain names once a custom prefix is set', async () => {+ await expect(buildXml({ json: { a: { '@_id': '1' } }, attributePrefix: '$' })).rejects.toThrow('"@_id" at a.@_id is not a valid XML element name');+ });++ test('wraps top-level attributes or text in the root element', async () => {+ expect(await buildXml({ json: { '@_version': '2', item: 'x' } })).toBe('<root version="2"><item>x</item></root>');+ expect(await buildXml({ json: { '#text': 'hi' } })).toBe('<root>hi</root>');+ });+ });++ describe('escaping and unicode', () => {+ test('escapes special characters in text', async () => {+ expect(await buildXml({ json: { a: `x & y <z> "q" 'r'` } })).toBe('<a>x & y <z> "q" 'r'</a>');+ });++ test('escapes special characters in attribute values', async () => {+ expect(await buildXml({ json: { a: { '@_t': `x"y&<>'`, b: 1 } } })).toBe('<a t="x"y&<>'"><b>1</b></a>');+ });++ test('does not double-escape existing entities', async () => {+ expect(await buildXml({ json: { a: '&' } })).toBe('<a>&amp;</a>');+ });++ test('keeps unicode and emoji as-is in text, attributes and names', async () => {+ expect(await buildXml({ json: { name: { '@_e': '😀', '#text': 'café 日本 😀' } } })).toBe('<name e="😀">café 日本 😀</name>');+ expect(await buildXml({ json: { 'café': { 日本: 1 } } })).toBe('<café><日本>1</日本></café>');+ });+ });++ describe('root element and top-level shapes', () => {+ test('keeps a single top-level key as the root', async () => {+ expect(await buildXml({ json: { person: { name: 'Alice', address: { city: 'LA' } } } })).toBe(+ '<person><name>Alice</name><address><city>LA</city></address></person>',+ );+ });++ test('wraps a single top-level key when Root Element is set', async () => {+ expect(await buildXml({ json: { person: { name: 'Alice' } }, rootElement: 'data' })).toBe('<data><person><name>Alice</name></person></data>');+ });++ test('wraps several top-level keys in one root element', async () => {+ expect(await buildXml({ json: { a: 1, b: 2 } })).toBe('<root><a>1</a><b>2</b></root>');+ expect(await buildXml({ json: { a: 1, b: 2 }, rootElement: 'data' })).toBe('<data><a>1</a><b>2</b></data>');+ });++ test('trims Root Element and List Item Element and falls back when blank', async () => {+ expect(await buildXml({ json: [1], rootElement: ' rows ', listItemElement: ' ' })).toBe('<rows><item>1</item></rows>');+ });++ test('wraps a top-level list in root and item elements', async () => {+ expect(await buildXml({ json: [{ a: 1 }, { b: 2 }] })).toBe('<root><item><a>1</a></item><item><b>2</b></item></root>');+ });++ test('uses a custom list item element for a top-level list', async () => {+ expect(await buildXml({ json: [{ a: 1 }, { a: 2 }], rootElement: 'rows', listItemElement: 'row' })).toBe(+ '<rows><row><a>1</a></row><row><a>2</a></row></rows>',+ );+ expect(await buildXml({ json: ['x', 'y'], listItemElement: 'v' })).toBe('<root><v>x</v><v>y</v></root>');+ });++ test('writes an empty root for an empty object or list', async () => {+ expect(await buildXml({ json: {} })).toBe('<root></root>');+ expect(await buildXml({ json: [] })).toBe('<root></root>');+ expect(await buildXml({ json: {}, rootElement: 'data', selfCloseEmptyElements: true })).toBe('<data/>');+ });++ test('wraps a top-level primitive in the root element', async () => {+ expect(await buildXml({ json: 'abc' })).toBe('<root>abc</root>');+ expect(await buildXml({ json: 0 })).toBe('<root>0</root>');+ expect(await buildXml({ json: false })).toBe('<root>false</root>');+ expect(await buildXml({ json: '' })).toBe('<root></root>');+ });++ test('writes an empty root for null or undefined', async () => {+ expect(await buildXml({ json: null })).toBe('<root></root>');+ expect(await buildXml({ json: undefined })).toBe('<root></root>');+ expect(await buildXml({ json: null, rootElement: 'data' })).toBe('<data></data>');+ });+ });++ describe('declaration and formatting', () => {+ test('adds the XML declaration when asked', async () => {+ expect(await buildXml({ json: { a: 1 }, includeDeclaration: true })).toBe('<?xml version="1.0" encoding="UTF-8"?><a>1</a>');+ });++ test('leaves the declaration out by default', async () => {+ expect(await buildXml({ json: { a: 1 } })).toBe('<a>1</a>');+ });++ test('uses a ?xml key instead of the default declaration and does not duplicate it', async () => {+ const json = { '?xml': { '@_version': '1.0', '@_encoding': 'UTF-8', '@_standalone': 'yes' }, a: 1 };+ const expected = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a>1</a>';+ expect(await buildXml({ json, includeDeclaration: true })).toBe(expected);+ expect(await buildXml({ json, includeDeclaration: false })).toBe(expected);+ });++ test('keeps a ?xml key outside the root element it wraps around', async () => {+ expect(await buildXml({ json: { '?xml': { '@_version': '1.0' }, a: 1, b: 2 }, includeDeclaration: true })).toBe(+ '<?xml version="1.0"?><root><a>1</a><b>2</b></root>',+ );+ expect(await buildXml({ json: { '?xml': { '@_version': '1.0' }, a: [1, 2] } })).toBe('<?xml version="1.0"?><root><a>1</a><a>2</a></root>');+ });++ test('pretty prints with two-space indentation', async () => {+ expect(await buildXml({ json: { r: { a: 1, b: { c: [1, 2] } } }, prettyPrint: true, includeDeclaration: true })).toBe(+ '<?xml version="1.0" encoding="UTF-8"?>\n<r>\n <a>1</a>\n <b>\n <c>1</c>\n <c>2</c>\n </b>\n</r>',+ );+ });++ test('pretty prints a ?xml declaration on its own line', async () => {+ expect(await buildXml({ json: { '?xml': { '@_version': '1.0' }, a: 1 }, prettyPrint: true, includeDeclaration: true })).toBe(+ '<?xml version="1.0"?>\n<a>1</a>',+ );+ });++ test('keeps newlines inside text when pretty printing', async () => {+ expect(await buildXml({ json: { r: { a: 'x\ny' } }, prettyPrint: true })).toBe('<r>\n <a>x\ny</a>\n</r>');+ });++ test('adds the declaration when the document starts with another processing instruction', async () => {+ const json = { '?xml-stylesheet': { '@_type': 'text/xsl', '@_href': 's.xsl' }, rss: { a: 1 } };+ expect(await buildXml({ json, includeDeclaration: true })).toBe(+ '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="s.xsl"?><rss><a>1</a></rss>',+ );+ });++ test('writes a ?xml key first even when another instruction comes before it', async () => {+ const json = { '?pi': { '@_a': '1' }, '?xml': { '@_version': '1.0' }, r: { a: 1 } };+ expect(await buildXml({ json })).toBe('<?xml version="1.0"?><?pi a="1"?><r><a>1</a></r>');+ expect(await buildXml({ json, includeDeclaration: true })).toBe('<?xml version="1.0"?><?pi a="1"?><r><a>1</a></r>');+ });++ test('writes instructions before the root element even when the root key comes first', async () => {+ const json = { r: { a: 1 }, '?pi': { '@_a': '1' }, '?xml': { '@_version': '1.0' } };+ expect(await buildXml({ json })).toBe('<?xml version="1.0"?><?pi a="1"?><r><a>1</a></r>');+ });++ test('keeps an element that mixes text and child elements on one line when pretty printing', async () => {+ const json = { doc: { title: 'T', p: { '@_x': '1', '#text': 'Hello ', b: 'world' } } };+ expect(await buildXml({ json, prettyPrint: true })).toBe('<doc>\n <title>T</title>\n <p x="1">Hello <b>world</b></p>\n</doc>');+ expect(await parseXml({ xml: await buildXml({ json, prettyPrint: true }) })).toEqual(await parseXml({ xml: await buildXml({ json }) }));+ });++ test('keeps CDATA inside its element when pretty printing', async () => {+ const json = { r: { a: 1, note: { '#cdata': 'raw <b>html</b>' } } };+ expect(await buildXml({ json, prettyPrint: true })).toBe('<r>\n <a>1</a>\n <note><![CDATA[raw <b>html</b>]]></note>\n</r>');+ });++ test('keeps each mixed item of a list on one line and escapes its text', async () => {+ const json = { r: { p: [{ '#text': 'a & b ', i: 'x' }, { '#text': 'c', i: 'y' }] } };+ expect(await buildXml({ json, prettyPrint: true })).toBe('<r>\n <p>a & b <i>x</i></p>\n <p>c<i>y</i></p>\n</r>');+ });++ test('leaves user text that looks like the internal placeholder alone', async () => {+ const json = { r: { a: 'apinlinexml0_', p: { '#text': 'mixed ', b: 'bold' } } };+ expect(await buildXml({ json, prettyPrint: true })).toBe('<r>\n <a>apinlinexml0_</a>\n <p>mixed <b>bold</b></p>\n</r>');+ });++ test('never mistakes user text for the internal placeholder, whatever it contains', async () => {+ const lookalikes = Array.from({ length: 12 }, (_, index) => `apinlinexml${'x'.repeat(index)}0_`);+ const json = { r: { a: lookalikes, p: { '#text': 'mixed ', b: 'bold' } } };+ const expected = ['<r>', ...lookalikes.map((text) => ` <a>${text}</a>`), ' <p>mixed <b>bold</b></p>', '</r>'].join('\n');+ expect(await buildXml({ json, prettyPrint: true })).toBe(expected);+ expect(await buildXml({ json: { apinlinexml0_: { '#text': 'x ', b: 'y' } }, prettyPrint: true })).toBe('<apinlinexml0_>x <b>y</b></apinlinexml0_>');+ });++ test('keeps a self-closed empty CDATA element self-closed when pretty printing', async () => {+ expect(await buildXml({ json: { r: { a: 1, n: { '#cdata': null } } }, prettyPrint: true, selfCloseEmptyElements: true })).toBe('<r>\n <a>1</a>\n <n/>\n</r>');+ });++ test('Pretty Print only adds line breaks and indentation between tags', async () => {+ const random = seededRandom({ seed: 7 });+ for (let index = 0; index < 500; index++) {+ const json = { r: randomNode({ random, depth: 0 }) };+ for (const selfCloseEmptyElements of [false, true]) {+ const compact = await buildXml({ json, selfCloseEmptyElements }).catch(() => undefined);+ if (compact === undefined) {+ continue;+ }+ const pretty = await buildXml({ json, prettyPrint: true, selfCloseEmptyElements });+ expect(pretty.replace(/>\n\s*</g, '><')).toBe(compact);+ }+ }+ });++ test('still enforces the depth limit inside a mixed element', async () => {+ await expect(buildXml({ json: { r: { '#text': 't', deep: nest({ depth: 120 }) } }, prettyPrint: true })).rejects.toThrow('100 levels');+ });+ });++ describe('empty and scalar values', () => {+ test('writes null as a self-closed element and empty string as an open-close pair', async () => {+ expect(await buildXml({ json: { r: { a: null, c: '' } } })).toBe('<r><a/><c></c></r>');+ });++ test('skips undefined values', async () => {+ expect(await buildXml({ json: { r: { a: 1, b: undefined } } })).toBe('<r><a>1</a></r>');+ });++ test('self-closes every empty element when asked', async () => {+ expect(await buildXml({ json: { r: { a: null, c: '', o: {}, x: { '@_id': '1' } } }, selfCloseEmptyElements: true })).toBe(+ '<r><a/><c/><o/><x id="1"/></r>',+ );+ });++ test('writes booleans and numbers as text', async () => {+ expect(await buildXml({ json: { r: { t: true, f: false, zero: 0, n: 1.5, neg: -3, big: 12345678901234 } } })).toBe(+ '<r><t>true</t><f>false</f><zero>0</zero><n>1.5</n><neg>-3</neg><big>12345678901234</big></r>',+ );+ });++ test('writes nested nulls as empty elements', async () => {+ expect(await buildXml({ json: { r: { a: { b: null, c: { d: null } } } } })).toBe('<r><a><b/><c><d/></c></a></r>');+ });++ test('keeps leading-zero strings as written', async () => {+ expect(await buildXml({ json: { r: { zip: '02134', id: '007' } } })).toBe('<r><zip>02134</zip><id>007</id></r>');+ });+ });++ describe('awkward key names', () => {+ test('handles a key named length', async () => {+ expect(await buildXml({ json: { a: { length: 3 } } })).toBe('<a><length>3</length></a>');+ expect(await buildXml({ json: { length: 3 } })).toBe('<length>3</length>');+ });++ test('handles __proto__ and constructor keys without touching the prototype', async () => {+ expect(await buildXml({ json: JSON.parse('{"r":{"__proto__":{"x":1},"constructor":2}}') })).toBe(+ '<r><__proto__><x>1</x></__proto__><constructor>2</constructor></r>',+ );+ expect(await buildXml({ json: JSON.parse('{"__proto__":{"polluted":true}}') })).toBe('<__proto__><polluted>true</polluted></__proto__>');+ expect(Object.prototype).not.toHaveProperty('polluted');+ });++ test('handles keys named after Object methods', async () => {+ expect(await buildXml({ json: { r: { hasOwnProperty: 1, toString: 2, valueOf: 3 } } })).toBe(+ '<r><hasOwnProperty>1</hasOwnProperty><toString>2</toString><valueOf>3</valueOf></r>',+ );+ });+ });++ describe('invalid names', () => {+ test('fails with the key, its path and the line on an element name with a space', async () => {+ const error = await buildXml({ json: { r: { ok: 1, 'bad key': 1 } } }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(Error);+ expect(String(error)).toContain('InvalidXmlError');+ expect(String(error)).toContain('does not produce valid XML');+ expect(String(error)).toContain('"bad key" at r.bad key is not a valid XML element name');+ expect(String(error)).toContain('(line 1)');+ });++ test('reports the line of the bad element when pretty printing', async () => {+ await expect(buildXml({ json: { r: { a: 1, b: 2, '1st': 3 } }, prettyPrint: true })).rejects.toThrow('(line 4)');+ });++ test('fails on an element name that starts with a digit', async () => {+ await expect(buildXml({ json: { r: { '1st': 1 } } })).rejects.toThrow(/"1st" at r\.1st is not a valid XML element name\. Tag '1st' is an invalid name\. \(line 1\)/);+ });++ test('fails on an invalid attribute name', async () => {+ await expect(buildXml({ json: { r: { '@_bad attr': 1 } } })).rejects.toThrow('"bad attr" at r.@_bad attr is not a valid XML attribute name');+ });++ test('fails on an empty key, a key with symbols and an invalid root element', async () => {+ await expect(buildXml({ json: { r: { '': 1 } } })).rejects.toThrow('is not a valid XML element name');+ await expect(buildXml({ json: { r: { 'a$b': 1 } } })).rejects.toThrow('"a$b" at r.a$b is not a valid XML element name');+ await expect(buildXml({ json: { a: 1 }, rootElement: 'bad root' })).rejects.toThrow('"bad root" at bad root is not a valid XML element name');+ });++ test('fails on a list directly inside a list', async () => {+ await expect(buildXml({ json: { m: { row: [[1, 2], [3]] } } })).rejects.toThrow('The list at m.row[0] sits directly inside another list');+ });++ test('finds a bad name deep inside a list of objects', async () => {+ await expect(buildXml({ json: { r: { row: [{ ok: 1 }, { deep: { 'no good': 1 } }] } } })).rejects.toThrow(+ '"no good" at r.row[1].deep.no good is not a valid XML element name',+ );+ });+ });++ describe('size and depth', () => {+ test('builds 99 levels of nesting quickly', async () => {+ const started = performance.now();+ const xml = await buildXml({ json: nest({ depth: 99 }) });+ expect(performance.now() - started).toBeLessThan(1000);+ expect(xml.startsWith('<n><n><n>')).toBe(true);+ expect(xml.match(/<n>/g)).toHaveLength(99);+ expect(await parseXml({ xml })).toEqual(nest({ depth: 99 }));+ });++ test('fails fast with a clear error past 100 levels of nesting', async () => {+ const started = performance.now();+ await expect(buildXml({ json: nest({ depth: 100 }) })).rejects.toThrow('nested more than 100 levels deep');+ await expect(buildXml({ json: nest({ depth: 5000 }) })).rejects.toThrow('nested more than 100 levels deep');+ expect(performance.now() - started).toBeLessThan(1000);+ });++ test('builds 60 levels of nesting quickly with pretty print and round-trips it', async () => {+ const json = nest({ depth: 60 });+ const started = performance.now();+ const xml = await buildXml({ json, prettyPrint: true });+ expect(performance.now() - started).toBeLessThan(1000);+ expect(await parseXml({ xml })).toEqual(json);+ });++ test('pretty prints an object with 10,000 keys and mixed content quickly', async () => {+ const wide = Object.fromEntries(Array.from({ length: 10_000 }, (_, index) => [`k${index}`, { '#text': `t${index} `, b: index }]));+ const started = performance.now();+ const xml = await buildXml({ json: { r: wide }, prettyPrint: true });+ expect(performance.now() - started).toBeLessThan(5000);+ expect(xml).toContain('\n <k9999>t9999 <b>9999</b></k9999>\n');+ });++ test('picks a placeholder in linear time when the text holds a long run of lookalike characters', async () => {+ const text = `apinlinexml${'x'.repeat(200_000)}`;+ const started = performance.now();+ const xml = await buildXml({ json: { r: { a: text, p: { '#text': 'mixed ', b: 'bold' } } }, prettyPrint: true });+ expect(performance.now() - started).toBeLessThan(2000);+ expect(xml).toBe(`<r>\n <a>${text}</a>\n <p>mixed <b>bold</b></p>\n</r>`);+ });++ test('pretty prints a list of 200,000 mixed-content items without a stack overflow', async () => {+ const items = Array.from({ length: 200_000 }, (_, index) => ({ '#text': `t${index} `, b: 'x' }));+ const xml = await buildXml({ json: { r: { p: items } }, prettyPrint: true });+ expect(xml.endsWith(' <p>t199999 <b>x</b></p>\n</r>')).toBe(true);+ }, 30_000);++ test('builds a list of 10,000 items', async () => {+ const rows = Array.from({ length: 10_000 }, (_, index) => ({ '@_id': String(index), name: `row ${index}`, code: `C-${index}` }));+ const started = performance.now();+ const xml = await buildXml({ json: { rows: { row: rows } } });+ expect(performance.now() - started).toBeLessThan(5000);+ expect(xml.match(/<row /g)).toHaveLength(10_000);+ expect(xml.endsWith('<row id="9999"><name>row 9999</name><code>C-9999</code></row></rows>')).toBe(true);+ expect(await parseXml({ xml })).toEqual({ rows: { row: rows } });+ });+ });++ describe('round-trips with Convert XML to JSON', () => {+ test.each([+ ['attributes and repeated objects', { catalog: { book: [{ '@_id': '1', title: 'Dune', price: 9.5 }, { '@_id': '2', title: 'Emma', price: 7 }] } }],+ ['repeated values', { root: { tag: ['a', 'b', 'c'] } }],+ ['text next to an attribute', { price: { '@_currency': 'USD', '#text': 9.5 } }],+ ['namespaces in a SOAP envelope', soapEnvelope],+ ['escaping in text and attributes', { note: { '@_title': `x"y&<>'`, text: `x & y <z> "q" 'r'` } }],+ ['unicode and emoji', { note: { '@_lang': '日本', name: 'café 日本 😀' } }],+ ['booleans, zero and negative numbers', { flags: { on: true, off: false, zero: 0, neg: -2.5 } }],+ ['empty string', { root: { a: '' } }],+ ['nested objects', { a: { b: { c: { d: 'deep' } } } }],+ ])('JSON to XML to JSON: %s', async (_name, json) => {+ expect(await parseXml({ xml: await buildXml({ json }) })).toEqual(json);+ expect(await parseXml({ xml: await buildXml({ json, prettyPrint: true, includeDeclaration: true }) })).toEqual(json);+ expect(await parseXml({ xml: await buildXml({ json, selfCloseEmptyElements: true }) })).toEqual(json);+ });++ test('CDATA content survives, but comes back as plain text', async () => {+ const xml = await buildXml({ json: { a: { '#cdata': '<b>bold</b> & more' } } });+ expect(await parseXml({ xml })).toEqual({ a: '<b>bold</b> & more' });+ });++ test('leading zeros are written, but Convert XML to JSON reads them back as numbers', async () => {+ const xml = await buildXml({ json: { address: { zip: '02134' } } });+ expect(xml).toBe('<address><zip>02134</zip></address>');+ expect(await parseXml({ xml })).toEqual({ address: { zip: 2134 } });+ });++ test('shapes Convert XML to JSON cannot give back unchanged', async () => {+ expect(await parseXml({ xml: await buildXml({ json: { r: { tag: ['only'] } } }) })).toEqual({ r: { tag: 'only' } });+ expect(await parseXml({ xml: await buildXml({ json: { r: { id: '123', ratio: '1.50', yes: 'true' } } }) })).toEqual({ r: { id: 123, ratio: 1.5, yes: true } });+ expect(await parseXml({ xml: await buildXml({ json: { r: { '@_n': 5 } } }) })).toEqual({ r: { '@_n': '5' } });+ expect(await parseXml({ xml: await buildXml({ json: { r: { a: null, b: {}, c: [] } } }) })).toEqual({ r: { a: '', b: '' } });+ await expect(parseXml({ xml: await buildXml({ json: JSON.parse('{"r":{"__proto__":1}}') }) })).rejects.toThrow('prototype pollution');+ });++ test('XML to JSON to XML', async () => {+ const xml =+ '<catalog><book id="1" lang="en"><title>Dune</title><tag>x</tag><tag>y</tag></book><book id="2"><title>Emma & co</title><price currency="EUR">7</price></book></catalog>';+ expect(await buildXml({ json: await parseXml({ xml }) })).toBe(xml);+ });++ test('XML to JSON to XML for a SOAP envelope with a declaration', async () => {+ const xml =+ '<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><m:GetPrice xmlns:m="https://example.com/prices"><m:Item>Apples & Pears</m:Item><m:Zip>SW1A 1AA</m:Zip></m:GetPrice></soap:Body></soap:Envelope>';+ expect(await buildXml({ json: await parseXml({ xml }), includeDeclaration: true })).toBe(xml);+ });+ });+});++describe('convertJsonToXml keeps its output unchanged', () => {+ test.each([+ ['merges list items into one element', { tags: ['a', 'b'] }, undefined, undefined, '<tags>ab</tags>'],+ [+ 'copies the attr object onto every child and adds a header',+ { person: { name: 'Alice', attr: { id: '1' }, age: 30 } },+ undefined,+ true,+ '<?xml version="1.0" encoding="UTF-8"?><person><name id="1">Alice</name><age id="1">30</age></person>',+ ],+ [+ 'escapes text but not attribute values',+ { note: { text: `x & y <z> "q"`, attr: { t: `a"b&` } } },+ undefined,+ undefined,+ '<note><text t="a"b&">x & y <z> "q"</text></note>',+ ],+ ['flattens a list of objects', { rows: [{ c: 1 }, { c: 2 }] }, undefined, undefined, '<rows><c>1</c><c>2</c></rows>'],+ ['uses a custom attribute key', { item: { meta: { lang: 'en' }, v: null, e: '' } }, 'meta', false, '<item><v lang="en"/><e lang="en"/></item>'],+ ])('%s', async (_name, json, attributesKey, header, expected) => {+ const ctx = createMockActionContext<typeof convertJsonToXml.props>({+ propsValue: { json, attributes_key: attributesKey, header },+ });+ expect(await convertJsonToXml.run(ctx)).toBe(expected);+ });+});++const soapEnvelope = {+ 'soap:Envelope': {+ '@_xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/',+ 'soap:Body': { 'm:GetPrice': { '@_xmlns:m': 'https://example.com/prices', 'm:Item': 'Apples' } },+ },+};++async function buildXml({ json, ...options }: BuildXmlParams): Promise<string> {+ const ctx = createMockActionContext<typeof createXml.props>({+ propsValue: {+ rootElement: undefined,+ listItemElement: undefined,+ prettyPrint: false,+ includeDeclaration: false,+ selfCloseEmptyElements: false,+ attributePrefix: undefined,+ textKey: undefined,+ cdataKey: undefined,+ ...options,+ json,+ },+ });+ return String(await createXml.run(ctx));+}++async function parseXml({ xml }: { xml: string }): Promise<unknown> {+ const ctx = createMockActionContext<typeof convertXmlToJson.props>({+ propsValue: { xml, ignoreAttributes: false },+ });+ return convertXmlToJson.run(ctx);+}++function seededRandom({ seed }: { seed: number }): (limit: number) => number {+ let state = seed;+ return (limit) => {+ state = (state * 1103515245 + 12345) % 2147483648;+ return state % limit;+ };+}++function randomNode({ random, depth }: { random: (limit: number) => number; depth: number }): unknown {+ const values = ['', 'a', 'x & y', ' spaced ', '<b>', 'apinlinexml0_', null, 0, false, 'é😀'];+ if (depth > 4) {+ return values[random(values.length)];+ }+ const kind = random(7);+ if (kind === 0) {+ return values[random(values.length)];+ }+ if (kind === 1) {+ return [randomNode({ random, depth: depth + 1 }), randomNode({ random, depth: depth + 1 })];+ }+ const attribute = random(2) === 1 ? { '@_id': String(random(9)) } : {};+ const text = random(3) === 0 ? { '#text': values[random(values.length)] } : {};+ const cdata = random(4) === 0 ? { '#cdata': [values[random(values.length)], ''][random(2)] } : {};+ const children = Object.fromEntries(+ Array.from({ length: random(3) }, (_, index) => [`${['a', 'b', 'ns:c'][random(3)]}${index || ''}`, randomNode({ random, depth: depth + 1 })]),+ );+ return { ...attribute, ...text, ...cdata, ...children };+}++function nest({ depth }: { depth: number }): Record<string, unknown> {+ return Array.from({ length: depth }).reduce<Record<string, unknown>>((inner) => ({ n: inner }), { v: 'leaf' });+}++type BuildXmlParams = {+ json: unknown;+ rootElement?: string;+ listItemElement?: string;+ prettyPrint?: boolean;+ includeDeclaration?: boolean;+ selfCloseEmptyElements?: boolean;+ attributePrefix?: string;+ textKey?: string;+ cdataKey?: string;+};