docxtemplater
Version:
Generate docx, pptx, and xlsx from templates (Word, Powerpoint and Excel documents), from Node.js, the Browser and the command line
1,480 lines (1,447 loc) • 198 kB
JavaScript
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 60:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var traits = __webpack_require__(536);
var _require = __webpack_require__(207),
isContent = _require.isContent;
var _require2 = __webpack_require__(946),
throwRawTagShouldBeOnlyTextInParagraph = _require2.throwRawTagShouldBeOnlyTextInParagraph,
getInvalidRawXMLValueException = _require2.getInvalidRawXMLValueException;
var wrapper = __webpack_require__(899);
var moduleName = "rawxml";
function getInner(_ref) {
var part = _ref.part,
left = _ref.left,
right = _ref.right,
postparsed = _ref.postparsed,
index = _ref.index;
var paragraphParts = postparsed.slice(left + 1, right);
for (var i = 0, len = paragraphParts.length; i < len; i++) {
if (i === index - left - 1) {
continue;
}
var p = paragraphParts[i];
if (isContent(p)) {
throwRawTagShouldBeOnlyTextInParagraph({
paragraphParts: paragraphParts,
part: part
});
}
}
return part;
}
var RawXmlModule = /*#__PURE__*/function () {
function RawXmlModule() {
_classCallCheck(this, RawXmlModule);
this.name = "RawXmlModule";
this.prefix = "@";
}
return _createClass(RawXmlModule, [{
key: "optionsTransformer",
value: function optionsTransformer(options, docxtemplater) {
this.fileTypeConfig = docxtemplater.fileTypeConfig;
return options;
}
}, {
key: "matchers",
value: function matchers() {
return [[this.prefix, moduleName]];
}
}, {
key: "postparse",
value: function postparse(postparsed) {
return traits.expandToOne(postparsed, {
moduleName: moduleName,
getInner: getInner,
expandTo: this.fileTypeConfig.tagRawXml,
error: {
message: "Raw tag not in paragraph",
id: "raw_tag_outerxml_invalid",
explanation: function explanation(part) {
return "The tag \"".concat(part.value, "\" is not inside a paragraph, putting raw tags inside an inline loop is disallowed.");
}
}
});
}
}, {
key: "render",
value: function render(part, options) {
if (part.module !== moduleName) {
return null;
}
var value;
var errors = [];
try {
value = options.scopeManager.getValue(part.value, {
part: part
});
value !== null && value !== void 0 ? value : value = options.nullGetter(part);
} catch (e) {
errors.push(e);
return {
errors: errors
};
}
value = value ? value : "";
if (typeof value === "string") {
return {
value: value
};
}
return {
errors: [getInvalidRawXMLValueException({
tag: part.value,
value: value,
offset: part.offset
})]
};
}
}]);
}();
module.exports = function () {
return wrapper(new RawXmlModule());
};
/***/ }),
/***/ 183:
/***/ (function(module) {
/*
* Convert string to array (typed, when possible)
* Stryker disable all : because this is a utility function that was copied
* from
* https://github.com/open-xml-templating/pizzip/blob/34a840553c604980859dc6d0dcd1f89b6e5527b3/es6/utf8.js#L33
*/
function string2buf(str) {
var c,
c2,
mPos,
i,
bufLen = 0;
var strLen = str.length;
// count binary size
for (mPos = 0; mPos < strLen; mPos++) {
c = str.charCodeAt(mPos);
if ((c & 0xfc00) === 0xd800 && mPos + 1 < strLen) {
c2 = str.charCodeAt(mPos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
mPos++;
}
}
bufLen += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
var buf = new Uint8Array(bufLen);
// convert
for (i = 0, mPos = 0; i < bufLen; mPos++) {
c = str.charCodeAt(mPos);
if ((c & 0xfc00) === 0xd800 && mPos + 1 < strLen) {
c2 = str.charCodeAt(mPos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
mPos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xc0 | c >>> 6;
buf[i++] = 0x80 | c & 0x3f;
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xe0 | c >>> 12;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
} else {
/* four bytes */
buf[i++] = 0xf0 | c >>> 18;
buf[i++] = 0x80 | c >>> 12 & 0x3f;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
}
}
return buf;
}
// Stryker restore all
function postrender(parts, options) {
for (var _i2 = 0, _options$modules2 = options.modules; _i2 < _options$modules2.length; _i2++) {
var _module = _options$modules2[_i2];
parts = _module.postrender(parts, options);
}
var fullLength = 0;
var newParts = options.joinUncorrupt(parts, options);
var longStr = "";
var lenStr = 0;
var maxCompact = 65536;
var uintArrays = [];
for (var i = 0, len = newParts.length; i < len; i++) {
var part = newParts[i];
/*
* This condition should be hit in the integration test at :
* it("should not regress with long file (hit maxCompact value of 65536)", function () {
* Stryker disable all : because this is an optimisation that won't make any tests fail
*/
if (part.length + lenStr > maxCompact) {
var _arr = string2buf(longStr);
fullLength += _arr.length;
uintArrays.push(_arr);
longStr = "";
}
// Stryker restore all
longStr += part;
lenStr += part.length;
delete newParts[i];
}
var arr = string2buf(longStr);
fullLength += arr.length;
uintArrays.push(arr);
var array = new Uint8Array(fullLength);
var j = 0;
// Stryker disable all : because this is an optimisation that won't make any tests fail
for (var _i4 = 0; _i4 < uintArrays.length; _i4++) {
var buf = uintArrays[_i4];
for (var _i5 = 0; _i5 < buf.length; ++_i5) {
array[_i5 + j] = buf[_i5];
}
j += buf.length;
} // Stryker restore all
return array;
}
module.exports = postrender;
/***/ }),
/***/ 201:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var traitName = "expandPair";
var mergeSort = __webpack_require__(798);
var _require = __webpack_require__(207),
getLeft = _require.getLeft,
getRight = _require.getRight,
pushArray = _require.pushArray;
var wrapper = __webpack_require__(899);
var _require2 = __webpack_require__(536),
getExpandToDefault = _require2.getExpandToDefault;
var _require3 = __webpack_require__(946),
getUnmatchedLoopException = _require3.getUnmatchedLoopException,
getClosingTagNotMatchOpeningTag = _require3.getClosingTagNotMatchOpeningTag,
getUnbalancedLoopException = _require3.getUnbalancedLoopException;
function getOpenCountChange(part) {
switch (part.location) {
case "start":
return 1;
case "end":
return -1;
}
}
function match(start, end) {
return start != null && end != null && (start.part.location === "start" && end.part.location === "end" && start.part.value === end.part.value || end.part.value === "");
}
function transformer(traits) {
var i = 0;
var errors = [];
while (i < traits.length) {
var part = traits[i].part;
if (part.location === "end") {
if (i === 0) {
traits.splice(0, 1);
errors.push(getUnmatchedLoopException(part));
return {
traits: traits,
errors: errors
};
}
var endIndex = i;
var startIndex = i - 1;
var offseter = 1;
if (match(traits[startIndex], traits[endIndex])) {
traits.splice(endIndex, 1);
traits.splice(startIndex, 1);
return {
errors: errors,
traits: traits
};
}
while (offseter < 50) {
var startCandidate = traits[startIndex - offseter];
var endCandidate = traits[endIndex + offseter];
if (match(startCandidate, traits[endIndex])) {
traits.splice(endIndex, 1);
traits.splice(startIndex - offseter, 1);
return {
errors: errors,
traits: traits
};
}
if (match(traits[startIndex], endCandidate)) {
traits.splice(endIndex + offseter, 1);
traits.splice(startIndex, 1);
return {
errors: errors,
traits: traits
};
}
offseter++;
}
errors.push(getClosingTagNotMatchOpeningTag({
tags: [traits[startIndex].part, traits[endIndex].part]
}));
traits.splice(endIndex, 1);
traits.splice(startIndex, 1);
return {
traits: traits,
errors: errors
};
}
i++;
}
for (var _i2 = 0; _i2 < traits.length; _i2++) {
var _part = traits[_i2].part;
errors.push(getUnmatchedLoopException(_part));
}
return {
traits: [],
errors: errors
};
}
function getPairs(traits) {
var levelTraits = {};
var errors = [];
var pairs = [];
var transformedTraits = [];
pushArray(transformedTraits, traits);
while (transformedTraits.length > 0) {
var result = transformer(transformedTraits);
pushArray(errors, result.errors);
transformedTraits = result.traits;
}
// Stryker disable all : because this check makes the function return quicker
if (errors.length > 0) {
return {
pairs: pairs,
errors: errors
};
}
// Stryker restore all
var countOpen = 0;
for (var _i4 = 0; _i4 < traits.length; _i4++) {
var currentTrait = traits[_i4];
var part = currentTrait.part;
var change = getOpenCountChange(part);
countOpen += change;
if (change === 1) {
levelTraits[countOpen] = currentTrait;
} else {
var startTrait = levelTraits[countOpen + 1];
if (countOpen === 0) {
pairs.push([startTrait, currentTrait]);
}
}
countOpen = countOpen >= 0 ? countOpen : 0;
}
return {
pairs: pairs,
errors: errors
};
}
var ExpandPairTrait = /*#__PURE__*/function () {
function ExpandPairTrait() {
_classCallCheck(this, ExpandPairTrait);
this.name = "ExpandPairTrait";
}
return _createClass(ExpandPairTrait, [{
key: "optionsTransformer",
value: function optionsTransformer(options, docxtemplater) {
if (docxtemplater.options.paragraphLoop) {
pushArray(docxtemplater.fileTypeConfig.expandTags, docxtemplater.fileTypeConfig.onParagraphLoop);
}
this.expandTags = docxtemplater.fileTypeConfig.expandTags;
return options;
}
}, {
key: "postparse",
value: function postparse(postparsed, _ref) {
var _this = this;
var getTraits = _ref.getTraits,
_postparse = _ref.postparse,
fileType = _ref.fileType;
var traits = getTraits(traitName, postparsed);
traits = traits.map(function (trait) {
return trait || [];
});
traits = mergeSort(traits);
var _getPairs = getPairs(traits),
pairs = _getPairs.pairs,
errors = _getPairs.errors;
var lastRight = 0;
var lastPair = null;
var expandedPairs = pairs.map(function (pair) {
var expandTo = pair[0].part.expandTo;
if (expandTo === "auto" && fileType !== "text") {
var result = getExpandToDefault(postparsed, pair, _this.expandTags);
if (result.error) {
errors.push(result.error);
}
expandTo = result.value;
}
if (!expandTo || fileType === "text") {
var _left = pair[0].offset;
var _right = pair[1].offset;
if (_left < lastRight && !_this.docxtemplater.options.syntax.allowUnbalancedLoops) {
errors.push(getUnbalancedLoopException(pair, lastPair));
}
lastPair = pair;
lastRight = _right;
return [_left, _right];
}
var left, right;
try {
left = getLeft(postparsed, expandTo, pair[0].offset);
} catch (e) {
errors.push(e);
}
try {
right = getRight(postparsed, expandTo, pair[1].offset);
} catch (e) {
errors.push(e);
}
if (left < lastRight && !_this.docxtemplater.options.syntax.allowUnbalancedLoops) {
errors.push(getUnbalancedLoopException(pair, lastPair));
}
lastRight = right;
lastPair = pair;
return [left, right];
});
// Stryker disable all : because this check makes the function return quicker
if (errors.length > 0) {
return {
postparsed: postparsed,
errors: errors
};
}
// Stryker restore all
var currentPairIndex = 0;
var innerParts;
var newParsed = postparsed.reduce(function (newParsed, part, i) {
var inPair = currentPairIndex < pairs.length && expandedPairs[currentPairIndex][0] <= i && i <= expandedPairs[currentPairIndex][1];
var pair = pairs[currentPairIndex];
var expandedPair = expandedPairs[currentPairIndex];
if (!inPair) {
newParsed.push(part);
return newParsed;
}
// We're inside the pair
if (expandedPair[0] === i) {
// Start pair
innerParts = [];
}
if (pair[0].offset !== i && pair[1].offset !== i) {
// Exclude inner pair indexes
innerParts.push(part);
}
if (expandedPair[1] === i) {
// End pair
var basePart = postparsed[pair[0].offset];
basePart.subparsed = _postparse(innerParts, {
basePart: basePart
});
basePart.endLindex = pair[1].part.lIndex;
delete basePart.location;
delete basePart.expandTo;
newParsed.push(basePart);
currentPairIndex++;
var _expandedPair = expandedPairs[currentPairIndex];
while (_expandedPair && _expandedPair[0] < i) {
/*
* If we have :
* expandedPairs =[[5,72],[51,67],[90,106]]
* Then after treating [5,72], we need to treat [90,106]
* Fixed since v3.58.4
*/
currentPairIndex++;
_expandedPair = expandedPairs[currentPairIndex];
}
}
return newParsed;
}, []);
return {
postparsed: newParsed,
errors: errors
};
}
}]);
}();
module.exports = function () {
return wrapper(new ExpandPairTrait());
};
/***/ }),
/***/ 207:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var _require = __webpack_require__(673),
DOMParser = _require.DOMParser,
XMLSerializer = _require.XMLSerializer;
var _require2 = __webpack_require__(946),
throwXmlTagNotFound = _require2.throwXmlTagNotFound;
var _require3 = __webpack_require__(320),
last = _require3.last,
first = _require3.first;
function isWhiteSpace(value) {
return /^[ \n\r\t]+$/.test(value);
}
function parser(tag) {
return {
get: function get(scope) {
if (tag === ".") {
return scope;
}
if (scope) {
return scope[tag];
}
return scope;
}
};
}
var attrToRegex = {};
function setSingleAttribute(partValue, attr, attrValue) {
var regex;
// Stryker disable next-line all : because this is an optimisation
if (attrToRegex[attr]) {
regex = attrToRegex[attr];
} else {
regex = new RegExp("(<.* ".concat(attr, "=\")([^\"]*)(\".*)$"));
attrToRegex[attr] = regex;
}
if (regex.test(partValue)) {
return partValue.replace(regex, "$1".concat(attrValue, "$3"));
}
var end = partValue.lastIndexOf("/>");
if (end === -1) {
end = partValue.lastIndexOf(">");
}
return partValue.substr(0, end) + " ".concat(attr, "=\"").concat(attrValue, "\"") + partValue.substr(end);
}
function getSingleAttribute(value, attributeName) {
var index = value.indexOf(" ".concat(attributeName, "=\""));
if (index === -1) {
return null;
}
var startIndex = value.substr(index).search(/["']/) + index;
var endIndex = value.substr(startIndex + 1).search(/["']/) + startIndex;
return value.substr(startIndex + 1, endIndex - startIndex);
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function startsWith(str, prefix) {
return str.substring(0, prefix.length) === prefix;
}
function getDuplicates(arr) {
var duplicates = [];
var hash = {},
result = [];
for (var i = 0, l = arr.length; i < l; ++i) {
if (!hash[arr[i]]) {
hash[arr[i]] = true;
result.push(arr[i]);
} else {
duplicates.push(arr[i]);
}
}
return duplicates;
}
function uniq(arr) {
var hash = {},
result = [];
for (var i = 0, l = arr.length; i < l; ++i) {
if (!hash[arr[i]]) {
hash[arr[i]] = true;
result.push(arr[i]);
}
}
return result;
}
function chunkBy(parsed, f) {
var chunks = [[]];
for (var _i2 = 0; _i2 < parsed.length; _i2++) {
var p = parsed[_i2];
var currentChunk = chunks[chunks.length - 1];
var res = f(p);
if (res === "start") {
chunks.push([p]);
} else if (res === "end") {
currentChunk.push(p);
chunks.push([]);
} else {
currentChunk.push(p);
}
} // Remove empty chunks
var result = [];
for (var _i4 = 0; _i4 < chunks.length; _i4++) {
var chunk = chunks[_i4];
if (chunk.length > 0) {
result.push(chunk);
}
}
return result;
}
function getDefaults() {
return {
errorLogging: "json",
stripInvalidXMLChars: false,
paragraphLoop: false,
nullGetter: function nullGetter(part) {
return part.module ? "" : "undefined";
},
xmlFileNames: ["[Content_Types].xml"],
parser: parser,
linebreaks: false,
fileTypeConfig: null,
delimiters: {
start: "{",
end: "}"
},
syntax: {
changeDelimiterPrefix: "="
}
};
}
function xml2str(xmlNode) {
return new XMLSerializer().serializeToString(xmlNode).replace(/xmlns(:[a-z0-9]+)?="" ?/g, "");
}
function str2xml(str) {
if (str.charCodeAt(0) === 65279) {
// BOM sequence
str = str.substr(1);
}
return new DOMParser().parseFromString(str, "text/xml");
}
var charMap = [["&", "&"], ["<", "<"], [">", ">"], ['"', """], ["'", "'"]];
var charMapRegexes = charMap.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
endChar = _ref2[0],
startChar = _ref2[1];
return {
rstart: new RegExp(startChar, "g"),
rend: new RegExp(endChar, "g"),
start: startChar,
end: endChar
};
});
function wordToUtf8(string) {
for (var i = charMapRegexes.length - 1; i >= 0; i--) {
var r = charMapRegexes[i];
string = string.replace(r.rstart, r.end);
}
return string;
}
function utf8ToWord(string) {
// To make sure that the object given is a string (this is a noop for strings).
string = string.toString();
var r;
for (var i = 0, l = charMapRegexes.length; i < l; i++) {
r = charMapRegexes[i];
string = string.replace(r.rend, r.start);
}
return string;
}
// This function is written with for loops for performance
function concatArrays(arrays) {
var result = [];
for (var _i6 = 0; _i6 < arrays.length; _i6++) {
var array = arrays[_i6];
for (var _i8 = 0; _i8 < array.length; _i8++) {
var el = array[_i8];
result.push(el);
}
}
return result;
}
function pushArray(array1, array2) {
if (!array2) {
return array1;
}
for (var i = 0, len = array2.length; i < len; i++) {
array1.push(array2[i]);
}
return array1;
}
var spaceRegexp = new RegExp(String.fromCharCode(160), "g");
function convertSpaces(s) {
return s.replace(spaceRegexp, " ");
}
function pregMatchAll(regex, content) {
/*
* Regex is a string, content is the content. It returns an array of all
* matches with their offset, for example:
*
* regex=la
* content=lolalolilala
*
* Returns:
*
* [
* {array: {0: 'la'}, offset: 2},
* {array: {0: 'la'}, offset: 8},
* {array: {0: 'la'}, offset: 10}
* ]
*/
var matchArray = [];
var match;
while ((match = regex.exec(content)) != null) {
matchArray.push({
array: match,
offset: match.index
});
}
return matchArray;
}
function isEnding(value, element) {
return value === "</" + element + ">";
}
function isStarting(value, element) {
return value.indexOf("<" + element) === 0 && [">", " ", "/"].indexOf(value[element.length + 1]) !== -1;
}
function getRight(parsed, element, index) {
var val = getRightOrNull(parsed, element, index);
if (val !== null) {
return val;
}
throwXmlTagNotFound({
position: "right",
element: element,
parsed: parsed,
index: index
});
}
function getRightOrNull(parsed, elements, index) {
if (typeof elements === "string") {
elements = [elements];
}
var level = 1;
for (var i = index, l = parsed.length; i < l; i++) {
var part = parsed[i];
for (var _i10 = 0, _elements2 = elements; _i10 < _elements2.length; _i10++) {
var element = _elements2[_i10];
if (isEnding(part.value, element)) {
level--;
}
if (isStarting(part.value, element)) {
level++;
}
if (level === 0) {
return i;
}
}
}
return null;
}
function getLeft(parsed, element, index) {
var val = getLeftOrNull(parsed, element, index);
if (val !== null) {
return val;
}
throwXmlTagNotFound({
position: "left",
element: element,
parsed: parsed,
index: index
});
}
function getLeftOrNull(parsed, elements, index) {
if (typeof elements === "string") {
elements = [elements];
}
var level = 1;
for (var i = index; i >= 0; i--) {
var part = parsed[i];
for (var _i12 = 0, _elements4 = elements; _i12 < _elements4.length; _i12++) {
var element = _elements4[_i12];
if (isStarting(part.value, element)) {
level--;
}
if (isEnding(part.value, element)) {
level++;
}
if (level === 0) {
return i;
}
}
}
return null;
}
/*
* Stryker disable all : because those are functions that depend on the parsed
* structure based and we don't want minimal code here, but rather code that
* makes things clear.
*/
function isTagStart(tagType, _ref3) {
var type = _ref3.type,
tag = _ref3.tag,
position = _ref3.position;
return type === "tag" && tag === tagType && (position === "start" || position === "selfclosing");
}
function isTagEnd(tagType, _ref4) {
var type = _ref4.type,
tag = _ref4.tag,
position = _ref4.position;
return type === "tag" && tag === tagType && position === "end";
}
function isParagraphStart(_ref5) {
var type = _ref5.type,
tag = _ref5.tag,
position = _ref5.position;
return ["w:p", "a:p"].indexOf(tag) !== -1 && type === "tag" && position === "start";
}
function isParagraphEnd(_ref6) {
var type = _ref6.type,
tag = _ref6.tag,
position = _ref6.position;
return ["w:p", "a:p"].indexOf(tag) !== -1 && type === "tag" && position === "end";
}
function isTextStart(_ref7) {
var type = _ref7.type,
position = _ref7.position,
text = _ref7.text;
return text && type === "tag" && position === "start";
}
function isTextEnd(_ref8) {
var type = _ref8.type,
position = _ref8.position,
text = _ref8.text;
return text && type === "tag" && position === "end";
}
function isContent(_ref9) {
var type = _ref9.type,
position = _ref9.position;
return type === "placeholder" || type === "content" && position === "insidetag";
}
function isModule(_ref10, modules) {
var module = _ref10.module,
type = _ref10.type;
if (!(modules instanceof Array)) {
modules = [modules];
}
return type === "placeholder" && modules.indexOf(module) !== -1;
}
// Stryker restore all
var corruptCharacters = /[\x00-\x08\x0B\x0C\x0E-\x1F]/g;
/*
* 00 NUL '\0' (null character)
* 01 SOH (start of heading)
* 02 STX (start of text)
* 03 ETX (end of text)
* 04 EOT (end of transmission)
* 05 ENQ (enquiry)
* 06 ACK (acknowledge)
* 07 BEL '\a' (bell)
* 08 BS '\b' (backspace)
* 0B VT '\v' (vertical tab)
* 0C FF '\f' (form feed)
* 0E SO (shift out)
* 0F SI (shift in)
* 10 DLE (data link escape)
* 11 DC1 (device control 1)
* 12 DC2 (device control 2)
* 13 DC3 (device control 3)
* 14 DC4 (device control 4)
* 15 NAK (negative ack.)
* 16 SYN (synchronous idle)
* 17 ETB (end of trans. blk)
* 18 CAN (cancel)
* 19 EM (end of medium)
* 1A SUB (substitute)
* 1B ESC (escape)
* 1C FS (file separator)
* 1D GS (group separator)
* 1E RS (record separator)
* 1F US (unit separator)
*/
function hasCorruptCharacters(string) {
corruptCharacters.lastIndex = 0;
return corruptCharacters.test(string);
}
function removeCorruptCharacters(string) {
if (typeof string !== "string") {
string = String(string);
}
return string.replace(corruptCharacters, "");
}
function invertMap(map) {
var invertedMap = {};
for (var key in map) {
var value = map[key];
invertedMap[value] || (invertedMap[value] = []);
invertedMap[value].push(key);
}
return invertedMap;
}
/*
* This ensures that the sort is stable. The default Array.sort of the browser
* is not stable in firefox, as the JS spec does not enforce the sort to be
* stable.
*/
function stableSort(arr, compare) {
// 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.
return arr.map(function (item, index) {
return {
item: item,
index: index
};
}).sort(function (a, b) {
return compare(a.item, b.item) || a.index - b.index;
}).map(function (_ref11) {
var item = _ref11.item;
return item;
});
// Stryker restore all
}
module.exports = {
endsWith: endsWith,
startsWith: startsWith,
isContent: isContent,
isParagraphStart: isParagraphStart,
isParagraphEnd: isParagraphEnd,
isTagStart: isTagStart,
isTagEnd: isTagEnd,
isTextStart: isTextStart,
isTextEnd: isTextEnd,
isStarting: isStarting,
isEnding: isEnding,
isModule: isModule,
uniq: uniq,
getDuplicates: getDuplicates,
chunkBy: chunkBy,
last: last,
first: first,
xml2str: xml2str,
str2xml: str2xml,
getRightOrNull: getRightOrNull,
getRight: getRight,
getLeftOrNull: getLeftOrNull,
getLeft: getLeft,
pregMatchAll: pregMatchAll,
convertSpaces: convertSpaces,
charMapRegexes: charMapRegexes,
hasCorruptCharacters: hasCorruptCharacters,
removeCorruptCharacters: removeCorruptCharacters,
getDefaults: getDefaults,
wordToUtf8: wordToUtf8,
utf8ToWord: utf8ToWord,
concatArrays: concatArrays,
pushArray: pushArray,
invertMap: invertMap,
charMap: charMap,
getSingleAttribute: getSingleAttribute,
setSingleAttribute: setSingleAttribute,
isWhiteSpace: isWhiteSpace,
stableSort: stableSort
};
/***/ }),
/***/ 208:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var _require = __webpack_require__(207),
startsWith = _require.startsWith,
endsWith = _require.endsWith,
isStarting = _require.isStarting,
isEnding = _require.isEnding,
isWhiteSpace = _require.isWhiteSpace;
var filetypes = __webpack_require__(322);
function addEmptyParagraphAfterTable(parts) {
var lastNonEmpty = "";
for (var i = 0, len = parts.length; i < len; i++) {
var p = parts[i];
if (isWhiteSpace(p) || startsWith(p, "<w:bookmarkEnd")) {
continue;
}
if (endsWith(lastNonEmpty, "</w:tbl>")) {
if (!startsWith(p, "<w:p") && !startsWith(p, "<w:tbl") && !startsWith(p, "<w:sectPr")) {
p = "<w:p/>".concat(p);
}
}
lastNonEmpty = p;
parts[i] = p;
}
return parts;
}
// eslint-disable-next-line complexity
function joinUncorrupt(parts, options) {
var contains = options.fileTypeConfig.tagShouldContain || [];
/*
* Before doing this "uncorruption" method here, this was done with the
* `part.emptyValue` trick, however, there were some corruptions that were
* not handled, for example with a template like this :
*
* ------------------------------------------------
* | {-w:p falsy}My para{/falsy} | |
* | {-w:p falsy}My para{/falsy} | |
* ------------------------------------------------
*/
var collecting = "";
var currentlyCollecting = -1;
if (filetypes.docx.indexOf(options.contentType) !== -1) {
parts = addEmptyParagraphAfterTable(parts);
}
var startIndex = -1;
for (var j = 0, len2 = contains.length; j < len2; j++) {
var _contains$j = contains[j],
tag = _contains$j.tag,
shouldContain = _contains$j.shouldContain,
value = _contains$j.value,
drop = _contains$j.drop,
dropParent = _contains$j.dropParent;
for (var i = 0, len = parts.length; i < len; i++) {
var part = parts[i];
if (currentlyCollecting === j) {
if (isEnding(part, tag)) {
currentlyCollecting = -1;
if (dropParent) {
var start = -1;
for (var k = startIndex; k > 0; k--) {
if (isStarting(parts[k], dropParent)) {
start = k;
break;
}
}
for (var _k = start; _k <= parts.length; _k++) {
if (isEnding(parts[_k], dropParent)) {
parts[_k] = "";
break;
}
parts[_k] = "";
}
} else {
for (var _k2 = startIndex; _k2 <= i; _k2++) {
parts[_k2] = "";
}
if (!drop) {
parts[i] = collecting + value + part;
}
}
}
collecting += part;
for (var _k3 = 0, len3 = shouldContain.length; _k3 < len3; _k3++) {
var sc = shouldContain[_k3];
if (isStarting(part, sc)) {
currentlyCollecting = -1;
break;
}
}
}
if (currentlyCollecting === -1 && isStarting(part, tag) &&
/*
* To verify that the part doesn't have multiple tags,
* such as <w:tc><w:p>
*/
part.substr(1).indexOf("<") === -1) {
// self-closing tag such as <w:t/>
if (part[part.length - 2] === "/") {
parts[i] = "";
} else {
startIndex = i;
currentlyCollecting = j;
collecting = part;
}
}
}
}
return parts;
}
module.exports = joinUncorrupt;
/***/ }),
/***/ 245:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var _require = __webpack_require__(207),
pushArray = _require.pushArray,
wordToUtf8 = _require.wordToUtf8,
convertSpaces = _require.convertSpaces;
var xmlMatcher = __webpack_require__(367);
var Lexer = __webpack_require__(263);
var Parser = __webpack_require__(690);
var _render = __webpack_require__(789);
var postrender = __webpack_require__(183);
var resolve = __webpack_require__(945);
var joinUncorrupt = __webpack_require__(208);
function _getFullText(content, tagsXmlArray) {
var matcher = xmlMatcher(content, tagsXmlArray);
var result = matcher.matches.map(function (match) {
return match.array[2];
});
return wordToUtf8(convertSpaces(result.join("")));
}
module.exports = /*#__PURE__*/function () {
function XmlTemplater(content, options) {
_classCallCheck(this, XmlTemplater);
this.cachedParsers = {};
this.content = content;
for (var key in options) {
this[key] = options[key];
}
this.setModules({
inspect: {
filePath: options.filePath
}
});
}
return _createClass(XmlTemplater, [{
key: "resolveTags",
value: function resolveTags(tags) {
var _this = this;
this.tags = tags;
var options = this.getOptions();
var filePath = this.filePath;
options.scopeManager = this.scopeManager;
options.resolve = resolve;
var errors = [];
return Promise.all(this.modules.map(function (module) {
return Promise.resolve(module.preResolve(options))["catch"](function (e) {
errors.push(e);
});
})).then(function () {
if (errors.length !== 0) {
throw errors;
}
return resolve(options).then(function (_ref) {
var resolved = _ref.resolved,
errors = _ref.errors;
errors = errors.map(function (error) {
var _error;
// If a string is thrown, convert it to a real Error
if (!(error instanceof Error)) {
error = new Error(error);
}
/*
* error properties might not be defined if some foreign error
* (unhandled error not thrown by docxtemplater willingly) is
* thrown.
*/
(_error = error).properties || (_error.properties = {});
error.properties.file = filePath;
return error;
});
if (errors.length !== 0) {
throw errors;
}
return Promise.all(resolved).then(function (resolved) {
options.scopeManager.root.finishedResolving = true;
options.scopeManager.resolved = resolved;
_this.setModules({
inspect: {
resolved: resolved,
filePath: filePath
}
});
return resolved;
});
})["catch"](function (error) {
_this.errorChecker(error);
throw error;
});
});
}
}, {
key: "getFullText",
value: function getFullText() {
return _getFullText(this.content, this.fileTypeConfig.tagsXmlTextArray);
}
}, {
key: "setModules",
value: function setModules(obj) {
for (var _i2 = 0, _this$modules2 = this.modules; _i2 < _this$modules2.length; _i2++) {
var _module = _this$modules2[_i2];
_module.set(obj);
}
}
}, {
key: "preparse",
value: function preparse() {
this.allErrors = [];
this.xmllexed = Lexer.xmlparse(this.content, {
text: this.fileTypeConfig.tagsXmlTextArray,
other: this.fileTypeConfig.tagsXmlLexedArray
});
this.setModules({
inspect: {
filePath: this.filePath,
xmllexed: this.xmllexed
}
});
var _Lexer$parse = Lexer.parse(this.xmllexed, this.delimiters, this.syntax, this.fileType),
lexed = _Lexer$parse.lexed,
lexerErrors = _Lexer$parse.errors;
pushArray(this.allErrors, lexerErrors);
this.lexed = lexed;
this.setModules({
inspect: {
filePath: this.filePath,
lexed: this.lexed
}
});
var options = this.getOptions();
this.lexed = Parser.preparse(this.lexed, this.modules, options);
}
}, {
key: "parse",
value: function parse() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
noPostParse = _ref2.noPostParse;
this.setModules({
inspect: {
filePath: this.filePath
}
});
var options = this.getOptions();
this.parsed = Parser.parse(this.lexed, this.modules, options);
this.setModules({
inspect: {
filePath: this.filePath,
parsed: this.parsed
}
});
if (noPostParse) {
return this;
}
// In v4, we could remove this "this.postparse()" so that users have to call this manually.
return this.postparse();
}
}, {
key: "postparse",
value: function postparse() {
var options = this.getOptions();
var _Parser$postparse = Parser.postparse(this.parsed, this.modules, options),
postparsed = _Parser$postparse.postparsed,
postparsedErrors = _Parser$postparse.errors;
this.postparsed = postparsed;
this.setModules({
inspect: {
filePath: this.filePath,
postparsed: this.postparsed
}
});
pushArray(this.allErrors, postparsedErrors);
this.errorChecker(this.allErrors);
return this;
}
}, {
key: "errorChecker",
value: function errorChecker(errors) {
for (var _i4 = 0, _errors2 = errors; _i4 < _errors2.length; _i4++) {
var error = _errors2[_i4];
/*
* error properties might not be defined if some foreign
* (unhandled error not thrown by docxtemplater willingly) is
* thrown.
*/
error.properties || (error.properties = {});
error.properties.file = this.filePath;
}
for (var _i6 = 0, _this$modules4 = this.modules; _i6 < _this$modules4.length; _i6++) {
var _module2 = _this$modules4[_i6];
errors = _module2.errorsTransformer(errors);
}
}
}, {
key: "baseNullGetter",
value: function baseNullGetter(part, sm) {
var _this2 = this;
var value = this.modules.reduce(function (value, module) {
if (value != null) {
return value;
}
return module.nullGetter(part, sm, _this2);
}, null);
if (value != null) {
return value;
}
return this.nullGetter(part, sm);
}
}, {
key: "getOptions",
value: function getOptions() {
return {
compiled: this.postparsed,
cachedParsers: this.cachedParsers,
tags: this.tags,
modules: this.modules,
parser: this.parser,
contentType: this.contentType,
relsType: this.relsType,
baseNullGetter: this.baseNullGetter.bind(this),
filePath: this.filePath,
fileTypeConfig: this.fileTypeConfig,
fileType: this.fileType,
linebreaks: this.linebreaks,
stripInvalidXMLChars: this.stripInvalidXMLChars
};
}
}, {
key: "render",
value: function render(to) {
this.filePath = to;
var options = this.getOptions();
options.resolved = this.scopeManager.resolved;
options.scopeManager = this.scopeManager;
options.render = _render;
options.joinUncorrupt = joinUncorrupt;
var _render2 = _render(options),
errors = _render2.errors,
parts = _render2.parts;
if (errors.length > 0) {
this.allErrors = errors;
this.errorChecker(errors);
return this;
}
this.content = postrender(parts, options);
this.setModules({
inspect: {
filePath: this.filePath,
content: this.content
}
});
return this;
}
}]);
}();
/***/ }),
/***/ 263:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var _require = __webpack_require__(946),
getUnclosedTagException = _require.getUnclosedTagException,
getUnopenedTagException = _require.getUnopenedTagException,
getDuplicateOpenTagException = _require.getDuplicateOpenTagException,
getDuplicateCloseTagException = _require.getDuplicateCloseTagException,
throwMalformedXml = _require.throwMalformedXml,
throwXmlInvalid = _require.throwXmlInvalid,
XTTemplateError = _require.XTTemplateError;
var _require2 = __webpack_require__(207),
isTextStart = _require2.isTextStart,
isTextEnd = _require2.isTextEnd,
wordToUtf8 = _require2.wordToUtf8,
pushArray = _require2.pushArray;
var DELIMITER_NONE = 0,
DELIMITER_EQUAL = 1,
DELIMITER_START = 2,
DELIMITER_END = 3;
function inRange(range, match) {
return range[0] <= match.offset && match.offset < range[1];
}
function updateInTextTag(part, inTextTag) {
if (isTextStart(part)) {
if (inTextTag) {
throwMalformedXml();
}
return true;
}
if (isTextEnd(part)) {
if (!inTextTag) {
throwMalformedXml();
}
return false;
}
return inTextTag;
}
function getTag(tag) {
var position = "";
var start = 1;
var end = tag.indexOf(" ");
if (tag[tag.length - 2] === "/") {
position = "selfclosing";
if (end === -1) {
end = tag.length - 2;
}
} else if (tag[1] === "/") {
start = 2;
position = "end";
if (end === -1) {
end = tag.length - 1;
}
} else {
position = "start";
if (end === -1) {
end = tag.length - 1;
}
}
return {
tag: tag.slice(start, end),
position: position
};
}
function tagMatcher(content, textMatchArray, othersMatchArray) {
var cursor = 0;
var contentLength = content.length;
var allMatches = {};
for (var _i2 = 0; _i2 < textMatchArray.length; _i2++) {
var m = textMatchArray[_i2];
allMatches[m] = true;
}
for (var _i4 = 0; _i4 < othersMatchArray.length; _i4++) {
var _m = othersMatchArray[_i4];
allMatches[_m] = false;
}
var totalMatches = [];
while (cursor < contentLength) {
cursor = content.indexOf("<", cursor);
if (cursor === -1) {
break;
}
var offset = cursor;
var nextOpening = content.indexOf("<", cursor + 1);
cursor = content.indexOf(">", cursor);
if (cursor === -1 || nextOpening !== -1 && cursor > nextOpening) {
throwXmlInvalid(content, offset);
}
var tagText = content.slice(offset, cursor + 1);
var _getTag = getTag(tagText),
tag = _getTag.tag,
position = _getTag.position;
var text = allMatches[tag];
if (text == null) {
continue;
}
totalMatches.push({
type: "tag",
position: position,
text: text,
offset: offset,
value: tagText,
tag: tag
});
}
return totalMatches;
}
function getDe