"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index_esm$1 = require("../../min-dash/dist/index.esm.js");
const index_esm$2 = require("../../saxen/dist/index.esm.js");
const index_esm = require("../../moddle/dist/index.esm.js");
function K(e) {
  return e.xml && e.xml.tagAlias === "lowerCase";
}
var me = {
  xsi: "http://www.w3.org/2001/XMLSchema-instance",
  xml: "http://www.w3.org/XML/1998/namespace"
}, C = "xsi:type";
function Q(e) {
  return e.xml && e.xml.serialize;
}
function Y(e) {
  return Q(e) === C;
}
function ye(e) {
  return Q(e) === "property";
}
function ve(e) {
  return e.charAt(0).toUpperCase() + e.slice(1);
}
function q(e, t) {
  return K(t) ? e.prefix + ":" + ve(e.localName) : e.name;
}
function ge(e, t) {
  var r = e.name, n = e.localName, i = t.xml && t.xml.typePrefix;
  return i && n.indexOf(i) === 0 ? e.prefix + ":" + n.slice(i.length) : r;
}
function Ne(e, t) {
  var r = index_esm.parseNameNS(e), n = t.getPackage(r.prefix);
  return ge(r, n);
}
function P(e) {
  return new Error(e);
}
function T(e) {
  return e.$descriptor;
}
function xe(e) {
  index_esm$1.assign(this, e), this.elementsById = {}, this.references = [], this.warnings = [], this.addReference = function(t) {
    this.references.push(t);
  }, this.addElement = function(t) {
    if (!t)
      throw P("expected element");
    var r = this.elementsById, n = T(t), i = n.idProperty, a;
    if (i && (a = t.get(i.name), a)) {
      if (!/^([a-z][\w-.]*:)?[a-z_][\w-.]*$/i.test(a))
        throw new Error("illegal ID <" + a + ">");
      if (r[a])
        throw P("duplicate ID <" + a + ">");
      r[a] = t;
    }
  }, this.addWarning = function(t) {
    this.warnings.push(t);
  };
}
function M() {
}
M.prototype.handleEnd = function() {
};
M.prototype.handleText = function() {
};
M.prototype.handleNode = function() {
};
function k() {
}
k.prototype = Object.create(M.prototype);
k.prototype.handleNode = function() {
  return this;
};
function z() {
}
z.prototype = Object.create(M.prototype);
z.prototype.handleText = function(e) {
  this.body = (this.body || "") + e;
};
function B(e, t) {
  this.property = e, this.context = t;
}
B.prototype = Object.create(z.prototype);
B.prototype.handleNode = function(e) {
  if (this.element)
    throw P("expected no sub nodes");
  return this.element = this.createReference(e), this;
};
B.prototype.handleEnd = function() {
  this.element.id = this.body;
};
B.prototype.createReference = function(e) {
  return {
    property: this.property.ns.name,
    id: ""
  };
};
function D(e, t) {
  this.element = t, this.propertyDesc = e;
}
D.prototype = Object.create(z.prototype);
D.prototype.handleEnd = function() {
  var e = this.body || "", t = this.element, r = this.propertyDesc;
  e = index_esm.coerceType(r.type, e), r.isMany ? t.get(r.name).push(e) : t.set(r.name, e);
};
function L() {
}
L.prototype = Object.create(z.prototype);
L.prototype.handleNode = function(e) {
  var t = this, r = this.element;
  return r ? t = this.handleChild(e) : (r = this.element = this.createElement(e), this.context.addElement(r)), t;
};
function v(e, t, r) {
  this.model = e, this.type = e.getType(t), this.context = r;
}
v.prototype = Object.create(L.prototype);
v.prototype.addReference = function(e) {
  this.context.addReference(e);
};
v.prototype.handleText = function(e) {
  var t = this.element, r = T(t), n = r.bodyProperty;
  if (!n)
    throw P("unexpected body text <" + e + ">");
  z.prototype.handleText.call(this, e);
};
v.prototype.handleEnd = function() {
  var e = this.body, t = this.element, r = T(t), n = r.bodyProperty;
  n && e !== void 0 && (e = index_esm.coerceType(n.type, e), t.set(n.name, e));
};
v.prototype.createElement = function(e) {
  var t = e.attributes, r = this.type, n = T(r), i = this.context, a = new r({}), s = this.model, o;
  return index_esm$1.forEach(t, function(p, l) {
    var h = n.propertiesByName[l], m;
    h && h.isReference ? h.isMany ? (m = p.split(" "), index_esm$1.forEach(m, function(I) {
      i.addReference({
        element: a,
        property: h.ns.name,
        id: I
      });
    })) : i.addReference({
      element: a,
      property: h.ns.name,
      id: p
    }) : (h ? p = index_esm.coerceType(h.type, p) : l !== "xmlns" && (o = index_esm.parseNameNS(l, n.ns.prefix), s.getPackage(o.prefix) && i.addWarning({
      message: "unknown attribute <" + l + ">",
      element: a,
      property: l,
      value: p
    })), a.set(l, p));
  }), a;
};
v.prototype.getPropertyForNode = function(e) {
  var t = e.name, r = index_esm.parseNameNS(t), n = this.type, i = this.model, a = T(n), s = r.name, o = a.propertiesByName[s], p, l;
  if (o && !o.isAttr)
    return Y(o) && (p = e.attributes[C], p) ? (p = Ne(p, i), l = i.getType(p), index_esm$1.assign({}, o, {
      effectiveType: T(l).name
    })) : o;
  var h = i.getPackage(r.prefix);
  if (h) {
    if (p = q(r, h), l = i.getType(p), o = index_esm$1.find(a.properties, function(m) {
      return !m.isVirtual && !m.isReference && !m.isAttribute && l.hasType(m.type);
    }), o)
      return index_esm$1.assign({}, o, {
        effectiveType: T(l).name
      });
  } else if (o = index_esm$1.find(a.properties, function(m) {
    return !m.isReference && !m.isAttribute && m.type === "Element";
  }), o)
    return o;
  throw P("unrecognized element <" + r.name + ">");
};
v.prototype.toString = function() {
  return "ElementDescriptor[" + T(this.type).name + "]";
};
v.prototype.valueHandler = function(e, t) {
  return new D(e, t);
};
v.prototype.referenceHandler = function(e) {
  return new B(e, this.context);
};
v.prototype.handler = function(e) {
  return e === "Element" ? new U(this.model, e, this.context) : new v(this.model, e, this.context);
};
v.prototype.handleChild = function(e) {
  var t, r, n, i;
  if (t = this.getPropertyForNode(e), n = this.element, r = t.effectiveType || t.type, index_esm.isSimpleType(r))
    return this.valueHandler(t, n);
  t.isReference ? i = this.referenceHandler(t).handleNode(e) : i = this.handler(r).handleNode(e);
  var a = i.element;
  return a !== void 0 && (t.isMany ? n.get(t.name).push(a) : n.set(t.name, a), t.isReference ? (index_esm$1.assign(a, {
    element: n
  }), this.context.addReference(a)) : a.$parent = n), i;
};
function W(e, t, r) {
  v.call(this, e, t, r);
}
W.prototype = Object.create(v.prototype);
W.prototype.createElement = function(e) {
  var t = e.name, r = index_esm.parseNameNS(t), n = this.model, i = this.type, a = n.getPackage(r.prefix), s = a && q(r, a) || t;
  if (!i.hasType(s))
    throw P("unexpected element <" + e.originalName + ">");
  return v.prototype.createElement.call(this, e);
};
function U(e, t, r) {
  this.model = e, this.context = r;
}
U.prototype = Object.create(L.prototype);
U.prototype.createElement = function(e) {
  var t = e.name, r = index_esm.parseNameNS(t), n = r.prefix, i = e.ns[n + "$uri"], a = e.attributes;
  return this.model.createAny(t, i, a);
};
U.prototype.handleChild = function(e) {
  var t = new U(this.model, "Element", this.context).handleNode(e), r = this.element, n = t.element, i;
  return n !== void 0 && (i = r.$children = r.$children || [], i.push(n), n.$parent = r), t;
};
U.prototype.handleEnd = function() {
  this.body && (this.element.$body = this.body);
};
function J(e) {
  e instanceof index_esm.Moddle && (e = {
    model: e
  }), index_esm$1.assign(this, { lax: false }, e);
}
J.prototype.fromXML = function(e, t, r) {
  var n = t.rootHandler;
  t instanceof v ? (n = t, t = {}) : typeof t == "string" ? (n = this.handler(t), t = {}) : typeof n == "string" && (n = this.handler(n));
  var i = this.model, a = this.lax, s = new xe(index_esm$1.assign({}, t, { rootHandler: n })), o = new index_esm$2.Parser({ proxy: true }), p = be();
  n.context = s, p.push(n);
  function l(u, f, d) {
    var y = f(), b = y.line, A = y.column, g = y.data;
    g.charAt(0) === "<" && g.indexOf(" ") !== -1 && (g = g.slice(0, g.indexOf(" ")) + ">");
    var x = "unparsable content " + (g ? g + " " : "") + `detected
	line: ` + b + `
	column: ` + A + `
	nested error: ` + u.message;
    if (d)
      return s.addWarning({
        message: x,
        error: u
      }), true;
    throw P(x);
  }
  function h(u, f) {
    return l(u, f, true);
  }
  function m() {
    var u = s.elementsById, f = s.references, d, y;
    for (d = 0; y = f[d]; d++) {
      var b = y.element, A = u[y.id], g = T(b).propertiesByName[y.property];
      if (A || s.addWarning({
        message: "unresolved reference <" + y.id + ">",
        element: y.element,
        property: y.property,
        value: y.id
      }), g.isMany) {
        var x = b.get(g.name), E = x.indexOf(y);
        E === -1 && (E = x.length), A ? x[E] = A : x.splice(E, 1);
      } else
        b.set(g.name, A);
    }
  }
  function I() {
    p.pop().handleEnd();
  }
  var ne = /^<\?xml /i, ie = / encoding="([^"]+)"/i, ae = /^utf-8$/i;
  function se(u) {
    if (ne.test(u)) {
      var f = ie.exec(u), d = f && f[1];
      !d || ae.test(d) || s.addWarning({
        message: "unsupported document encoding <" + d + ">, falling back to UTF-8"
      });
    }
  }
  function oe(u, f) {
    var d = p.peek();
    try {
      p.push(d.handleNode(u));
    } catch (y) {
      l(y, f, a) && p.push(new k());
    }
  }
  function X(u, f) {
    try {
      p.peek().handleText(u);
    } catch (d) {
      h(d, f);
    }
  }
  function pe(u, f) {
    u.trim() && X(u, f);
  }
  var ue = i.getPackages().reduce(function(u, f) {
    return u[f.uri] = f.prefix, u;
  }, {
    "http://www.w3.org/XML/1998/namespace": "xml"
    // add default xml ns
  });
  return o.ns(ue).on("openTag", function(u, f, d, y) {
    var b = u.attrs || {}, A = Object.keys(b).reduce(function(x, E) {
      var ce = f(b[E]);
      return x[E] = ce, x;
    }, {}), g = {
      name: u.name,
      originalName: u.originalName,
      attributes: A,
      ns: u.ns
    };
    oe(g, y);
  }).on("question", se).on("closeTag", I).on("cdata", X).on("text", function(u, f, d) {
    pe(f(u), d);
  }).on("error", l).on("warn", h), new Promise(function(u, f) {
    var d;
    try {
      o.parse(e), m();
    } catch (x) {
      d = x;
    }
    var y = n.element;
    !d && !y && (d = P("failed to parse document as <" + n.type.$descriptor.name + ">"));
    var b = s.warnings, A = s.references, g = s.elementsById;
    return d ? (d.warnings = b, f(d)) : u({
      rootElement: y,
      elementsById: g,
      references: A,
      warnings: b
    });
  });
};
J.prototype.handler = function(e) {
  return new W(this.model, e);
};
function be() {
  var e = [];
  return Object.defineProperty(e, "peek", {
    value: function() {
      return this[this.length - 1];
    }
  }), e;
}
var we = `<?xml version="1.0" encoding="UTF-8"?>
`, Ae = /<|>|'|"|&|\n\r|\n/g, Z = /<|>|&/g;
function Te(e) {
  var t = {}, r = {}, n = {}, i = [], a = [];
  this.byUri = function(s) {
    return r[s] || e && e.byUri(s);
  }, this.add = function(s, o) {
    r[s.uri] = s, o ? i.push(s) : a.push(s), this.mapPrefix(s.prefix, s.uri);
  }, this.uriByPrefix = function(s) {
    return t[s || "xmlns"];
  }, this.mapPrefix = function(s, o) {
    t[s || "xmlns"] = o;
  }, this.getNSKey = function(s) {
    return s.prefix !== void 0 ? s.uri + "|" + s.prefix : s.uri;
  }, this.logUsed = function(s) {
    var o = s.uri, p = this.getNSKey(s);
    n[p] = this.byUri(o), e && e.logUsed(s);
  }, this.getUsed = function(s) {
    function o(h) {
      var m = p.getNSKey(h);
      return n[m];
    }
    var p = this, l = [].concat(i, a);
    return l.filter(o);
  };
}
function Pe(e) {
  return e.charAt(0).toLowerCase() + e.slice(1);
}
function Ee(e, t) {
  return K(t) ? Pe(e) : e;
}
function ee(e, t) {
  e.super_ = t, e.prototype = Object.create(t.prototype, {
    constructor: {
      value: e,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
}
function te(e) {
  return index_esm$1.isString(e) ? e : (e.prefix ? e.prefix + ":" : "") + e.localName;
}
function Re(e) {
  return e.getUsed().filter(function(t) {
    return t.prefix !== "xml";
  }).map(function(t) {
    var r = "xmlns" + (t.prefix ? ":" + t.prefix : "");
    return { name: r, value: t.uri };
  });
}
function Se(e, t) {
  return t.isGeneric ? index_esm$1.assign({ localName: t.ns.localName }, e) : index_esm$1.assign({ localName: Ee(t.ns.localName, t.$pkg) }, e);
}
function Ue(e, t) {
  return index_esm$1.assign({ localName: t.ns.localName }, e);
}
function ze(e) {
  var t = e.$descriptor;
  return index_esm$1.filter(t.properties, function(r) {
    var n = r.name;
    if (r.isVirtual || !index_esm$1.has(e, n))
      return false;
    var i = e[n];
    return i === r.default || i === null ? false : r.isMany ? i.length : true;
  });
}
var Me = {
  "\n": "#10",
  "\n\r": "#10",
  '"': "#34",
  "'": "#39",
  "<": "#60",
  ">": "#62",
  "&": "#38"
}, Be = {
  "<": "lt",
  ">": "gt",
  "&": "amp"
};
function re(e, t, r) {
  return e = index_esm$1.isString(e) ? e : "" + e, e.replace(t, function(n) {
    return "&" + r[n] + ";";
  });
}
function $e(e) {
  return re(e, Ae, Me);
}
function Ce(e) {
  return re(e, Z, Be);
}
function Le(e) {
  return index_esm$1.filter(e, function(t) {
    return t.isAttr;
  });
}
function He(e) {
  return index_esm$1.filter(e, function(t) {
    return !t.isAttr;
  });
}
function j(e) {
  this.tagName = e;
}
j.prototype.build = function(e) {
  return this.element = e, this;
};
j.prototype.serializeTo = function(e) {
  e.appendIndent().append("<" + this.tagName + ">" + this.element.id + "</" + this.tagName + ">").appendNewLine();
};
function R() {
}
R.prototype.serializeValue = R.prototype.serializeTo = function(e) {
  e.append(
    this.escape ? Ce(this.value) : this.value
  );
};
R.prototype.build = function(e, t) {
  return this.value = t, e.type === "String" && t.search(Z) !== -1 && (this.escape = true), this;
};
function G(e) {
  this.tagName = e;
}
ee(G, R);
G.prototype.serializeTo = function(e) {
  e.appendIndent().append("<" + this.tagName + ">"), this.serializeValue(e), e.append("</" + this.tagName + ">").appendNewLine();
};
function c(e, t) {
  this.body = [], this.attrs = [], this.parent = e, this.propertyDescriptor = t;
}
c.prototype.build = function(e) {
  this.element = e;
  var t = e.$descriptor, r = this.propertyDescriptor, n, i, a = t.isGeneric;
  return a ? n = this.parseGeneric(e) : n = this.parseNsAttributes(e), r ? this.ns = this.nsPropertyTagName(r) : this.ns = this.nsTagName(t), this.tagName = this.addTagName(this.ns), a || (i = ze(e), this.parseAttributes(Le(i)), this.parseContainments(He(i))), this.parseGenericAttributes(e, n), this;
};
c.prototype.nsTagName = function(e) {
  var t = this.logNamespaceUsed(e.ns);
  return Se(t, e);
};
c.prototype.nsPropertyTagName = function(e) {
  var t = this.logNamespaceUsed(e.ns);
  return Ue(t, e);
};
c.prototype.isLocalNs = function(e) {
  return e.uri === this.ns.uri;
};
c.prototype.nsAttributeName = function(e) {
  var t;
  if (index_esm$1.isString(e) ? t = index_esm.parseNameNS(e) : t = e.ns, e.inherited)
    return { localName: t.localName };
  var r = this.logNamespaceUsed(t);
  return this.getNamespaces().logUsed(r), this.isLocalNs(r) ? { localName: t.localName } : index_esm$1.assign({ localName: t.localName }, r);
};
c.prototype.parseGeneric = function(e) {
  var t = this, r = this.body, n = [];
  return index_esm$1.forEach(e, function(i, a) {
    var s;
    a === "$body" ? r.push(new R().build({ type: "String" }, i)) : a === "$children" ? index_esm$1.forEach(i, function(o) {
      r.push(new c(t).build(o));
    }) : a.indexOf("$") !== 0 && (s = t.parseNsAttribute(e, a, i), s && n.push({ name: a, value: i }));
  }), n;
};
c.prototype.parseNsAttribute = function(e, t, r) {
  var n = e.$model, i = index_esm.parseNameNS(t), a;
  if (i.prefix === "xmlns" && (a = { prefix: i.localName, uri: r }), !i.prefix && i.localName === "xmlns" && (a = { uri: r }), !a)
    return {
      name: t,
      value: r
    };
  if (n && n.getPackage(r))
    this.logNamespace(a, true, true);
  else {
    var s = this.logNamespaceUsed(a, true);
    this.getNamespaces().logUsed(s);
  }
};
c.prototype.parseNsAttributes = function(e, t) {
  var r = this, n = e.$attrs, i = [];
  return index_esm$1.forEach(n, function(a, s) {
    var o = r.parseNsAttribute(e, s, a);
    o && i.push(o);
  }), i;
};
c.prototype.parseGenericAttributes = function(e, t) {
  var r = this;
  index_esm$1.forEach(t, function(n) {
    if (n.name !== C)
      try {
        r.addAttribute(r.nsAttributeName(n.name), n.value);
      } catch (i) {
        console.warn(
          "missing namespace information for ",
          n.name,
          "=",
          n.value,
          "on",
          e,
          i
        );
      }
  });
};
c.prototype.parseContainments = function(e) {
  var t = this, r = this.body, n = this.element;
  index_esm$1.forEach(e, function(i) {
    var a = n.get(i.name), s = i.isReference, o = i.isMany;
    if (o || (a = [a]), i.isBody)
      r.push(new R().build(i, a[0]));
    else if (index_esm.isSimpleType(i.type))
      index_esm$1.forEach(a, function(h) {
        r.push(new G(t.addTagName(t.nsPropertyTagName(i))).build(i, h));
      });
    else if (s)
      index_esm$1.forEach(a, function(h) {
        r.push(new j(t.addTagName(t.nsPropertyTagName(i))).build(h));
      });
    else {
      var p = Y(i), l = ye(i);
      index_esm$1.forEach(a, function(h) {
        var m;
        p ? m = new H(t, i) : l ? m = new c(t, i) : m = new c(t), r.push(m.build(h));
      });
    }
  });
};
c.prototype.getNamespaces = function(e) {
  var t = this.namespaces, r = this.parent, n;
  return t || (n = r && r.getNamespaces(), e || !n ? this.namespaces = t = new Te(n) : t = n), t;
};
c.prototype.logNamespace = function(e, t, r) {
  var n = this.getNamespaces(r), i = e.uri, a = e.prefix, s = n.byUri(i);
  return (!s || r) && n.add(e, t), n.mapPrefix(a, i), e;
};
c.prototype.logNamespaceUsed = function(e, t) {
  var r = this.element, n = r.$model, i = this.getNamespaces(t), a = e.prefix, s = e.uri, o, p, l;
  if (!a && !s)
    return { localName: e.localName };
  if (l = me[a] || n && (n.getPackage(a) || {}).uri, s = s || l || i.uriByPrefix(a), !s)
    throw new Error("no namespace uri given for prefix <" + a + ">");
  if (e = i.byUri(s), !e) {
    for (o = a, p = 1; i.uriByPrefix(o); )
      o = a + "_" + p++;
    e = this.logNamespace({ prefix: o, uri: s }, l === s);
  }
  return a && i.mapPrefix(a, s), e;
};
c.prototype.parseAttributes = function(e) {
  var t = this, r = this.element;
  index_esm$1.forEach(e, function(n) {
    var i = r.get(n.name);
    if (n.isReference)
      if (!n.isMany)
        i = i.id;
      else {
        var a = [];
        index_esm$1.forEach(i, function(s) {
          a.push(s.id);
        }), i = a.join(" ");
      }
    t.addAttribute(t.nsAttributeName(n), i);
  });
};
c.prototype.addTagName = function(e) {
  var t = this.logNamespaceUsed(e);
  return this.getNamespaces().logUsed(t), te(e);
};
c.prototype.addAttribute = function(e, t) {
  var r = this.attrs;
  index_esm$1.isString(t) && (t = $e(t));
  var n = index_esm$1.findIndex(r, function(a) {
    return a.name.localName === e.localName && a.name.uri === e.uri && a.name.prefix === e.prefix;
  }), i = { name: e, value: t };
  n !== -1 ? r.splice(n, 1, i) : r.push(i);
};
c.prototype.serializeAttributes = function(e) {
  var t = this.attrs, r = this.namespaces;
  r && (t = Re(r).concat(t)), index_esm$1.forEach(t, function(n) {
    e.append(" ").append(te(n.name)).append('="').append(n.value).append('"');
  });
};
c.prototype.serializeTo = function(e) {
  var t = this.body[0], r = t && t.constructor !== R;
  e.appendIndent().append("<" + this.tagName), this.serializeAttributes(e), e.append(t ? ">" : " />"), t && (r && e.appendNewLine().indent(), index_esm$1.forEach(this.body, function(n) {
    n.serializeTo(e);
  }), r && e.unindent().appendIndent(), e.append("</" + this.tagName + ">")), e.appendNewLine();
};
function H(e, t) {
  c.call(this, e, t);
}
ee(H, c);
H.prototype.parseNsAttributes = function(e) {
  var t = c.prototype.parseNsAttributes.call(this, e), r = e.$descriptor;
  if (r.name === this.propertyDescriptor.type)
    return t;
  var n = this.typeNs = this.nsTagName(r);
  this.getNamespaces().logUsed(this.typeNs);
  var i = e.$model.getPackage(n.uri), a = i.xml && i.xml.typePrefix || "";
  return this.addAttribute(
    this.nsAttributeName(C),
    (n.prefix ? n.prefix + ":" : "") + a + r.ns.localName
  ), t;
};
H.prototype.isLocalNs = function(e) {
  return e.uri === (this.typeNs || this.ns).uri;
};
function Ie() {
  this.value = "", this.write = function(e) {
    this.value += e;
  };
}
function Oe(e, t) {
  var r = [""];
  this.append = function(n) {
    return e.write(n), this;
  }, this.appendNewLine = function() {
    return t && e.write(`
`), this;
  }, this.appendIndent = function() {
    return t && e.write(r.join("  ")), this;
  }, this.indent = function() {
    return r.push(""), this;
  }, this.unindent = function() {
    return r.pop(), this;
  };
}
function We(e) {
  e = index_esm$1.assign({ format: false, preamble: true }, e || {});
  function t(r, n) {
    var i = n || new Ie(), a = new Oe(i, e.format);
    if (e.preamble && a.append(we), new c().build(r).serializeTo(a), !n)
      return i.value;
  }
  return {
    toXML: t
  };
}
exports.Reader = J;
exports.Writer = We;
