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99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// DasuMae Doc core -- minimal, offset-aware, namespace-aware XML parser and
// structure-aware splice editor.
//
// Why not DOMParser/XMLSerializer? Per the design, re-serializing an OOXML
// part risks mangling namespace prefixes and whitespace. Instead this parser
// records the exact source byte offsets of every element, attribute, and text
// node, and all edits are performed as *splices on the original source string*.
// Parts we do not touch are never reparsed or reserialized; parts we do touch
// keep every byte outside the edited regions identical. This is the
// "structure-aware transform" the design calls for: edits are expressed at the
// element/attribute level (remove node, unwrap node, replace inner text, remove
// attribute), not as fragile substring hacks.

/** @typedef {{prefix:string, local:string, ns:string, name:string, value:string, start:number, end:number}} Attr */

export class XmlNode {
  constructor(type) {
    this.type = type; // 'element' | 'text' | 'cdata' | 'comment' | 'pi' | 'decl'
    this.prefix = '';
    this.local = '';
    this.ns = '';
    this.name = ''; // raw qualified name as written
    /** @type {Attr[]} */
    this.attrs = [];
    /** @type {XmlNode[]} */
    this.children = [];
    this.parent = null;
    // byte offsets into source
    this.start = 0; // '<' of this node
    this.openEnd = 0; // index just past '>' of the open/self-closing tag
    this.closeStart = 0; // '<' of the closing tag (== end for self-closing/void)
    this.end = 0; // index just past the node
    this.selfClosing = false;
    this.text = ''; // for text/cdata/comment: the raw inner value
  }

  attr(ns, local) {
    for (const a of this.attrs) {
      if (a.local === local && (ns == null || a.ns === ns)) return a.value;
    }
    return null;
  }

  // attribute match by local name only, ignoring namespace (useful for attrs
  // that are conventionally unprefixed, e.g. relationship Target/Type).
  attrLocal(local) {
    for (const a of this.attrs) if (a.local === local) return a.value;
    return null;
  }

  attrNode(ns, local) {
    for (const a of this.attrs) {
      if (a.local === local && (ns == null || a.ns === ns)) return a;
    }
    return null;
  }

  // Direct element children, optionally filtered by (ns, local).
  elements(ns, local) {
    const out = [];
    for (const c of this.children) {
      if (c.type !== 'element') continue;
      if (ns != null && c.ns !== ns) continue;
      if (local != null && c.local !== local) continue;
      out.push(c);
    }
    return out;
  }

  // Concatenated text of descendant text/cdata nodes, in document order.
  // skip(node) -> true to prune an element's entire subtree (e.g. w:delText,
  // or runs that carry w:vanish).
  textContent(skip) {
    let out = '';
    const walk = (n) => {
      if (n.type === 'text' || n.type === 'cdata') {
        out += decodeEntities(n.text);
        return;
      }
      if (n.type !== 'element') return;
      if (skip && skip(n)) return;
      for (const c of n.children) walk(c);
    };
    for (const c of this.children) walk(c);
    return out;
  }
}

export class XmlDoc {
  constructor(source, root, all) {
    this.source = source;
    this.root = root;
    this._all = all; // flat list of all element nodes
  }

  // All element nodes in document order matching (ns, local); either may be null.
  find(ns, local) {
    const out = [];
    for (const n of this._all) {
      if (ns != null && n.ns !== ns) continue;
      if (local != null && n.local !== local) continue;
      out.push(n);
    }
    return out;
  }

  all() {
    return this._all;
  }
}

const NAME_START = /[A-Za-z_:]/;

export function parseXml(source) {
  if (typeof source !== 'string') source = new TextDecoder('utf-8').decode(source);
  let i = 0;
  const n = source.length;
  const all = [];
  // namespace scope stack: array of maps prefix->uri (''-> default ns)
  const scope = [{ '': '', xml: 'http://www.w3.org/XML/1998/namespace' }];

  function resolve(prefix) {
    for (let s = scope.length - 1; s >= 0; s--) {
      if (prefix in scope[s]) return scope[s][prefix];
    }
    return '';
  }

  function parseNodes(parentStopName) {
    const nodes = [];
    while (i < n) {
      if (source[i] === '<') {
        if (source.startsWith('<!--', i)) {
          const node = new XmlNode('comment');
          node.start = i;
          const close = source.indexOf('-->', i + 4);
          const endIdx = close === -1 ? n : close + 3;
          node.text = source.slice(i + 4, close === -1 ? n : close);
          node.end = node.openEnd = node.closeStart = endIdx;
          i = endIdx;
          nodes.push(node);
          continue;
        }
        if (source.startsWith('<![CDATA[', i)) {
          const node = new XmlNode('cdata');
          node.start = i;
          const close = source.indexOf(']]>', i + 9);
          const endIdx = close === -1 ? n : close + 3;
          node.text = source.slice(i + 9, close === -1 ? n : close);
          node.end = node.openEnd = node.closeStart = endIdx;
          i = endIdx;
          nodes.push(node);
          continue;
        }
        if (source.startsWith('<?', i)) {
          const node = new XmlNode(source.startsWith('<?xml', i) ? 'decl' : 'pi');
          node.start = i;
          const close = source.indexOf('?>', i + 2);
          const endIdx = close === -1 ? n : close + 2;
          node.text = source.slice(i + 2, close === -1 ? n : close);
          node.end = node.openEnd = node.closeStart = endIdx;
          i = endIdx;
          nodes.push(node);
          continue;
        }
        if (source.startsWith('<!', i)) {
          // DOCTYPE or similar -- skip to matching '>'
          const node = new XmlNode('pi');
          node.start = i;
          const close = source.indexOf('>', i + 2);
          const endIdx = close === -1 ? n : close + 1;
          node.end = node.openEnd = node.closeStart = endIdx;
          i = endIdx;
          nodes.push(node);
          continue;
        }
        if (source[i + 1] === '/') {
          // closing tag -- belongs to parent; stop.
          return nodes;
        }
        // opening or self-closing element
        const node = parseElement();
        nodes.push(node);
        continue;
      }
      // text run
      const lt = source.indexOf('<', i);
      const endIdx = lt === -1 ? n : lt;
      const node = new XmlNode('text');
      node.start = i;
      node.end = node.openEnd = node.closeStart = endIdx;
      node.text = source.slice(i, endIdx);
      i = endIdx;
      nodes.push(node);
    }
    return nodes;
  }

  function parseElement() {
    const node = new XmlNode('element');
    node.start = i;
    i++; // consume '<'
    const nameStart = i;
    while (i < n && !/[\s/>]/.test(source[i])) i++;
    node.name = source.slice(nameStart, i);
    const ci = node.name.indexOf(':');
    if (ci === -1) {
      node.prefix = '';
      node.local = node.name;
    } else {
      node.prefix = node.name.slice(0, ci);
      node.local = node.name.slice(ci + 1);
    }

    // parse attributes; record raw spans
    const rawAttrs = [];
    while (i < n) {
      // record leading whitespace start
      const wsStart = i;
      while (i < n && /\s/.test(source[i])) i++;
      if (i >= n) break;
      if (source[i] === '/' || source[i] === '>') break;
      const aStart = i; // name start (no leading ws)
      while (i < n && !/[\s=/>]/.test(source[i])) i++;
      const aName = source.slice(aStart, i);
      while (i < n && /\s/.test(source[i])) i++;
      let aValue = '';
      if (source[i] === '=') {
        i++; // '='
        while (i < n && /\s/.test(source[i])) i++;
        const q = source[i];
        if (q === '"' || q === "'") {
          i++;
          const vStart = i;
          while (i < n && source[i] !== q) i++;
          aValue = source.slice(vStart, i);
          i++; // closing quote
        }
      }
      const aEnd = i;
      rawAttrs.push({ name: aName, value: aValue, start: wsStart, end: aEnd });
    }

    // push a new namespace scope from xmlns attrs
    const localScope = {};
    for (const a of rawAttrs) {
      if (a.name === 'xmlns') localScope[''] = decodeEntities(a.value);
      else if (a.name.startsWith('xmlns:')) localScope[a.name.slice(6)] = decodeEntities(a.value);
    }
    scope.push(localScope);

    // resolve attr namespaces (unprefixed attrs have NO namespace)
    for (const a of rawAttrs) {
      const ci2 = a.name.indexOf(':');
      let prefix = '';
      let local = a.name;
      if (ci2 !== -1) {
        prefix = a.name.slice(0, ci2);
        local = a.name.slice(ci2 + 1);
      }
      const ns = prefix === '' ? '' : resolve(prefix);
      node.attrs.push({
        prefix, local, ns, name: a.name, value: decodeEntities(a.value),
        start: a.start, end: a.end,
      });
    }

    node.ns = resolve(node.prefix);

    // consume '/>' or '>'
    if (source[i] === '/') {
      node.selfClosing = true;
      i += 2; // '/>'
      node.openEnd = node.closeStart = node.end = i;
      scope.pop();
      all.push(node);
      return node;
    }
    i++; // '>'
    node.openEnd = i;

    // children
    const children = parseNodes(node.name);
    for (const c of children) {
      c.parent = node;
      node.children.push(c);
    }
    // closing tag
    if (source.startsWith('</', i)) {
      node.closeStart = i;
      const gt = source.indexOf('>', i);
      i = gt === -1 ? n : gt + 1;
      node.end = i;
    } else {
      node.closeStart = node.end = i;
    }
    scope.pop();
    all.push(node);
    return node;
  }

  const top = parseNodes(null);
  let root = null;
  for (const node of top) {
    if (node.type === 'element') { root = node; break; }
  }
  return new XmlDoc(source, root, all);
}

export function decodeEntities(s) {
  if (s.indexOf('&') === -1) return s;
  return s.replace(/&(#x?[0-9A-Fa-f]+|[a-zA-Z]+);/g, (m, g) => {
    switch (g) {
      case 'amp': return '&';
      case 'lt': return '<';
      case 'gt': return '>';
      case 'quot': return '"';
      case 'apos': return "'";
      default:
        if (g[0] === '#') {
          const code = g[1] === 'x' || g[1] === 'X'
            ? parseInt(g.slice(2), 16)
            : parseInt(g.slice(1), 10);
          if (!isNaN(code)) return String.fromCodePoint(code);
        }
        return m;
    }
  });
}

export function escapeXml(s) {
  return String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

export function escapeAttr(s) {
  return escapeXml(s).replace(/"/g, '&quot;');
}

// ---------------------------------------------------------------------------
// Splice editor: collect edits against the ORIGINAL source, apply last-first so
// offsets stay valid. Overlapping edits are rejected.
// ---------------------------------------------------------------------------
export class XmlEditor {
  constructor(doc) {
    this.doc = doc;
    this.source = doc.source;
    this.edits = []; // {start, end, text}
  }

  _splice(start, end, text) {
    this.edits.push({ start, end, text });
  }

  removeNode(node) {
    this._splice(node.start, node.end, '');
    return this;
  }

  // Replace the whole element with its inner content (drop open+close tags).
  unwrapNode(node) {
    if (node.selfClosing) { this._splice(node.start, node.end, ''); return this; }
    this._splice(node.start, node.openEnd, '');
    this._splice(node.closeStart, node.end, '');
    return this;
  }

  replaceInnerText(node, text) {
    if (node.selfClosing) return this; // cannot hold text
    this._splice(node.openEnd, node.closeStart, escapeXml(text));
    return this;
  }

  removeAttr(attrNode) {
    if (!attrNode) return this;
    this._splice(attrNode.start, attrNode.end, '');
    return this;
  }

  replaceNode(node, text) {
    this._splice(node.start, node.end, text);
    return this;
  }

  isEmpty() {
    return this.edits.length === 0;
  }

  apply() {
    const edits = this.edits.slice().sort((a, b) => b.start - a.start || b.end - a.end);
    // reject overlaps
    for (let k = 0; k < edits.length - 1; k++) {
      const cur = edits[k];
      const next = edits[k + 1];
      if (next.end > cur.start) {
        throw new Error(`overlapping XML edits at ${next.start}-${next.end} and ${cur.start}-${cur.end}`);
      }
    }
    let s = this.source;
    for (const e of edits) s = s.slice(0, e.start) + e.text + s.slice(e.end);
    return s;
  }
}