@digipair/skill-docxtemplater 0.136.0 → 0.136.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -714,6 +714,11 @@ if (UNICODE_SUPPORT) {
714
714
  // eslint-disable-next-line es5/no-unicode-code-point-escape
715
715
  Char = reg('[', chars(Char), '\\u{10000}-\\u{10FFFF}', ']');
716
716
  }
717
+ // Negation of Char: matches any character that is NOT a valid XML 1.0 Char.
718
+ // Derived directly from the Char character class above (after the unicode-support extension).
719
+ // XML 1.0 Char production [2]: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
720
+ // @see https://www.w3.org/TR/xml/#NT-Char
721
+ var InvalidChar = new RegExp('[^' + chars(Char) + ']', UNICODE_SUPPORT ? 'u' : '');
717
722
  var _SChar = /[\x20\x09\x0D\x0A]/;
718
723
  var SChar_s = chars(_SChar);
719
724
  // https://www.w3.org/TR/xml11/#NT-S
@@ -921,6 +926,12 @@ var PUBLIC = 'PUBLIC';
921
926
  // `[75] ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral`
922
927
  var ExternalID = regg(regg(SYSTEM, S, SystemLiteral), '|', regg(PUBLIC, S, PubidLiteral, S, SystemLiteral));
923
928
  var ExternalID_match = reg('^', regg(regg(SYSTEM, S, '(?<SystemLiteralOnly>', SystemLiteral, ')'), '|', regg(PUBLIC, S, '(?<PubidLiteral>', PubidLiteral, ')', S, '(?<SystemLiteral>', SystemLiteral, ')')));
929
+ // Full-string anchored matcher for requireWellFormed serializer checks
930
+ // https://w3c.github.io/DOM-Parsing/#xml-serializing-a-document-node
931
+ var PubidLiteral_match = reg('^', PubidLiteral, '$');
932
+ // Full-string anchored matcher for requireWellFormed serializer checks
933
+ // https://w3c.github.io/DOM-Parsing/#xml-serializing-a-document-node
934
+ var SystemLiteral_match = reg('^', SystemLiteral, '$');
924
935
  // https://www.w3.org/TR/xml11/#NT-NDataDecl
925
936
  // `[76] NDataDecl ::= S 'NDATA' S Name` [VC: Notation Declared]
926
937
  var NDataDecl = regg(S, 'NDATA', S, Name);
@@ -1032,6 +1043,7 @@ grammar.PEReference = PEReference;
1032
1043
  grammar.PI = PI;
1033
1044
  grammar.PUBLIC = PUBLIC;
1034
1045
  grammar.PubidLiteral = PubidLiteral;
1046
+ grammar.PubidLiteral_match = PubidLiteral_match;
1035
1047
  grammar.QName = QName;
1036
1048
  grammar.QName_exact = QName_exact;
1037
1049
  grammar.QName_group = QName_group;
@@ -1040,6 +1052,8 @@ grammar.SChar_s = SChar_s;
1040
1052
  grammar.S_OPT = S_OPT;
1041
1053
  grammar.SYSTEM = SYSTEM;
1042
1054
  grammar.SystemLiteral = SystemLiteral;
1055
+ grammar.SystemLiteral_match = SystemLiteral_match;
1056
+ grammar.InvalidChar = InvalidChar;
1043
1057
  grammar.UNICODE_REPLACEMENT_CHARACTER = UNICODE_REPLACEMENT_CHARACTER;
1044
1058
  grammar.UNICODE_SUPPORT = UNICODE_SUPPORT;
1045
1059
  grammar.XMLDecl = XMLDecl;
@@ -1349,13 +1363,38 @@ NodeList.prototype = {
1349
1363
  /**
1350
1364
  * Returns a string representation of the NodeList.
1351
1365
  *
1352
- * @param {unknown} nodeFilter
1353
- * __A filter function? Not implemented according to the spec?__.
1366
+ * Accepts the same `options` object as `XMLSerializer.prototype.serializeToString`
1367
+ * (`requireWellFormed`, `splitCDATASections`, `nodeFilter`). Passing a function is treated as
1368
+ * a legacy `nodeFilter` for backward compatibility.
1369
+ *
1370
+ * @param {Object | function} [options]
1371
+ * @param {boolean} [options.requireWellFormed=false]
1372
+ * @param {boolean} [options.splitCDATASections=true]
1373
+ * @param {function} [options.nodeFilter]
1354
1374
  * @returns {string}
1355
- * A string representation of the NodeList.
1356
- */ toString: function toString(nodeFilter) {
1375
+ */ toString: function toString(options) {
1376
+ var opts;
1377
+ if (typeof options === 'function') {
1378
+ opts = {
1379
+ requireWellFormed: false,
1380
+ splitCDATASections: true,
1381
+ nodeFilter: options
1382
+ };
1383
+ } else if (!!options) {
1384
+ opts = {
1385
+ requireWellFormed: !!options.requireWellFormed,
1386
+ splitCDATASections: options.splitCDATASections !== false,
1387
+ nodeFilter: options.nodeFilter || null
1388
+ };
1389
+ } else {
1390
+ opts = {
1391
+ requireWellFormed: false,
1392
+ splitCDATASections: true,
1393
+ nodeFilter: null
1394
+ };
1395
+ }
1357
1396
  for(var buf = [], i = 0; i < this.length; i++){
1358
- serializeToString(this[i], buf, nodeFilter);
1397
+ serializeToString(this[i], buf, null, opts);
1359
1398
  }
1360
1399
  return buf.join('');
1361
1400
  },
@@ -1855,11 +1894,21 @@ DOMImplementation$1.prototype = {
1855
1894
  * The {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified
1856
1895
  * name} of the document type to be created.
1857
1896
  * @param {string} [publicId]
1858
- * The external subset public identifier.
1897
+ * The external subset public identifier. Stored verbatim including surrounding quotes.
1898
+ * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
1899
+ * if the value is non-empty and does not match the XML `PubidLiteral` production
1900
+ * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [12]). Creation-time validation is not
1901
+ * enforced — deferred to a future breaking release.
1859
1902
  * @param {string} [systemId]
1860
- * The external subset system identifier.
1903
+ * The external subset system identifier. Stored verbatim including surrounding quotes.
1904
+ * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
1905
+ * if the value is non-empty and does not match the XML `SystemLiteral` production
1906
+ * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [11]). Creation-time validation is not
1907
+ * enforced — deferred to a future breaking release.
1861
1908
  * @param {string} [internalSubset]
1862
- * the internal subset or an empty string if it is not present
1909
+ * The internal subset or an empty string if it is not present. Stored verbatim.
1910
+ * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
1911
+ * if the value contains `"]>"`. Creation-time validation is not enforced.
1863
1912
  * @returns {DocumentType}
1864
1913
  * A new {@link DocumentType} node with {@link Node#ownerDocument} set to null.
1865
1914
  * @throws {DOMException}
@@ -2052,7 +2101,7 @@ Node.prototype = {
2052
2101
  var parent = other;
2053
2102
  do {
2054
2103
  if (this === parent) return true;
2055
- parent = other.parentNode;
2104
+ parent = parent.parentNode;
2056
2105
  }while (parent);
2057
2106
  return false;
2058
2107
  },
@@ -2082,50 +2131,73 @@ Node.prototype = {
2082
2131
  /**
2083
2132
  * Checks whether the given node is equal to this node.
2084
2133
  *
2134
+ * Two nodes are equal when they have the same type, defining characteristics (for the type),
2135
+ * and the same childNodes. The comparison is iterative to avoid stack overflows on
2136
+ * deeply-nested trees. Attribute nodes of each Element pair are also pushed onto the stack
2137
+ * and compared the same way.
2138
+ *
2085
2139
  * @param {Node} [otherNode]
2140
+ * @returns {boolean}
2086
2141
  * @see https://dom.spec.whatwg.org/#concept-node-equals
2142
+ * @see ../docs/walk-dom.md.
2087
2143
  */ isEqualNode: function isEqualNode(otherNode) {
2088
2144
  if (!otherNode) return false;
2089
- if (this.nodeType !== otherNode.nodeType) return false;
2090
- switch(this.nodeType){
2091
- case this.DOCUMENT_TYPE_NODE:
2092
- if (this.name !== otherNode.name) return false;
2093
- if (this.publicId !== otherNode.publicId) return false;
2094
- if (this.systemId !== otherNode.systemId) return false;
2095
- break;
2096
- case this.ELEMENT_NODE:
2097
- if (this.namespaceURI !== otherNode.namespaceURI) return false;
2098
- if (this.prefix !== otherNode.prefix) return false;
2099
- if (this.localName !== otherNode.localName) return false;
2100
- if (this.attributes.length !== otherNode.attributes.length) return false;
2101
- for(var i = 0; i < this.attributes.length; i++){
2102
- var attr = this.attributes.item(i);
2103
- if (!attr.isEqualNode(otherNode.getAttributeNodeNS(attr.namespaceURI, attr.localName))) {
2104
- return false;
2145
+ // Use an explicit {node, other} pair stack to avoid call-stack overflow on deep trees.
2146
+ // walkDOM cannot be used here — parallel two-tree traversal requires pairing
2147
+ // corresponding nodes at each step across both trees simultaneously.
2148
+ var stack = [
2149
+ {
2150
+ node: this,
2151
+ other: otherNode
2152
+ }
2153
+ ];
2154
+ while(stack.length > 0){
2155
+ var pair = stack.pop();
2156
+ var node = pair.node;
2157
+ var other = pair.other;
2158
+ if (node.nodeType !== other.nodeType) return false;
2159
+ switch(node.nodeType){
2160
+ case node.DOCUMENT_TYPE_NODE:
2161
+ if (node.name !== other.name) return false;
2162
+ if (node.publicId !== other.publicId) return false;
2163
+ if (node.systemId !== other.systemId) return false;
2164
+ break;
2165
+ case node.ELEMENT_NODE:
2166
+ if (node.namespaceURI !== other.namespaceURI) return false;
2167
+ if (node.prefix !== other.prefix) return false;
2168
+ if (node.localName !== other.localName) return false;
2169
+ if (node.attributes.length !== other.attributes.length) return false;
2170
+ for(var i = 0; i < node.attributes.length; i++){
2171
+ var attr = node.attributes.item(i);
2172
+ var otherAttr = other.getAttributeNodeNS(attr.namespaceURI, attr.localName);
2173
+ if (!otherAttr) return false;
2174
+ stack.push({
2175
+ node: attr,
2176
+ other: otherAttr
2177
+ });
2105
2178
  }
2106
- }
2107
- break;
2108
- case this.ATTRIBUTE_NODE:
2109
- if (this.namespaceURI !== otherNode.namespaceURI) return false;
2110
- if (this.localName !== otherNode.localName) return false;
2111
- if (this.value !== otherNode.value) return false;
2112
- break;
2113
- case this.PROCESSING_INSTRUCTION_NODE:
2114
- if (this.target !== otherNode.target || this.data !== otherNode.data) {
2115
- return false;
2116
- }
2117
- break;
2118
- case this.TEXT_NODE:
2119
- case this.COMMENT_NODE:
2120
- if (this.data !== otherNode.data) return false;
2121
- break;
2122
- }
2123
- if (this.childNodes.length !== otherNode.childNodes.length) {
2124
- return false;
2125
- }
2126
- for(var i = 0; i < this.childNodes.length; i++){
2127
- if (!this.childNodes[i].isEqualNode(otherNode.childNodes[i])) {
2128
- return false;
2179
+ break;
2180
+ case node.ATTRIBUTE_NODE:
2181
+ if (node.namespaceURI !== other.namespaceURI) return false;
2182
+ if (node.localName !== other.localName) return false;
2183
+ if (node.value !== other.value) return false;
2184
+ break;
2185
+ case node.PROCESSING_INSTRUCTION_NODE:
2186
+ if (node.target !== other.target || node.data !== other.data) return false;
2187
+ break;
2188
+ case node.TEXT_NODE:
2189
+ case node.CDATA_SECTION_NODE:
2190
+ case node.COMMENT_NODE:
2191
+ if (node.data !== other.data) return false;
2192
+ break;
2193
+ }
2194
+ if (node.childNodes.length !== other.childNodes.length) return false;
2195
+ // Push children in reverse order so index 0 is processed first (LIFO).
2196
+ for(var i = node.childNodes.length - 1; i >= 0; i--){
2197
+ stack.push({
2198
+ node: node.childNodes[i],
2199
+ other: other.childNodes[i]
2200
+ });
2129
2201
  }
2130
2202
  }
2131
2203
  return true;
@@ -2237,7 +2309,7 @@ Node.prototype = {
2237
2309
  * is `TEXT_NODE`) into a single node with the combined data. It also removes any empty text
2238
2310
  * nodes.
2239
2311
  *
2240
- * This method operates recursively, so it also normalizes any and all descendent nodes within
2312
+ * This method iterativly traverses all child nodes to normalize all descendent nodes within
2241
2313
  * the subtree.
2242
2314
  *
2243
2315
  * @throws {DOMException}
@@ -2246,18 +2318,27 @@ Node.prototype = {
2246
2318
  * @since Modified in DOM Level 2
2247
2319
  * @see {@link Node.removeChild}
2248
2320
  * @see {@link CharacterData.appendData}
2321
+ * @see ../docs/walk-dom.md.
2249
2322
  */ normalize: function normalize() {
2250
- var child = this.firstChild;
2251
- while(child){
2252
- var next = child.nextSibling;
2253
- if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
2254
- this.removeChild(next);
2255
- child.appendData(next.data);
2256
- } else {
2257
- child.normalize();
2258
- child = next;
2323
+ walkDOM(this, null, {
2324
+ enter: function enter(node) {
2325
+ // Merge adjacent text children of node before walkDOM schedules them.
2326
+ // walkDOM reads lastChild/previousSibling after enter returns, so the
2327
+ // surviving post-merge children are what it descends into.
2328
+ var child = node.firstChild;
2329
+ while(child){
2330
+ var next = child.nextSibling;
2331
+ if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) {
2332
+ node.removeChild(next);
2333
+ child.appendData(next.data);
2334
+ // Do not advance child: re-check new nextSibling for another text run
2335
+ } else {
2336
+ child = next;
2337
+ }
2338
+ }
2339
+ return true; // descend into surviving children
2259
2340
  }
2260
- }
2341
+ });
2261
2342
  },
2262
2343
  /**
2263
2344
  * Checks whether the DOM implementation implements a specific feature and its version.
@@ -2452,22 +2533,118 @@ copy(NodeType, Node.prototype);
2452
2533
  copy(DocumentPosition, Node);
2453
2534
  copy(DocumentPosition, Node.prototype);
2454
2535
  /**
2455
- * @param callback
2456
- * Return true for continue,false for break.
2457
- * @returns
2458
- * boolean true: break visit;
2536
+ * Visits every node in the subtree rooted at `node` in depth-first pre-order.
2537
+ *
2538
+ * Delegates to {@link walkDOM} for traversal. The `callback` is called on each node;
2539
+ * if it returns a truthy value, traversal stops immediately.
2540
+ *
2541
+ * @param {Node} node
2542
+ * Root of the subtree to visit.
2543
+ * @param {function(Node): *} callback
2544
+ * Called for each node. A truthy return value stops traversal early.
2459
2545
  */ function _visitNode(node, callback) {
2460
- if (callback(node)) {
2461
- return true;
2462
- }
2463
- if (node = node.firstChild) {
2464
- do {
2465
- if (_visitNode(node, callback)) {
2466
- return true;
2546
+ walkDOM(node, null, {
2547
+ enter: function enter(n) {
2548
+ return callback(n) ? walkDOM.STOP : true;
2549
+ }
2550
+ });
2551
+ }
2552
+ /**
2553
+ * Depth-first pre/post-order DOM tree walker.
2554
+ *
2555
+ * Visits every node in the subtree rooted at `node`. For each node:
2556
+ *
2557
+ * 1. Calls `callbacks.enter(node, context)` before descending into the node's children. The
2558
+ * return value becomes the `context` passed to each child's `enter` call and to the matching
2559
+ * `exit` call.
2560
+ * 2. If `enter` returns `null` or `undefined`, the node's children are skipped;
2561
+ * sibling traversal continues normally.
2562
+ * 3. If `enter` returns `walkDOM.STOP`, the entire traversal is aborted immediately — no
2563
+ * further `enter` or `exit` calls are made.
2564
+ * 4. `lastChild` and `previousSibling` are read **after** `enter` returns, so `enter` may
2565
+ * safely modify the node's own child list before the walker descends. Modifying siblings of
2566
+ * the current node or any other part of the tree produces unpredictable results: nodes already
2567
+ * queued on the stack are visited regardless of DOM changes, and newly inserted nodes outside
2568
+ * the current child list are never visited.
2569
+ * 5. Calls `callbacks.exit(node, context)` (if provided) after all of a node's children have
2570
+ * been visited, passing the same `context` that `enter`
2571
+ * returned for that node.
2572
+ *
2573
+ * This implementation uses an explicit stack and does not recurse — it is safe on arbitrarily
2574
+ * deep trees.
2575
+ *
2576
+ * @param {Node} node
2577
+ * Root of the subtree to walk.
2578
+ * @param {*} context
2579
+ * Initial context value passed to the root node's `enter`.
2580
+ * @param {{ enter: function(Node, *): *, exit?: function(Node, *): void }} callbacks
2581
+ * @returns {void | walkDOM.STOP}
2582
+ * @see ../docs/walk-dom.md.
2583
+ */ function walkDOM(node, context, callbacks) {
2584
+ // Each stack frame is {node, context, phase}:
2585
+ // walkDOM.ENTER — call enter, then push children
2586
+ // walkDOM.EXIT — call exit
2587
+ var stack = [
2588
+ {
2589
+ node: node,
2590
+ context: context,
2591
+ phase: walkDOM.ENTER
2592
+ }
2593
+ ];
2594
+ while(stack.length > 0){
2595
+ var frame = stack.pop();
2596
+ if (frame.phase === walkDOM.ENTER) {
2597
+ var childContext = callbacks.enter(frame.node, frame.context);
2598
+ if (childContext === walkDOM.STOP) {
2599
+ return walkDOM.STOP;
2467
2600
  }
2468
- }while (node = node.nextSibling);
2601
+ // Push exit frame before children so it fires after all children are processed (Last In First Out)
2602
+ stack.push({
2603
+ node: frame.node,
2604
+ context: childContext,
2605
+ phase: walkDOM.EXIT
2606
+ });
2607
+ if (childContext === null || childContext === undefined) {
2608
+ continue; // skip children
2609
+ }
2610
+ // lastChild is read after enter returns, so enter may modify the child list.
2611
+ var child = frame.node.lastChild;
2612
+ // Traverse from lastChild backwards so that pushing onto the stack
2613
+ // naturally yields firstChild on top (processed first).
2614
+ while(child){
2615
+ stack.push({
2616
+ node: child,
2617
+ context: childContext,
2618
+ phase: walkDOM.ENTER
2619
+ });
2620
+ child = child.previousSibling;
2621
+ }
2622
+ } else {
2623
+ // frame.phase === walkDOM.EXIT
2624
+ if (callbacks.exit) {
2625
+ callbacks.exit(frame.node, frame.context);
2626
+ }
2627
+ }
2469
2628
  }
2470
2629
  }
2630
+ /**
2631
+ * Sentinel value returned from a `walkDOM` `enter` callback to abort the entire traversal
2632
+ * immediately.
2633
+ *
2634
+ * @type {symbol}
2635
+ */ walkDOM.STOP = Symbol('walkDOM.STOP');
2636
+ /**
2637
+ * Phase constant for a stack frame that has not yet been visited.
2638
+ * The `enter` callback is called and children are scheduled.
2639
+ *
2640
+ * @type {number}
2641
+ */ walkDOM.ENTER = 0;
2642
+ /**
2643
+ * Phase constant for a stack frame whose subtree has been fully visited.
2644
+ * The `exit` callback is called.
2645
+ *
2646
+ * @type {number}
2647
+ */ walkDOM.EXIT = 1;
2471
2648
  /**
2472
2649
  * @typedef DocumentOptions
2473
2650
  * @property {string} [contentType=MIME_TYPE.XML_APPLICATION]
@@ -2987,8 +3164,20 @@ Document.prototype = {
2987
3164
  this.documentElement = newChild;
2988
3165
  }
2989
3166
  },
2990
- // Introduced in DOM Level 2:
2991
- importNode: function importNode1(importedNode, deep) {
3167
+ /**
3168
+ * Imports a node from another document into this document, creating a new copy owned by this
3169
+ * document. The source node and its subtree are not modified.
3170
+ *
3171
+ * @param {Node} importedNode
3172
+ * The node to import.
3173
+ * @param {boolean} deep
3174
+ * If true, the contents of the node are recursively imported.
3175
+ * If false, only the node itself (and its attributes, if it is an element) are imported.
3176
+ * @returns {Node}
3177
+ * Returns the newly created import of the node.
3178
+ * @see {@link importNode}
3179
+ * @see {@link https://dom.spec.whatwg.org/#dom-document-importnode}
3180
+ */ importNode: function importNode1(importedNode, deep) {
2992
3181
  return importNode(this, importedNode, deep);
2993
3182
  },
2994
3183
  // Introduced in DOM Level 2:
@@ -3059,6 +3248,15 @@ Document.prototype = {
3059
3248
  /**
3060
3249
  * @param {string} data
3061
3250
  * @returns {Comment}
3251
+ * @see https://dom.spec.whatwg.org/#dom-document-createcomment
3252
+ * @see https://www.w3.org/TR/xml/#NT-Comment XML 1.0 production [15]
3253
+ * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.3
3254
+ *
3255
+ * Note: no validation is performed at creation time. When the resulting document is
3256
+ * serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
3257
+ * if the comment data contains `--` anywhere, ends with `-`, or contains characters
3258
+ * outside the XML Char production (W3C DOM Parsing §3.2.1.3). Without that option the
3259
+ * data is emitted verbatim.
3062
3260
  */ createComment: function createComment(data) {
3063
3261
  var node = new Comment(PDC);
3064
3262
  node.ownerDocument = this;
@@ -3067,9 +3265,21 @@ Document.prototype = {
3067
3265
  return node;
3068
3266
  },
3069
3267
  /**
3268
+ * Returns a new CDATASection node whose data is `data`.
3269
+ *
3270
+ * __This implementation differs from the specification:__ - calling this method on an HTML
3271
+ * document does not throw `NotSupportedError`.
3272
+ *
3070
3273
  * @param {string} data
3071
3274
  * @returns {CDATASection}
3275
+ * @throws {DOMException}
3276
+ * With code `INVALID_CHARACTER_ERR` if `data` contains `"]]>"`.
3277
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection
3278
+ * @see https://dom.spec.whatwg.org/#dom-document-createcdatasection
3072
3279
  */ createCDATASection: function createCDATASection(data) {
3280
+ if (data.indexOf(']]>') !== -1) {
3281
+ throw new DOMException$1(DOMException$1.INVALID_CHARACTER_ERR, 'data contains "]]>"');
3282
+ }
3073
3283
  var node = new CDATASection(PDC);
3074
3284
  node.ownerDocument = this;
3075
3285
  node.childNodes = new NodeList();
@@ -3077,9 +3287,24 @@ Document.prototype = {
3077
3287
  return node;
3078
3288
  },
3079
3289
  /**
3290
+ * Returns a ProcessingInstruction node whose target is target and data is data.
3291
+ *
3292
+ * __This behavior is slightly different from the in the specs__:
3293
+ * - it does not do any input validation on the arguments and doesn't throw
3294
+ * "InvalidCharacterError".
3295
+ *
3296
+ * Note: When the resulting document is serialized with `requireWellFormed: true`, the
3297
+ * serializer throws `InvalidStateError` if `.target` contains `:` or is an ASCII
3298
+ * case-insensitive match for `"xml"`, or if `.data` contains `?>` or characters outside the
3299
+ * XML Char production (W3C DOM Parsing §3.2.1.7). Without that option the data is emitted
3300
+ * verbatim.
3301
+ *
3080
3302
  * @param {string} target
3081
3303
  * @param {string} data
3082
3304
  * @returns {ProcessingInstruction}
3305
+ * @see https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction
3306
+ * @see https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction
3307
+ * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.7
3083
3308
  */ createProcessingInstruction: function createProcessingInstruction(target, data) {
3084
3309
  var node = new ProcessingInstruction(PDC);
3085
3310
  node.ownerDocument = this;
@@ -3483,7 +3708,31 @@ CDATASection.prototype = {
3483
3708
  nodeType: CDATA_SECTION_NODE
3484
3709
  };
3485
3710
  _extends(CDATASection, Text);
3486
- function DocumentType(symbol) {
3711
+ /**
3712
+ * @class DocumentType
3713
+ * @augments Node
3714
+ * @property {string} publicId
3715
+ * The external subset public identifier, stored verbatim (including surrounding quotes).
3716
+ * Declared `readonly` by the WHATWG DOM spec; xmldom does not enforce this constraint —
3717
+ * direct property writes succeed and the written value is serialized verbatim.
3718
+ * When serialized with `requireWellFormed: true`, the serializer validates the value against
3719
+ * the XML `PubidLiteral` production and throws `InvalidStateError` if it does not match.
3720
+ * @property {string} systemId
3721
+ * The external subset system identifier, stored verbatim (including surrounding quotes).
3722
+ * Declared `readonly` by the WHATWG DOM spec; xmldom does not enforce this constraint —
3723
+ * direct property writes succeed and the written value is serialized verbatim.
3724
+ * When serialized with `requireWellFormed: true`, the serializer validates the value against
3725
+ * the XML `SystemLiteral` production and throws `InvalidStateError` if it does not match.
3726
+ * @property {string} internalSubset
3727
+ * The internal subset string (the raw content between `[` and `]`), or an empty string.
3728
+ * Declared `readonly` by the WHATWG DOM spec; xmldom does not enforce this constraint —
3729
+ * direct property writes succeed and the written value is serialized verbatim.
3730
+ * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
3731
+ * if the value contains `"]>"`.
3732
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/DocumentType MDN
3733
+ * @see https://dom.spec.whatwg.org/#interface-documenttype WHATWG DOM
3734
+ * @prettierignore
3735
+ */ function DocumentType(symbol) {
3487
3736
  checkSymbol(symbol);
3488
3737
  }
3489
3738
  DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
@@ -3515,11 +3764,89 @@ function ProcessingInstruction(symbol) {
3515
3764
  ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
3516
3765
  _extends(ProcessingInstruction, CharacterData);
3517
3766
  function XMLSerializer$1() {}
3518
- XMLSerializer$1.prototype.serializeToString = function(node, nodeFilter) {
3519
- return nodeSerializeToString.call(node, nodeFilter);
3767
+ /**
3768
+ * Returns the result of serializing `node` to XML.
3769
+ *
3770
+ * When `options.requireWellFormed` is `true`, the serializer throws `InvalidStateError` for
3771
+ * content that would produce ill-formed XML (e.g. CDATASection data containing `"]]>"`, Text
3772
+ * data containing characters outside the XML Char production, or a Document with no
3773
+ * `documentElement`).
3774
+ *
3775
+ * When `options.splitCDATASections` is `false`, CDATASection data is emitted verbatim even
3776
+ * when it contains `"]]>"`. When `true` (the default), `"]]>"` sequences are split across
3777
+ * concatenated CDATA sections — this behavior is **deprecated** and will be removed in the
3778
+ * next breaking release. Callers should migrate to `{ requireWellFormed: true }`, which throws
3779
+ * `InvalidStateError` instead of transforming.
3780
+ *
3781
+ * __This implementation differs from the specification:__ - CDATASection serialization is not
3782
+ * specified by W3C DOM Parsing or WHATWG DOM Parsing (see
3783
+ * {@link https://github.com/w3c/DOM-Parsing/issues/38 w3c/DOM-Parsing#38}).
3784
+ * When `splitCDATASections` is `true` (the default), `"]]>"` sequences in CDATASection data
3785
+ * are split across concatenated CDATA sections — this mechanism is derived from DOM Level 3
3786
+ * Core and is **deprecated**. The split mechanics will be removed in the next breaking
3787
+ * release. Callers that rely on this behavior should migrate to `{ requireWellFormed: true }`.
3788
+ * - W3C DOM Parsing §3.2.1.1 requires well-formedness checks on Element `localName`s,
3789
+ * prefixes,
3790
+ * and attribute serialization (duplicate attributes, namespace declarations, attribute value
3791
+ * characters) when `requireWellFormed` is `true`. These checks are **not implemented** in this
3792
+ * release — see the tracking issue filed against the next breaking milestone.
3793
+ *
3794
+ * @param {Node} node
3795
+ * @param {Object | function} [options]
3796
+ * Options object, or a legacy nodeFilter function (backward compatible).
3797
+ * @param {boolean} [options.requireWellFormed=false]
3798
+ * When `true`, throws `InvalidStateError` for content that would produce ill-formed XML.
3799
+ * @param {boolean} [options.splitCDATASections=true]
3800
+ * When `true` (default), splits `"]]>"` sequences in CDATASection data across concatenated
3801
+ * CDATA sections. **Deprecated** — will be removed in the next breaking release.
3802
+ * @param {function} [options.nodeFilter]
3803
+ * A filter function applied to each node before serialization.
3804
+ * @returns {string}
3805
+ * @throws {DOMException}
3806
+ * With name `InvalidStateError` when `requireWellFormed` is `true` and any of the following
3807
+ * conditions hold:
3808
+ * - CDATASection data contains `"]]>"`
3809
+ * - Text data contains characters outside the XML Char production
3810
+ * - a Comment node's data contains `--` anywhere or ends with `-`
3811
+ * - a ProcessingInstruction's target contains `:` or is an ASCII case-insensitive match for
3812
+ * `"xml"`, or its data contains `?>` or characters outside the XML Char production
3813
+ * - a DocumentType's `publicId` is non-empty and does not match the XML `PubidLiteral`
3814
+ * production (W3C DOM Parsing §3.2.1.3; XML 1.0 production [12])
3815
+ * - a DocumentType's `systemId` is non-empty and does not match the XML `SystemLiteral`
3816
+ * production (W3C DOM Parsing §3.2.1.3; XML 1.0 production [11])
3817
+ * - a DocumentType's `internalSubset` contains `"]>"`
3818
+ * - the Document has no `documentElement`
3819
+ * @see https://developer.mozilla.org/docs/Web/API/XMLSerializer/serializeToString
3820
+ * @see https://html.spec.whatwg.org/#dom-xmlserializer-serializetostring
3821
+ * @see https://github.com/w3c/DOM-Parsing/issues/84
3822
+ * @prettierignore
3823
+ */ XMLSerializer$1.prototype.serializeToString = function(node, options) {
3824
+ return nodeSerializeToString.call(node, options);
3520
3825
  };
3521
3826
  Node.prototype.toString = nodeSerializeToString;
3522
- function nodeSerializeToString(nodeFilter) {
3827
+ function nodeSerializeToString(options) {
3828
+ // Normalize the user-supplied options into a single internal opts object so that the
3829
+ // internal serializer always works with a consistent shape rather than positional flags.
3830
+ var opts;
3831
+ if (typeof options === 'function') {
3832
+ opts = {
3833
+ requireWellFormed: false,
3834
+ splitCDATASections: true,
3835
+ nodeFilter: options
3836
+ };
3837
+ } else if (options != null) {
3838
+ opts = {
3839
+ requireWellFormed: !!options.requireWellFormed,
3840
+ splitCDATASections: options.splitCDATASections !== false,
3841
+ nodeFilter: options.nodeFilter || null
3842
+ };
3843
+ } else {
3844
+ opts = {
3845
+ requireWellFormed: false,
3846
+ splitCDATASections: true,
3847
+ nodeFilter: null
3848
+ };
3849
+ }
3523
3850
  var buf = [];
3524
3851
  var refNode = this.nodeType === DOCUMENT_NODE && this.documentElement || this;
3525
3852
  var prefix = refNode.prefix;
@@ -3535,7 +3862,7 @@ function nodeSerializeToString(nodeFilter) {
3535
3862
  ];
3536
3863
  }
3537
3864
  }
3538
- serializeToString(this, buf, nodeFilter, visibleNamespaces);
3865
+ serializeToString(this, buf, visibleNamespaces, opts);
3539
3866
  return buf.join('');
3540
3867
  }
3541
3868
  function needNamespaceDefine(node, isHTML, visibleNamespaces) {
@@ -3581,222 +3908,302 @@ function needNamespaceDefine(node, isHTML, visibleNamespaces) {
3581
3908
  */ function addSerializedAttribute(buf, qualifiedName, value) {
3582
3909
  buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
3583
3910
  }
3584
- function serializeToString(node, buf, nodeFilter, visibleNamespaces) {
3911
+ function serializeToString(node, buf, visibleNamespaces, opts) {
3585
3912
  if (!visibleNamespaces) {
3586
3913
  visibleNamespaces = [];
3587
3914
  }
3915
+ var nodeFilter = opts.nodeFilter;
3916
+ var requireWellFormed = opts.requireWellFormed;
3917
+ var splitCDATASections = opts.splitCDATASections;
3588
3918
  var doc = node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument;
3589
3919
  var isHTML = doc.type === 'html';
3590
- if (nodeFilter) {
3591
- node = nodeFilter(node);
3592
- if (node) {
3593
- if (typeof node == 'string') {
3594
- buf.push(node);
3595
- return;
3596
- }
3597
- } else {
3598
- return;
3599
- }
3600
- //buf.sort.apply(attrs, attributeSorter);
3601
- }
3602
- switch(node.nodeType){
3603
- case ELEMENT_NODE:
3604
- var attrs = node.attributes;
3605
- var len = attrs.length;
3606
- var child = node.firstChild;
3607
- var nodeName = node.tagName;
3608
- var prefixedNodeName = nodeName;
3609
- if (!isHTML && !node.prefix && node.namespaceURI) {
3610
- var defaultNS;
3611
- // lookup current default ns from `xmlns` attribute
3612
- for(var ai = 0; ai < attrs.length; ai++){
3613
- if (attrs.item(ai).name === 'xmlns') {
3614
- defaultNS = attrs.item(ai).value;
3615
- break;
3920
+ walkDOM(node, {
3921
+ ns: visibleNamespaces
3922
+ }, {
3923
+ enter: function enter(n, ctx) {
3924
+ var namespaces = ctx.ns;
3925
+ if (nodeFilter) {
3926
+ n = nodeFilter(n);
3927
+ if (n) {
3928
+ if (typeof n == 'string') {
3929
+ buf.push(n);
3930
+ return null;
3616
3931
  }
3932
+ } else {
3933
+ return null;
3617
3934
  }
3618
- if (!defaultNS) {
3619
- // lookup current default ns in visibleNamespaces
3620
- for(var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--){
3621
- var namespace = visibleNamespaces[nsi];
3622
- if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
3623
- defaultNS = namespace.namespace;
3624
- break;
3935
+ }
3936
+ switch(n.nodeType){
3937
+ case ELEMENT_NODE:
3938
+ var attrs = n.attributes;
3939
+ var len = attrs.length;
3940
+ var nodeName = n.tagName;
3941
+ var prefixedNodeName = nodeName;
3942
+ if (!isHTML && !n.prefix && n.namespaceURI) {
3943
+ var defaultNS;
3944
+ // lookup current default ns from `xmlns` attribute
3945
+ for(var ai = 0; ai < attrs.length; ai++){
3946
+ if (attrs.item(ai).name === 'xmlns') {
3947
+ defaultNS = attrs.item(ai).value;
3948
+ break;
3949
+ }
3950
+ }
3951
+ if (!defaultNS) {
3952
+ // lookup current default ns in visibleNamespaces
3953
+ for(var nsi = namespaces.length - 1; nsi >= 0; nsi--){
3954
+ var nsEntry = namespaces[nsi];
3955
+ if (nsEntry.prefix === '' && nsEntry.namespace === n.namespaceURI) {
3956
+ defaultNS = nsEntry.namespace;
3957
+ break;
3958
+ }
3959
+ }
3960
+ }
3961
+ if (defaultNS !== n.namespaceURI) {
3962
+ for(var nsi = namespaces.length - 1; nsi >= 0; nsi--){
3963
+ var nsEntry = namespaces[nsi];
3964
+ if (nsEntry.namespace === n.namespaceURI) {
3965
+ if (nsEntry.prefix) {
3966
+ prefixedNodeName = nsEntry.prefix + ':' + nodeName;
3967
+ }
3968
+ break;
3969
+ }
3970
+ }
3625
3971
  }
3626
3972
  }
3627
- }
3628
- if (defaultNS !== node.namespaceURI) {
3629
- for(var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--){
3630
- var namespace = visibleNamespaces[nsi];
3631
- if (namespace.namespace === node.namespaceURI) {
3632
- if (namespace.prefix) {
3633
- prefixedNodeName = namespace.prefix + ':' + nodeName;
3973
+ buf.push('<', prefixedNodeName);
3974
+ // Build a fresh namespace snapshot for this element's children.
3975
+ // The slice prevents sibling elements from inheriting each other's declarations.
3976
+ var childNamespaces = namespaces.slice();
3977
+ for(var i = 0; i < len; i++){
3978
+ // add namespaces for attributes
3979
+ var attr = attrs.item(i);
3980
+ if (attr.prefix == 'xmlns') {
3981
+ childNamespaces.push({
3982
+ prefix: attr.localName,
3983
+ namespace: attr.value
3984
+ });
3985
+ } else if (attr.nodeName == 'xmlns') {
3986
+ childNamespaces.push({
3987
+ prefix: '',
3988
+ namespace: attr.value
3989
+ });
3990
+ }
3991
+ }
3992
+ for(var i = 0; i < len; i++){
3993
+ var attr = attrs.item(i);
3994
+ if (needNamespaceDefine(attr, isHTML, childNamespaces)) {
3995
+ var attrPrefix = attr.prefix || '';
3996
+ var uri = attr.namespaceURI;
3997
+ addSerializedAttribute(buf, attrPrefix ? 'xmlns:' + attrPrefix : 'xmlns', uri);
3998
+ childNamespaces.push({
3999
+ prefix: attrPrefix,
4000
+ namespace: uri
4001
+ });
4002
+ }
4003
+ // Apply nodeFilter and serialize the attribute.
4004
+ var filteredAttr = nodeFilter ? nodeFilter(attr) : attr;
4005
+ if (filteredAttr) {
4006
+ if (typeof filteredAttr === 'string') {
4007
+ buf.push(filteredAttr);
4008
+ } else {
4009
+ addSerializedAttribute(buf, filteredAttr.name, filteredAttr.value);
3634
4010
  }
3635
- break;
3636
4011
  }
3637
4012
  }
3638
- }
3639
- }
3640
- buf.push('<', prefixedNodeName);
3641
- for(var i = 0; i < len; i++){
3642
- // add namespaces for attributes
3643
- var attr = attrs.item(i);
3644
- if (attr.prefix == 'xmlns') {
3645
- visibleNamespaces.push({
3646
- prefix: attr.localName,
3647
- namespace: attr.value
3648
- });
3649
- } else if (attr.nodeName == 'xmlns') {
3650
- visibleNamespaces.push({
3651
- prefix: '',
3652
- namespace: attr.value
3653
- });
3654
- }
3655
- }
3656
- for(var i = 0; i < len; i++){
3657
- var attr = attrs.item(i);
3658
- if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
3659
- var prefix = attr.prefix || '';
3660
- var uri = attr.namespaceURI;
3661
- addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : 'xmlns', uri);
3662
- visibleNamespaces.push({
3663
- prefix: prefix,
3664
- namespace: uri
3665
- });
3666
- }
3667
- serializeToString(attr, buf, nodeFilter, visibleNamespaces);
3668
- }
3669
- // add namespace for current node
3670
- if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
3671
- var prefix = node.prefix || '';
3672
- var uri = node.namespaceURI;
3673
- addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : 'xmlns', uri);
3674
- visibleNamespaces.push({
3675
- prefix: prefix,
3676
- namespace: uri
3677
- });
3678
- }
3679
- // in XML elements can be closed when they have no children
3680
- var canCloseTag = !child;
3681
- if (canCloseTag && (isHTML || node.namespaceURI === NAMESPACE$2.HTML)) {
3682
- // in HTML (doc or ns) only void elements can be closed right away
3683
- canCloseTag = isHTMLVoidElement(nodeName);
3684
- }
3685
- if (canCloseTag) {
3686
- buf.push('/>');
3687
- } else {
3688
- buf.push('>');
3689
- //if is cdata child node
3690
- if (isHTML && isHTMLRawTextElement$1(nodeName)) {
3691
- while(child){
3692
- if (child.data) {
3693
- buf.push(child.data);
3694
- } else {
3695
- serializeToString(child, buf, nodeFilter, visibleNamespaces.slice());
4013
+ // add namespace for current node
4014
+ if (nodeName === prefixedNodeName && needNamespaceDefine(n, isHTML, childNamespaces)) {
4015
+ var nodePrefix = n.prefix || '';
4016
+ var uri = n.namespaceURI;
4017
+ addSerializedAttribute(buf, nodePrefix ? 'xmlns:' + nodePrefix : 'xmlns', uri);
4018
+ childNamespaces.push({
4019
+ prefix: nodePrefix,
4020
+ namespace: uri
4021
+ });
4022
+ }
4023
+ // in XML elements can be closed when they have no children
4024
+ var canCloseTag = !n.firstChild;
4025
+ if (canCloseTag && (isHTML || n.namespaceURI === NAMESPACE$2.HTML)) {
4026
+ // in HTML (doc or ns) only void elements can be closed right away
4027
+ canCloseTag = isHTMLVoidElement(nodeName);
4028
+ }
4029
+ if (canCloseTag) {
4030
+ buf.push('/>');
4031
+ // Self-closing: no children and no closing tag needed from exit.
4032
+ return null;
4033
+ }
4034
+ buf.push('>');
4035
+ // HTML raw text elements: serialize children as raw data without further descent.
4036
+ if (isHTML && isHTMLRawTextElement$1(nodeName)) {
4037
+ var child = n.firstChild;
4038
+ while(child){
4039
+ if (child.data) {
4040
+ buf.push(child.data);
4041
+ } else {
4042
+ serializeToString(child, buf, childNamespaces.slice(), opts);
4043
+ }
4044
+ child = child.nextSibling;
3696
4045
  }
3697
- child = child.nextSibling;
4046
+ buf.push('</', prefixedNodeName, '>');
4047
+ // Children handled manually above; prevent walkDOM from also traversing them.
4048
+ return null;
3698
4049
  }
3699
- } else {
3700
- while(child){
3701
- serializeToString(child, buf, nodeFilter, visibleNamespaces.slice());
3702
- child = child.nextSibling;
4050
+ // Return child context so walkDOM descends; exit will emit the closing tag.
4051
+ return {
4052
+ ns: childNamespaces,
4053
+ tag: prefixedNodeName
4054
+ };
4055
+ case DOCUMENT_NODE:
4056
+ case DOCUMENT_FRAGMENT_NODE:
4057
+ if (requireWellFormed && n.nodeType === DOCUMENT_NODE && n.documentElement == null) {
4058
+ throw new DOMException$1('The Document has no documentElement', DOMExceptionName.InvalidStateError);
3703
4059
  }
3704
- }
3705
- buf.push('</', prefixedNodeName, '>');
3706
- }
3707
- // remove added visible namespaces
3708
- //visibleNamespaces.length = startVisibleNamespaces;
3709
- return;
3710
- case DOCUMENT_NODE:
3711
- case DOCUMENT_FRAGMENT_NODE:
3712
- var child = node.firstChild;
3713
- while(child){
3714
- serializeToString(child, buf, nodeFilter, visibleNamespaces.slice());
3715
- child = child.nextSibling;
3716
- }
3717
- return;
3718
- case ATTRIBUTE_NODE:
3719
- return addSerializedAttribute(buf, node.name, node.value);
3720
- case TEXT_NODE:
3721
- /*
3722
- * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
3723
- * except when used as markup delimiters, or within a comment, a processing instruction,
3724
- * or a CDATA section.
3725
- * If they are needed elsewhere, they must be escaped using either numeric character
3726
- * references or the strings `&amp;` and `&lt;` respectively.
3727
- * The right angle bracket (>) may be represented using the string " &gt; ",
3728
- * and must, for compatibility, be escaped using either `&gt;`,
3729
- * or a character reference when it appears in the string `]]>` in content,
3730
- * when that string is not marking the end of a CDATA section.
3731
- *
3732
- * In the content of elements, character data is any string of characters which does not
3733
- * contain the start-delimiter of any markup and does not include the CDATA-section-close
3734
- * delimiter, `]]>`.
3735
- *
3736
- * @see https://www.w3.org/TR/xml/#NT-CharData
3737
- * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
3738
- */ return buf.push(node.data.replace(/[<&>]/g, _xmlEncoder));
3739
- case CDATA_SECTION_NODE:
3740
- return buf.push(g$1.CDATA_START, node.data, g$1.CDATA_END);
3741
- case COMMENT_NODE:
3742
- return buf.push(g$1.COMMENT_START, node.data, g$1.COMMENT_END);
3743
- case DOCUMENT_TYPE_NODE:
3744
- var pubid = node.publicId;
3745
- var sysid = node.systemId;
3746
- buf.push(g$1.DOCTYPE_DECL_START, ' ', node.name);
3747
- if (pubid) {
3748
- buf.push(' ', g$1.PUBLIC, ' ', pubid);
3749
- if (sysid && sysid !== '.') {
3750
- buf.push(' ', sysid);
3751
- }
3752
- } else if (sysid && sysid !== '.') {
3753
- buf.push(' ', g$1.SYSTEM, ' ', sysid);
4060
+ // Pass namespaces through; each child element will slice independently.
4061
+ return {
4062
+ ns: namespaces
4063
+ };
4064
+ case ATTRIBUTE_NODE:
4065
+ addSerializedAttribute(buf, n.name, n.value);
4066
+ return null;
4067
+ case TEXT_NODE:
4068
+ /*
4069
+ * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
4070
+ * except when used as markup delimiters, or within a comment, a processing instruction,
4071
+ * or a CDATA section.
4072
+ * If they are needed elsewhere, they must be escaped using either numeric character
4073
+ * references or the strings `&amp;` and `&lt;` respectively.
4074
+ * The right angle bracket (>) may be represented using the string " &gt; ",
4075
+ * and must, for compatibility, be escaped using either `&gt;`,
4076
+ * or a character reference when it appears in the string `]]>` in content,
4077
+ * when that string is not marking the end of a CDATA section.
4078
+ *
4079
+ * In the content of elements, character data is any string of characters which does not
4080
+ * contain the start-delimiter of any markup and does not include the CDATA-section-close
4081
+ * delimiter, `]]>`.
4082
+ *
4083
+ * @see https://www.w3.org/TR/xml/#NT-CharData
4084
+ * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
4085
+ */ if (requireWellFormed && g$1.InvalidChar.test(n.data)) {
4086
+ throw new DOMException$1('The Text node data contains characters outside the XML Char production', DOMExceptionName.InvalidStateError);
4087
+ }
4088
+ buf.push(n.data.replace(/[<&>]/g, _xmlEncoder));
4089
+ return null;
4090
+ case CDATA_SECTION_NODE:
4091
+ if (requireWellFormed && n.data.indexOf(']]>') !== -1) {
4092
+ throw new DOMException$1('The CDATASection data contains "]]>"', DOMExceptionName.InvalidStateError);
4093
+ }
4094
+ if (splitCDATASections) {
4095
+ buf.push(g$1.CDATA_START, n.data.replace(/]]>/g, ']]]]><![CDATA[>'), g$1.CDATA_END);
4096
+ } else {
4097
+ buf.push(g$1.CDATA_START, n.data, g$1.CDATA_END);
4098
+ }
4099
+ return null;
4100
+ case COMMENT_NODE:
4101
+ if (requireWellFormed) {
4102
+ if (g$1.InvalidChar.test(n.data)) {
4103
+ throw new DOMException$1('The comment node data contains characters outside the XML Char production', DOMExceptionName.InvalidStateError);
4104
+ }
4105
+ if (n.data.indexOf('--') !== -1 || n.data[n.data.length - 1] === '-') {
4106
+ throw new DOMException$1('The comment node data contains "--" or ends with "-"', DOMExceptionName.InvalidStateError);
4107
+ }
4108
+ }
4109
+ buf.push(g$1.COMMENT_START, n.data, g$1.COMMENT_END);
4110
+ return null;
4111
+ case DOCUMENT_TYPE_NODE:
4112
+ var pubid = n.publicId;
4113
+ var sysid = n.systemId;
4114
+ if (requireWellFormed) {
4115
+ if (pubid && !g$1.PubidLiteral_match.test(pubid)) {
4116
+ throw new DOMException$1('DocumentType publicId is not a valid PubidLiteral', DOMExceptionName.InvalidStateError);
4117
+ }
4118
+ if (sysid && sysid !== '.' && !g$1.SystemLiteral_match.test(sysid)) {
4119
+ throw new DOMException$1('DocumentType systemId is not a valid SystemLiteral', DOMExceptionName.InvalidStateError);
4120
+ }
4121
+ if (n.internalSubset && n.internalSubset.indexOf(']>') !== -1) {
4122
+ throw new DOMException$1('DocumentType internalSubset contains "]>"', DOMExceptionName.InvalidStateError);
4123
+ }
4124
+ }
4125
+ buf.push(g$1.DOCTYPE_DECL_START, ' ', n.name);
4126
+ if (pubid) {
4127
+ buf.push(' ', g$1.PUBLIC, ' ', pubid);
4128
+ if (sysid && sysid !== '.') {
4129
+ buf.push(' ', sysid);
4130
+ }
4131
+ } else if (sysid && sysid !== '.') {
4132
+ buf.push(' ', g$1.SYSTEM, ' ', sysid);
4133
+ }
4134
+ if (n.internalSubset) {
4135
+ buf.push(' [', n.internalSubset, ']');
4136
+ }
4137
+ buf.push('>');
4138
+ return null;
4139
+ case PROCESSING_INSTRUCTION_NODE:
4140
+ if (requireWellFormed) {
4141
+ if (n.target.indexOf(':') !== -1 || n.target.toLowerCase() === 'xml') {
4142
+ throw new DOMException$1('The ProcessingInstruction target is not well-formed', DOMExceptionName.InvalidStateError);
4143
+ }
4144
+ if (g$1.InvalidChar.test(n.data)) {
4145
+ throw new DOMException$1('The ProcessingInstruction data contains characters outside the XML Char production', DOMExceptionName.InvalidStateError);
4146
+ }
4147
+ if (n.data.indexOf('?>') !== -1) {
4148
+ throw new DOMException$1('The ProcessingInstruction data contains "?>"', DOMExceptionName.InvalidStateError);
4149
+ }
4150
+ }
4151
+ buf.push('<?', n.target, ' ', n.data, '?>');
4152
+ return null;
4153
+ case ENTITY_REFERENCE_NODE:
4154
+ buf.push('&', n.nodeName, ';');
4155
+ return null;
4156
+ //case ENTITY_NODE:
4157
+ //case NOTATION_NODE:
4158
+ default:
4159
+ buf.push('??', n.nodeName);
4160
+ return null;
3754
4161
  }
3755
- if (node.internalSubset) {
3756
- buf.push(' [', node.internalSubset, ']');
4162
+ },
4163
+ exit: function exit(n, childCtx) {
4164
+ // Emit the closing tag for elements that were opened (not self-closed, not raw text).
4165
+ if (childCtx && childCtx.tag) {
4166
+ buf.push('</', childCtx.tag, '>');
3757
4167
  }
3758
- buf.push('>');
3759
- return;
3760
- case PROCESSING_INSTRUCTION_NODE:
3761
- return buf.push('<?', node.target, ' ', node.data, '?>');
3762
- case ENTITY_REFERENCE_NODE:
3763
- return buf.push('&', node.nodeName, ';');
3764
- //case ENTITY_NODE:
3765
- //case NOTATION_NODE:
3766
- default:
3767
- buf.push('??', node.nodeName);
3768
- }
4168
+ }
4169
+ });
3769
4170
  }
3770
- function importNode(doc, node, deep) {
3771
- var node2;
3772
- switch(node.nodeType){
3773
- case ELEMENT_NODE:
3774
- node2 = node.cloneNode(false);
3775
- node2.ownerDocument = doc;
3776
- //var attrs = node2.attributes;
3777
- //var len = attrs.length;
3778
- //for(var i=0;i<len;i++){
3779
- //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
3780
- //}
3781
- case DOCUMENT_FRAGMENT_NODE:
3782
- break;
3783
- case ATTRIBUTE_NODE:
3784
- deep = true;
3785
- break;
3786
- }
3787
- if (!node2) {
3788
- node2 = node.cloneNode(false); //false
3789
- }
3790
- node2.ownerDocument = doc;
3791
- node2.parentNode = null;
3792
- if (deep) {
3793
- var child = node.firstChild;
3794
- while(child){
3795
- node2.appendChild(importNode(doc, child, deep));
3796
- child = child.nextSibling;
4171
+ /**
4172
+ * Imports a node from a different document into `doc`, creating a new copy.
4173
+ * Delegates to {@link walkDOM} for traversal. Each node in the subtree is shallow-cloned,
4174
+ * stamped with `doc` as its `ownerDocument`, and detached (`parentNode` set to `null`).
4175
+ * Children are imported recursively when `deep` is `true`; for {@link Attr} nodes `deep` is
4176
+ * always forced to `true`
4177
+ * because an attribute's value lives in a child text node.
4178
+ *
4179
+ * @param {Document} doc
4180
+ * The document that will own the imported node.
4181
+ * @param {Node} node
4182
+ * The node to import.
4183
+ * @param {boolean} deep
4184
+ * If `true`, descendants are imported recursively.
4185
+ * @returns {Node}
4186
+ * The newly imported node, now owned by `doc`.
4187
+ */ function importNode(doc, node, deep) {
4188
+ var destRoot;
4189
+ walkDOM(node, null, {
4190
+ enter: function enter(srcNode, destParent) {
4191
+ // Shallow-clone the node and stamp it into the target document.
4192
+ var destNode = srcNode.cloneNode(false);
4193
+ destNode.ownerDocument = doc;
4194
+ destNode.parentNode = null;
4195
+ // capture as the root of the imported subtree or attach to parent.
4196
+ if (destParent === null) {
4197
+ destRoot = destNode;
4198
+ } else {
4199
+ destParent.appendChild(destNode);
4200
+ }
4201
+ // ATTRIBUTE_NODE must always be imported deeply: its value lives in a child text node.
4202
+ var shouldDeep = srcNode.nodeType === ATTRIBUTE_NODE || deep;
4203
+ return shouldDeep ? destNode : null;
3797
4204
  }
3798
- }
3799
- return node2;
4205
+ });
4206
+ return destRoot;
3800
4207
  }
3801
4208
  /**
3802
4209
  * Creates a copy of a node from an existing one.
@@ -3814,46 +4221,73 @@ function importNode(doc, node, deep) {
3814
4221
  * May throw a DOMException if operations within setAttributeNode or appendChild (which are
3815
4222
  * potentially invoked in this function) do not meet their specific constraints.
3816
4223
  */ function cloneNode(doc, node, deep) {
3817
- var node2 = new node.constructor(PDC);
3818
- for(var n in node){
3819
- if (hasOwn$1(node, n)) {
3820
- var v = node[n];
3821
- if ((typeof v === "undefined" ? "undefined" : _type_of(v)) != 'object') {
3822
- if (v != node2[n]) {
3823
- node2[n] = v;
4224
+ var destRoot;
4225
+ walkDOM(node, null, {
4226
+ enter: function enter(srcNode, destParent) {
4227
+ // 1. Create a blank node of the same type and copy all scalar own properties.
4228
+ var destNode = new srcNode.constructor(PDC);
4229
+ for(var n in srcNode){
4230
+ if (hasOwn$1(srcNode, n)) {
4231
+ var v = srcNode[n];
4232
+ if ((typeof v === "undefined" ? "undefined" : _type_of(v)) != 'object') {
4233
+ if (v != destNode[n]) {
4234
+ destNode[n] = v;
4235
+ }
4236
+ }
3824
4237
  }
3825
4238
  }
3826
- }
3827
- }
3828
- if (node.childNodes) {
3829
- node2.childNodes = new NodeList();
3830
- }
3831
- node2.ownerDocument = doc;
3832
- switch(node2.nodeType){
3833
- case ELEMENT_NODE:
3834
- var attrs = node.attributes;
3835
- var attrs2 = node2.attributes = new NamedNodeMap();
3836
- var len = attrs.length;
3837
- attrs2._ownerElement = node2;
3838
- for(var i = 0; i < len; i++){
3839
- node2.setAttributeNode(cloneNode(doc, attrs.item(i), true));
4239
+ if (srcNode.childNodes) {
4240
+ destNode.childNodes = new NodeList();
3840
4241
  }
3841
- break;
3842
- case ATTRIBUTE_NODE:
3843
- deep = true;
3844
- }
3845
- if (deep) {
3846
- var child = node.firstChild;
3847
- while(child){
3848
- node2.appendChild(cloneNode(doc, child, deep));
3849
- child = child.nextSibling;
4242
+ destNode.ownerDocument = doc;
4243
+ // 2. Handle node-type-specific setup.
4244
+ // Attributes are not DOM children, so they are cloned inline here
4245
+ // rather than by walkDOM descent.
4246
+ // ATTRIBUTE_NODE forces deep=true so its own children are walked.
4247
+ var shouldDeep = deep;
4248
+ switch(destNode.nodeType){
4249
+ case ELEMENT_NODE:
4250
+ var attrs = srcNode.attributes;
4251
+ var attrs2 = destNode.attributes = new NamedNodeMap();
4252
+ var len = attrs.length;
4253
+ attrs2._ownerElement = destNode;
4254
+ for(var i = 0; i < len; i++){
4255
+ destNode.setAttributeNode(cloneNode(doc, attrs.item(i), true));
4256
+ }
4257
+ break;
4258
+ case ATTRIBUTE_NODE:
4259
+ shouldDeep = true;
4260
+ }
4261
+ // 3. Attach to parent, or capture as the root of the cloned subtree.
4262
+ if (destParent !== null) {
4263
+ destParent.appendChild(destNode);
4264
+ } else {
4265
+ destRoot = destNode;
4266
+ }
4267
+ // 4. Return destNode as the context for children (causes walkDOM to descend),
4268
+ // or null to skip children (shallow clone).
4269
+ return shouldDeep ? destNode : null;
3850
4270
  }
3851
- }
3852
- return node2;
4271
+ });
4272
+ return destRoot;
3853
4273
  }
3854
4274
  function __set__(object, key, value) {
3855
4275
  object[key] = value;
3856
4276
  }
4277
+ // Returns a new array of direct Element children.
4278
+ // Passed to LiveNodeList to implement ParentNode.children.
4279
+ // https://dom.spec.whatwg.org/#dom-parentnode-children
4280
+ function childrenRefresh(node) {
4281
+ var ls = [];
4282
+ var child = node.firstChild;
4283
+ while(child){
4284
+ if (child.nodeType === ELEMENT_NODE) {
4285
+ ls.push(child);
4286
+ }
4287
+ child = child.nextSibling;
4288
+ }
4289
+ return ls;
4290
+ }
3857
4291
  //do dynamic
3858
4292
  try {
3859
4293
  if (Object.defineProperty) {
@@ -3863,9 +4297,36 @@ try {
3863
4297
  return this.$$length;
3864
4298
  }
3865
4299
  });
3866
- Object.defineProperty(Node.prototype, 'textContent', {
4300
+ /**
4301
+ * The text content of this node and its descendants.
4302
+ *
4303
+ * For {@link Element} and {@link DocumentFragment} nodes, returns the concatenation of the
4304
+ * `nodeValue` of every descendant text node, excluding processing instruction and comment
4305
+ * nodes. For all other node types, returns `nodeValue`.
4306
+ *
4307
+ * Setting `textContent` on an element or document fragment replaces all child nodes with a
4308
+ * single text node; on other nodes it sets `data`, `value`, and `nodeValue` directly.
4309
+ *
4310
+ * @type {string | null}
4311
+ * @see {@link https://dom.spec.whatwg.org/#dom-node-textcontent}
4312
+ */ Object.defineProperty(Node.prototype, 'textContent', {
3867
4313
  get: function get() {
3868
- return getTextContent(this);
4314
+ if (this.nodeType === ELEMENT_NODE || this.nodeType === DOCUMENT_FRAGMENT_NODE) {
4315
+ var buf = [];
4316
+ walkDOM(this, null, {
4317
+ enter: function enter(n) {
4318
+ if (n.nodeType === ELEMENT_NODE || n.nodeType === DOCUMENT_FRAGMENT_NODE) {
4319
+ return true; // enter children
4320
+ }
4321
+ if (n.nodeType === PROCESSING_INSTRUCTION_NODE || n.nodeType === COMMENT_NODE) {
4322
+ return null; // excluded from text content
4323
+ }
4324
+ buf.push(n.nodeValue);
4325
+ }
4326
+ });
4327
+ return buf.join('');
4328
+ }
4329
+ return this.nodeValue;
3869
4330
  },
3870
4331
  set: function set(data) {
3871
4332
  switch(this.nodeType){
@@ -3885,23 +4346,21 @@ try {
3885
4346
  }
3886
4347
  }
3887
4348
  });
3888
- function getTextContent(node) {
3889
- switch(node.nodeType){
3890
- case ELEMENT_NODE:
3891
- case DOCUMENT_FRAGMENT_NODE:
3892
- var buf = [];
3893
- node = node.firstChild;
3894
- while(node){
3895
- if (node.nodeType !== 7 && node.nodeType !== 8) {
3896
- buf.push(getTextContent(node));
3897
- }
3898
- node = node.nextSibling;
3899
- }
3900
- return buf.join('');
3901
- default:
3902
- return node.nodeValue;
4349
+ Object.defineProperty(Element.prototype, 'children', {
4350
+ get: function get() {
4351
+ return new LiveNodeList(this, childrenRefresh);
3903
4352
  }
3904
- }
4353
+ });
4354
+ Object.defineProperty(Document.prototype, 'children', {
4355
+ get: function get() {
4356
+ return new LiveNodeList(this, childrenRefresh);
4357
+ }
4358
+ });
4359
+ Object.defineProperty(DocumentFragment.prototype, 'children', {
4360
+ get: function get() {
4361
+ return new LiveNodeList(this, childrenRefresh);
4362
+ }
4363
+ });
3905
4364
  __set__ = function __set__(object, key, value) {
3906
4365
  //console.log(value)
3907
4366
  object['$$' + key] = value;
@@ -3929,6 +4388,7 @@ dom$2.NodeList = NodeList;
3929
4388
  dom$2.Notation = Notation;
3930
4389
  dom$2.Text = Text;
3931
4390
  dom$2.ProcessingInstruction = ProcessingInstruction;
4391
+ dom$2.walkDOM = walkDOM;
3932
4392
  dom$2.XMLSerializer = XMLSerializer$1;
3933
4393
 
3934
4394
  var domParser$1 = {};
@@ -7632,76 +8092,200 @@ function requireErrors () {
7632
8092
  this.stack = new Error(message).stack;
7633
8093
  }
7634
8094
  XTAPIVersionError.prototype = new XTError();
7635
- function throwApiVersionError(msg, properties) {
8095
+ /*
8096
+ * Version/Compatibility Errors
8097
+ * ============================
8098
+ */ function throwApiVersionError(msg, properties) {
7636
8099
  var err = new XTAPIVersionError(msg);
7637
- err.properties = _objectSpread({
8100
+ /*
8101
+ * This error arises when a recent module version necessitates a more
8102
+ * current version of the docxtemplater core. Docxtemplater specifies an
8103
+ * "APIVersion," and if a module requires API Version 3.55 or higher,
8104
+ * but the docxtemplater instance provides API 3.52, this error will
8105
+ * occur. To resolve this issue, please update to the latest version of
8106
+ * docxtemplater.
8107
+ */ err.properties = _objectSpread({
7638
8108
  id: "api_version_error"
7639
8109
  }, properties);
7640
8110
  throw err;
7641
8111
  }
7642
- function throwMultiError(errors) {
7643
- var err = new XTTemplateError("Multi error");
7644
- err.properties = {
7645
- errors: errors,
7646
- id: "multi_error",
7647
- explanation: "The template has multiple errors"
8112
+ function throwFileTypeNotIdentified(zip) {
8113
+ var files = Object.keys(zip.files).slice(0, 10);
8114
+ var msg = "";
8115
+ if (files.length === 0) {
8116
+ msg = "Empty zip file";
8117
+ } else {
8118
+ msg = "Zip file contains : ".concat(files.join(","));
8119
+ }
8120
+ var err = new XTInternalError("The filetype for this file could not be identified, is this file corrupted ? ".concat(msg));
8121
+ /*
8122
+ * This error happens if you're creating docxtemplater with a zip file, but that file is not recognized as a docx/pptx/xlsx or odt file.
8123
+ *
8124
+ * Note that xlsx files and odt files need a paid module to be templated.
8125
+ *
8126
+ * Other zip files (zip, odp, ods) will trigger the same error.
8127
+ */ err.properties = {
8128
+ id: "filetype_not_identified",
8129
+ explanation: "The filetype for this file could not be identified, is this file corrupted ? ".concat(msg)
7648
8130
  };
7649
8131
  throw err;
7650
8132
  }
7651
- function getUnopenedTagException(options) {
7652
- var err = new XTTemplateError("Unopened tag");
7653
- err.properties = {
8133
+ function throwFileTypeNotHandled(fileType) {
8134
+ var err = new XTInternalError("The filetype \"".concat(fileType, "\" is not handled by docxtemplater"));
8135
+ /*
8136
+ * This error happens if the filetype was recognized (xlsx, odt), but
8137
+ * without the correct module, this file cannot be templated
8138
+ */ err.properties = {
8139
+ id: "filetype_not_handled",
8140
+ explanation: "The file you are trying to generate is of type \"".concat(fileType, "\", but only docx and pptx formats are handled"),
8141
+ fileType: fileType
8142
+ };
8143
+ throw err;
8144
+ }
8145
+ /*
8146
+ * Template Errors
8147
+ * ===============
8148
+ */ function throwMultiError(errors) {
8149
+ var err = new XTTemplateError("Multi error");
8150
+ /*
8151
+ * This error is an Error that contains all template errors.
8152
+ * It is a multi error because it contains all errors of the template in :
8153
+ * err.properties.errors.
8154
+ *
8155
+ * You can then map on each sub error like this :
8156
+ *
8157
+ * ```js
8158
+ * for (const err of error.properties.errors) {
8159
+ * console.log(err.properties.explanation);
8160
+ * }
8161
+ * ```
8162
+ */ err.properties = {
8163
+ errors: errors,
8164
+ id: "multi_error",
8165
+ explanation: "The template has multiple errors"
8166
+ };
8167
+ throw err;
8168
+ }
8169
+ function getUnopenedTagException(options) {
8170
+ var err = new XTTemplateError("Unopened tag");
8171
+ /*
8172
+ * This error happens if a tag is closed but not opened. For example with
8173
+ * the following template:
8174
+ *
8175
+ * ```docx
8176
+ * Hello name} !
8177
+ * ```
8178
+ */ err.properties = {
7654
8179
  xtag: last(options.xtag.split(" ")),
7655
8180
  id: "unopened_tag",
7656
8181
  context: options.xtag,
7657
8182
  offset: options.offset,
7658
8183
  lIndex: options.lIndex,
7659
- explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 10), "\" is unopened")
8184
+ explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 30), "\" is unopened")
7660
8185
  };
7661
8186
  return err;
7662
8187
  }
7663
8188
  function getDuplicateOpenTagException(options) {
7664
8189
  var err = new XTTemplateError("Duplicate open tag, expected one open tag");
7665
- err.properties = {
8190
+ /*
8191
+ * This error happens with following template :
8192
+ *
8193
+ * ```docx
8194
+ * Hello {{name
8195
+ * ```
8196
+ */ err.properties = {
7666
8197
  xtag: first(options.xtag.split(" ")),
7667
8198
  id: "duplicate_open_tag",
7668
8199
  context: options.xtag,
7669
8200
  offset: options.offset,
7670
8201
  lIndex: options.lIndex,
7671
- explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 10), "\" has duplicate open tags")
8202
+ explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 30), "\" has duplicate open tags")
7672
8203
  };
7673
8204
  return err;
7674
8205
  }
7675
8206
  function getDuplicateCloseTagException(options) {
7676
8207
  var err = new XTTemplateError("Duplicate close tag, expected one close tag");
7677
- err.properties = {
8208
+ /*
8209
+ * This error happens with following template :
8210
+ *
8211
+ * ```docx
8212
+ * Hello {name}}
8213
+ * ```
8214
+ */ err.properties = {
7678
8215
  xtag: first(options.xtag.split(" ")),
7679
8216
  id: "duplicate_close_tag",
7680
8217
  context: options.xtag,
7681
8218
  offset: options.offset,
7682
8219
  lIndex: options.lIndex,
7683
- explanation: "The tag ending with \"".concat(options.xtag.substr(0, 10), "\" has duplicate close tags")
8220
+ explanation: "The tag ending with \"".concat(options.xtag.substr(0, 30), "\" has duplicate close tags")
7684
8221
  };
7685
8222
  return err;
7686
8223
  }
7687
8224
  function getUnclosedTagException(options) {
7688
8225
  var err = new XTTemplateError("Unclosed tag");
7689
- err.properties = {
8226
+ /*
8227
+ * This error happens if a tag is opened but not closed.
8228
+ * For example with the following template:
8229
+ *
8230
+ * ```docx
8231
+ * Hello {name !
8232
+ * ```
8233
+ */ err.properties = {
7690
8234
  xtag: first(options.xtag.split(" ")).substr(1),
8235
+ // name
7691
8236
  id: "unclosed_tag",
7692
8237
  context: options.xtag,
7693
8238
  offset: options.offset,
7694
8239
  lIndex: options.lIndex,
7695
- explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 10), "\" is unclosed")
8240
+ explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 30), "\" is unclosed")
7696
8241
  };
7697
8242
  return err;
7698
8243
  }
7699
8244
  function throwXmlTagNotFound(options) {
8245
+ if (options.position === "left") {
8246
+ throwXmlTagNotFoundLeft(options);
8247
+ } else {
8248
+ throwXmlTagNotFoundRight(options);
8249
+ }
8250
+ }
8251
+ /*
8252
+ * Raw XML / XML Expansion Errors
8253
+ * ==============================
8254
+ */ function throwXmlTagNotFoundLeft(options) {
7700
8255
  var err = new XTTemplateError("No tag \"".concat(options.element, "\" was found at the ").concat(options.position));
7701
8256
  var part = options.parsed[options.index];
7702
- err.properties = {
7703
- id: "no_xml_tag_found_at_".concat(options.position),
7704
- explanation: "No tag \"".concat(options.element, "\" was found at the ").concat(options.position),
8257
+ /*
8258
+ * This error is not directly linked to the template, it means that some
8259
+ * tag tried to expand to adjacent XML tags, but those elements cannot be
8260
+ * accessed from the current node.
8261
+ *
8262
+ * This error happens if a rawXMLTag doesn't find a `<w:p>` element
8263
+ *
8264
+ * ```docx
8265
+ * <w:p><w:t>{@raw}</w:t>
8266
+ * // Note that the `</w:p>` tag is missing.
8267
+ * ```
8268
+ */ err.properties = {
8269
+ id: "no_xml_tag_found_at_left",
8270
+ explanation: "No tag \"".concat(options.element, "\" was found at the left"),
8271
+ offset: part.offset,
8272
+ part: part,
8273
+ parsed: options.parsed,
8274
+ index: options.index,
8275
+ element: options.element
8276
+ };
8277
+ throw err;
8278
+ }
8279
+ function throwXmlTagNotFoundRight(options) {
8280
+ var err = new XTTemplateError("No tag \"".concat(options.element, "\" was found at the ").concat(options.position));
8281
+ var part = options.parsed[options.index];
8282
+ /*
8283
+ * This error is not directly linked to the template, it means that some
8284
+ * tag tried to expand to adjacent XML tags, but those elements cannot be
8285
+ * accessed from the current node.
8286
+ */ err.properties = {
8287
+ id: "no_xml_tag_found_at_right",
8288
+ explanation: "No tag \"".concat(options.element, "\" was found at the right"),
7705
8289
  offset: part.offset,
7706
8290
  part: part,
7707
8291
  parsed: options.parsed,
@@ -7713,24 +8297,35 @@ function requireErrors () {
7713
8297
  function getCorruptCharactersException(_ref) {
7714
8298
  var tag = _ref.tag, value = _ref.value, offset = _ref.offset;
7715
8299
  var err = new XTRenderingError("There are some XML corrupt characters");
7716
- err.properties = {
8300
+ /*
8301
+ * This error prevents the docx document to become corrupt.
8302
+ * It happens if you're trying to render text that would produce invalid XML output.
8303
+ *
8304
+ * See #corrupt-character-error on how this can be fixed by changing your parser.
8305
+ */ err.properties = {
7717
8306
  id: "invalid_xml_characters",
7718
8307
  xtag: tag,
7719
8308
  value: value,
7720
8309
  offset: offset,
7721
- explanation: "There are some corrupt characters for the field ".concat(tag)
8310
+ explanation: "There are some corrupt characters for the field \"".concat(tag, "\"")
7722
8311
  };
7723
8312
  return err;
7724
8313
  }
7725
8314
  function getInvalidRawXMLValueException(_ref2) {
7726
- var tag = _ref2.tag, value = _ref2.value, offset = _ref2.offset;
8315
+ var tag = _ref2.tag, value = _ref2.value, offset = _ref2.offset, partDelims = _ref2.partDelims;
7727
8316
  var err = new XTRenderingError("Non string values are not allowed for rawXML tags");
7728
- err.properties = {
8317
+ /*
8318
+ * This error happens if you try to render a rawXml tag, such as : {@raw}
8319
+ * And the value of the data for "raw" is truthy but not a string.
8320
+ *
8321
+ * (If the value of the data is falsy, than the tag is simply dropped and
8322
+ * no error is thrown)
8323
+ */ err.properties = {
7729
8324
  id: "invalid_raw_xml_value",
7730
8325
  xtag: tag,
7731
8326
  value: value,
7732
8327
  offset: offset,
7733
- explanation: "The value of the raw tag : '".concat(tag, "' is not a string")
8328
+ explanation: "The value of the raw tag : \"".concat(partDelims, "\" is not a string")
7734
8329
  };
7735
8330
  return err;
7736
8331
  }
@@ -7741,7 +8336,10 @@ function requireErrors () {
7741
8336
  if (typeof explanation === "function") {
7742
8337
  explanation = explanation(part);
7743
8338
  }
7744
- var err = new XTTemplateError(message);
8339
+ /*
8340
+ * This error happens if you try to render a rawXml tag, such as : {@raw},
8341
+ * but that tag is not placed inside a paragraph.
8342
+ */ var err = new XTTemplateError(message);
7745
8343
  err.properties = {
7746
8344
  id: id,
7747
8345
  explanation: explanation,
@@ -7757,7 +8355,36 @@ function requireErrors () {
7757
8355
  function throwRawTagShouldBeOnlyTextInParagraph(options) {
7758
8356
  var err = new XTTemplateError("Raw tag should be the only text in paragraph");
7759
8357
  var tag = options.part.value;
7760
- err.properties = {
8358
+ /*
8359
+ * This happens when a rawXMLTag {@raw} is not the only text in the
8360
+ * paragraph. For example, writing ` {@raw}` (Note the spaces)
8361
+ * is not acceptable because the {@raw} tag replaces the full paragraph. We
8362
+ * prefer to throw an Error now rather than have "strange behavior"
8363
+ * because the spaces "disappeared".
8364
+ *
8365
+ * To correct this error, you have to add manually the text that you want
8366
+ * in your raw tag. (Or you can use the [docxtemplater word-run
8367
+ * module](/modules/word-run/) which adds a tag
8368
+ * that can replace rawXML inside a tag).
8369
+ *
8370
+ * Writing
8371
+ *
8372
+ * ```docx
8373
+ * {@my_first_tag}{my_second_tag}
8374
+ * ```
8375
+ *
8376
+ * Or even
8377
+ *
8378
+ * ```docx
8379
+ * Hello {@my_first_tag}
8380
+ * ```
8381
+ *
8382
+ * Is misusing docxtemplater.
8383
+ *
8384
+ * The `@` at the beginning means "replace the xml of **the
8385
+ * current paragraph** with scope.my_first_tag" so that means that
8386
+ * everything else in that Paragraph will be removed.
8387
+ */ err.properties = {
7761
8388
  id: "raw_xml_tag_should_be_only_text_in_paragraph",
7762
8389
  explanation: "The raw tag \"".concat(tag, "\" should be the only text in this paragraph. This means that this tag should not be surrounded by any text or spaces."),
7763
8390
  xtag: tag,
@@ -7766,13 +8393,23 @@ function requireErrors () {
7766
8393
  };
7767
8394
  throw err;
7768
8395
  }
7769
- function getUnmatchedLoopException(part) {
8396
+ /*
8397
+ * Loop / Table Structure Errors
8398
+ * =============================
8399
+ */ function getUnmatchedLoopException(part) {
7770
8400
  var location = part.location, offset = part.offset, square = part.square;
7771
8401
  var t = location === "start" ? "unclosed" : "unopened";
7772
8402
  var T = location === "start" ? "Unclosed" : "Unopened";
7773
8403
  var err = new XTTemplateError("".concat(T, " loop"));
7774
8404
  var tag = part.value;
7775
- err.properties = {
8405
+ /*
8406
+ * This error happens with following template :
8407
+ *
8408
+ * ```docx
8409
+ * {#users}
8410
+ * {/companies}
8411
+ * ```
8412
+ */ err.properties = {
7776
8413
  id: "".concat(t, "_loop"),
7777
8414
  explanation: "The loop with tag \"".concat(tag, "\" is ").concat(t),
7778
8415
  xtag: tag,
@@ -7789,7 +8426,25 @@ function requireErrors () {
7789
8426
  var lastR = lastPair[1].part.value;
7790
8427
  var l = pair[0].part.value;
7791
8428
  var r = pair[1].part.value;
7792
- err.properties = {
8429
+ /*
8430
+ * This error happens if you create a table and misplace tags inside the table :
8431
+ *
8432
+ * ```docx-md
8433
+ * | Head1 | Head2 |
8434
+ * | -------- | ------------ |
8435
+ * | {#a}X | {/a}{#b}Y{/b} |
8436
+ * ```
8437
+ *
8438
+ * In the case above, the {#a} and {/a} will expand to the whole loop, but this is not possible because of the other loop in {#b}Y{/b}
8439
+ *
8440
+ * Instead, you should usually write :
8441
+ *
8442
+ * ```docx-md
8443
+ * | Head1 | Head2 |
8444
+ * | -------- | ------------ |
8445
+ * | {#a}X | {#b}Y{/b}{/a} |
8446
+ * ```
8447
+ */ err.properties = {
7793
8448
  id: "unbalanced_loop_tags",
7794
8449
  explanation: "Unbalanced loop tags {#".concat(lastL, "}{/").concat(lastR, "}{#").concat(l, "}{/").concat(r, "}"),
7795
8450
  offset: [
@@ -7810,7 +8465,17 @@ function requireErrors () {
7810
8465
  function getClosingTagNotMatchOpeningTag(_ref3) {
7811
8466
  var tags = _ref3.tags;
7812
8467
  var err = new XTTemplateError("Closing tag does not match opening tag");
7813
- err.properties = {
8468
+ /*
8469
+ * This error happens if your loop tags are incorrectly closed
8470
+ *
8471
+ * ```docx
8472
+ * {#condition1}
8473
+ * Some text
8474
+ * {/otherCondition}
8475
+ * ```
8476
+ *
8477
+ * Since the start tag does not match the open tag, the template is invalid.
8478
+ */ err.properties = {
7814
8479
  id: "closing_tag_does_not_match_opening_tag",
7815
8480
  explanation: "The tag \"".concat(tags[0].value, "\" is closed by the tag \"").concat(tags[1].value, "\""),
7816
8481
  openingtag: first(tags).value,
@@ -7828,10 +8493,53 @@ function requireErrors () {
7828
8493
  }
7829
8494
  return err;
7830
8495
  }
7831
- function getScopeCompilationError(_ref4) {
7832
- var tag = _ref4.tag, rootError = _ref4.rootError, offset = _ref4.offset;
8496
+ function getLoopPositionProducesInvalidXMLError(_ref4) {
8497
+ var tag = _ref4.tag, offset = _ref4.offset;
8498
+ var err = new XTTemplateError("The position of the loop tags \"".concat(tag, "\" would produce invalid XML"));
8499
+ /*
8500
+ * This happens when a loop would produce invalid XML.
8501
+ *
8502
+ * For example, if you write:
8503
+ *
8504
+ * ```docx-md
8505
+ * | Head1 | Head2 |
8506
+ * | -------- | ------------ |
8507
+ * | {#users} | content |
8508
+ *
8509
+ * {/users}
8510
+ * ```
8511
+ *
8512
+ * this is not allowed since a loop that starts in a table must also end
8513
+ * in that table.
8514
+ */ err.properties = {
8515
+ xtag: tag,
8516
+ id: "loop_position_invalid",
8517
+ explanation: "The tags \"".concat(tag, "\" are misplaced in the document, for example one of them is in a table and the other one outside the table"),
8518
+ offset: offset
8519
+ };
8520
+ return err;
8521
+ }
8522
+ /*
8523
+ * Scope Parser Errors
8524
+ * ===================
8525
+ */ function getScopeCompilationError(_ref5) {
8526
+ var tag = _ref5.tag, rootError = _ref5.rootError, offset = _ref5.offset;
7833
8527
  var err = new XTScopeParserError("Scope parser compilation failed");
7834
- err.properties = {
8528
+ /*
8529
+ * This happens when your parser throws an error during compilation. The
8530
+ * parser is the second argument of the constructor
8531
+ * `new Docxtemplater(zip, {parser: function parser(tag) {}});`
8532
+ *
8533
+ * For example, if your template is:
8534
+ *
8535
+ * ```docx
8536
+ * {name++}
8537
+ * ```
8538
+ *
8539
+ * and you use the angular expression parser, you will have this error. The error
8540
+ * happens when you call parser('name++'); The underlying error can be
8541
+ * read in `e.properties.rootError`
8542
+ */ err.properties = {
7835
8543
  id: "scopeparser_compilation_failed",
7836
8544
  offset: offset,
7837
8545
  xtag: tag,
@@ -7840,12 +8548,47 @@ function requireErrors () {
7840
8548
  };
7841
8549
  return err;
7842
8550
  }
7843
- function getScopeParserExecutionError(_ref5) {
7844
- var tag = _ref5.tag, scope = _ref5.scope, error = _ref5.error, offset = _ref5.offset;
8551
+ function getScopeParserExecutionError(_ref6) {
8552
+ var tag = _ref6.tag, scope = _ref6.scope, error = _ref6.error, offset = _ref6.offset;
7845
8553
  var err = new XTScopeParserError("Scope parser execution failed");
7846
- err.properties = {
8554
+ /*
8555
+ * This happens when your parser throws an error during execution. The
8556
+ * parser is the second argument of the constructor
8557
+ * `new Docxtemplater(zip, {parser: function parser(tag) {}});`
8558
+ *
8559
+ * For example, if your template is:
8560
+ *
8561
+ * ```docx
8562
+ * {test | toFixed}
8563
+ * ```
8564
+ *
8565
+ * and your code is :
8566
+ *
8567
+ * ```js
8568
+ * const expressionParser = require("docxtemplater/expressions.js");
8569
+ * const doc = new Docxtemplater(zip, {
8570
+ * paragraphLoop: true,
8571
+ * linebreaks: true,
8572
+ * parser: expressionParser.configure({
8573
+ * filters: {
8574
+ * toFixed(input) {
8575
+ * return input.toFixed();
8576
+ * }
8577
+ * }
8578
+ * }),
8579
+ * });
8580
+ * doc.render({
8581
+ * test: false
8582
+ * });
8583
+ * ```
8584
+ *
8585
+ * Since false.toFixed() triggers an error in Javascript, this will then throw an error "Scope parser execution failed".
8586
+ *
8587
+ * You can either fix your data or make your toFixed function more robust
8588
+ * by returning "input" if the input is not a number.
8589
+ */ err.properties = {
7847
8590
  id: "scopeparser_execution_failed",
7848
- explanation: "The scope parser for the tag ".concat(tag, " failed to execute"),
8591
+ explanation: "The scope parser for the tag \"".concat(tag, "\" failed to execute"),
7849
8592
  scope: scope,
7850
8593
  offset: offset,
7851
8594
  xtag: tag,
@@ -7853,24 +8596,20 @@ function requireErrors () {
7853
8596
  };
7854
8597
  return err;
7855
8598
  }
7856
- function getLoopPositionProducesInvalidXMLError(_ref6) {
7857
- var tag = _ref6.tag, offset = _ref6.offset;
7858
- var err = new XTTemplateError("The position of the loop tags \"".concat(tag, "\" would produce invalid XML"));
7859
- err.properties = {
7860
- xtag: tag,
7861
- id: "loop_position_invalid",
7862
- explanation: "The tags \"".concat(tag, "\" are misplaced in the document, for example one of them is in a table and the other one outside the table"),
7863
- offset: offset
7864
- };
7865
- return err;
7866
- }
7867
- function throwUnimplementedTagType(part, index) {
8599
+ /*
8600
+ * Internal / API Misuse Errors
8601
+ * ============================
8602
+ */ function throwUnimplementedTagType(part, index) {
7868
8603
  var errorMsg = "Unimplemented tag type \"".concat(part.type, "\"");
7869
8604
  if (part.module) {
7870
8605
  errorMsg += " \"".concat(part.module, "\"");
7871
8606
  }
7872
8607
  var err = new XTTemplateError(errorMsg);
7873
- err.properties = {
8608
+ /*
8609
+ * This happens when a tag type is not implemented. It should normally not happen,
8610
+ * unless you changed docxtemplater code or created your own module and didn't
8611
+ * implement the `render` function of your module correctly.
8612
+ */ err.properties = {
7874
8613
  part: part,
7875
8614
  index: index,
7876
8615
  id: "unimplemented_tag_type"
@@ -7879,7 +8618,10 @@ function requireErrors () {
7879
8618
  }
7880
8619
  function throwMalformedXml() {
7881
8620
  var err = new XTInternalError("Malformed xml");
7882
- err.properties = {
8621
+ /*
8622
+ * This happens when an xml file of the document cannot be parsed
8623
+ * correctly.
8624
+ */ err.properties = {
7883
8625
  explanation: "The template contains malformed xml",
7884
8626
  id: "malformed_xml"
7885
8627
  };
@@ -7887,7 +8629,13 @@ function requireErrors () {
7887
8629
  }
7888
8630
  function throwResolveBeforeCompile() {
7889
8631
  var err = new XTInternalError("You must run `.compile()` before running `.resolveData()`");
7890
- err.properties = {
8632
+ /*
8633
+ * This happens if you're calling `resolveData()` before you run `.compile()`.
8634
+ *
8635
+ * You should always call `compile` first and then only `resolveData`
8636
+ *
8637
+ * Or you can migrate to [the constructor with two arguments](/docs/get-started-node/#usage)
8638
+ */ err.properties = {
7891
8639
  id: "resolve_before_compile",
7892
8640
  explanation: "You must run `.compile()` before running `.resolveData()`"
7893
8641
  };
@@ -7895,7 +8643,9 @@ function requireErrors () {
7895
8643
  }
7896
8644
  function throwRenderInvalidTemplate() {
7897
8645
  var err = new XTInternalError("You should not call .render on a document that had compilation errors");
7898
- err.properties = {
8646
+ /*
8647
+ * This happens if you're calling `render()` on a document that had template errors
8648
+ */ err.properties = {
7899
8649
  id: "render_on_invalid_template",
7900
8650
  explanation: "You should not call .render on a document that had compilation errors"
7901
8651
  };
@@ -7903,30 +8653,25 @@ function requireErrors () {
7903
8653
  }
7904
8654
  function throwRenderTwice() {
7905
8655
  var err = new XTInternalError("You should not call .render twice on the same docxtemplater instance");
7906
- err.properties = {
8656
+ /*
8657
+ * This happens if you're calling `render()` on a document twice.
8658
+ *
8659
+ * You should always create a new docxtemplater instance if you need to create two output documents.
8660
+ */ err.properties = {
7907
8661
  id: "render_twice",
7908
8662
  explanation: "You should not call .render twice on the same docxtemplater instance"
7909
8663
  };
7910
8664
  throw err;
7911
8665
  }
7912
- function throwFileTypeNotIdentified(zip) {
7913
- var files = Object.keys(zip.files).slice(0, 10);
7914
- var msg = "";
7915
- if (files.length === 0) {
7916
- msg = "Empty zip file";
7917
- } else {
7918
- msg = "Zip file contains : ".concat(files.join(","));
7919
- }
7920
- var err = new XTInternalError("The filetype for this file could not be identified, is this file corrupted ? ".concat(msg));
7921
- err.properties = {
7922
- id: "filetype_not_identified",
7923
- explanation: "The filetype for this file could not be identified, is this file corrupted ? ".concat(msg)
7924
- };
7925
- throw err;
7926
- }
7927
8666
  function throwXmlInvalid(content, offset) {
7928
8667
  var err = new XTTemplateError("An XML file has invalid xml");
7929
- err.properties = {
8668
+ /*
8669
+ * This error happens if the XML is invalid in your template file.
8670
+ *
8671
+ * This should be very rare except if you were using a tool to preprocess
8672
+ * the template (an XML error in a docx file means that the template file
8673
+ * is already corrupt).
8674
+ */ err.properties = {
7930
8675
  id: "file_has_invalid_xml",
7931
8676
  content: content,
7932
8677
  offset: offset,
@@ -7934,15 +8679,6 @@ function requireErrors () {
7934
8679
  };
7935
8680
  throw err;
7936
8681
  }
7937
- function throwFileTypeNotHandled(fileType) {
7938
- var err = new XTInternalError("The filetype \"".concat(fileType, "\" is not handled by docxtemplater"));
7939
- err.properties = {
7940
- id: "filetype_not_handled",
7941
- explanation: "The file you are trying to generate is of type \"".concat(fileType, "\", but only docx and pptx formats are handled"),
7942
- fileType: fileType
7943
- };
7944
- throw err;
7945
- }
7946
8682
  errors = {
7947
8683
  XTError: XTError,
7948
8684
  XTTemplateError: XTTemplateError,
@@ -8046,6 +8782,14 @@ function parser(tag) {
8046
8782
  }
8047
8783
  };
8048
8784
  }
8785
+ function defaultWarnFn(errors) {
8786
+ for(var _i2 = 0; _i2 < errors.length; _i2++){
8787
+ var error = errors[_i2];
8788
+ if (error.message) {
8789
+ /* eslint-disable-next-line no-console */ console.warn("Warning : " + error.message);
8790
+ }
8791
+ }
8792
+ }
8049
8793
  var attrToRegex = {};
8050
8794
  function setSingleAttribute(partValue, attr, attrValue) {
8051
8795
  var regex;
@@ -8107,8 +8851,8 @@ function chunkBy(parsed, f) {
8107
8851
  var chunks = [
8108
8852
  []
8109
8853
  ];
8110
- for(var _i2 = 0; _i2 < parsed.length; _i2++){
8111
- var p = parsed[_i2];
8854
+ for(var _i4 = 0; _i4 < parsed.length; _i4++){
8855
+ var p = parsed[_i4];
8112
8856
  var currentChunk = chunks[chunks.length - 1];
8113
8857
  var res = f(p);
8114
8858
  if (res === "start") {
@@ -8123,8 +8867,8 @@ function chunkBy(parsed, f) {
8123
8867
  }
8124
8868
  } // Remove empty chunks
8125
8869
  var result = [];
8126
- for(var _i4 = 0; _i4 < chunks.length; _i4++){
8127
- var chunk = chunks[_i4];
8870
+ for(var _i6 = 0; _i6 < chunks.length; _i6++){
8871
+ var chunk = chunks[_i6];
8128
8872
  if (chunk.length > 0) {
8129
8873
  result.push(chunk);
8130
8874
  }
@@ -8143,6 +8887,7 @@ function getDefaults() {
8143
8887
  "[Content_Types].xml"
8144
8888
  ],
8145
8889
  parser: parser,
8890
+ warnFn: defaultWarnFn,
8146
8891
  linebreaks: false,
8147
8892
  fileTypeConfig: null,
8148
8893
  delimiters: {
@@ -8150,7 +8895,11 @@ function getDefaults() {
8150
8895
  end: "}"
8151
8896
  },
8152
8897
  syntax: {
8153
- changeDelimiterPrefix: "="
8898
+ changeDelimiterPrefix: "=",
8899
+ preserveNewlinesInTags: false,
8900
+ allowUnopenedTag: false,
8901
+ allowUnclosedTag: false,
8902
+ allowUnbalancedLoops: false
8154
8903
  }
8155
8904
  };
8156
8905
  }
@@ -8220,10 +8969,10 @@ function utf8ToWord(string) {
8220
8969
  // This function is written with for loops for performance
8221
8970
  function concatArrays(arrays) {
8222
8971
  var result = [];
8223
- for(var _i6 = 0; _i6 < arrays.length; _i6++){
8224
- var array = arrays[_i6];
8225
- for(var _i8 = 0; _i8 < array.length; _i8++){
8226
- var el = array[_i8];
8972
+ for(var _i8 = 0; _i8 < arrays.length; _i8++){
8973
+ var array = arrays[_i8];
8974
+ for(var _i0 = 0; _i0 < array.length; _i0++){
8975
+ var el = array[_i0];
8227
8976
  result.push(el);
8228
8977
  }
8229
8978
  }
@@ -8298,8 +9047,8 @@ function getRightOrNull(parsed, elements, index) {
8298
9047
  var level = 1;
8299
9048
  for(var i = index, l = parsed.length; i < l; i++){
8300
9049
  var part = parsed[i];
8301
- for(var _i0 = 0, _elements2 = elements; _i0 < _elements2.length; _i0++){
8302
- var element = _elements2[_i0];
9050
+ for(var _i10 = 0, _elements2 = elements; _i10 < _elements2.length; _i10++){
9051
+ var element = _elements2[_i10];
8303
9052
  if (isEnding(part.value, element)) {
8304
9053
  level--;
8305
9054
  }
@@ -8334,8 +9083,8 @@ function getLeftOrNull(parsed, elements, index) {
8334
9083
  var level = 1;
8335
9084
  for(var i = index; i >= 0; i--){
8336
9085
  var part = parsed[i];
8337
- for(var _i10 = 0, _elements4 = elements; _i10 < _elements4.length; _i10++){
8338
- var element = _elements4[_i10];
9086
+ for(var _i12 = 0, _elements4 = elements; _i12 < _elements4.length; _i12++){
9087
+ var element = _elements4[_i12];
8339
9088
  if (isStarting(part.value, element)) {
8340
9089
  level--;
8341
9090
  }
@@ -8377,20 +9126,27 @@ function isParagraphEnd(_ref6) {
8377
9126
  "text:p"
8378
9127
  ].indexOf(tag) !== -1 && type === "tag" && position === "end";
8379
9128
  }
8380
- function isTextStart(_ref7) {
8381
- var type = _ref7.type, position = _ref7.position, text = _ref7.text;
8382
- return text && type === "tag" && position === "start";
9129
+ function isBreakTag(_ref7) {
9130
+ var type = _ref7.type, tag = _ref7.tag, position = _ref7.position;
9131
+ return [
9132
+ "w:br",
9133
+ "a:br"
9134
+ ].indexOf(tag) !== -1 && type === "tag" && (position === "start" || position === "selfclosing");
8383
9135
  }
8384
- function isTextEnd(_ref8) {
9136
+ function isTextStart(_ref8) {
8385
9137
  var type = _ref8.type, position = _ref8.position, text = _ref8.text;
9138
+ return text && type === "tag" && position === "start";
9139
+ }
9140
+ function isTextEnd(_ref9) {
9141
+ var type = _ref9.type, position = _ref9.position, text = _ref9.text;
8386
9142
  return text && type === "tag" && position === "end";
8387
9143
  }
8388
- function isContent(_ref9) {
8389
- var type = _ref9.type, position = _ref9.position;
9144
+ function isContent(_ref0) {
9145
+ var type = _ref0.type, position = _ref0.position;
8390
9146
  return type === "placeholder" || type === "content" && position === "insidetag";
8391
9147
  }
8392
- function isModule(_ref0, modules) {
8393
- var _$module = _ref0.module, type = _ref0.type;
9148
+ function isModule(_ref1, modules) {
9149
+ var _$module = _ref1.module, type = _ref1.type;
8394
9150
  if (!_instanceof$2(modules, Array)) {
8395
9151
  modules = [
8396
9152
  modules
@@ -8454,26 +9210,35 @@ function invertMap(map) {
8454
9210
  * is not stable in firefox, as the JS spec does not enforce the sort to be
8455
9211
  * stable.
8456
9212
  */ function stableSort(arr, compare) {
8457
- // Stryker disable all : in previous versions of Chrome, sort was not stable by itself, so we had to add this. This is to support older versions of JS runners.
8458
- return arr.map(function(item, index) {
8459
- return {
8460
- item: item,
8461
- index: index
8462
- };
8463
- }).sort(function(a, b) {
9213
+ // Stryker disable all
9214
+ var withIndex = [];
9215
+ for(var i = 0; i < arr.length; i++){
9216
+ withIndex.push({
9217
+ item: arr[i],
9218
+ index: i
9219
+ });
9220
+ }
9221
+ withIndex.sort(function(a, b) {
8464
9222
  return compare(a.item, b.item) || a.index - b.index;
8465
- }).map(function(_ref1) {
8466
- var item = _ref1.item;
8467
- return item;
8468
9223
  });
9224
+ var result = [];
9225
+ for(var _i13 = 0; _i13 < withIndex.length; _i13++){
9226
+ result.push(withIndex[_i13].item);
9227
+ }
9228
+ return result;
8469
9229
  // Stryker restore all
8470
9230
  }
9231
+ function getPartWithDelimiters(part, options) {
9232
+ return options.delimiters.start + part.raw + options.delimiters.end;
9233
+ }
8471
9234
  var docUtils = {
9235
+ getPartWithDelimiters: getPartWithDelimiters,
8472
9236
  endsWith: endsWith,
8473
9237
  startsWith: startsWith,
8474
9238
  isContent: isContent,
8475
9239
  isParagraphStart: isParagraphStart,
8476
9240
  isParagraphEnd: isParagraphEnd,
9241
+ isBreakTag: isBreakTag,
8477
9242
  isTagStart: isTagStart,
8478
9243
  isTagEnd: isTagEnd,
8479
9244
  isTextStart: isTextStart,
@@ -8915,20 +9680,18 @@ function requireGetContentTypes () {
8915
9680
  var partName = override.getAttribute("PartName").substr(1);
8916
9681
  partNames[partName] = contentType;
8917
9682
  }
8918
- var _loop = function _loop() {
8919
- var def = defaults[_i4];
8920
- var contentType = def.getAttribute("ContentType");
8921
- var extension = def.getAttribute("Extension");
8922
- zip.file(/./).map(function(_ref) {
8923
- var name = _ref.name;
9683
+ zip.file(/./).map(function(_ref) {
9684
+ var name = _ref.name;
9685
+ for(var _i4 = 0; _i4 < defaults.length; _i4++){
9686
+ var def = defaults[_i4];
9687
+ var _contentType = def.getAttribute("ContentType");
9688
+ var extension = def.getAttribute("Extension");
8924
9689
  if (name.slice(name.length - extension.length) === extension && !partNames[name] && name !== ctXML) {
8925
- partNames[name] = contentType;
9690
+ partNames[name] = _contentType;
8926
9691
  }
8927
- });
8928
- };
8929
- for(var _i4 = 0; _i4 < defaults.length; _i4++){
8930
- _loop();
8931
- }
9692
+ }
9693
+ partNames[name] || (partNames[name] = "");
9694
+ });
8932
9695
  return partNames;
8933
9696
  }
8934
9697
  function getContentTypes(zip) {
@@ -8963,24 +9726,24 @@ function requireModuleWrapper () {
8963
9726
  }
8964
9727
  moduleWrapper = function(module1) {
8965
9728
  var defaults = {
9729
+ on: emptyFun,
8966
9730
  set: emptyFun,
9731
+ getFileType: emptyFun,
9732
+ optionsTransformer: identity,
9733
+ preparse: identity,
8967
9734
  matchers: function matchers() {
8968
9735
  return [];
8969
9736
  },
8970
9737
  parse: emptyFun,
8971
- render: emptyFun,
8972
9738
  getTraits: emptyFun,
8973
- getFileType: emptyFun,
8974
- nullGetter: emptyFun,
8975
- optionsTransformer: identity,
8976
- postrender: identity,
8977
- errorsTransformer: identity,
8978
- getRenderedMap: identity,
8979
- preparse: identity,
8980
9739
  postparse: identity,
8981
- on: emptyFun,
9740
+ errorsTransformer: identity,
9741
+ preResolve: emptyFun,
8982
9742
  resolve: emptyFun,
8983
- preResolve: emptyFun
9743
+ getRenderedMap: identity,
9744
+ render: emptyFun,
9745
+ nullGetter: emptyFun,
9746
+ postrender: identity
8984
9747
  };
8985
9748
  if (Object.keys(defaults).every(function(key) {
8986
9749
  return !module1[key];
@@ -9244,25 +10007,7 @@ function requireTraits () {
9244
10007
  return false;
9245
10008
  }
9246
10009
  function getExpandToDefault(postparsed, pair, expandTags) {
9247
- var parts = postparsed.slice(pair[0].offset, pair[1].offset);
9248
- var xmlElements = getListXmlElements(parts);
9249
- var closingTagCount = xmlElements.filter(function(tag) {
9250
- return tag[1] === "/";
9251
- }).length;
9252
- var startingTagCount = xmlElements.filter(function(tag) {
9253
- return tag[1] !== "/" && tag[tag.length - 2] !== "/";
9254
- }).length;
9255
- if (closingTagCount !== startingTagCount) {
9256
- return {
9257
- error: getLoopPositionProducesInvalidXMLError({
9258
- tag: first(pair).part.value,
9259
- offset: [
9260
- first(pair).part.offset,
9261
- last(pair).part.offset
9262
- ]
9263
- })
9264
- };
9265
- }
10010
+ var xmlElements = getListXmlElements(postparsed.slice(pair[0].offset, pair[1].offset));
9266
10011
  var _loop = function _loop() {
9267
10012
  var _expandTags$_i = expandTags[_i6], contains = _expandTags$_i.contains, expand = _expandTags$_i.expand, onlyTextInTag = _expandTags$_i.onlyTextInTag;
9268
10013
  if (has(contains, xmlElements)) {
@@ -9272,7 +10017,8 @@ function requireTraits () {
9272
10017
  if (left === null || right === null) {
9273
10018
  return 0; // continue
9274
10019
  }
9275
- var chunks = chunkBy(postparsed.slice(left, right), function(p) {
10020
+ var subparsed = postparsed.slice(left, right);
10021
+ var chunks = chunkBy(subparsed, function(p) {
9276
10022
  return isTagStart(contains, p) ? "start" : isTagEnd(contains, p) ? "end" : null;
9277
10023
  });
9278
10024
  var firstChunk = first(chunks);
@@ -9283,6 +10029,33 @@ function requireTraits () {
9283
10029
  return 0; // continue
9284
10030
  }
9285
10031
  }
10032
+ var structured = getStructuredTagPositions(xmlElements);
10033
+ var openCount = 0;
10034
+ for(var _i8 = 0; _i8 < structured.length; _i8++){
10035
+ var _structured$_i = structured[_i8], tag = _structured$_i.tag, position = _structured$_i.position;
10036
+ if (tag === expand) {
10037
+ if (position === "start") {
10038
+ openCount++;
10039
+ }
10040
+ if (position === "end") {
10041
+ openCount--;
10042
+ }
10043
+ }
10044
+ }
10045
+ if (openCount !== 0) {
10046
+ // Tested by #regression-loop-with-field-and-nofield
10047
+ return {
10048
+ v: {
10049
+ error: getLoopPositionProducesInvalidXMLError({
10050
+ tag: first(pair).part.value,
10051
+ offset: [
10052
+ first(pair).part.offset,
10053
+ last(pair).part.offset
10054
+ ]
10055
+ })
10056
+ }
10057
+ };
10058
+ }
9286
10059
  return {
9287
10060
  v: {
9288
10061
  value: expand
@@ -9295,8 +10068,50 @@ function requireTraits () {
9295
10068
  if (_ret === 0) continue;
9296
10069
  if (_ret) return _ret.v;
9297
10070
  }
10071
+ if (!checkStartEnd(xmlElements)) {
10072
+ return {
10073
+ error: getLoopPositionProducesInvalidXMLError({
10074
+ tag: first(pair).part.value,
10075
+ offset: [
10076
+ first(pair).part.offset,
10077
+ last(pair).part.offset
10078
+ ]
10079
+ })
10080
+ };
10081
+ }
9298
10082
  return {};
9299
10083
  }
10084
+ function getStructuredTagPositions(xmlElements) {
10085
+ var result = [];
10086
+ for(var _i0 = 0; _i0 < xmlElements.length; _i0++){
10087
+ var el = xmlElements[_i0];
10088
+ var tag = getTagName(el);
10089
+ var position = /^\s*<\//.test(el) ? "end" : "start";
10090
+ result.push({
10091
+ tag: tag,
10092
+ position: position
10093
+ });
10094
+ }
10095
+ return result;
10096
+ }
10097
+ function getTagName(tag) {
10098
+ return tag.replace(/^\s*<\/?([a-zA-Z:]+).*/, "$1");
10099
+ }
10100
+ function checkStartEnd(xmlElements) {
10101
+ if (xmlElements.length % 2 === 1) {
10102
+ return false;
10103
+ }
10104
+ for(var i = 0, len = xmlElements.length / 2; i < len; i++){
10105
+ var start = xmlElements[i];
10106
+ var end = xmlElements[xmlElements.length - i - 1];
10107
+ var tagNameStart = getTagName(start);
10108
+ var tagNameEnd = getTagName(end);
10109
+ if (tagNameStart !== tagNameEnd) {
10110
+ return false;
10111
+ }
10112
+ }
10113
+ return true;
10114
+ }
9300
10115
  function getExpandLimit(part, index, postparsed, options) {
9301
10116
  var expandTo = part.expandTo || options.expandTo;
9302
10117
  // Stryker disable all : because this condition can be removed in v4 (the only usage was the image module before version 3.12.3 of the image module
@@ -9400,10 +10215,10 @@ function requireTraits () {
9400
10215
  });
9401
10216
  var maxRight = -1;
9402
10217
  var offset = 0;
9403
- for(var _i7 = 0, _len = limits.length; _i7 < _len; _i7++){
10218
+ for(var _i1 = 0, _len = limits.length; _i1 < _len; _i1++){
9404
10219
  var _postparsed;
9405
- var _limit2 = limits[_i7];
9406
- maxRight = Math.max(maxRight, _i7 > 0 ? limits[_i7 - 1].right : 0);
10220
+ var _limit2 = limits[_i1];
10221
+ maxRight = Math.max(maxRight, _i1 > 0 ? limits[_i1 - 1].right : 0);
9407
10222
  if (_limit2.left < maxRight) {
9408
10223
  continue;
9409
10224
  }
@@ -9643,7 +10458,7 @@ function requireCommon () {
9643
10458
  }
9644
10459
  }
9645
10460
  if (ftCandidate) {
9646
- return ftCandidate;
10461
+ continue;
9647
10462
  }
9648
10463
  }
9649
10464
  return ftCandidate;
@@ -9723,6 +10538,7 @@ function requireScopeManager () {
9723
10538
  function _getValue(tag, meta, num) {
9724
10539
  var _this = this;
9725
10540
  var scope = this.scopeList[num];
10541
+ var lastScope = this.scopeList[this.scopeList.length - 1];
9726
10542
  if (this.root.finishedResolving) {
9727
10543
  var w = this.resolved;
9728
10544
  var _loop = function _loop() {
@@ -9768,11 +10584,24 @@ function requireScopeManager () {
9768
10584
  if (result == null && num > 0) {
9769
10585
  return _getValue.call(this, tag, meta, num - 1);
9770
10586
  }
10587
+ if (typeof result === "function") {
10588
+ try {
10589
+ result = result(lastScope, this);
10590
+ } catch (error) {
10591
+ throw getScopeParserExecutionError({
10592
+ tag: tag,
10593
+ scope: scope,
10594
+ error: error,
10595
+ offset: meta.part.offset
10596
+ });
10597
+ }
10598
+ }
9771
10599
  return result;
9772
10600
  }
9773
10601
  function _getValueAsync(tag, meta, num) {
9774
10602
  var _this2 = this;
9775
10603
  var scope = this.scopeList[num];
10604
+ var lastScope = this.scopeList[this.scopeList.length - 1];
9776
10605
  // search in the scopes (in reverse order) and keep the first defined value
9777
10606
  var parser;
9778
10607
  if (!this.cachedParsers || !meta.part) {
@@ -9802,6 +10631,20 @@ function requireScopeManager () {
9802
10631
  return _getValueAsync.call(_this2, tag, meta, num - 1);
9803
10632
  }
9804
10633
  return result;
10634
+ }).then(function(result) {
10635
+ if (typeof result === "function") {
10636
+ try {
10637
+ result = result(lastScope, _this2);
10638
+ } catch (error) {
10639
+ throw getScopeParserExecutionError({
10640
+ tag: tag,
10641
+ scope: scope,
10642
+ error: error,
10643
+ offset: meta.part.offset
10644
+ });
10645
+ }
10646
+ }
10647
+ return result;
9805
10648
  });
9806
10649
  }
9807
10650
  var ScopeManager = /*#__PURE__*/ function() {
@@ -9871,22 +10714,13 @@ function requireScopeManager () {
9871
10714
  key: "getValue",
9872
10715
  value: function getValue(tag, meta) {
9873
10716
  var result = _getValue.call(this, tag, meta, this.scopeList.length - 1);
9874
- if (typeof result === "function") {
9875
- return result(this.scopeList[this.scopeList.length - 1], this);
9876
- }
9877
10717
  return result;
9878
10718
  }
9879
10719
  },
9880
10720
  {
9881
10721
  key: "getValueAsync",
9882
10722
  value: function getValueAsync(tag, meta) {
9883
- var _this3 = this;
9884
- return _getValueAsync.call(this, tag, meta, this.scopeList.length - 1).then(function(result) {
9885
- if (typeof result === "function") {
9886
- return result(_this3.scopeList[_this3.scopeList.length - 1], _this3);
9887
- }
9888
- return result;
9889
- });
10723
+ return _getValueAsync.call(this, tag, meta, this.scopeList.length - 1);
9890
10724
  }
9891
10725
  },
9892
10726
  {
@@ -10185,11 +11019,6 @@ function requireLexer () {
10185
11019
  xtag: wordToUtf8(xtag),
10186
11020
  offset: lastDelimiterOffset
10187
11021
  }));
10188
- lastDelimiterMatch = currDelimiterMatch;
10189
- delimiterAcc.push(_objectSpread(_objectSpread({}, currDelimiterMatch), {}, {
10190
- error: true
10191
- }));
10192
- return delimiterAcc;
10193
11022
  }
10194
11023
  delimiterAcc.pop();
10195
11024
  }
@@ -10232,9 +11061,8 @@ function requireLexer () {
10232
11061
  xtag: wordToUtf8(xtag),
10233
11062
  offset: lastDelimiterOffset
10234
11063
  }));
10235
- } else {
10236
- delimiterWithErrors.pop();
10237
11064
  }
11065
+ delimiterWithErrors.pop();
10238
11066
  }
10239
11067
  return {
10240
11068
  delimiterWithErrors: delimiterWithErrors,
@@ -10353,28 +11181,35 @@ function requireLexer () {
10353
11181
  }
10354
11182
  }
10355
11183
  function parseDelimiters(innerContentParts, delimiters, syntaxOptions) {
10356
- var full = innerContentParts.map(function(p) {
10357
- return p.value;
10358
- }).join("");
11184
+ var full = "";
11185
+ for(var _i6 = 0; _i6 < innerContentParts.length; _i6++){
11186
+ var p = innerContentParts[_i6];
11187
+ full += p.value;
11188
+ }
10359
11189
  var delimiterMatches = getAllDelimiterIndexes(full, delimiters, syntaxOptions);
10360
11190
  var offset = 0;
10361
- var ranges = innerContentParts.map(function(part) {
11191
+ var ranges = [];
11192
+ for(var _i8 = 0; _i8 < innerContentParts.length; _i8++){
11193
+ var part = innerContentParts[_i8];
10362
11194
  offset += part.value.length;
10363
- return {
11195
+ ranges.push({
10364
11196
  offset: offset - part.value.length,
10365
11197
  lIndex: part.lIndex
10366
- };
10367
- });
11198
+ });
11199
+ }
10368
11200
  var _getDelimiterErrors = getDelimiterErrors(delimiterMatches, full, syntaxOptions), delimiterWithErrors = _getDelimiterErrors.delimiterWithErrors, errors = _getDelimiterErrors.errors;
10369
11201
  var cutNext = 0;
10370
11202
  var delimiterIndex = 0;
10371
- var parsed = ranges.map(function(p, i) {
10372
- var offset = p.offset;
11203
+ var parsed = [];
11204
+ for(var i = 0; i < ranges.length; i++){
11205
+ var _p = ranges[i];
11206
+ var innerContentPart = innerContentParts[i];
11207
+ var _offset = _p.offset;
10373
11208
  var range = [
10374
- offset,
10375
- offset + innerContentParts[i].value.length
11209
+ _offset,
11210
+ _offset + innerContentPart.value.length
10376
11211
  ];
10377
- var partContent = innerContentParts[i].value;
11212
+ var partContent = innerContentPart.value;
10378
11213
  var delimitersInOffset = [];
10379
11214
  while(delimiterIndex < delimiterWithErrors.length && inRange(range, delimiterWithErrors[delimiterIndex])){
10380
11215
  delimitersInOffset.push(delimiterWithErrors[delimiterIndex]);
@@ -10386,9 +11221,9 @@ function requireLexer () {
10386
11221
  cursor = cutNext;
10387
11222
  cutNext = 0;
10388
11223
  }
10389
- for(var _i6 = 0; _i6 < delimitersInOffset.length; _i6++){
10390
- var delimiterInOffset = delimitersInOffset[_i6];
10391
- var _value = partContent.substr(cursor, delimiterInOffset.offset - offset - cursor);
11224
+ for(var _i0 = 0; _i0 < delimitersInOffset.length; _i0++){
11225
+ var delimiterInOffset = delimitersInOffset[_i0];
11226
+ var _value = partContent.substr(cursor, delimiterInOffset.offset - _offset - cursor);
10392
11227
  if (delimiterInOffset.changedelimiter) {
10393
11228
  if (delimiterInOffset.position === "start") {
10394
11229
  if (_value.length > 0) {
@@ -10398,7 +11233,7 @@ function requireLexer () {
10398
11233
  });
10399
11234
  }
10400
11235
  } else {
10401
- cursor = delimiterInOffset.offset - offset + delimiterInOffset.length;
11236
+ cursor = delimiterInOffset.offset - _offset + delimiterInOffset.length;
10402
11237
  }
10403
11238
  continue;
10404
11239
  }
@@ -10412,10 +11247,10 @@ function requireLexer () {
10412
11247
  var delimiterPart = {
10413
11248
  type: "delimiter",
10414
11249
  position: delimiterInOffset.position,
10415
- offset: cursor + offset
11250
+ offset: cursor + _offset
10416
11251
  };
10417
11252
  parts.push(delimiterPart);
10418
- cursor = delimiterInOffset.offset - offset + delimiterInOffset.length;
11253
+ cursor = delimiterInOffset.offset - _offset + delimiterInOffset.length;
10419
11254
  }
10420
11255
  cutNext = cursor - partContent.length;
10421
11256
  var value = partContent.substr(cursor);
@@ -10425,8 +11260,8 @@ function requireLexer () {
10425
11260
  value: value
10426
11261
  });
10427
11262
  }
10428
- return parts;
10429
- }, this);
11263
+ parsed.push(parts);
11264
+ }
10430
11265
  return {
10431
11266
  parsed: parsed,
10432
11267
  errors: errors
@@ -10442,8 +11277,8 @@ function requireLexer () {
10442
11277
  }
10443
11278
  function decodeContentParts(xmlparsed, fileType) {
10444
11279
  var inTextTag = false;
10445
- for(var _i8 = 0; _i8 < xmlparsed.length; _i8++){
10446
- var part = xmlparsed[_i8];
11280
+ for(var _i10 = 0; _i10 < xmlparsed.length; _i10++){
11281
+ var part = xmlparsed[_i10];
10447
11282
  inTextTag = updateInTextTag(part, inTextTag);
10448
11283
  if (part.type === "content") {
10449
11284
  part.position = inTextTag ? "insidetag" : "outsidetag";
@@ -10461,11 +11296,11 @@ function requireLexer () {
10461
11296
  var lexed = [];
10462
11297
  var index = 0;
10463
11298
  var lIndex = 0;
10464
- for(var _i0 = 0; _i0 < xmllexed.length; _i0++){
10465
- var part = xmllexed[_i0];
11299
+ for(var _i12 = 0; _i12 < xmllexed.length; _i12++){
11300
+ var part = xmllexed[_i12];
10466
11301
  if (isInsideContent(part)) {
10467
- for(var _i10 = 0, _delimiterParsed$inde2 = delimiterParsed[index]; _i10 < _delimiterParsed$inde2.length; _i10++){
10468
- var p = _delimiterParsed$inde2[_i10];
11302
+ for(var _i14 = 0, _delimiterParsed$inde2 = delimiterParsed[index]; _i14 < _delimiterParsed$inde2.length; _i14++){
11303
+ var p = _delimiterParsed$inde2[_i14];
10469
11304
  if (p.type === "content") {
10470
11305
  p.position = "insidetag";
10471
11306
  }
@@ -10487,8 +11322,8 @@ function requireLexer () {
10487
11322
  var matches = tagMatcher(content, xmltags.text, xmltags.other);
10488
11323
  var cursor = 0;
10489
11324
  var parsed = [];
10490
- for(var _i12 = 0; _i12 < matches.length; _i12++){
10491
- var match = matches[_i12];
11325
+ for(var _i16 = 0; _i16 < matches.length; _i16++){
11326
+ var match = matches[_i16];
10492
11327
  if (content.length > cursor && match.offset - cursor > 0) {
10493
11328
  parsed.push({
10494
11329
  type: "content",
@@ -10887,7 +11722,7 @@ function requireParser () {
10887
11722
  function _arrayWithHoles(r) {
10888
11723
  if (Array.isArray(r)) return r;
10889
11724
  }
10890
- var _require = docUtils, wordToUtf8 = _require.wordToUtf8, pushArray = _require.pushArray;
11725
+ var _require = docUtils, wordToUtf8 = _require.wordToUtf8, pushArray = _require.pushArray, isParagraphStart = _require.isParagraphStart, isBreakTag = _require.isBreakTag;
10891
11726
  var _require2 = requirePrefixMatcher(), match = _require2.match, getValue = _require2.getValue, getValues = _require2.getValues;
10892
11727
  function getMatchers(modules, options) {
10893
11728
  var allMatchers = [];
@@ -11022,6 +11857,9 @@ function requireParser () {
11022
11857
  return parsed;
11023
11858
  }
11024
11859
  if (token.type !== "content" || token.position !== "insidetag") {
11860
+ if (options.syntax.preserveNewlinesInTags && (isBreakTag(token) || isParagraphStart(token))) {
11861
+ placeHolderContent += "\n";
11862
+ }
11025
11863
  if (droppedTags.indexOf(token.tag) !== -1) {
11026
11864
  return parsed;
11027
11865
  }
@@ -11033,17 +11871,20 @@ function requireParser () {
11033
11871
  }, []);
11034
11872
  },
11035
11873
  postparse: function postparse(postparsed, modules, options) {
11036
- function getTraits(traitName, postparsed) {
11037
- return modules.map(function(module1) {
11038
- return module1.getTraits(traitName, postparsed);
11039
- });
11874
+ function getTraits(traitName, postparsed, options) {
11875
+ var result = [];
11876
+ for(var _i10 = 0; _i10 < modules.length; _i10++){
11877
+ var _module5 = modules[_i10];
11878
+ result.push(_module5.getTraits(traitName, postparsed, options));
11879
+ }
11880
+ return result;
11040
11881
  }
11041
11882
  var errors = [];
11042
11883
  function _postparse(postparsed, options) {
11043
11884
  var newPostparsed = postparsed;
11044
- for(var _i10 = 0; _i10 < modules.length; _i10++){
11045
- var _module5 = modules[_i10];
11046
- var postparseResult = _module5.postparse(newPostparsed, _objectSpread(_objectSpread({}, options), {}, {
11885
+ for(var _i12 = 0; _i12 < modules.length; _i12++){
11886
+ var _module6 = modules[_i12];
11887
+ var postparseResult = _module6.postparse(newPostparsed, _objectSpread(_objectSpread({}, options), {}, {
11047
11888
  postparse: function postparse(parsed, opts) {
11048
11889
  return _postparse(parsed, _objectSpread(_objectSpread({}, options), opts));
11049
11890
  },
@@ -11353,58 +12194,99 @@ function requireResolve () {
11353
12194
  }
11354
12195
  return false;
11355
12196
  }
12197
+ function resolvePart(part, resolved, errors, options) {
12198
+ var moduleResolved = moduleResolve(part, _objectSpread(_objectSpread({}, options), {}, {
12199
+ resolvedId: getResolvedId(part, options)
12200
+ }));
12201
+ if (moduleResolved) {
12202
+ return moduleResolved.then(function(value) {
12203
+ resolved.push({
12204
+ tag: part.value,
12205
+ lIndex: part.lIndex,
12206
+ value: value
12207
+ });
12208
+ })["catch"](function(e) {
12209
+ if (_instanceof(e, Array)) {
12210
+ pushArray(errors, e);
12211
+ } else {
12212
+ errors.push(e);
12213
+ }
12214
+ });
12215
+ }
12216
+ if (part.type === "placeholder") {
12217
+ return options.scopeManager.getValueAsync(part.value, {
12218
+ part: part
12219
+ }).then(function(value) {
12220
+ return value == null ? options.nullGetter(part) : value;
12221
+ }).then(function(value) {
12222
+ resolved.push({
12223
+ tag: part.value,
12224
+ lIndex: part.lIndex,
12225
+ value: value
12226
+ });
12227
+ })["catch"](function(e) {
12228
+ if (_instanceof(e, Array)) {
12229
+ pushArray(errors, e);
12230
+ } else {
12231
+ errors.push(e);
12232
+ }
12233
+ });
12234
+ }
12235
+ }
11356
12236
  function resolve(options) {
11357
12237
  var resolved = [];
12238
+ var errors = [];
11358
12239
  var baseNullGetter = options.baseNullGetter;
11359
- var compiled = options.compiled, scopeManager = options.scopeManager;
12240
+ var scopeManager = options.scopeManager;
11360
12241
  options.nullGetter = function(part, sm) {
11361
12242
  return baseNullGetter(part, sm || scopeManager);
11362
12243
  };
11363
12244
  options.resolved = resolved;
11364
- var errors = [];
11365
- return Promise.all(compiled.filter(function(part) {
11366
- return [
12245
+ var p = resolveSerial(options, errors, resolved);
12246
+ if (p) {
12247
+ return p.then(function() {
12248
+ return resolveParallel(options, errors, resolved);
12249
+ });
12250
+ }
12251
+ return resolveParallel(options, errors, resolved);
12252
+ }
12253
+ function resolveSerial(options, errors, resolved) {
12254
+ var p = null;
12255
+ var _loop = function _loop() {
12256
+ var part = _options$compiled2[_i4];
12257
+ if ([
11367
12258
  "content",
11368
12259
  "tag"
11369
- ].indexOf(part.type) === -1;
11370
- }).reduce(function(promises, part) {
11371
- var moduleResolved = moduleResolve(part, _objectSpread(_objectSpread({}, options), {}, {
11372
- resolvedId: getResolvedId(part, options)
11373
- }));
11374
- var result;
11375
- if (moduleResolved) {
11376
- result = moduleResolved.then(function(value) {
11377
- resolved.push({
11378
- tag: part.value,
11379
- lIndex: part.lIndex,
11380
- value: value
11381
- });
11382
- });
11383
- } else if (part.type === "placeholder") {
11384
- result = scopeManager.getValueAsync(part.value, {
11385
- part: part
11386
- }).then(function(value) {
11387
- return value == null ? options.nullGetter(part) : value;
11388
- }).then(function(value) {
11389
- resolved.push({
11390
- tag: part.value,
11391
- lIndex: part.lIndex,
11392
- value: value
11393
- });
11394
- return value;
12260
+ ].indexOf(part.type) !== -1) {
12261
+ return 1; // continue
12262
+ }
12263
+ if (part.resolveFirst) {
12264
+ p !== null && p !== void 0 ? p : p = Promise.resolve(null);
12265
+ p = p.then(function() {
12266
+ return resolvePart(part, resolved, errors, options);
11395
12267
  });
11396
- } else {
11397
- return;
11398
12268
  }
11399
- promises.push(result["catch"](function(e) {
11400
- if (_instanceof(e, Array)) {
11401
- pushArray(errors, e);
11402
- } else {
11403
- errors.push(e);
11404
- }
11405
- }));
11406
- return promises;
11407
- }, [])).then(function() {
12269
+ };
12270
+ for(var _i4 = 0, _options$compiled2 = options.compiled; _i4 < _options$compiled2.length; _i4++){
12271
+ if (_loop()) continue;
12272
+ }
12273
+ return p;
12274
+ }
12275
+ function resolveParallel(options, errors, resolved) {
12276
+ var promises = [];
12277
+ for(var _i6 = 0, _options$compiled4 = options.compiled; _i6 < _options$compiled4.length; _i6++){
12278
+ var part = _options$compiled4[_i6];
12279
+ if ([
12280
+ "content",
12281
+ "tag"
12282
+ ].indexOf(part.type) !== -1) {
12283
+ continue;
12284
+ }
12285
+ if (!part.resolveFirst) {
12286
+ promises.push(resolvePart(part, resolved, errors, options));
12287
+ }
12288
+ }
12289
+ return Promise.all(promises).then(function() {
11408
12290
  return {
11409
12291
  errors: errors,
11410
12292
  resolved: resolved
@@ -11579,9 +12461,11 @@ function requireXmlTemplater () {
11579
12461
  var joinUncorrupt = requireJoinUncorrupt();
11580
12462
  function _getFullText(content, tagsXmlArray) {
11581
12463
  var matcher = xmlMatcher(content, tagsXmlArray);
11582
- var result = matcher.matches.map(function(match) {
11583
- return match.array[2];
11584
- });
12464
+ var result = [];
12465
+ for(var _i2 = 0, _matcher$matches2 = matcher.matches; _i2 < _matcher$matches2.length; _i2++){
12466
+ var match = _matcher$matches2[_i2];
12467
+ result.push(match.array[2]);
12468
+ }
11585
12469
  return wordToUtf8(convertSpaces(result.join("")));
11586
12470
  }
11587
12471
  xmlTemplater = /*#__PURE__*/ function() {
@@ -11609,18 +12493,22 @@ function requireXmlTemplater () {
11609
12493
  options.scopeManager = this.scopeManager;
11610
12494
  options.resolve = resolve;
11611
12495
  var errors = [];
11612
- return Promise.all(this.modules.map(function(module1) {
11613
- return Promise.resolve(module1.preResolve(options))["catch"](function(e) {
12496
+ var promises = [];
12497
+ for(var _i4 = 0, _this$modules2 = this.modules; _i4 < _this$modules2.length; _i4++){
12498
+ var _module = _this$modules2[_i4];
12499
+ promises.push(Promise.resolve(_module.preResolve(options))["catch"](function(e) {
11614
12500
  errors.push(e);
11615
- });
11616
- })).then(function() {
12501
+ }));
12502
+ }
12503
+ return Promise.all(promises).then(function() {
11617
12504
  if (errors.length !== 0) {
11618
12505
  throw errors;
11619
12506
  }
11620
12507
  return resolve(options).then(function(_ref) {
11621
12508
  var resolved = _ref.resolved, errors = _ref.errors;
11622
- errors = errors.map(function(error) {
12509
+ for(var i = 0; i < errors.length; i++){
11623
12510
  var _error;
12511
+ var error = errors[i];
11624
12512
  // If a string is thrown, convert it to a real Error
11625
12513
  if (!_instanceof(error, Error)) {
11626
12514
  error = new Error(error);
@@ -11631,8 +12519,8 @@ function requireXmlTemplater () {
11631
12519
  * thrown.
11632
12520
  */ (_error = error).properties || (_error.properties = {});
11633
12521
  error.properties.file = filePath;
11634
- return error;
11635
- });
12522
+ errors[i] = error;
12523
+ }
11636
12524
  if (errors.length !== 0) {
11637
12525
  throw errors;
11638
12526
  }
@@ -11663,9 +12551,9 @@ function requireXmlTemplater () {
11663
12551
  {
11664
12552
  key: "setModules",
11665
12553
  value: function setModules(obj) {
11666
- for(var _i2 = 0, _this$modules2 = this.modules; _i2 < _this$modules2.length; _i2++){
11667
- var _module = _this$modules2[_i2];
11668
- _module.set(obj);
12554
+ for(var _i6 = 0, _this$modules4 = this.modules; _i6 < _this$modules4.length; _i6++){
12555
+ var _module2 = _this$modules4[_i6];
12556
+ _module2.set(obj);
11669
12557
  }
11670
12558
  }
11671
12559
  },
@@ -11740,8 +12628,8 @@ function requireXmlTemplater () {
11740
12628
  {
11741
12629
  key: "errorChecker",
11742
12630
  value: function errorChecker(errors) {
11743
- for(var _i4 = 0, _errors2 = errors; _i4 < _errors2.length; _i4++){
11744
- var error = _errors2[_i4];
12631
+ for(var _i8 = 0, _errors2 = errors; _i8 < _errors2.length; _i8++){
12632
+ var error = _errors2[_i8];
11745
12633
  /*
11746
12634
  * error properties might not be defined if some foreign
11747
12635
  * (unhandled error not thrown by docxtemplater willingly) is
@@ -11749,9 +12637,9 @@ function requireXmlTemplater () {
11749
12637
  */ error.properties || (error.properties = {});
11750
12638
  error.properties.file = this.filePath;
11751
12639
  }
11752
- for(var _i6 = 0, _this$modules4 = this.modules; _i6 < _this$modules4.length; _i6++){
11753
- var _module2 = _this$modules4[_i6];
11754
- errors = _module2.errorsTransformer(errors);
12640
+ for(var _i0 = 0, _this$modules6 = this.modules; _i0 < _this$modules6.length; _i0++){
12641
+ var _module3 = _this$modules6[_i0];
12642
+ errors = _module3.errorsTransformer(errors);
11755
12643
  }
11756
12644
  }
11757
12645
  },
@@ -11759,12 +12647,12 @@ function requireXmlTemplater () {
11759
12647
  key: "baseNullGetter",
11760
12648
  value: function baseNullGetter(part, sm) {
11761
12649
  var value = null;
11762
- for(var _i8 = 0, _this$modules6 = this.modules; _i8 < _this$modules6.length; _i8++){
11763
- var _module3 = _this$modules6[_i8];
12650
+ for(var _i10 = 0, _this$modules8 = this.modules; _i10 < _this$modules8.length; _i10++){
12651
+ var _module4 = _this$modules8[_i10];
11764
12652
  if (value != null) {
11765
12653
  continue;
11766
12654
  }
11767
- value = _module3.nullGetter(part, sm, this);
12655
+ value = _module4.nullGetter(part, sm, this);
11768
12656
  }
11769
12657
  if (value != null) {
11770
12658
  return value;
@@ -11785,6 +12673,7 @@ function requireXmlTemplater () {
11785
12673
  relsType: this.relsType,
11786
12674
  baseNullGetter: this.baseNullGetter.bind(this),
11787
12675
  filePath: this.filePath,
12676
+ syntax: this.syntax,
11788
12677
  fileTypeConfig: this.fileTypeConfig,
11789
12678
  fileType: this.fileType,
11790
12679
  linebreaks: this.linebreaks,
@@ -11942,15 +12831,20 @@ function requireLoop () {
11942
12831
  var _require = docUtils, chunkBy = _require.chunkBy, last = _require.last, isParagraphStart = _require.isParagraphStart, isModule = _require.isModule, pushArray = _require.pushArray, isParagraphEnd = _require.isParagraphEnd, isContent = _require.isContent, startsWith = _require.startsWith, isTagEnd = _require.isTagEnd, isTagStart = _require.isTagStart, getSingleAttribute = _require.getSingleAttribute, setSingleAttribute = _require.setSingleAttribute;
11943
12832
  var filetypes = requireFiletypes();
11944
12833
  var wrapper = requireModuleWrapper();
12834
+ var _require2 = docUtils, isWhiteSpace = _require2.isWhiteSpace;
11945
12835
  var moduleName = "loop";
11946
12836
  function hasContent(parts) {
11947
- return parts.some(function(part) {
11948
- return isContent(part);
11949
- });
12837
+ for(var _i2 = 0; _i2 < parts.length; _i2++){
12838
+ var part = parts[_i2];
12839
+ if (isContent(part)) {
12840
+ return true;
12841
+ }
12842
+ }
12843
+ return false;
11950
12844
  }
11951
12845
  function getFirstMeaningFulPart(parsed) {
11952
- for(var _i2 = 0; _i2 < parsed.length; _i2++){
11953
- var part = parsed[_i2];
12846
+ for(var _i4 = 0; _i4 < parsed.length; _i4++){
12847
+ var part = parsed[_i4];
11954
12848
  if (part.type !== "content") {
11955
12849
  return part;
11956
12850
  }
@@ -11982,74 +12876,94 @@ function requireLoop () {
11982
12876
  subRendered.parts.unshift('<w:p><w:r><w:br w:type="page"/></w:r></w:p>');
11983
12877
  }
11984
12878
  function isContinuous(parts) {
11985
- return parts.some(function(part) {
11986
- return isTagStart("w:type", part) && part.value.indexOf("continuous") !== -1;
11987
- });
12879
+ for(var _i6 = 0; _i6 < parts.length; _i6++){
12880
+ var part = parts[_i6];
12881
+ if (isTagStart("w:type", part) && part.value.indexOf("continuous") !== -1) {
12882
+ return true;
12883
+ }
12884
+ }
12885
+ return false;
11988
12886
  }
11989
12887
  function isNextPage(parts) {
11990
- return parts.some(function(part) {
11991
- return isTagStart("w:type", part) && part.value.indexOf('w:val="nextPage"') !== -1;
11992
- });
12888
+ for(var _i8 = 0; _i8 < parts.length; _i8++){
12889
+ var part = parts[_i8];
12890
+ if (isTagStart("w:type", part) && part.value.indexOf('w:val="nextPage"') !== -1) {
12891
+ return true;
12892
+ }
12893
+ }
12894
+ return false;
11993
12895
  }
11994
12896
  function addSectionBefore(parts, sect) {
11995
- return pushArray([
11996
- "<w:p><w:pPr>".concat(sect.map(function(_ref) {
11997
- var value = _ref.value;
11998
- return value;
11999
- }).join(""), "</w:pPr></w:p>")
12000
- ], parts);
12897
+ var result = "";
12898
+ for(var _i0 = 0; _i0 < sect.length; _i0++){
12899
+ var value = sect[_i0].value;
12900
+ result += value;
12901
+ }
12902
+ parts.unshift("<w:p><w:pPr>".concat(result, "</w:pPr></w:p>"));
12001
12903
  }
12002
12904
  function addContinuousType(parts) {
12003
12905
  var stop = false;
12004
12906
  var inSectPr = false;
12005
- var result = [];
12006
- for(var _i4 = 0; _i4 < parts.length; _i4++){
12007
- var part = parts[_i4];
12008
- if (stop === false && startsWith(part, "<w:sectPr")) {
12907
+ for(var i = 0; i < parts.length; i++){
12908
+ var part = parts[i];
12909
+ if (!stop && startsWith(part, "<w:sectPr")) {
12009
12910
  inSectPr = true;
12010
12911
  }
12011
12912
  if (inSectPr) {
12012
12913
  if (startsWith(part, "<w:type")) {
12013
12914
  stop = true;
12014
12915
  }
12015
- if (stop === false && startsWith(part, "</w:sectPr")) {
12016
- result.push('<w:type w:val="continuous"/>');
12916
+ if (!stop && startsWith(part, "</w:sectPr")) {
12917
+ parts.splice(i, 0, '<w:type w:val="continuous"/>');
12918
+ i++; // Skip re-processing the now-shifted closing tag to avoid infinite insertion
12017
12919
  }
12018
12920
  }
12019
- result.push(part);
12020
12921
  }
12021
- return result;
12922
+ return parts;
12022
12923
  }
12023
12924
  function dropHeaderFooterRefs(parts) {
12024
- return parts.filter(function(text) {
12025
- return !startsWith(text, "<w:headerReference") && !startsWith(text, "<w:footerReference");
12026
- });
12925
+ var writeIndex = 0;
12926
+ for(var readIndex = 0; readIndex < parts.length; readIndex++){
12927
+ if (!startsWith(parts[readIndex], "<w:headerReference") && !startsWith(parts[readIndex], "<w:footerReference")) {
12928
+ parts[writeIndex] = parts[readIndex];
12929
+ writeIndex++;
12930
+ }
12931
+ }
12932
+ parts.length = writeIndex;
12933
+ return parts;
12027
12934
  }
12028
12935
  function hasPageBreak(chunk) {
12029
- return chunk.some(function(part) {
12030
- return part.tag === "w:br" && part.value.indexOf('w:type="page"') !== -1;
12031
- });
12936
+ for(var _i10 = 0; _i10 < chunk.length; _i10++){
12937
+ var part = chunk[_i10];
12938
+ if (part.tag === "w:br" && part.value.indexOf('w:type="page"') !== -1) {
12939
+ return true;
12940
+ }
12941
+ }
12942
+ return false;
12032
12943
  }
12033
12944
  function hasImage(chunk) {
12034
- return chunk.some(function(_ref2) {
12035
- var tag = _ref2.tag;
12036
- return tag === "w:drawing";
12037
- });
12945
+ for(var _i12 = 0; _i12 < chunk.length; _i12++){
12946
+ var el = chunk[_i12];
12947
+ if (el.tag === "w:drawing") {
12948
+ return true;
12949
+ }
12950
+ }
12951
+ return false;
12038
12952
  }
12039
12953
  function getSectPr(chunks) {
12040
- var collectSectPr = false;
12041
12954
  var sectPrs = [];
12042
- for(var _i6 = 0; _i6 < chunks.length; _i6++){
12043
- var part = chunks[_i6];
12955
+ var currentSectPr = null;
12956
+ for(var _i14 = 0; _i14 < chunks.length; _i14++){
12957
+ var part = chunks[_i14];
12044
12958
  if (isTagStart("w:sectPr", part)) {
12045
- sectPrs.push([]);
12046
- collectSectPr = true;
12959
+ currentSectPr = [];
12960
+ sectPrs.push(currentSectPr);
12047
12961
  }
12048
- if (collectSectPr) {
12049
- sectPrs[sectPrs.length - 1].push(part);
12962
+ if (currentSectPr !== null) {
12963
+ currentSectPr.push(part);
12050
12964
  }
12051
12965
  if (isTagEnd("w:sectPr", part)) {
12052
- collectSectPr = false;
12966
+ currentSectPr = null;
12053
12967
  }
12054
12968
  }
12055
12969
  return sectPrs;
@@ -12057,8 +12971,8 @@ function requireLoop () {
12057
12971
  function getSectPrHeaderFooterChangeCount(chunks) {
12058
12972
  var collectSectPr = false;
12059
12973
  var sectPrCount = 0;
12060
- for(var _i8 = 0; _i8 < chunks.length; _i8++){
12061
- var part = chunks[_i8];
12974
+ for(var _i16 = 0; _i16 < chunks.length; _i16++){
12975
+ var part = chunks[_i16];
12062
12976
  if (isTagStart("w:sectPr", part)) {
12063
12977
  collectSectPr = true;
12064
12978
  }
@@ -12079,7 +12993,11 @@ function requireLoop () {
12079
12993
  var inSectPr = false;
12080
12994
  for(var i = parsed.length - 1; i >= 0; i--){
12081
12995
  var part = parsed[i];
12082
- if (isTagEnd("w:sectPr", part)) {
12996
+ /*
12997
+ * Since we try to get the last sectPr, we traverse the parsed array
12998
+ * from the end to beginning, this is why inSectPr becomes true when we
12999
+ * we see a </w:sectPr> closing tag
13000
+ */ if (isTagEnd("w:sectPr", part)) {
12083
13001
  inSectPr = true;
12084
13002
  }
12085
13003
  if (isTagStart("w:sectPr", part)) {
@@ -12121,8 +13039,8 @@ function requireLoop () {
12121
13039
  },
12122
13040
  {
12123
13041
  key: "preparse",
12124
- value: function preparse(parsed, _ref3) {
12125
- var contentType = _ref3.contentType;
13042
+ value: function preparse(parsed, _ref) {
13043
+ var contentType = _ref.contentType;
12126
13044
  if (filetypes.main.indexOf(contentType) !== -1) {
12127
13045
  this.sects = getSectPr(parsed);
12128
13046
  }
@@ -12161,8 +13079,8 @@ function requireLoop () {
12161
13079
  [
12162
13080
  this.prefix.dash,
12163
13081
  _$module,
12164
- function(_ref4) {
12165
- var _ref5 = _slicedToArray(_ref4, 3), expandTo = _ref5[1], value = _ref5[2];
13082
+ function(_ref2) {
13083
+ var _ref3 = _slicedToArray(_ref2, 3), expandTo = _ref3[1], value = _ref3[2];
12166
13084
  return {
12167
13085
  location: "start",
12168
13086
  inverted: false,
@@ -12197,18 +13115,19 @@ function requireLoop () {
12197
13115
  },
12198
13116
  {
12199
13117
  key: "postparse",
12200
- value: function postparse(parsed, _ref6) {
12201
- var basePart = _ref6.basePart;
13118
+ value: function postparse(parsed, _ref4) {
13119
+ var basePart = _ref4.basePart;
12202
13120
  if (basePart && this.docxtemplater.fileType === "docx" && parsed.length > 0) {
12203
13121
  basePart.sectPrCount = getSectPrHeaderFooterChangeCount(parsed);
12204
13122
  this.totalSectPr += basePart.sectPrCount;
12205
13123
  var sects = this.sects;
12206
- sects.some(function(sect, index) {
13124
+ for(var index = 0, len = sects.length; index < len; index++){
13125
+ var sect = sects[index];
12207
13126
  if (basePart.lIndex < sect[0].lIndex) {
12208
13127
  if (index + 1 < sects.length && isContinuous(sects[index + 1])) {
12209
13128
  basePart.addContinuousType = true;
12210
13129
  }
12211
- return true;
13130
+ break;
12212
13131
  }
12213
13132
  if (parsed[0].lIndex < sect[0].lIndex && sect[0].lIndex < basePart.lIndex) {
12214
13133
  if (isNextPage(sects[index])) {
@@ -12216,9 +13135,9 @@ function requireLoop () {
12216
13135
  index: index
12217
13136
  };
12218
13137
  }
12219
- return true;
13138
+ break;
12220
13139
  }
12221
- });
13140
+ }
12222
13141
  basePart.lastParagrapSectPr = getLastSectPr(parsed);
12223
13142
  }
12224
13143
  if (!basePart || basePart.expandTo !== "auto" || basePart.module !== moduleName || !isEnclosedByParagraphs(parsed)) {
@@ -12245,6 +13164,12 @@ function requireLoop () {
12245
13164
  var lastChunk = last(chunks);
12246
13165
  var firstOffset = getOffset(firstChunk);
12247
13166
  var lastOffset = getOffset(lastChunk);
13167
+ if (firstOffset > 0 && chunks[1][0].type === "content" && isWhiteSpace(chunks[1][0].value)) {
13168
+ firstOffset += 1;
13169
+ }
13170
+ if (lastOffset > 0 && last(chunks[chunks.length - 2]).type === "content" && isWhiteSpace(last(chunks[chunks.length - 2]).value)) {
13171
+ lastOffset += 1;
13172
+ }
12248
13173
  basePart.hasPageBreakBeginning = hasPageBreak(firstChunk);
12249
13174
  basePart.hasPageBreak = hasPageBreak(lastChunk);
12250
13175
  if (hasImage(firstChunk)) {
@@ -12259,6 +13184,7 @@ function requireLoop () {
12259
13184
  {
12260
13185
  key: "resolve",
12261
13186
  value: function resolve(part, options) {
13187
+ var self = this;
12262
13188
  if (!isModule(part, moduleName)) {
12263
13189
  return null;
12264
13190
  }
@@ -12267,46 +13193,59 @@ function requireLoop () {
12267
13193
  part: part
12268
13194
  });
12269
13195
  var promises = [];
13196
+ var lastPromise;
13197
+ if (self.resolveSerially) {
13198
+ lastPromise = Promise.resolve(null);
13199
+ }
12270
13200
  function loopOver(scope, i, length) {
12271
13201
  var scopeManager = sm.createSubScopeManager(scope, part.value, i, part, length);
12272
- promises.push(options.resolve(_objectSpread(_objectSpread({}, options), {}, {
12273
- compiled: part.subparsed,
12274
- tags: {},
12275
- scopeManager: scopeManager
12276
- })));
13202
+ if (self.resolveSerially) {
13203
+ lastPromise = lastPromise.then(function() {
13204
+ return options.resolve(_objectSpread(_objectSpread({}, options), {}, {
13205
+ compiled: part.subparsed,
13206
+ tags: {},
13207
+ scopeManager: scopeManager
13208
+ }));
13209
+ });
13210
+ promises.push(lastPromise);
13211
+ } else {
13212
+ promises.push(options.resolve(_objectSpread(_objectSpread({}, options), {}, {
13213
+ compiled: part.subparsed,
13214
+ tags: {},
13215
+ scopeManager: scopeManager
13216
+ })));
13217
+ }
12277
13218
  }
12278
13219
  var errorList = [];
12279
13220
  return promisedValue.then(function(values) {
12280
13221
  values !== null && values !== void 0 ? values : values = options.nullGetter(part);
12281
- return new Promise(function(resolve) {
12282
- if (_instanceof(values, Promise)) {
12283
- return values.then(function(values) {
12284
- if (_instanceof(values, Array)) {
12285
- Promise.all(values).then(resolve);
12286
- } else {
12287
- resolve(values);
12288
- }
12289
- });
12290
- }
12291
- if (_instanceof(values, Array)) {
12292
- Promise.all(values).then(resolve);
12293
- } else {
12294
- resolve(values);
12295
- }
12296
- }).then(function(values) {
12297
- sm.loopOverValue(values, loopOver, part.inverted);
12298
- return Promise.all(promises).then(function(r) {
12299
- return r.map(function(_ref7) {
12300
- var resolved = _ref7.resolved, errors = _ref7.errors;
12301
- pushArray(errorList, errors);
12302
- return resolved;
12303
- });
12304
- }).then(function(value) {
12305
- if (errorList.length > 0) {
12306
- throw errorList;
13222
+ if (_instanceof(values, Promise)) {
13223
+ return values.then(function(values) {
13224
+ if (_instanceof(values, Array)) {
13225
+ return Promise.all(values);
12307
13226
  }
12308
- return value;
13227
+ return values;
12309
13228
  });
13229
+ }
13230
+ if (_instanceof(values, Array)) {
13231
+ return Promise.all(values);
13232
+ }
13233
+ return values;
13234
+ }).then(function(values) {
13235
+ sm.loopOverValue(values, loopOver, part.inverted);
13236
+ return Promise.all(promises).then(function(r) {
13237
+ var result = [];
13238
+ for(var _i18 = 0; _i18 < r.length; _i18++){
13239
+ var _r$_i = r[_i18], resolved = _r$_i.resolved, errors = _r$_i.errors;
13240
+ pushArray(errorList, errors);
13241
+ result.push(resolved);
13242
+ }
13243
+ return result;
13244
+ }).then(function(value) {
13245
+ if (errorList.length > 0) {
13246
+ throw errorList;
13247
+ }
13248
+ return value;
12310
13249
  });
12311
13250
  });
12312
13251
  }
@@ -12314,11 +13253,12 @@ function requireLoop () {
12314
13253
  {
12315
13254
  key: "render",
12316
13255
  value: function render(part, options) {
13256
+ var self = this;
12317
13257
  if (part.tag === "p:xfrm") {
12318
- this.inXfrm = part.position === "start";
13258
+ self.inXfrm = part.position === "start";
12319
13259
  }
12320
- if (part.tag === "a:ext" && this.inXfrm) {
12321
- this.lastExt = part;
13260
+ if (part.tag === "a:ext" && self.inXfrm) {
13261
+ self.lastExt = part;
12322
13262
  return part;
12323
13263
  }
12324
13264
  if (!isModule(part, moduleName)) {
@@ -12327,7 +13267,6 @@ function requireLoop () {
12327
13267
  var totalValue = [];
12328
13268
  var errors = [];
12329
13269
  var heightOffset = 0;
12330
- var self = this;
12331
13270
  var firstTag = part.subparsed[0];
12332
13271
  var tagHeight = 0;
12333
13272
  if ((firstTag === null || firstTag === void 0 ? void 0 : firstTag.tag) === "a:tr") {
@@ -12339,8 +13278,8 @@ function requireLoop () {
12339
13278
  function loopOver(scope, i, length) {
12340
13279
  heightOffset += tagHeight;
12341
13280
  var scopeManager = options.scopeManager.createSubScopeManager(scope, part.value, i, part, length);
12342
- for(var _i0 = 0, _part$subparsed2 = part.subparsed; _i0 < _part$subparsed2.length; _i0++){
12343
- var pp = _part$subparsed2[_i0];
13281
+ for(var _i20 = 0, _part$subparsed2 = part.subparsed; _i20 < _part$subparsed2.length; _i20++){
13282
+ var pp = _part$subparsed2[_i20];
12344
13283
  if (isTagStart("a16:rowId", pp)) {
12345
13284
  var val = +getSingleAttribute(pp.value, "val") + a16RowIdOffset;
12346
13285
  a16RowIdOffset = 1;
@@ -12366,7 +13305,7 @@ function requireLoop () {
12366
13305
  subRendered.parts = addContinuousType(subRendered.parts);
12367
13306
  }
12368
13307
  } else if (part.addNextPage) {
12369
- subRendered.parts = addSectionBefore(subRendered.parts, self.sects[part.addNextPage.index]);
13308
+ addSectionBefore(subRendered.parts, self.sects[part.addNextPage.index]);
12370
13309
  }
12371
13310
  if (part.addNextPage) {
12372
13311
  addPageBreakAtEnd(subRendered);
@@ -12374,8 +13313,8 @@ function requireLoop () {
12374
13313
  if (part.hasPageBreakBeginning && insideParagraphLoop) {
12375
13314
  addPageBreakAtBeginning(subRendered);
12376
13315
  }
12377
- for(var _i10 = 0, _subRendered$parts2 = subRendered.parts; _i10 < _subRendered$parts2.length; _i10++){
12378
- var _val = _subRendered$parts2[_i10];
13316
+ for(var _i22 = 0, _subRendered$parts2 = subRendered.parts; _i22 < _subRendered$parts2.length; _i22++){
13317
+ var _val = _subRendered$parts2[_i22];
12379
13318
  totalValue.push(_val);
12380
13319
  }
12381
13320
  pushArray(errors, subRendered.errors);
@@ -12403,11 +13342,11 @@ function requireLoop () {
12403
13342
  };
12404
13343
  }
12405
13344
  if (heightOffset !== 0) {
12406
- var cy = +getSingleAttribute(this.lastExt.value, "cy");
13345
+ var cy = +getSingleAttribute(self.lastExt.value, "cy");
12407
13346
  /*
12408
13347
  * We do edit the value of a previous result here
12409
13348
  * #edit-value-backwards
12410
- */ this.lastExt.value = setSingleAttribute(this.lastExt.value, "cy", cy + heightOffset);
13349
+ */ self.lastExt.value = setSingleAttribute(self.lastExt.value, "cy", cy + heightOffset);
12411
13350
  }
12412
13351
  return {
12413
13352
  value: options.joinUncorrupt(totalValue, _objectSpread(_objectSpread({}, options), {}, {
@@ -12623,7 +13562,7 @@ function requireRawxml () {
12623
13562
  return (String )(t);
12624
13563
  }
12625
13564
  var traits = requireTraits();
12626
- var _require = docUtils, isContent = _require.isContent;
13565
+ var _require = docUtils, isContent = _require.isContent, getPartWithDelimiters = _require.getPartWithDelimiters;
12627
13566
  var _require2 = requireErrors(), throwRawTagShouldBeOnlyTextInParagraph = _require2.throwRawTagShouldBeOnlyTextInParagraph, getInvalidRawXMLValueException = _require2.getInvalidRawXMLValueException;
12628
13567
  var wrapper = requireModuleWrapper();
12629
13568
  var moduleName = "rawxml";
@@ -12672,6 +13611,7 @@ function requireRawxml () {
12672
13611
  {
12673
13612
  key: "postparse",
12674
13613
  value: function postparse(postparsed) {
13614
+ var _this = this;
12675
13615
  return traits.expandToOne(postparsed, {
12676
13616
  moduleName: moduleName,
12677
13617
  getInner: getInner,
@@ -12680,7 +13620,7 @@ function requireRawxml () {
12680
13620
  message: "Raw tag not in paragraph",
12681
13621
  id: "raw_tag_outerxml_invalid",
12682
13622
  explanation: function explanation(part) {
12683
- return "The tag \"".concat(part.value, "\" is not inside a paragraph, putting raw tags inside an inline loop is disallowed.");
13623
+ return "The tag \"".concat(getPartWithDelimiters(part, _this.docxtemplater), "\" is not inside a paragraph, putting raw tags inside an inline loop is disallowed.");
12684
13624
  }
12685
13625
  }
12686
13626
  });
@@ -12716,6 +13656,8 @@ function requireRawxml () {
12716
13656
  getInvalidRawXMLValueException({
12717
13657
  tag: part.value,
12718
13658
  value: value,
13659
+ partDelims: getPartWithDelimiters(part, this.docxtemplater),
13660
+ part: part,
12719
13661
  offset: part.offset
12720
13662
  })
12721
13663
  ]
@@ -12968,10 +13910,10 @@ function requireExpandPairTrait () {
12968
13910
  },
12969
13911
  {
12970
13912
  key: "postparse",
12971
- value: function postparse(postparsed, _ref) {
13913
+ value: function postparse(postparsed, options) {
12972
13914
  var _this = this;
12973
- var getTraits = _ref.getTraits, _postparse = _ref.postparse, fileType = _ref.fileType;
12974
- var traits = getTraits(traitName, postparsed);
13915
+ var getTraits = options.getTraits, postparse = options.postparse, fileType = options.fileType;
13916
+ var traits = getTraits(traitName, postparsed, options);
12975
13917
  traits = traits.map(function(trait) {
12976
13918
  return trait || [];
12977
13919
  });
@@ -13052,7 +13994,7 @@ function requireExpandPairTrait () {
13052
13994
  if (expandedPair[1] === i) {
13053
13995
  // End pair
13054
13996
  var basePart = postparsed[pair[0].offset];
13055
- basePart.subparsed = _postparse(innerParts, {
13997
+ basePart.subparsed = postparse(innerParts, {
13056
13998
  basePart: basePart
13057
13999
  });
13058
14000
  basePart.endLindex = pair[1].part.lIndex;
@@ -13158,17 +14100,6 @@ function requireRender () {
13158
14100
  this.recordedRun = [];
13159
14101
  }
13160
14102
  return _createClass(Render, [
13161
- {
13162
- key: "optionsTransformer",
13163
- value: function optionsTransformer(options, docxtemplater) {
13164
- this.docxtemplater = docxtemplater;
13165
- this.brTag = docxtemplater.fileType === "docx" ? "<w:r><w:br/></w:r>" : "<a:br/>";
13166
- this.prefix = ftprefix[docxtemplater.fileType];
13167
- this.runStartTag = "".concat(this.prefix, ":r");
13168
- this.runPropsStartTag = "".concat(this.prefix, ":rPr");
13169
- return options;
13170
- }
13171
- },
13172
14103
  {
13173
14104
  key: "set",
13174
14105
  value: function set(obj) {
@@ -13181,15 +14112,14 @@ function requireRender () {
13181
14112
  }
13182
14113
  },
13183
14114
  {
13184
- key: "getRenderedMap",
13185
- value: function getRenderedMap(mapper) {
13186
- for(var from in this.compiled){
13187
- mapper[from] = {
13188
- from: from,
13189
- data: this.data
13190
- };
13191
- }
13192
- return mapper;
14115
+ key: "optionsTransformer",
14116
+ value: function optionsTransformer(options, docxtemplater) {
14117
+ this.docxtemplater = docxtemplater;
14118
+ this.brTag = docxtemplater.fileType === "docx" ? "<w:r><w:br/></w:r>" : "<a:br/>";
14119
+ this.prefix = ftprefix[docxtemplater.fileType];
14120
+ this.runStartTag = "".concat(this.prefix, ":r");
14121
+ this.runPropsStartTag = "".concat(this.prefix, ":rPr");
14122
+ return options;
13193
14123
  }
13194
14124
  },
13195
14125
  {
@@ -13219,6 +14149,18 @@ function requireRender () {
13219
14149
  };
13220
14150
  }
13221
14151
  },
14152
+ {
14153
+ key: "getRenderedMap",
14154
+ value: function getRenderedMap(mapper) {
14155
+ for(var from in this.compiled){
14156
+ mapper[from] = {
14157
+ from: from,
14158
+ data: this.data
14159
+ };
14160
+ }
14161
+ return mapper;
14162
+ }
14163
+ },
13222
14164
  {
13223
14165
  key: "render",
13224
14166
  value: function render(part, _ref) {
@@ -13332,6 +14274,9 @@ function requireFileTypeConfig () {
13332
14274
  getTemplatedFiles: function getTemplatedFiles() {
13333
14275
  return [];
13334
14276
  },
14277
+ templatedNs: [
14278
+ "http://schemas.microsoft.com/office/2006/coverPageProps"
14279
+ ],
13335
14280
  textPath: function textPath(doc) {
13336
14281
  return doc.textTarget;
13337
14282
  },
@@ -13346,6 +14291,12 @@ function requireFileTypeConfig () {
13346
14291
  "dc:subject",
13347
14292
  "dc:title",
13348
14293
  "cp:contentStatus",
14294
+ "PublishDate",
14295
+ "Abstract",
14296
+ "CompanyAddress",
14297
+ "CompanyPhone",
14298
+ "CompanyFax",
14299
+ "CompanyEmail",
13349
14300
  "w:t",
13350
14301
  "a:t",
13351
14302
  "m:t",
@@ -13699,7 +14650,8 @@ function requireFileTypeConfig () {
13699
14650
  linebreaks: z["boolean"]().optional(),
13700
14651
  nullGetter: z["function"]().optional(),
13701
14652
  syntax: dxtSyntaxSchema.optional(),
13702
- stripInvalidXMLChars: z["boolean"]().optional()
14653
+ stripInvalidXMLChars: z["boolean"]().optional(),
14654
+ warnFn: z["function"]().optional()
13703
14655
  }).strict();
13704
14656
  var _require = requireGetRelationTypes(), getRelsTypes = _require.getRelsTypes;
13705
14657
  var _require2 = requireGetContentTypes(), collectContentTypes = _require2.collectContentTypes, getContentTypes = _require2.getContentTypes;
@@ -13725,22 +14677,24 @@ function requireFileTypeConfig () {
13725
14677
  2
13726
14678
  ];
13727
14679
  function throwIfDuplicateModules(modules) {
13728
- var duplicates = getDuplicates(modules.map(function(_ref) {
13729
- var name = _ref.name;
13730
- return name;
13731
- }));
14680
+ var names = [];
14681
+ for(var _i2 = 0; _i2 < modules.length; _i2++){
14682
+ var mod = modules[_i2];
14683
+ names.push(mod.name);
14684
+ }
14685
+ var duplicates = getDuplicates(names);
13732
14686
  if (duplicates.length > 0) {
13733
14687
  throw new XTInternalError("Detected duplicate module \"".concat(duplicates[0], "\""));
13734
14688
  }
13735
14689
  }
13736
14690
  function addXmlFileNamesFromXmlContentType(doc) {
13737
- for(var _i2 = 0, _doc$modules2 = doc.modules; _i2 < _doc$modules2.length; _i2++){
13738
- var _module = _doc$modules2[_i2];
13739
- for(var _i4 = 0, _ref3 = _module.xmlContentTypes || []; _i4 < _ref3.length; _i4++){
13740
- var contentType = _ref3[_i4];
14691
+ for(var _i4 = 0, _doc$modules2 = doc.modules; _i4 < _doc$modules2.length; _i4++){
14692
+ var _module = _doc$modules2[_i4];
14693
+ for(var _i6 = 0, _ref2 = _module.xmlContentTypes || []; _i6 < _ref2.length; _i6++){
14694
+ var contentType = _ref2[_i6];
13741
14695
  var candidates = doc.invertedContentTypes[contentType] || [];
13742
- for(var _i6 = 0; _i6 < candidates.length; _i6++){
13743
- var candidate = candidates[_i6];
14696
+ for(var _i8 = 0; _i8 < candidates.length; _i8++){
14697
+ var candidate = candidates[_i8];
13744
14698
  if (doc.zip.files[candidate]) {
13745
14699
  doc.options.xmlFileNames.push(candidate);
13746
14700
  }
@@ -13793,10 +14747,10 @@ function requireFileTypeConfig () {
13793
14747
  "xl/",
13794
14748
  "ppt/"
13795
14749
  ];
13796
- for(var _i8 = 0; _i8 < allFiles.length; _i8++){
13797
- var _name = allFiles[_i8];
13798
- for(var _i0 = 0; _i0 < prefixes.length; _i0++){
13799
- var prefix = prefixes[_i0];
14750
+ for(var _i0 = 0; _i0 < allFiles.length; _i0++){
14751
+ var _name = allFiles[_i0];
14752
+ for(var _i10 = 0; _i10 < prefixes.length; _i10++){
14753
+ var prefix = prefixes[_i10];
13800
14754
  if (_name.indexOf("".concat(prefix)) === 0) {
13801
14755
  resultFiles.push(_name);
13802
14756
  }
@@ -13804,8 +14758,8 @@ function requireFileTypeConfig () {
13804
14758
  }
13805
14759
  /*
13806
14760
  * Push the rest of files, such as docProps/core.xml and docProps/app.xml
13807
- */ for(var _i10 = 0; _i10 < allFiles.length; _i10++){
13808
- var _name2 = allFiles[_i10];
14761
+ */ for(var _i12 = 0; _i12 < allFiles.length; _i12++){
14762
+ var _name2 = allFiles[_i12];
13809
14763
  if (resultFiles.indexOf(_name2) === -1) {
13810
14764
  resultFiles.push(_name2);
13811
14765
  }
@@ -13857,7 +14811,7 @@ function requireFileTypeConfig () {
13857
14811
  }
13858
14812
  var Docxtemplater = /*#__PURE__*/ function() {
13859
14813
  function Docxtemplater(zip) {
13860
- var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref4$modules = _ref4.modules, modules = _ref4$modules === void 0 ? [] : _ref4$modules, options = _objectWithoutProperties(_ref4, _excluded);
14814
+ var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref3$modules = _ref3.modules, modules = _ref3$modules === void 0 ? [] : _ref3$modules, options = _objectWithoutProperties(_ref3, _excluded);
13861
14815
  _classCallCheck(this, Docxtemplater);
13862
14816
  this.targets = [];
13863
14817
  this.rendered = false;
@@ -13883,8 +14837,8 @@ function requireFileTypeConfig () {
13883
14837
  if (!Array.isArray(modules)) {
13884
14838
  throw new Error("The modules argument of docxtemplater's constructor must be an array");
13885
14839
  }
13886
- for(var _i12 = 0; _i12 < modules.length; _i12++){
13887
- var _module2 = modules[_i12];
14840
+ for(var _i14 = 0; _i14 < modules.length; _i14++){
14841
+ var _module2 = modules[_i14];
13888
14842
  this.attachModule(_module2);
13889
14843
  }
13890
14844
  this.loadZip(zip);
@@ -13897,9 +14851,10 @@ function requireFileTypeConfig () {
13897
14851
  {
13898
14852
  key: "verifyApiVersion",
13899
14853
  value: function verifyApiVersion(neededVersion) {
13900
- neededVersion = neededVersion.split(".").map(function(i) {
13901
- return parseInt(i, 10);
13902
- });
14854
+ neededVersion = neededVersion.split(".");
14855
+ for(var i = 0; i < neededVersion.length; i++){
14856
+ neededVersion[i] = parseInt(neededVersion[i], 10);
14857
+ }
13903
14858
  if (neededVersion.length !== 3) {
13904
14859
  throwApiVersionError("neededVersion is not a valid version", {
13905
14860
  neededVersion: neededVersion,
@@ -13933,8 +14888,8 @@ function requireFileTypeConfig () {
13933
14888
  {
13934
14889
  key: "setModules",
13935
14890
  value: function setModules(obj) {
13936
- for(var _i14 = 0, _this$modules2 = this.modules; _i14 < _this$modules2.length; _i14++){
13937
- var _module3 = _this$modules2[_i14];
14891
+ for(var _i16 = 0, _this$modules2 = this.modules; _i16 < _this$modules2.length; _i16++){
14892
+ var _module3 = _this$modules2[_i16];
13938
14893
  _module3.set(obj);
13939
14894
  }
13940
14895
  }
@@ -13942,8 +14897,8 @@ function requireFileTypeConfig () {
13942
14897
  {
13943
14898
  key: "sendEvent",
13944
14899
  value: function sendEvent(eventName) {
13945
- for(var _i16 = 0, _this$modules4 = this.modules; _i16 < _this$modules4.length; _i16++){
13946
- var _module4 = _this$modules4[_i16];
14900
+ for(var _i18 = 0, _this$modules4 = this.modules; _i18 < _this$modules4.length; _i18++){
14901
+ var _module4 = _this$modules4[_i18];
13947
14902
  _module4.on(eventName);
13948
14903
  }
13949
14904
  }
@@ -13985,8 +14940,8 @@ function requireFileTypeConfig () {
13985
14940
  {
13986
14941
  key: "findModule",
13987
14942
  value: function findModule(name) {
13988
- for(var _i18 = 0, _this$modules6 = this.modules; _i18 < _this$modules6.length; _i18++){
13989
- var _module5 = _this$modules6[_i18];
14943
+ for(var _i20 = 0, _this$modules6 = this.modules; _i20 < _this$modules6.length; _i20++){
14944
+ var _module5 = _this$modules6[_i20];
13990
14945
  if (_module5.name === name) {
13991
14946
  return _module5;
13992
14947
  }
@@ -14030,6 +14985,11 @@ function requireFileTypeConfig () {
14030
14985
  if (zip.loadAsync) {
14031
14986
  throw new XTInternalError("Docxtemplater doesn't handle JSZip version >=3, please use pizzip");
14032
14987
  }
14988
+ if (zip.xtRendered) {
14989
+ this.options.warnFn([
14990
+ new Error("This zip file appears to be the outcome of a previous docxtemplater generation. This typically indicates that docxtemplater was integrated by reusing the same zip file. It is recommended to create a new Pizzip instance for each docxtemplater generation.")
14991
+ ]);
14992
+ }
14033
14993
  this.zip = zip;
14034
14994
  this.updateFileTypeConfig();
14035
14995
  this.modules = concatArrays([
@@ -14038,8 +14998,8 @@ function requireFileTypeConfig () {
14038
14998
  }),
14039
14999
  this.modules
14040
15000
  ]);
14041
- for(var _i20 = 0, _this$modules8 = this.modules; _i20 < _this$modules8.length; _i20++){
14042
- var _module6 = _this$modules8[_i20];
15001
+ for(var _i22 = 0, _this$modules8 = this.modules; _i22 < _this$modules8.length; _i22++){
15002
+ var _module6 = _this$modules8[_i22];
14043
15003
  _module6.zip = this.zip;
14044
15004
  _module6.docxtemplater = this;
14045
15005
  _module6.fileTypeConfig = this.fileTypeConfig;
@@ -14095,9 +15055,11 @@ function requireFileTypeConfig () {
14095
15055
  _this.mapper = _this.modules.reduce(function(value, module1) {
14096
15056
  return module1.getRenderedMap(value);
14097
15057
  }, {});
14098
- return Promise.all(Object.keys(_this.mapper).map(function(to) {
15058
+ var promises = [];
15059
+ var _loop = function _loop() {
15060
+ var to = _Object$keys2[_i24];
14099
15061
  var _this$mapper$to = _this.mapper[to], from = _this$mapper$to.from, _$data = _this$mapper$to.data;
14100
- return Promise.resolve(_$data).then(function(data) {
15062
+ promises.push(Promise.resolve(_$data).then(function(data) {
14101
15063
  var currentFile = _this.compiled[from];
14102
15064
  currentFile.filePath = to;
14103
15065
  currentFile.scopeManager = _this.getScopeManager(to, currentFile, data);
@@ -14107,8 +15069,12 @@ function requireFileTypeConfig () {
14107
15069
  }, function(errs) {
14108
15070
  pushArray(errors, errs);
14109
15071
  });
14110
- });
14111
- })).then(function(resolved) {
15072
+ }));
15073
+ };
15074
+ for(var _i24 = 0, _Object$keys2 = Object.keys(_this.mapper); _i24 < _Object$keys2.length; _i24++){
15075
+ _loop();
15076
+ }
15077
+ return Promise.all(promises).then(function(resolved) {
14112
15078
  if (errors.length !== 0) {
14113
15079
  if (_this.options.errorLogging) {
14114
15080
  logErrors(errors, _this.options.errorLogging);
@@ -14131,14 +15097,14 @@ function requireFileTypeConfig () {
14131
15097
  return this;
14132
15098
  }
14133
15099
  var options = this.options;
14134
- for(var _i22 = 0, _this$modules0 = this.modules; _i22 < _this$modules0.length; _i22++){
14135
- var _module7 = _this$modules0[_i22];
15100
+ for(var _i26 = 0, _this$modules0 = this.modules; _i26 < _this$modules0.length; _i26++){
15101
+ var _module7 = _this$modules0[_i26];
14136
15102
  options = _module7.optionsTransformer(options, this);
14137
15103
  }
14138
15104
  this.options = options;
14139
15105
  this.options.xmlFileNames = uniq(this.options.xmlFileNames);
14140
- for(var _i24 = 0, _this$options$xmlFile2 = this.options.xmlFileNames; _i24 < _this$options$xmlFile2.length; _i24++){
14141
- var fileName = _this$options$xmlFile2[_i24];
15106
+ for(var _i28 = 0, _this$options$xmlFile2 = this.options.xmlFileNames; _i28 < _this$options$xmlFile2.length; _i28++){
15107
+ var fileName = _this$options$xmlFile2[_i28];
14142
15108
  var content = this.zip.files[fileName].asText();
14143
15109
  this.xmlDocuments[fileName] = str2xml(content);
14144
15110
  }
@@ -14146,8 +15112,8 @@ function requireFileTypeConfig () {
14146
15112
  zip: this.zip,
14147
15113
  xmlDocuments: this.xmlDocuments
14148
15114
  });
14149
- for(var _i26 = 0, _this$modules10 = this.modules; _i26 < _this$modules10.length; _i26++){
14150
- var _module8 = _this$modules10[_i26];
15115
+ for(var _i30 = 0, _this$modules10 = this.modules; _i30 < _this$modules10.length; _i30++){
15116
+ var _module8 = _this$modules10[_i30];
14151
15117
  _module8.xmlDocuments = this.xmlDocuments;
14152
15118
  }
14153
15119
  this.getTemplatedFiles();
@@ -14155,15 +15121,15 @@ function requireFileTypeConfig () {
14155
15121
  * Loop inside all templatedFiles (ie xml files with content).
14156
15122
  * Sometimes they don't exist (footer.xml for example)
14157
15123
  */ this.sendEvent("before-preparse");
14158
- for(var _i28 = 0, _this$templatedFiles2 = this.templatedFiles; _i28 < _this$templatedFiles2.length; _i28++){
14159
- var _fileName = _this$templatedFiles2[_i28];
15124
+ for(var _i32 = 0, _this$templatedFiles2 = this.templatedFiles; _i32 < _this$templatedFiles2.length; _i32++){
15125
+ var _fileName = _this$templatedFiles2[_i32];
14160
15126
  if (this.zip.files[_fileName] != null) {
14161
15127
  this.precompileFile(_fileName);
14162
15128
  }
14163
15129
  }
14164
15130
  this.sendEvent("after-preparse");
14165
- for(var _i30 = 0, _this$templatedFiles4 = this.templatedFiles; _i30 < _this$templatedFiles4.length; _i30++){
14166
- var _fileName2 = _this$templatedFiles4[_i30];
15131
+ for(var _i34 = 0, _this$templatedFiles4 = this.templatedFiles; _i34 < _this$templatedFiles4.length; _i34++){
15132
+ var _fileName2 = _this$templatedFiles4[_i34];
14167
15133
  if (this.zip.files[_fileName2] != null) {
14168
15134
  this.compiled[_fileName2].parse({
14169
15135
  noPostParse: true
@@ -14171,8 +15137,8 @@ function requireFileTypeConfig () {
14171
15137
  }
14172
15138
  }
14173
15139
  this.sendEvent("after-parse");
14174
- for(var _i32 = 0, _this$templatedFiles6 = this.templatedFiles; _i32 < _this$templatedFiles6.length; _i32++){
14175
- var _fileName3 = _this$templatedFiles6[_i32];
15140
+ for(var _i36 = 0, _this$templatedFiles6 = this.templatedFiles; _i36 < _this$templatedFiles6.length; _i36++){
15141
+ var _fileName3 = _this$templatedFiles6[_i36];
14176
15142
  if (this.zip.files[_fileName3] != null) {
14177
15143
  this.compiled[_fileName3].postparse();
14178
15144
  }
@@ -14202,8 +15168,8 @@ function requireFileTypeConfig () {
14202
15168
  if (this.zip.files.mimetype) {
14203
15169
  fileType = "odt";
14204
15170
  }
14205
- for(var _i34 = 0, _this$modules12 = this.modules; _i34 < _this$modules12.length; _i34++){
14206
- var _module9 = _this$modules12[_i34];
15171
+ for(var _i38 = 0, _this$modules12 = this.modules; _i38 < _this$modules12.length; _i38++){
15172
+ var _module9 = _this$modules12[_i38];
14207
15173
  fileType = _module9.getFileType({
14208
15174
  zip: this.zip,
14209
15175
  contentTypes: contentTypes,
@@ -14254,6 +15220,7 @@ function requireFileTypeConfig () {
14254
15220
  this.hideDeprecations = true;
14255
15221
  var promise = this.resolveData(data);
14256
15222
  this.hideDeprecations = false;
15223
+ this.zip.xtRendered = true;
14257
15224
  return promise.then(function() {
14258
15225
  return _this2.render();
14259
15226
  });
@@ -14262,6 +15229,7 @@ function requireFileTypeConfig () {
14262
15229
  {
14263
15230
  key: "render",
14264
15231
  value: function render(data) {
15232
+ this.zip.xtRendered = true;
14265
15233
  if (this.rendered) {
14266
15234
  throwRenderTwice();
14267
15235
  }
@@ -14295,11 +15263,11 @@ function requireFileTypeConfig () {
14295
15263
  ]);
14296
15264
  delete currentFile.content;
14297
15265
  }
14298
- for(var _i36 = 0; _i36 < output.length; _i36++){
14299
- var outputPart = output[_i36];
15266
+ for(var _i40 = 0; _i40 < output.length; _i40++){
15267
+ var outputPart = output[_i40];
14300
15268
  var _outputPart = _slicedToArray(outputPart, 3), content = _outputPart[1], _currentFile = _outputPart[2];
14301
- for(var _i38 = 0, _this$modules14 = this.modules; _i38 < _this$modules14.length; _i38++){
14302
- var _module0 = _this$modules14[_i38];
15269
+ for(var _i42 = 0, _this$modules14 = this.modules; _i42 < _this$modules14.length; _i42++){
15270
+ var _module0 = _this$modules14[_i42];
14303
15271
  if (_module0.preZip) {
14304
15272
  var result = _module0.preZip(content, _currentFile);
14305
15273
  if (typeof result === "string") {
@@ -14308,8 +15276,8 @@ function requireFileTypeConfig () {
14308
15276
  }
14309
15277
  }
14310
15278
  }
14311
- for(var _i40 = 0; _i40 < output.length; _i40++){
14312
- var _output$_i = _slicedToArray(output[_i40], 2), _to = _output$_i[0], _content = _output$_i[1];
15279
+ for(var _i44 = 0; _i44 < output.length; _i44++){
15280
+ var _output$_i = _slicedToArray(output[_i44], 2), _to = _output$_i[0], _content = _output$_i[1];
14313
15281
  this.zip.file(_to, _content, {
14314
15282
  createFolders: true
14315
15283
  });
@@ -14370,8 +15338,8 @@ function requireFileTypeConfig () {
14370
15338
  "fileType",
14371
15339
  "modules"
14372
15340
  ]);
14373
- for(var _i42 = 0; _i42 < defaultKeys.length; _i42++){
14374
- var key = defaultKeys[_i42];
15341
+ for(var _i46 = 0; _i46 < defaultKeys.length; _i46++){
15342
+ var key = defaultKeys[_i46];
14375
15343
  xmltOptions[key] = this[key];
14376
15344
  }
14377
15345
  return new Docxtemplater.XmlTemplater(content, xmltOptions);
@@ -14388,6 +15356,20 @@ function requireFileTypeConfig () {
14388
15356
  value: function getTemplatedFiles() {
14389
15357
  this.templatedFiles = this.fileTypeConfig.getTemplatedFiles(this.zip);
14390
15358
  pushArray(this.templatedFiles, this.targets);
15359
+ var templatedNs = this.fileTypeConfig.templatedNs || [];
15360
+ if (templatedNs.length > 0) {
15361
+ for(var key in this.filesContentTypes){
15362
+ if (/^customXml\/item\d+\.xml$/.test(key)) {
15363
+ for(var _i48 = 0; _i48 < templatedNs.length; _i48++){
15364
+ var ns = templatedNs[_i48];
15365
+ var text = this.zip.file(key).asText();
15366
+ if (text.indexOf("xmlns=\"".concat(ns, "\"")) !== -1) {
15367
+ this.templatedFiles.push(key);
15368
+ }
15369
+ }
15370
+ }
15371
+ }
15372
+ }
14391
15373
  this.templatedFiles = uniq(this.templatedFiles);
14392
15374
  return this.templatedFiles;
14393
15375
  }