jstoxml.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. const ARRAY = "array";
  2. const BOOLEAN = "boolean";
  3. const DATE = "date";
  4. const NULL = "null";
  5. const NUMBER = "number";
  6. const OBJECT = "object";
  7. const SPECIAL_OBJECT = "special-object";
  8. const STRING = "string";
  9. const PRIVATE_VARS = ["_selfCloseTag", "_attrs"];
  10. const PRIVATE_VARS_REGEXP = new RegExp(PRIVATE_VARS.join("|"), "g");
  11. /**
  12. * Determines the indent string based on current tree depth.
  13. */
  14. const getIndentStr = (indent = "", depth = 0) => indent.repeat(depth);
  15. /**
  16. * Sugar function supplementing JS's quirky typeof operator, plus some extra help to detect
  17. * "special objects" expected by jstoxml.
  18. * Example:
  19. * getType(new Date());
  20. * -> 'date'
  21. */
  22. const getType = (val) =>
  23. (Array.isArray(val) && ARRAY) ||
  24. (typeof val === OBJECT && val !== null && val._name && SPECIAL_OBJECT) ||
  25. (val instanceof Date && DATE) ||
  26. (val === null && NULL) ||
  27. typeof val;
  28. /**
  29. * Replaces matching values in a string with a new value.
  30. * Example:
  31. * filterStr('foo&bar', { '&': '&' });
  32. * -> 'foo&bar'
  33. */
  34. const filterStr = (inputStr = "", filter = {}) => {
  35. // Passthrough/no-op for nonstrings (e.g. number, boolean).
  36. if (typeof inputStr !== "string") {
  37. return inputStr;
  38. }
  39. const regexp = new RegExp(
  40. `(${Object.keys(filter).join("|")})(?!(\\w|#)*;)`,
  41. "g"
  42. );
  43. return String(inputStr).replace(
  44. regexp,
  45. (str, entity) => filter[entity] || ""
  46. );
  47. };
  48. /**
  49. * Maps an object or array of arribute keyval pairs to a string.
  50. * Examples:
  51. * { foo: 'bar', baz: 'g' } -> 'foo="bar" baz="g"'
  52. * [ { ⚡: true }, { foo: 'bar' } ] -> '⚡ foo="bar"'
  53. */
  54. const getAttributeKeyVals = (attributes = {}, filter) => {
  55. let keyVals = [];
  56. if (Array.isArray(attributes)) {
  57. // Array containing complex objects and potentially duplicate attributes.
  58. keyVals = attributes.map((attr) => {
  59. const key = Object.keys(attr)[0];
  60. const val = attr[key];
  61. const filteredVal = filter ? filterStr(val, filter) : val;
  62. const valStr = filteredVal === true ? "" : `="${filteredVal}"`;
  63. return `${key}${valStr}`;
  64. });
  65. } else {
  66. const keys = Object.keys(attributes);
  67. keyVals = keys.map((key) => {
  68. // Simple object - keyval pairs.
  69. // For boolean true, simply output the key.
  70. const filteredVal = filter
  71. ? filterStr(attributes[key], filter)
  72. : attributes[key];
  73. const valStr = attributes[key] === true ? "" : `="${filteredVal}"`;
  74. return `${key}${valStr}`;
  75. });
  76. }
  77. return keyVals;
  78. };
  79. /**
  80. * Converts an attributes object/array to a string of keyval pairs.
  81. * Example:
  82. * formatAttributes({ a: 1, b: 2 })
  83. * -> 'a="1" b="2"'
  84. */
  85. const formatAttributes = (attributes = {}, filter) => {
  86. const keyVals = getAttributeKeyVals(attributes, filter);
  87. if (keyVals.length === 0) return "";
  88. const keysValsJoined = keyVals.join(" ");
  89. return ` ${keysValsJoined}`;
  90. };
  91. /**
  92. * Converts an object to a jstoxml array.
  93. * Example:
  94. * objToArray({ foo: 'bar', baz: 2 });
  95. * ->
  96. * [
  97. * {
  98. * _name: 'foo',
  99. * _content: 'bar'
  100. * },
  101. * {
  102. * _name: 'baz',
  103. * _content: 2
  104. * }
  105. * ]
  106. */
  107. const objToArray = (obj = {}) =>
  108. Object.keys(obj).map((key) => {
  109. return {
  110. _name: key,
  111. _content: obj[key],
  112. };
  113. });
  114. /**
  115. * Determines if a value is a primitive JavaScript value (not including Symbol).
  116. * Example:
  117. * isPrimitive(4);
  118. * -> true
  119. */
  120. const PRIMITIVE_TYPES = [STRING, NUMBER, BOOLEAN];
  121. const isPrimitive = (val) => PRIMITIVE_TYPES.includes(getType(val));
  122. /**
  123. * Determines if a value is a simple primitive type that can fit onto one line. Needed for
  124. * determining any needed indenting and line breaks.
  125. * Example:
  126. * isSimpleType(new Date());
  127. * -> true
  128. */
  129. const SIMPLE_TYPES = [...PRIMITIVE_TYPES, DATE, SPECIAL_OBJECT];
  130. const isSimpleType = (val) => SIMPLE_TYPES.includes(getType(val));
  131. /**
  132. * Determines if an XML string is a simple primitive, or contains nested data.
  133. * Example:
  134. * isSimpleXML('<foo />');
  135. * -> false
  136. */
  137. const isSimpleXML = (xmlStr) => !xmlStr.match("<");
  138. /**
  139. * Assembles an XML header as defined by the config.
  140. */
  141. const DEFAULT_XML_HEADER = '<?xml version="1.0" encoding="UTF-8"?>';
  142. const getHeaderString = ({ header, indent, isOutputStart /*, depth */ }) => {
  143. const shouldOutputHeader = header && isOutputStart;
  144. if (!shouldOutputHeader) return "";
  145. const shouldUseDefaultHeader = typeof header === BOOLEAN;
  146. // return `${shouldUseDefaultHeader ? DEFAULT_XML_HEADER : header}${indent ? "\n" : ""
  147. // }`;
  148. return shouldUseDefaultHeader ? DEFAULT_XML_HEADER : header;
  149. };
  150. /**
  151. * Recursively traverses an object tree and converts the output to an XML string.
  152. * Example:
  153. * toXML({ foo: 'bar' });
  154. * -> <foo>bar</foo>
  155. */
  156. const defaultEntityFilter = {
  157. "<": "&lt;",
  158. ">": "&gt;",
  159. "&": "&amp;",
  160. };
  161. export const toXML = (obj = {}, config = {}) => {
  162. const {
  163. // Tree depth
  164. depth = 0,
  165. indent,
  166. _isFirstItem,
  167. // _isLastItem,
  168. _isOutputStart = true,
  169. header,
  170. attributesFilter: rawAttributesFilter = {},
  171. filter: rawFilter = {},
  172. } = config;
  173. const shouldTurnOffAttributesFilter = typeof rawAttributesFilter === 'boolean' && !rawAttributesFilter;
  174. const attributesFilter = shouldTurnOffAttributesFilter ? {} : {
  175. ...defaultEntityFilter,
  176. ...{ '"': "&quot;" },
  177. ...rawAttributesFilter,
  178. };
  179. const shouldTurnOffFilter = typeof rawFilter === 'boolean' && !rawFilter;
  180. const filter = shouldTurnOffFilter ? {} : { ...defaultEntityFilter, ...rawFilter };
  181. // Determine indent string based on depth.
  182. const indentStr = getIndentStr(indent, depth);
  183. // For branching based on value type.
  184. const valType = getType(obj);
  185. const headerStr = getHeaderString({ header, indent, depth, isOutputStart: _isOutputStart });
  186. const isOutputStart = _isOutputStart && !headerStr && _isFirstItem && depth === 0;
  187. let outputStr = "";
  188. switch (valType) {
  189. case "special-object": {
  190. // Processes a specially-formatted object used by jstoxml.
  191. const { _name, _content } = obj;
  192. // Output text content without a tag wrapper.
  193. if (_content === null) {
  194. outputStr = _name;
  195. break;
  196. }
  197. // Handles arrays of primitive values. (#33)
  198. const isArrayOfPrimitives =
  199. Array.isArray(_content) && _content.every(isPrimitive);
  200. if (isArrayOfPrimitives) {
  201. const primitives = _content
  202. .map((a) => {
  203. return toXML(
  204. {
  205. _name,
  206. _content: a,
  207. },
  208. {
  209. ...config,
  210. depth,
  211. _isOutputStart: false
  212. }
  213. );
  214. });
  215. return primitives.join('');
  216. }
  217. // Don't output private vars (such as _attrs).
  218. if (_name.match(PRIVATE_VARS_REGEXP)) break;
  219. // Process the nested new value and create new config.
  220. const newVal = toXML(_content, { ...config, depth: depth + 1, _isOutputStart: isOutputStart });
  221. const newValType = getType(newVal);
  222. const isNewValSimple = isSimpleXML(newVal);
  223. // Pre-tag output (indent and line breaks).
  224. const preIndentStr = (indent && !isOutputStart) ? "\n" : "";
  225. const preTag = `${preIndentStr}${indentStr}`;
  226. // Special handling for comments, preserving preceding line breaks/indents.
  227. if (_name === '_comment') {
  228. outputStr += `${preTag}<!-- ${_content} -->`;
  229. break;
  230. }
  231. // Tag output.
  232. const valIsEmpty = newValType === "undefined" || newVal === "";
  233. const shouldSelfClose =
  234. typeof obj._selfCloseTag === BOOLEAN
  235. ? valIsEmpty && obj._selfCloseTag
  236. : valIsEmpty;
  237. const selfCloseStr = shouldSelfClose ? "/" : "";
  238. const attributesString = formatAttributes(obj._attrs, attributesFilter);
  239. const tag = `<${_name}${attributesString}${selfCloseStr}>`;
  240. // Post-tag output (closing tag, indent, line breaks).
  241. const preTagCloseStr = indent && !isNewValSimple ? `\n${indentStr}` : "";
  242. const postTag = !shouldSelfClose
  243. ? `${newVal}${preTagCloseStr}</${_name}>`
  244. : "";
  245. outputStr += `${preTag}${tag}${postTag}`;
  246. break;
  247. }
  248. case "object": {
  249. // Iterates over keyval pairs in an object, converting each item to a special-object.
  250. const keys = Object.keys(obj);
  251. const outputArr = keys.map((key, index) => {
  252. const newConfig = {
  253. ...config,
  254. _isFirstItem: index === 0,
  255. _isLastItem: index + 1 === keys.length,
  256. _isOutputStart: isOutputStart
  257. };
  258. const outputObj = { _name: key };
  259. if (getType(obj[key]) === "object") {
  260. // Sub-object contains an object.
  261. // Move private vars up as needed. Needed to support certain types of objects
  262. // E.g. { foo: { _attrs: { a: 1 } } } -> <foo a="1"/>
  263. PRIVATE_VARS.forEach((privateVar) => {
  264. const val = obj[key][privateVar];
  265. if (typeof val !== "undefined") {
  266. outputObj[privateVar] = val;
  267. delete obj[key][privateVar];
  268. }
  269. });
  270. const hasContent = typeof obj[key]._content !== "undefined";
  271. if (hasContent) {
  272. // _content has sibling keys, so pass as an array (edge case).
  273. // E.g. { foo: 'bar', _content: { baz: 2 } } -> <foo>bar</foo><baz>2</baz>
  274. if (Object.keys(obj[key]).length > 1) {
  275. const newContentObj = Object.assign({}, obj[key]);
  276. delete newContentObj._content;
  277. outputObj._content = [
  278. ...objToArray(newContentObj),
  279. obj[key]._content,
  280. ];
  281. }
  282. }
  283. }
  284. // Fallthrough: just pass the key as the content for the new special-object.
  285. if (typeof outputObj._content === "undefined")
  286. outputObj._content = obj[key];
  287. const xml = toXML(outputObj, newConfig, key);
  288. return xml;
  289. }, config);
  290. outputStr = outputArr.join('');
  291. break;
  292. }
  293. case "function": {
  294. // Executes a user-defined function and returns output.
  295. const fnResult = obj(config);
  296. outputStr = toXML(fnResult, config);
  297. break;
  298. }
  299. case "array": {
  300. // Iterates and converts each value in an array.
  301. const outputArr = obj.map((singleVal, index) => {
  302. const newConfig = {
  303. ...config,
  304. _isFirstItem: index === 0,
  305. _isLastItem: index + 1 === obj.length,
  306. _isOutputStart: isOutputStart
  307. };
  308. return toXML(singleVal, newConfig);
  309. });
  310. outputStr = outputArr.join('');
  311. break;
  312. }
  313. // number, string, boolean, date, null, etc
  314. default: {
  315. outputStr = filterStr(obj, filter);
  316. break;
  317. }
  318. }
  319. return `${headerStr}${outputStr}`;
  320. };
  321. export default {
  322. toXML,
  323. };