"use strict";

var _excluded = ["modules"];
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 _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 _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 _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
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 DocUtils = require("./doc-utils.js");
var z = require("./minizod.js");

// Schema definitions for DXT.ConstructorOptions
var dxtSyntaxSchema = z.object({
  allowUnopenedTag: z["boolean"]().optional(),
  allowUnclosedTag: z["boolean"]().optional(),
  allowUnbalancedLoops: z["boolean"]().optional(),
  changeDelimiterPrefix: z.string().optional().nullable()
});
var dxtOptionsSchema = z.object({
  delimiters: z.object({
    start: z.string().nullable(),
    end: z.string().nullable()
  }).strict().optional(),
  fileTypeConfig: z.object({}).optional(),
  paragraphLoop: z["boolean"]().optional(),
  parser: z["function"]().optional(),
  errorLogging: z.union([z["boolean"](), z.string()]).optional(),
  linebreaks: z["boolean"]().optional(),
  nullGetter: z["function"]().optional(),
  syntax: dxtSyntaxSchema.optional(),
  stripInvalidXMLChars: z["boolean"]().optional()
}).strict();
var _require = require("./get-relation-types.js"),
  getRelsTypes = _require.getRelsTypes;
var _require2 = require("./get-content-types.js"),
  collectContentTypes = _require2.collectContentTypes,
  getContentTypes = _require2.getContentTypes;
var moduleWrapper = require("./module-wrapper.js");
var traits = require("./traits.js");
var commonModule = require("./modules/common.js");
var createScope = require("./scope-manager.js");
var Lexer = require("./lexer.js");
var _require3 = require("./get-tags.js"),
  _getTags = _require3.getTags;
var logErrors = require("./error-logger.js");
var _require4 = require("./errors.js"),
  throwMultiError = _require4.throwMultiError,
  throwResolveBeforeCompile = _require4.throwResolveBeforeCompile,
  throwRenderInvalidTemplate = _require4.throwRenderInvalidTemplate,
  throwRenderTwice = _require4.throwRenderTwice,
  XTInternalError = _require4.XTInternalError,
  XTTemplateError = _require4.XTTemplateError,
  throwFileTypeNotIdentified = _require4.throwFileTypeNotIdentified,
  throwFileTypeNotHandled = _require4.throwFileTypeNotHandled,
  throwApiVersionError = _require4.throwApiVersionError;
DocUtils.getRelsTypes = getRelsTypes;
DocUtils.traits = traits;
DocUtils.moduleWrapper = moduleWrapper;
DocUtils.collectContentTypes = collectContentTypes;
DocUtils.getContentTypes = getContentTypes;
var getDefaults = DocUtils.getDefaults,
  str2xml = DocUtils.str2xml,
  xml2str = DocUtils.xml2str,
  concatArrays = DocUtils.concatArrays,
  uniq = DocUtils.uniq,
  getDuplicates = DocUtils.getDuplicates,
  stableSort = DocUtils.stableSort,
  pushArray = DocUtils.pushArray,
  utf8ToWord = DocUtils.utf8ToWord,
  invertMap = DocUtils.invertMap;
var ctXML = "[Content_Types].xml";
var relsFile = "_rels/.rels";
var currentModuleApiVersion = [3, 47, 2];
function throwIfDuplicateModules(modules) {
  var duplicates = getDuplicates(modules.map(function (_ref) {
    var name = _ref.name;
    return name;
  }));
  if (duplicates.length > 0) {
    throw new XTInternalError("Detected duplicate module \"".concat(duplicates[0], "\""));
  }
}
function addXmlFileNamesFromXmlContentType(doc) {
  for (var _i2 = 0, _doc$modules2 = doc.modules; _i2 < _doc$modules2.length; _i2++) {
    var _module = _doc$modules2[_i2];
    for (var _i4 = 0, _ref3 = _module.xmlContentTypes || []; _i4 < _ref3.length; _i4++) {
      var contentType = _ref3[_i4];
      var candidates = doc.invertedContentTypes[contentType] || [];
      for (var _i6 = 0; _i6 < candidates.length; _i6++) {
        var candidate = candidates[_i6];
        if (doc.zip.files[candidate]) {
          doc.options.xmlFileNames.push(candidate);
        }
      }
    }
  }
}
function reorderModules(modules) {
  /**
   * Modules will be sorted according to priority.
   *
   * Input example:
   * [
   *   { priority: 1, name: "FooMod" },
   *   { priority: -1, name: "XMod" },
   *   { priority: 4, name: "OtherMod" }
   * ]
   *
   * Output example (sorted by priority in descending order):
   * [
   *   { priority: 4, name: "OtherMod" },
   *   { priority: 1, name: "FooMod" },
   *   { priority: -1, name: "XMod" }
   * ]
   * Tested in #test-reorder-modules
   */
  return stableSort(modules, function (m1, m2) {
    return (m2.priority || 0) - (m1.priority || 0);
  });
}
function zipFileOrder(files) {
  var allFiles = [];
  for (var name in files) {
    allFiles.push(name);
  }
  /*
   * The first files that need to be put in the zip file are :
   * [Content_Types].xml and _rels/.rels
   */
  var resultFiles = [ctXML, relsFile];

  /*
   * The next files that should be in the zip file are :
   *
   * - word/* (ie word/document.xml, word/header1.xml, ...)
   * - xl/* (ie xl/worksheets/sheet1.xml)
   * - ppt/* (ie ppt/slides/slide1.xml)
   */
  var prefixes = ["word/", "xl/", "ppt/"];
  for (var _i8 = 0; _i8 < allFiles.length; _i8++) {
    var _name = allFiles[_i8];
    for (var _i0 = 0; _i0 < prefixes.length; _i0++) {
      var prefix = prefixes[_i0];
      if (_name.indexOf("".concat(prefix)) === 0) {
        resultFiles.push(_name);
      }
    }
  }
  /*
   * Push the rest of files, such as docProps/core.xml and docProps/app.xml
   */
  for (var _i10 = 0; _i10 < allFiles.length; _i10++) {
    var _name2 = allFiles[_i10];
    if (resultFiles.indexOf(_name2) === -1) {
      resultFiles.push(_name2);
    }
  }
  return resultFiles;
}
function deprecatedMessage(obj, message) {
  if (obj.hideDeprecations === true) {
    return;
  }
  // eslint-disable-next-line no-console
  console.warn(message);
}
function deprecatedMethod(obj, method) {
  if (obj.hideDeprecations === true) {
    return;
  }
  return deprecatedMessage(obj, "Deprecated method \".".concat(method, "\", view upgrade guide : https://docxtemplater.com/docs/api/#upgrade-guide, stack : ").concat(new Error().stack));
}
function dropUnsupportedFileTypesModules(doc) {
  doc.modules = doc.modules.filter(function (module) {
    if (!module.supportedFileTypes) {
      return true;
    }
    if (!Array.isArray(module.supportedFileTypes)) {
      throw new Error("The supportedFileTypes field of the module must be an array");
    }
    var isSupportedModule = module.supportedFileTypes.includes(doc.fileType);
    if (!isSupportedModule) {
      module.on("detached");
    }
    return isSupportedModule;
  });
}
function verifyErrors(doc) {
  var compiled = doc.compiled;
  doc.errors = concatArrays(Object.keys(compiled).map(function (name) {
    return compiled[name].allErrors;
  }));
  if (doc.errors.length !== 0) {
    if (doc.options.errorLogging) {
      logErrors(doc.errors, doc.options.errorLogging);
    }
    throwMultiError(doc.errors);
  }
}
function isBuffer(v) {
  return typeof Buffer !== "undefined" && typeof Buffer.isBuffer === "function" && Buffer.isBuffer(v);
}
var Docxtemplater = /*#__PURE__*/function () {
  function Docxtemplater(zip) {
    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);
    _classCallCheck(this, Docxtemplater);
    this.targets = [];
    this.rendered = false;
    this.scopeManagers = {};
    this.compiled = {};
    this.modules = [commonModule()];
    this.xmlDocuments = {};
    if (arguments.length === 0) {
      deprecatedMessage(this, "Deprecated docxtemplater constructor with no arguments, view upgrade guide : https://docxtemplater.com/docs/api/#upgrade-guide, stack : ".concat(new Error().stack));
      this.hideDeprecations = true;
      this.setOptions(options);
    } else {
      this.hideDeprecations = true;
      this.setOptions(options);
      if (isBuffer(zip)) {
        throw new Error("You passed a Buffer to the Docxtemplater constructor. The first argument of docxtemplater's constructor must be a valid zip file (jszip v2 or pizzip v3)");
      }
      if (!zip || !zip.files || typeof zip.file !== "function") {
        throw new Error("The first argument of docxtemplater's constructor must be a valid zip file (jszip v2 or pizzip v3)");
      }
      if (!Array.isArray(modules)) {
        throw new Error("The modules argument of docxtemplater's constructor must be an array");
      }
      for (var _i12 = 0; _i12 < modules.length; _i12++) {
        var _module2 = modules[_i12];
        this.attachModule(_module2);
      }
      this.loadZip(zip);
      this.compile();
      this.v4Constructor = true;
    }
    this.hideDeprecations = false;
  }
  return _createClass(Docxtemplater, [{
    key: "verifyApiVersion",
    value: function verifyApiVersion(neededVersion) {
      neededVersion = neededVersion.split(".").map(function (i) {
        return parseInt(i, 10);
      });
      if (neededVersion.length !== 3) {
        throwApiVersionError("neededVersion is not a valid version", {
          neededVersion: neededVersion,
          explanation: "the neededVersion must be an array of length 3"
        });
      }
      if (neededVersion[0] !== currentModuleApiVersion[0]) {
        throwApiVersionError("The major api version do not match, you probably have to update docxtemplater with npm install --save docxtemplater", {
          neededVersion: neededVersion,
          currentModuleApiVersion: currentModuleApiVersion,
          explanation: "moduleAPIVersionMismatch : needed=".concat(neededVersion.join("."), ", current=").concat(currentModuleApiVersion.join("."))
        });
      }
      if (neededVersion[1] > currentModuleApiVersion[1]) {
        throwApiVersionError("The minor api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater", {
          neededVersion: neededVersion,
          currentModuleApiVersion: currentModuleApiVersion,
          explanation: "moduleAPIVersionMismatch : needed=".concat(neededVersion.join("."), ", current=").concat(currentModuleApiVersion.join("."))
        });
      }
      if (neededVersion[1] === currentModuleApiVersion[1] && neededVersion[2] > currentModuleApiVersion[2]) {
        throwApiVersionError("The patch api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater", {
          neededVersion: neededVersion,
          currentModuleApiVersion: currentModuleApiVersion,
          explanation: "moduleAPIVersionMismatch : needed=".concat(neededVersion.join("."), ", current=").concat(currentModuleApiVersion.join("."))
        });
      }
      return true;
    }
  }, {
    key: "setModules",
    value: function setModules(obj) {
      for (var _i14 = 0, _this$modules2 = this.modules; _i14 < _this$modules2.length; _i14++) {
        var _module3 = _this$modules2[_i14];
        _module3.set(obj);
      }
    }
  }, {
    key: "sendEvent",
    value: function sendEvent(eventName) {
      for (var _i16 = 0, _this$modules4 = this.modules; _i16 < _this$modules4.length; _i16++) {
        var _module4 = _this$modules4[_i16];
        _module4.on(eventName);
      }
    }
  }, {
    key: "attachModule",
    value: function attachModule(module) {
      if (this.v4Constructor) {
        throw new XTInternalError("attachModule() should not be called manually when using the v4 constructor");
      }
      deprecatedMethod(this, "attachModule");
      var moduleType = _typeof(module);
      if (moduleType === "function") {
        throw new XTInternalError("Cannot attach a class/function as a module. Most probably you forgot to instantiate the module by using `new` on the module.");
      }
      if (!module || moduleType !== "object") {
        throw new XTInternalError("Cannot attachModule with a falsy value");
      }
      if (module.requiredAPIVersion) {
        this.verifyApiVersion(module.requiredAPIVersion);
      }
      if (module.attached === true) {
        if (typeof module.clone === "function") {
          module = module.clone();
        } else {
          throw new Error("Cannot attach a module that was already attached : \"".concat(module.name, "\". The most likely cause is that you are instantiating the module at the root level, and using it for multiple instances of Docxtemplater"));
        }
      }
      module.attached = true;
      var wrappedModule = moduleWrapper(module);
      this.modules.push(wrappedModule);
      wrappedModule.on("attached");
      if (this.fileType) {
        dropUnsupportedFileTypesModules(this);
      }
      return this;
    }
  }, {
    key: "findModule",
    value: function findModule(name) {
      for (var _i18 = 0, _this$modules6 = this.modules; _i18 < _this$modules6.length; _i18++) {
        var _module5 = _this$modules6[_i18];
        if (_module5.name === name) {
          return _module5;
        }
      }
    }
  }, {
    key: "setOptions",
    value: function setOptions(options) {
      var _this$delimiters, _this$delimiters2;
      if (this.v4Constructor) {
        throw new Error("setOptions() should not be called manually when using the v4 constructor");
      }
      if (!options) {
        throw new Error("setOptions should be called with an object as first parameter");
      }
      var result = dxtOptionsSchema.validate(options);
      if (result.success === false) {
        throw new Error(result.error);
      }
      deprecatedMethod(this, "setOptions");
      this.options = {};
      var defaults = getDefaults();
      for (var key in defaults) {
        var defaultValue = defaults[key];
        this.options[key] = options[key] != null ? options[key] : this[key] || defaultValue;
        this[key] = this.options[key];
      }
      (_this$delimiters = this.delimiters).start && (_this$delimiters.start = utf8ToWord(this.delimiters.start));
      (_this$delimiters2 = this.delimiters).end && (_this$delimiters2.end = utf8ToWord(this.delimiters.end));
      return this;
    }
  }, {
    key: "loadZip",
    value: function loadZip(zip) {
      if (this.v4Constructor) {
        throw new Error("loadZip() should not be called manually when using the v4 constructor");
      }
      deprecatedMethod(this, "loadZip");
      if (zip.loadAsync) {
        throw new XTInternalError("Docxtemplater doesn't handle JSZip version >=3, please use pizzip");
      }
      this.zip = zip;
      this.updateFileTypeConfig();
      this.modules = concatArrays([this.fileTypeConfig.baseModules.map(function (moduleFunction) {
        return moduleFunction();
      }), this.modules]);
      for (var _i20 = 0, _this$modules8 = this.modules; _i20 < _this$modules8.length; _i20++) {
        var _module6 = _this$modules8[_i20];
        _module6.zip = this.zip;
        _module6.docxtemplater = this;
        _module6.fileTypeConfig = this.fileTypeConfig;
        _module6.fileType = this.fileType;
        _module6.xtOptions = this.options;
        _module6.modules = this.modules;
      }
      dropUnsupportedFileTypesModules(this);
      return this;
    }
  }, {
    key: "precompileFile",
    value: function precompileFile(fileName) {
      var currentFile = this.createTemplateClass(fileName);
      currentFile.preparse();
      this.compiled[fileName] = currentFile;
    }
  }, {
    key: "compileFile",
    value: function compileFile(fileName) {
      this.compiled[fileName].parse();
    }
  }, {
    key: "getScopeManager",
    value: function getScopeManager(to, currentFile, tags) {
      var _this$scopeManagers;
      (_this$scopeManagers = this.scopeManagers)[to] || (_this$scopeManagers[to] = createScope({
        tags: tags,
        parser: this.parser,
        cachedParsers: currentFile.cachedParsers
      }));
      return this.scopeManagers[to];
    }
  }, {
    key: "resolveData",
    value: function resolveData(data) {
      var _this = this;
      deprecatedMethod(this, "resolveData");
      var errors = [];
      if (!Object.keys(this.compiled).length) {
        throwResolveBeforeCompile();
      }
      return Promise.resolve(data).then(function (data) {
        _this.data = data;
        _this.setModules({
          data: _this.data,
          Lexer: Lexer
        });
        _this.mapper = _this.modules.reduce(function (value, module) {
          return module.getRenderedMap(value);
        }, {});
        return Promise.all(Object.keys(_this.mapper).map(function (to) {
          var _this$mapper$to = _this.mapper[to],
            from = _this$mapper$to.from,
            data = _this$mapper$to.data;
          return Promise.resolve(data).then(function (data) {
            var currentFile = _this.compiled[from];
            currentFile.filePath = to;
            currentFile.scopeManager = _this.getScopeManager(to, currentFile, data);
            return currentFile.resolveTags(data).then(function (result) {
              currentFile.scopeManager.finishedResolving = true;
              return result;
            }, function (errs) {
              pushArray(errors, errs);
            });
          });
        })).then(function (resolved) {
          if (errors.length !== 0) {
            if (_this.options.errorLogging) {
              logErrors(errors, _this.options.errorLogging);
            }
            throwMultiError(errors);
          }
          return concatArrays(resolved);
        });
      });
    }
  }, {
    key: "compile",
    value: function compile() {
      deprecatedMethod(this, "compile");
      this.updateFileTypeConfig();
      throwIfDuplicateModules(this.modules);
      this.modules = reorderModules(this.modules);
      if (Object.keys(this.compiled).length) {
        return this;
      }
      var options = this.options;
      for (var _i22 = 0, _this$modules0 = this.modules; _i22 < _this$modules0.length; _i22++) {
        var _module7 = _this$modules0[_i22];
        options = _module7.optionsTransformer(options, this);
      }
      this.options = options;
      this.options.xmlFileNames = uniq(this.options.xmlFileNames);
      for (var _i24 = 0, _this$options$xmlFile2 = this.options.xmlFileNames; _i24 < _this$options$xmlFile2.length; _i24++) {
        var fileName = _this$options$xmlFile2[_i24];
        var content = this.zip.files[fileName].asText();
        this.xmlDocuments[fileName] = str2xml(content);
      }
      this.setModules({
        zip: this.zip,
        xmlDocuments: this.xmlDocuments
      });
      for (var _i26 = 0, _this$modules10 = this.modules; _i26 < _this$modules10.length; _i26++) {
        var _module8 = _this$modules10[_i26];
        _module8.xmlDocuments = this.xmlDocuments;
      }
      this.getTemplatedFiles();
      /*
       * Loop inside all templatedFiles (ie xml files with content).
       * Sometimes they don't exist (footer.xml for example)
       */
      this.sendEvent("before-preparse");
      for (var _i28 = 0, _this$templatedFiles2 = this.templatedFiles; _i28 < _this$templatedFiles2.length; _i28++) {
        var _fileName = _this$templatedFiles2[_i28];
        if (this.zip.files[_fileName] != null) {
          this.precompileFile(_fileName);
        }
      }
      this.sendEvent("after-preparse");
      for (var _i30 = 0, _this$templatedFiles4 = this.templatedFiles; _i30 < _this$templatedFiles4.length; _i30++) {
        var _fileName2 = _this$templatedFiles4[_i30];
        if (this.zip.files[_fileName2] != null) {
          this.compiled[_fileName2].parse({
            noPostParse: true
          });
        }
      }
      this.sendEvent("after-parse");
      for (var _i32 = 0, _this$templatedFiles6 = this.templatedFiles; _i32 < _this$templatedFiles6.length; _i32++) {
        var _fileName3 = _this$templatedFiles6[_i32];
        if (this.zip.files[_fileName3] != null) {
          this.compiled[_fileName3].postparse();
        }
      }
      this.sendEvent("after-postparse");
      this.setModules({
        compiled: this.compiled
      });
      verifyErrors(this);
      return this;
    }
  }, {
    key: "updateFileTypeConfig",
    value: function updateFileTypeConfig() {
      this.relsTypes = getRelsTypes(this.zip);
      var _getContentTypes = getContentTypes(this.zip),
        overrides = _getContentTypes.overrides,
        defaults = _getContentTypes.defaults,
        contentTypes = _getContentTypes.contentTypes,
        contentTypeXml = _getContentTypes.contentTypeXml;
      if (contentTypeXml) {
        this.filesContentTypes = collectContentTypes(overrides, defaults, this.zip);
        this.invertedContentTypes = invertMap(this.filesContentTypes);
        this.setModules({
          contentTypes: this.contentTypes,
          invertedContentTypes: this.invertedContentTypes
        });
      }
      var fileType;
      if (this.zip.files.mimetype) {
        fileType = "odt";
      }
      for (var _i34 = 0, _this$modules12 = this.modules; _i34 < _this$modules12.length; _i34++) {
        var _module9 = _this$modules12[_i34];
        fileType = _module9.getFileType({
          zip: this.zip,
          contentTypes: contentTypes,
          contentTypeXml: contentTypeXml,
          overrides: overrides,
          defaults: defaults,
          doc: this
        }) || fileType;
      }
      this.fileType = fileType;
      if (fileType === "odt") {
        throwFileTypeNotHandled(fileType);
      }
      if (!fileType) {
        throwFileTypeNotIdentified(this.zip);
      }
      addXmlFileNamesFromXmlContentType(this);
      dropUnsupportedFileTypesModules(this);
      this.fileTypeConfig = this.options.fileTypeConfig || this.fileTypeConfig;
      if (!this.fileTypeConfig) {
        if (Docxtemplater.FileTypeConfig[this.fileType]) {
          this.fileTypeConfig = Docxtemplater.FileTypeConfig[this.fileType]();
        } else {
          /*
           * Error case handled since v3.60.2
           * Throw specific error when trying to template xlsx file without xlsxmodule
           */
          var message = "Filetype \"".concat(this.fileType, "\" is not supported");
          var id = "filetype_not_supported";
          if (this.fileType === "xlsx") {
            message = "Filetype \"".concat(this.fileType, "\" is supported only with the paid XlsxModule");
            id = "xlsx_filetype_needs_xlsx_module";
          }
          var err = new XTTemplateError(message);
          err.properties = {
            id: id,
            explanation: message
          };
          throw err;
        }
      }
      return this;
    }
  }, {
    key: "renderAsync",
    value: function renderAsync(data) {
      var _this2 = this;
      this.hideDeprecations = true;
      var promise = this.resolveData(data);
      this.hideDeprecations = false;
      return promise.then(function () {
        return _this2.render();
      });
    }
  }, {
    key: "render",
    value: function render(data) {
      if (this.rendered) {
        throwRenderTwice();
      }
      this.rendered = true;
      if (Object.keys(this.compiled).length === 0) {
        this.compile();
      }
      if (this.errors.length > 0) {
        throwRenderInvalidTemplate();
      }
      if (arguments.length > 0) {
        this.data = data;
      }
      this.setModules({
        data: this.data,
        Lexer: Lexer
      });
      this.mapper || (this.mapper = this.modules.reduce(function (value, module) {
        return module.getRenderedMap(value);
      }, {}));
      var output = [];
      for (var to in this.mapper) {
        var _this$mapper$to2 = this.mapper[to],
          from = _this$mapper$to2.from,
          _data = _this$mapper$to2.data;
        var currentFile = this.compiled[from];
        currentFile.scopeManager = this.getScopeManager(to, currentFile, _data);
        currentFile.render(to);
        output.push([to, currentFile.content, currentFile]);
        delete currentFile.content;
      }
      for (var _i36 = 0; _i36 < output.length; _i36++) {
        var outputPart = output[_i36];
        var _outputPart = _slicedToArray(outputPart, 3),
          content = _outputPart[1],
          _currentFile = _outputPart[2];
        for (var _i38 = 0, _this$modules14 = this.modules; _i38 < _this$modules14.length; _i38++) {
          var _module0 = _this$modules14[_i38];
          if (_module0.preZip) {
            var result = _module0.preZip(content, _currentFile);
            if (typeof result === "string") {
              outputPart[1] = result;
            }
          }
        }
      }
      for (var _i40 = 0; _i40 < output.length; _i40++) {
        var _output$_i = _slicedToArray(output[_i40], 2),
          _to = _output$_i[0],
          _content = _output$_i[1];
        this.zip.file(_to, _content, {
          createFolders: true
        });
      }
      verifyErrors(this);
      this.sendEvent("syncing-zip");
      this.syncZip();
      // The synced-zip event is used in the subtemplate module for example
      this.sendEvent("synced-zip");
      return this;
    }
  }, {
    key: "syncZip",
    value: function syncZip() {
      for (var fileName in this.xmlDocuments) {
        this.zip.remove(fileName);
        var content = xml2str(this.xmlDocuments[fileName]);
        this.zip.file(fileName, content, {
          createFolders: true
        });
      }
    }
  }, {
    key: "setData",
    value: function setData(data) {
      deprecatedMethod(this, "setData");
      this.data = data;
      return this;
    }
  }, {
    key: "getZip",
    value: function getZip() {
      return this.zip;
    }
  }, {
    key: "createTemplateClass",
    value: function createTemplateClass(path) {
      var content = this.zip.files[path].asText();
      return this.createTemplateClassFromContent(content, path);
    }
  }, {
    key: "createTemplateClassFromContent",
    value: function createTemplateClassFromContent(content, filePath) {
      var xmltOptions = {
        filePath: filePath,
        contentType: this.filesContentTypes[filePath],
        relsType: this.relsTypes[filePath]
      };
      var defaults = getDefaults();
      var defaultKeys = pushArray(Object.keys(defaults), ["filesContentTypes", "fileTypeConfig", "fileType", "modules"]);
      for (var _i42 = 0; _i42 < defaultKeys.length; _i42++) {
        var key = defaultKeys[_i42];
        xmltOptions[key] = this[key];
      }
      return new Docxtemplater.XmlTemplater(content, xmltOptions);
    }
  }, {
    key: "getFullText",
    value: function getFullText(path) {
      return this.createTemplateClass(path || this.fileTypeConfig.textPath(this)).getFullText();
    }
  }, {
    key: "getTemplatedFiles",
    value: function getTemplatedFiles() {
      this.templatedFiles = this.fileTypeConfig.getTemplatedFiles(this.zip);
      pushArray(this.templatedFiles, this.targets);
      this.templatedFiles = uniq(this.templatedFiles);
      return this.templatedFiles;
    }
  }, {
    key: "getTags",
    value: function getTags() {
      var result = {
        headers: [],
        footers: []
      };
      for (var key in this.compiled) {
        var contentType = this.filesContentTypes[key];
        if (contentType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") {
          result.document = {
            target: key,
            tags: _getTags(this.compiled[key].postparsed)
          };
        }
        if (contentType === "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml") {
          result.headers.push({
            target: key,
            tags: _getTags(this.compiled[key].postparsed)
          });
        }
        if (contentType === "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml") {
          result.footers.push({
            target: key,
            tags: _getTags(this.compiled[key].postparsed)
          });
        }
      }
      return result;
    }

    /* Export functions, present since 3.62.0 */
  }, {
    key: "toBuffer",
    value: function toBuffer(options) {
      return this.zip.generate(_objectSpread(_objectSpread({
        compression: "DEFLATE",
        fileOrder: zipFileOrder
      }, options), {}, {
        type: "nodebuffer"
      }));
    }
    /* Export functions, present since 3.62.0 */
  }, {
    key: "toBlob",
    value: function toBlob(options) {
      return this.zip.generate(_objectSpread(_objectSpread({
        compression: "DEFLATE",
        fileOrder: zipFileOrder
      }, options), {}, {
        type: "blob"
      }));
    }
    /* Export functions, present since 3.62.0 */
  }, {
    key: "toBase64",
    value: function toBase64(options) {
      return this.zip.generate(_objectSpread(_objectSpread({
        compression: "DEFLATE",
        fileOrder: zipFileOrder
      }, options), {}, {
        type: "base64"
      }));
    }
    /* Export functions, present since 3.62.0 */
  }, {
    key: "toUint8Array",
    value: function toUint8Array(options) {
      return this.zip.generate(_objectSpread(_objectSpread({
        compression: "DEFLATE",
        fileOrder: zipFileOrder
      }, options), {}, {
        type: "uint8array"
      }));
    }
    /* Export functions, present since 3.62.0 */
  }, {
    key: "toArrayBuffer",
    value: function toArrayBuffer(options) {
      return this.zip.generate(_objectSpread(_objectSpread({
        compression: "DEFLATE",
        fileOrder: zipFileOrder
      }, options), {}, {
        type: "arraybuffer"
      }));
    }
  }]);
}();
Docxtemplater.DocUtils = DocUtils;
Docxtemplater.Errors = require("./errors.js");
Docxtemplater.XmlTemplater = require("./xml-templater.js");
Docxtemplater.FileTypeConfig = require("./file-type-config.js");
Docxtemplater.XmlMatcher = require("./xml-matcher.js");
module.exports = Docxtemplater;
module.exports["default"] = Docxtemplater;