@ohos-ports/html-minifier-next 8.4.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,1069 @@
1
+ /*
2
+ * HTML Parser By John Resig (ejohn.org)
3
+ * Modified by Juriy “kangax” Zaytsev and Jens Oliver Meiert
4
+ * Original code by Erik Arvidsson, Mozilla Public License
5
+ * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
6
+ */
7
+
8
+ import { isThenable, embedSource, findTagEnd } from './lib/utils.js';
9
+ import { endlessRawTextElements, escapableRawTextElements, genericRawTextElements, RE_HTML_ENCODING } from './lib/constants.js';
10
+
11
+ /** @import { HTMLAttribute } from './lib/attributes.js' */
12
+
13
+ // Type definitions
14
+
15
+ /**
16
+ * @typedef {{
17
+ * start?: Function,
18
+ * end?: Function,
19
+ * chars?: Function,
20
+ * comment?: Function,
21
+ * doctype?: Function,
22
+ * continueOnParseError?: boolean | undefined,
23
+ * partialMarkup?: boolean | undefined,
24
+ * wantsNextTag?: boolean | undefined,
25
+ * selfClosingSlash?: boolean | undefined,
26
+ * customAttrSurround?: RegExp[][] | undefined,
27
+ * customAttrAssign?: RegExp[] | undefined
28
+ * }} HTMLParserHandler
29
+ */
30
+
31
+ /*
32
+ * Use like so:
33
+ *
34
+ * HTMLParser(htmlString, {
35
+ * start: function(tag, attrs, unary) {},
36
+ * end: function(tag) {},
37
+ * chars: function(text) {},
38
+ * comment: function(text) {}
39
+ * });
40
+ */
41
+
42
+ // Regular expressions for parsing tags and attributes
43
+ const singleAttrIdentifier = /([^\s"'<>/=]+)/;
44
+ const singleAttrAssigns = [/=/];
45
+ const singleAttrValues = [
46
+ // Attr value double quotes
47
+ /"([^"]*)"+/.source,
48
+ // Attr value, single quotes
49
+ /'([^']*)'+/.source,
50
+ // Attr value, no quotes (strict: excludes `=` per HTML spec)
51
+ /([^ \t\n\f\r"'`=<>]+)/.source
52
+ ];
53
+ // Lenient unquoted value pattern for `continueOnParseError`:
54
+ // allows `<`, `=`, and ``` per HTML error-recovery rules
55
+ // (all are parse errors in unquoted-attribute-value state but appended to the value)
56
+ // `"` and `'` remain excluded—permitting them requires broader test coverage
57
+ const singleAttrValueLenientUnquoted = /([^ \t\n\f\r"'>]+)/.source;
58
+ // https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
59
+ const qnameCapture = (function () {
60
+ // https://www.npmjs.com/package/ncname
61
+ const combiningChar = '\u0300-\u0345\u0360\u0361\u0483-\u0486\u0591-\u05A1\u05A3-\u05B9\u05BB-\u05BD\u05BF\u05C1\u05C2\u05C4\u064B-\u0652\u0670\u06D6-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0901-\u0903\u093C\u093E-\u094D\u0951-\u0954\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A02\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A70\u0A71\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0B01-\u0B03\u0B3C\u0B3E-\u0B43\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B82\u0B83\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C82\u0C83\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0D02\u0D03\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86-\u0F8B\u0F90-\u0F95\u0F97\u0F99-\u0FAD\u0FB1-\u0FB7\u0FB9\u20D0-\u20DC\u20E1\u302A-\u302F\u3099\u309A';
62
+ const digit = '0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE7-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29';
63
+ const extender = '\xB7\u02D0\u02D1\u0387\u0640\u0E46\u0EC6\u3005\u3031-\u3035\u309D\u309E\u30FC-\u30FE';
64
+ const letter = 'A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7\u04C8\u04CB\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B36-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60\u0D61\u0E01-\u0E2E\u0E30\u0E32\u0E33\u0E40-\u0E45\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102\u1103\u1105-\u1107\u1109\u110B\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D\u116E\u1172\u1173\u1175\u119E\u11A8\u11AB\u11AE\u11AF\u11B7\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A\u212B\u212E\u2180-\u2182\u3007\u3021-\u3029\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\u4E00-\u9FA5\uAC00-\uD7A3';
65
+ const ncname = '[' + letter + '_][' + letter + digit + '\\.\\-_' + combiningChar + extender + ']*';
66
+ return '((?:' + ncname + '\\:)?' + ncname + ')';
67
+ })();
68
+ const startTagOpen = new RegExp('^<' + qnameCapture);
69
+ const endTagOpen = new RegExp('^</' + qnameCapture);
70
+ export const endTag = new RegExp('^</' + qnameCapture + '[^>]*>');
71
+
72
+ let IS_REGEX_CAPTURING_BROKEN = false;
73
+ 'x'.replace(/x(.)?/g, function (/** @type {string} */ m, /** @type {string | undefined} */ g) {
74
+ IS_REGEX_CAPTURING_BROKEN = g === '';
75
+ return m;
76
+ });
77
+
78
+ // Empty elements
79
+ const empty = new Set(['area', 'base', 'basefont', 'br', 'col', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
80
+
81
+ // Elements that you can, intentionally, leave open (and which close themselves)
82
+ const closeSelf = new Set(['colgroup', 'dd', 'dt', 'li', 'option', 'p', 'td', 'tfoot', 'th', 'thead', 'tr', 'source']);
83
+
84
+ // Attributes that have their values filled in `disabled='disabled'`
85
+ const fillAttrs = new Set(['checked', 'compact', 'declare', 'defer', 'disabled', 'ismap', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap', 'readonly', 'selected']);
86
+
87
+ // Special elements (can contain anything)
88
+ const special = new Set(['script', 'style']);
89
+
90
+ // Elements whose children are HTML rather than foreign content, each only in
91
+ // the namespace it belongs to (`annotation-xml` is one, too, but only for some
92
+ // `encoding` values, so it is checked separately)
93
+ // https://html.spec.whatwg.org/multipage/parsing.html#html-integration-point
94
+ const svgIntegrationPoints = new Set(['foreignobject', 'desc', 'title']);
95
+ const mathIntegrationPoints = new Set(['mi', 'mo', 'mn', 'ms', 'mtext']);
96
+
97
+ // HTML elements, https://html.spec.whatwg.org/multipage/indices.html#elements-3
98
+ // Phrasing content, https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
99
+ const nonPhrasing = new Set(['address', 'article', 'aside', 'base', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'legend', 'li', 'listing', 'main', 'menu', 'menuitem', 'meta', 'nav', 'ol', 'optgroup', 'option', 'param', 'plaintext', 'pre', 'rp', 'rt', 'search', 'section', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'xmp']);
100
+
101
+ // A tag name ends at whitespace, a slash, or the closing bracket, so `</scriptx>` names a
102
+ // different element and does not end this one
103
+ const endsTagName = (/** @type {string} */ character) =>
104
+ character === '' || character === '/' || character === '>' || /\s/.test(character);
105
+
106
+ // Fast path for tag names
107
+ /**
108
+ * @param {string} html
109
+ * @param {number} start - Position of the first name character (after `<` or `</`)
110
+ * @returns {number} Name length from `start`, or -1 to fall back to the qname regex
111
+ */
112
+ function scanAsciiTagName(html, start) {
113
+ const first = html.charCodeAt(start);
114
+ // First char: Letter or `_` (as for ncname)
115
+ if (!((first >= 65 && first <= 90) || (first >= 97 && first <= 122) || first === 95)) {
116
+ return -1;
117
+ }
118
+ let i = start + 1;
119
+ for (;;) {
120
+ const code = html.charCodeAt(i);
121
+ if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || code === 95 || code === 45 || code === 46) {
122
+ i++;
123
+ } else if (code === 58 || code >= 128) { // `:` or non-ASCII
124
+ return -1;
125
+ } else {
126
+ return i - start;
127
+ }
128
+ }
129
+ }
130
+
131
+ // The characters `\s` matches, by code: Tab through carriage return, space, and the
132
+ // Unicode whitespace and line terminators
133
+ const isWhitespaceCode = (/** @type {number} */ code) =>
134
+ (code >= 9 && code <= 13) || code === 32 || code === 0xA0 || code === 0x1680 ||
135
+ (code >= 0x2000 && code <= 0x200A) || code === 0x2028 || code === 0x2029 ||
136
+ code === 0x202F || code === 0x205F || code === 0x3000 || code === 0xFEFF;
137
+
138
+ /**
139
+ * @param {string} text - The input the tag stands in
140
+ * @param {number} nameEnd - Position right after the tag name
141
+ * @returns {number} Position of the `>` that ends the tag, or -1 where none follows
142
+ */
143
+ function findEndTagClose(text, nameEnd) {
144
+ const close = text.indexOf('>', nameEnd);
145
+ if (close === -1) {
146
+ return -1;
147
+ }
148
+ // A quoted attribute value can hold a `>` that does not end the tag it stands in, so a
149
+ // quote ahead of that bracket calls for a scan that knows about quoting. It stops at the
150
+ // next `<`, which no tag reaches past: The scans of consecutive tags then never overlap,
151
+ // and an unquoted value that spans one leaves the first bracket as the end, as before.
152
+ for (let index = nameEnd; index < close; index++) {
153
+ const character = text[index];
154
+ if (character === '"' || character === "'") {
155
+ const nextOpen = text.indexOf('<', nameEnd);
156
+ const quoted = findTagEnd(text, nameEnd, nextOpen === -1 ? text.length : nextOpen);
157
+ return quoted === -1 ? close : quoted;
158
+ }
159
+ }
160
+ return close;
161
+ }
162
+
163
+ /**
164
+ * @param {string} text - The input from the start of the content on
165
+ * @param {string} tag - Lowercase element name
166
+ * @returns {{content: string, length: number} | null} What the element holds and how far it
167
+ * reaches, or `null` where no end tag of its own follows
168
+ */
169
+ function findRawTextEnd(text, tag) {
170
+ const nameEnd = tag.length + 2;
171
+ for (let candidate = text.indexOf('</'); candidate !== -1; candidate = text.indexOf('</', candidate + 2)) {
172
+ if (text.slice(candidate + 2, candidate + nameEnd).toLowerCase() !== tag || !endsTagName(text.charAt(candidate + nameEnd))) {
173
+ continue;
174
+ }
175
+ // What follows the name is not part of it, and the tag ends at the next bracket outside
176
+ // its attribute values—where none follows, no later end tag can be complete, either
177
+ const end = findEndTagClose(text, candidate + nameEnd);
178
+ return end === -1 ? null : { content: text.slice(0, candidate), length: end + 1 };
179
+ }
180
+ return null;
181
+ }
182
+
183
+ // Cache for compiled attribute regexes per handler configuration
184
+ const attrRegexCache = new WeakMap();
185
+
186
+ /** @param {HTMLParserHandler} handler */
187
+ function buildAttrRegex(handler) {
188
+ const unquotedValue = handler.continueOnParseError ? singleAttrValueLenientUnquoted : singleAttrValues[2];
189
+ const attrValues = [singleAttrValues[0], singleAttrValues[1], unquotedValue];
190
+ let pattern = singleAttrIdentifier.source +
191
+ '(?:\\s*(' + joinSingleAttrAssigns(handler) + ')' +
192
+ '[ \\t\\n\\f\\r]*(?:' + attrValues.join('|') + '))?';
193
+ if (handler.customAttrSurround) {
194
+ if (!Array.isArray(handler.customAttrSurround)) {
195
+ throw new Error('`customAttrSurround` must be an array of `[RegExp, RegExp]` pairs');
196
+ }
197
+ const attrClauses = [];
198
+ for (let i = handler.customAttrSurround.length - 1; i >= 0; i--) {
199
+ const pair = handler.customAttrSurround[i];
200
+ if (!Array.isArray(pair) || !(pair[0] instanceof RegExp) || !(pair[1] instanceof RegExp)) {
201
+ throw new Error('`customAttrSurround` entries must be `[RegExp, RegExp]` pairs');
202
+ }
203
+ attrClauses[i] = '(?:' +
204
+ '(' + embedSource(pair[0]) + ')\\s*' +
205
+ pattern +
206
+ '\\s*(' + embedSource(pair[1]) + ')' +
207
+ ')';
208
+ }
209
+ attrClauses.push('(?:' + pattern + ')');
210
+ pattern = '(?:' + attrClauses.join('|') + ')';
211
+ }
212
+ return new RegExp('^\\s*' + pattern);
213
+ }
214
+
215
+ /** @param {HTMLParserHandler} handler */
216
+ function getAttrRegexForHandler(handler) {
217
+ const cached = attrRegexCache.get(handler);
218
+ if (cached) return cached;
219
+ const compiled = buildAttrRegex(handler);
220
+ attrRegexCache.set(handler, compiled);
221
+ return compiled;
222
+ }
223
+
224
+ // Cache for sticky attribute regexes (`y` flag for position-based matching on full string)
225
+ const attrRegexStickyCache = new WeakMap();
226
+
227
+ /** @param {HTMLParserHandler} handler */
228
+ function getAttrRegexStickyForHandler(handler) {
229
+ const cached = attrRegexStickyCache.get(handler);
230
+ if (cached) return cached;
231
+ const nonSticky = getAttrRegexForHandler(handler);
232
+ // Derive sticky version: Remove `^` anchor, add `y` flag
233
+ const compiled = new RegExp(nonSticky.source.slice(1), 'y');
234
+ attrRegexStickyCache.set(handler, compiled);
235
+ return compiled;
236
+ }
237
+
238
+ /** @param {HTMLParserHandler} handler */
239
+ function joinSingleAttrAssigns(handler) {
240
+ return singleAttrAssigns.concat(
241
+ handler.customAttrAssign || []
242
+ ).map(function (assign) {
243
+ return '(?:' + embedSource(assign) + ')';
244
+ }).join('|');
245
+ }
246
+
247
+ // Number of captured parts per `customAttrSurround` pattern
248
+ const NCP = 7;
249
+
250
+ export class HTMLParser {
251
+ /**
252
+ * @param {string} html
253
+ * @param {HTMLParserHandler} handler
254
+ */
255
+ constructor(html, handler) {
256
+ this.html = html;
257
+ this.handler = handler;
258
+ }
259
+
260
+ async parse() {
261
+ const handler = this.handler;
262
+ const fullHtml = this.html;
263
+ const fullLength = fullHtml.length;
264
+
265
+ /** @type {Array<{tag: string, lowerTag: string, attrs: HTMLAttribute[], namespace: string}>} */
266
+ const stack = [];
267
+ /** @type {string} */
268
+ let lastTag = '';
269
+ // Lowercase counterpart of `lastTag`, kept in sync to avoid per-iteration lowercasing
270
+ /** @type {string} */
271
+ let lastTagLower = '';
272
+ // Use cached attribute regex for this handler configuration
273
+ const attribute = getAttrRegexForHandler(handler);
274
+ const attributeY = getAttrRegexStickyForHandler(handler);
275
+ /** @type {string | undefined} */
276
+ let prevTag;
277
+ /** @type {string | undefined} */
278
+ let nextTag;
279
+ /** @type {HTMLAttribute[]} */
280
+ let prevAttrs = [];
281
+ /** @type {HTMLAttribute[]} */
282
+ let nextAttrs = [];
283
+
284
+ // Sticky regex versions for position-based matching (avoids string slicing)
285
+ const startTagOpenY = new RegExp(startTagOpen.source.slice(1), 'y');
286
+ const endTagOpenY = new RegExp(endTagOpen.source.slice(1), 'y');
287
+ const doctypeY = /<!DOCTYPE[^<>]+>/iy;
288
+ const commentTestY = /<!--/y;
289
+ const conditionalTestY = /<!\[/y;
290
+
291
+ // Cached next-tag from lookahead (avoids re-parsing the same tag)
292
+ let cachedNextStartTag = null;
293
+ let cachedNextEndTag = null;
294
+
295
+ // Index-based parsing
296
+ let pos = 0;
297
+ let lastPos;
298
+
299
+ // An end tag always ends at a `>`; without one ahead, matching the name only to find
300
+ // no bracket behind it repeats the name run at every position, which costs O(n²) on a
301
+ // long unclosed name (e.g., `</aaaa…` with no `>`). Track the next `>` monotonically—
302
+ // `pos` only advances, so the aggregate scan work stays O(n)—and skip the match when
303
+ // none lies ahead, where the tag could not be complete anyway.
304
+ let nextGtPos = fullHtml.indexOf('>');
305
+ const hasCloseAtOrAfter = (/** @type {number} */ p) => {
306
+ if (nextGtPos !== -1 && nextGtPos < p) {
307
+ nextGtPos = fullHtml.indexOf('>', p);
308
+ }
309
+ return nextGtPos !== -1;
310
+ };
311
+
312
+ // A `-->` that the opener at `pos` does not find is not there for any later one, either,
313
+ // and the same holds for the `]>` of a downlevel-revealed conditional comment. `pos`
314
+ // only advances, so remembering the search that came up empty keeps the aggregate work
315
+ // O(n), where searching again at every opener rescans the rest of the input each time.
316
+ let commentEndAhead = true;
317
+ let conditionalEndAhead = true;
318
+
319
+ // Helper to advance position
320
+ const advance = (/** @type {number} */ n) => { pos += n; };
321
+
322
+ // Lazy line/column calculation—only compute on actual errors
323
+ const getLineColumn = (/** @type {number} */ position) => {
324
+ let line = 1;
325
+ let column = 1;
326
+ for (let i = 0; i < position; i++) {
327
+ if (fullHtml[i] === '\n') {
328
+ line++;
329
+ column = 1;
330
+ } else {
331
+ column++;
332
+ }
333
+ }
334
+ return { line, column };
335
+ };
336
+
337
+ // Helper to safely extract substring when needed for stacked tag content
338
+ const sliceFromPos = (/** @type {number} */ startPos) => {
339
+ return fullHtml.slice(startPos);
340
+ };
341
+
342
+ // `annotation-xml` holds HTML only where its `encoding` says so; with any other value,
343
+ // and with none, its content stays MathML
344
+ const annotationHoldsHTML = (/** @type {{attrs?: HTMLAttribute[]}} */ entry) => {
345
+ for (const attr of entry.attrs ?? []) {
346
+ if (attr.name.toLowerCase() === 'encoding') {
347
+ return RE_HTML_ENCODING.test(attr.value ?? '');
348
+ }
349
+ }
350
+ return false;
351
+ };
352
+
353
+ // Escapable raw text is an HTML rule, so what decides it is the namespace the element sits
354
+ // in. Walking down from the root resolves that: `<svg>`/`<math>` lead out of HTML, an
355
+ // integration point leads back in, and a name counts only in the namespace it belongs to
356
+ // (`title` is one in SVG but not in MathML, `annotation-xml` one in MathML but not in SVG)
357
+ /** @param {{lowerTag: string, namespace: string, attrs?: HTMLAttribute[]} | undefined} entry */
358
+ const namespaceInside = (entry) => {
359
+ if (!entry) {
360
+ return '';
361
+ }
362
+ const { namespace, lowerTag } = entry;
363
+ if (!namespace) {
364
+ return lowerTag === 'svg' || lowerTag === 'math' ? lowerTag : '';
365
+ }
366
+ if (namespace === 'svg') {
367
+ return svgIntegrationPoints.has(lowerTag) ? '' : namespace;
368
+ }
369
+ return mathIntegrationPoints.has(lowerTag) || (lowerTag === 'annotation-xml' && annotationHoldsHTML(entry)) ? '' : namespace;
370
+ };
371
+
372
+ // The element itself never decides this: `<svg><title>` is SVG, what it holds is HTML
373
+ const inForeignContent = () => Boolean(stack[stack.length - 1]?.namespace);
374
+
375
+ // The same question for a start tag, which is not on the stack yet: The element enters the
376
+ // namespace its parent holds, except that `svg` and `math` lead out of HTML themselves
377
+ const startsForeignContent = (/** @type {string} */ lowerTag) =>
378
+ Boolean(namespaceInside(stack[stack.length - 1])) || lowerTag === 'svg' || lowerTag === 'math';
379
+
380
+ // Whether the content of the element being parsed is read as text rather than markup
381
+ // (`script` and `style` hold text in every namespace; the rest do so as HTML elements only)
382
+ const holdsRawText = (/** @type {string} */ tag) =>
383
+ special.has(tag) ||
384
+ ((genericRawTextElements.has(tag) || escapableRawTextElements.has(tag)) && !inForeignContent());
385
+
386
+ while (pos < fullLength) {
387
+ lastPos = pos;
388
+
389
+ // Make sure not to be in an element whose content is text, not markup
390
+ if (!lastTagLower || !holdsRawText(lastTagLower)) {
391
+ const textEnd = fullHtml.indexOf('<', pos);
392
+
393
+ if (textEnd === pos) {
394
+ // Tag found at current position
395
+
396
+ // Check cache from previous lookahead (avoids re-parsing the same tag)
397
+ if (cachedNextStartTag && cachedNextStartTag.pos === pos) {
398
+ const startTagMatch = cachedNextStartTag.match;
399
+ cachedNextStartTag = null;
400
+ cachedNextEndTag = null;
401
+ advance(startTagMatch.advance);
402
+ prevTag = await handleStartTag(startTagMatch);
403
+ continue;
404
+ }
405
+ if (cachedNextEndTag && cachedNextEndTag.pos === pos) {
406
+ const endTagMatch = cachedNextEndTag.match;
407
+ cachedNextStartTag = null;
408
+ cachedNextEndTag = null;
409
+ advance(endTagMatch.text.length);
410
+ prevTag = '/' + await parseEndTag(endTagMatch.text, endTagMatch.name);
411
+ prevAttrs = [];
412
+ continue;
413
+ }
414
+ cachedNextStartTag = null;
415
+ cachedNextEndTag = null;
416
+
417
+ // Dispatch on the character after `<`: Each branch below can only match
418
+ // with one leading character (`!` for markup declarations, `/` for end
419
+ // tags, a name character for start tags), so the matchers that require
420
+ // another one never run—a name lookup costs several regex executions
421
+ const nextCode = fullHtml.charCodeAt(pos + 1);
422
+ if (nextCode === 33) { // `!`
423
+ // Comment
424
+ commentTestY.lastIndex = pos;
425
+ if (commentTestY.test(fullHtml)) {
426
+ const commentEnd = commentEndAhead ? fullHtml.indexOf('-->', pos + 4) : -1;
427
+ if (commentEnd === -1) commentEndAhead = false;
428
+
429
+ if (commentEnd >= 0) {
430
+ if (handler.comment) {
431
+ const result = handler.comment(fullHtml.substring(pos + 4, commentEnd));
432
+ if (isThenable(result)) await result;
433
+ }
434
+ advance(commentEnd + 3 - pos);
435
+ prevTag = '';
436
+ prevAttrs = [];
437
+ continue;
438
+ }
439
+ }
440
+
441
+ // https://web.archive.org/web/20241201212701/https://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
442
+ conditionalTestY.lastIndex = pos;
443
+ if (conditionalTestY.test(fullHtml)) {
444
+ const conditionalEnd = conditionalEndAhead ? fullHtml.indexOf(']>', pos + 3) : -1;
445
+ if (conditionalEnd === -1) conditionalEndAhead = false;
446
+
447
+ if (conditionalEnd >= 0) {
448
+ if (handler.comment) {
449
+ const result = handler.comment(fullHtml.substring(pos + 2, conditionalEnd + 1), true /* Non-standard */);
450
+ if (isThenable(result)) await result;
451
+ }
452
+ advance(conditionalEnd + 2 - pos);
453
+ prevTag = '';
454
+ prevAttrs = [];
455
+ continue;
456
+ }
457
+ }
458
+
459
+ // Doctype
460
+ doctypeY.lastIndex = pos;
461
+ const doctypeMatch = doctypeY.exec(fullHtml);
462
+ if (doctypeMatch) {
463
+ if (handler.doctype) {
464
+ handler.doctype(doctypeMatch[0]);
465
+ }
466
+ advance(doctypeMatch[0].length);
467
+ prevTag = '';
468
+ prevAttrs = [];
469
+ continue;
470
+ }
471
+ } else if (nextCode === 47) { // `/`
472
+ // End tag—skip when no `>` lies ahead: The tag cannot be complete, and matching
473
+ // its name at every position would cost O(n²) on a long unclosed name
474
+ if (hasCloseAtOrAfter(pos)) {
475
+ const endTagMatch = matchEndTag(pos);
476
+ if (endTagMatch) {
477
+ advance(endTagMatch.text.length);
478
+ prevTag = '/' + await parseEndTag(endTagMatch.text, endTagMatch.name);
479
+ prevAttrs = [];
480
+ continue;
481
+ }
482
+ }
483
+ } else {
484
+ // Start tag
485
+ const startTagMatch = parseStartTag(pos);
486
+ if (startTagMatch) {
487
+ advance(startTagMatch.advance);
488
+ prevTag = await handleStartTag(startTagMatch);
489
+ continue;
490
+ }
491
+ }
492
+
493
+ // Treat `<` as text
494
+ if (handler.continueOnParseError) {
495
+ // Continue looking for next tag
496
+ }
497
+ }
498
+
499
+ let text;
500
+ if (textEnd >= 0) {
501
+ text = fullHtml.substring(pos, textEnd);
502
+ advance(textEnd - pos);
503
+ } else {
504
+ text = fullHtml.substring(pos);
505
+ advance(fullLength - pos);
506
+ }
507
+
508
+ // Next tag for whitespace processing context
509
+ if (handler.wantsNextTag) {
510
+ // Same dispatch as above: A start tag cannot follow `<` + `/` or `!`,
511
+ // an end tag requires `/`—the other matcher never runs
512
+ const nextCode = fullHtml.charCodeAt(pos + 1);
513
+ if (nextCode !== 47 && nextCode !== 33) {
514
+ const nextStartTagMatch = parseStartTag(pos);
515
+ if (nextStartTagMatch) {
516
+ nextTag = nextStartTagMatch.tagName;
517
+ // Extract minimal attribute info for whitespace logic (just name/value pairs)
518
+ nextAttrs = extractAttrInfo(nextStartTagMatch.attrs);
519
+ cachedNextStartTag = { match: nextStartTagMatch, pos };
520
+ } else {
521
+ nextTag = '';
522
+ nextAttrs = [];
523
+ }
524
+ } else if (nextCode === 47 && hasCloseAtOrAfter(pos)) {
525
+ const nextEndTagMatch = matchEndTag(pos);
526
+ if (nextEndTagMatch) {
527
+ nextTag = '/' + nextEndTagMatch.name;
528
+ nextAttrs = [];
529
+ cachedNextEndTag = { match: nextEndTagMatch, pos };
530
+ } else {
531
+ nextTag = '';
532
+ nextAttrs = [];
533
+ }
534
+ } else {
535
+ nextTag = '';
536
+ nextAttrs = [];
537
+ }
538
+ }
539
+
540
+ if (handler.chars) {
541
+ const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs);
542
+ if (isThenable(result)) await result;
543
+ }
544
+ prevTag = '';
545
+ prevAttrs = [];
546
+ } else {
547
+ const stackedTag = lastTagLower;
548
+ const isEscapableRawText = escapableRawTextElements.has(stackedTag);
549
+
550
+ const remaining = sliceFromPos(pos);
551
+ // Where the raw text has no end, no end tag of its own ends the element either
552
+ const rawText = endlessRawTextElements.has(stackedTag) ? null : findRawTextEnd(remaining, stackedTag);
553
+ if (rawText) {
554
+ const text = rawText.content;
555
+ if (handler.chars) {
556
+ // Escapable raw text is a text node like any other, so the handler gets the tags
557
+ // around it—it collapses and trims whitespace by what stands next to the text
558
+ const result = isEscapableRawText
559
+ ? handler.chars(text, stackedTag, '/' + stackedTag, prevAttrs, [])
560
+ : handler.chars(text);
561
+ if (isThenable(result)) await result;
562
+ }
563
+ // Advance HTML past the matched special tag content and its closing tag
564
+ advance(rawText.length);
565
+ await parseEndTag('</' + stackedTag + '>', stackedTag);
566
+ // What follows stands after that end tag, not after the start tag still named here—
567
+ // whitespace next to `textarea` stays verbatim only while the element is open
568
+ prevTag = '/' + stackedTag;
569
+ prevAttrs = [];
570
+ } else {
571
+ // Without an end tag of its own, the element holds the rest of the input as text
572
+ if (handler.chars && remaining) {
573
+ const result = isEscapableRawText
574
+ ? handler.chars(remaining, stackedTag, '', prevAttrs, [])
575
+ : handler.chars(remaining);
576
+ if (isThenable(result)) await result;
577
+ }
578
+ advance(remaining.length);
579
+ if (endlessRawTextElements.has(stackedTag)) {
580
+ // Nothing that stands behind the start tag is markup, so no end tag may be
581
+ // generated for the element, or for anything it stands in
582
+ stack.length = 0;
583
+ lastTag = '';
584
+ lastTagLower = '';
585
+ }
586
+ }
587
+ }
588
+
589
+ if (pos === lastPos) {
590
+ if (handler.continueOnParseError) {
591
+ // Skip the problematic character and continue
592
+ if (handler.chars) {
593
+ const result = handler.chars(fullHtml[pos], prevTag, '', prevAttrs, []);
594
+ if (isThenable(result)) await result;
595
+ }
596
+ advance(1);
597
+ prevTag = '';
598
+ prevAttrs = [];
599
+ continue;
600
+ }
601
+ const loc = getLineColumn(pos);
602
+ // Include some context before the error position so the snippet contains the offending markup plus preceding characters (e.g., `invalid<tag`)
603
+ const CONTEXT_BEFORE = 50;
604
+ const startPos = Math.max(0, pos - CONTEXT_BEFORE);
605
+ const snippet = fullHtml.slice(startPos, startPos + 200).replace(/\n/g, ' ');
606
+ throw new Error(`Parse error at line ${loc.line}, column ${loc.column}:\n${snippet}${fullHtml.length > startPos + 200 ? '…' : ''}`);
607
+ }
608
+ }
609
+
610
+ if (!handler.partialMarkup) {
611
+ // Clean up any remaining tags
612
+ await parseEndTag('', '');
613
+ }
614
+
615
+ // Helper to extract minimal attribute info (name/value pairs) from raw attribute matches
616
+ // Used for whitespace collapsing logic—doesn’t need full processing
617
+ function extractAttrInfo(/** @type {Array<Array<string | undefined>>} */ rawAttrs) {
618
+ if (!rawAttrs || !rawAttrs.length) return [];
619
+
620
+ const numCustomParts = handler.customAttrSurround ? handler.customAttrSurround.length * NCP : 0;
621
+ const baseIndex = 1 + numCustomParts;
622
+
623
+ return /** @type {HTMLAttribute[]} */ (rawAttrs.map((/** @type {Array<string | undefined>} */ args) => {
624
+ // Extract attribute name (always at `baseIndex`)
625
+ const name = args[baseIndex];
626
+ // Extract value from double-quoted (`baseIndex + 2`), single-quoted (`baseIndex + 3`), or unquoted (`baseIndex + 4`)
627
+ const value = args[baseIndex + 2] ?? args[baseIndex + 3] ?? args[baseIndex + 4];
628
+ return { name: name?.toLowerCase() ?? '', value };
629
+ }).filter(attr => attr.name)); // Filter out invalid entries
630
+ }
631
+
632
+ /**
633
+ * @param {number} startPos
634
+ * @returns {{text: string, name: string} | null} The end tag standing there, or `null`
635
+ * where none is complete
636
+ */
637
+ function matchEndTag(startPos) {
638
+ let name;
639
+ let nameEnd;
640
+ const scanned = scanAsciiTagName(fullHtml, startPos + 2);
641
+ if (scanned !== -1) {
642
+ nameEnd = startPos + 2 + scanned;
643
+ name = fullHtml.slice(startPos + 2, nameEnd);
644
+ } else {
645
+ endTagOpenY.lastIndex = startPos;
646
+ const open = endTagOpenY.exec(fullHtml);
647
+ if (!open) {
648
+ return null;
649
+ }
650
+ nameEnd = startPos + open[0].length;
651
+ name = open[1] ?? '';
652
+ }
653
+ const close = findEndTagClose(fullHtml, nameEnd);
654
+ return close === -1 ? null : { text: fullHtml.slice(startPos, close + 1), name };
655
+ }
656
+
657
+ // Where a tag ends: After optional whitespace, at `>` or `/>`. Scanned by hand in a
658
+ // single pass, where a regex did the same with one execution per attribute. The
659
+ // result packs length and slash into one number (`length << 1 | hasSlash`, 0 for no
660
+ // match) so the per-attribute loop allocates nothing.
661
+ function matchTagClose(/** @type {number} */ currentPos) {
662
+ let scan = currentPos;
663
+ let code = fullHtml.charCodeAt(scan);
664
+ while (isWhitespaceCode(code)) {
665
+ code = fullHtml.charCodeAt(++scan);
666
+ }
667
+ if (code === 62) { // `>`
668
+ return (scan - currentPos + 1) << 1;
669
+ }
670
+ if (code === 47 && fullHtml.charCodeAt(scan + 1) === 62) { // `/>`
671
+ return ((scan - currentPos + 2) << 1) | 1;
672
+ }
673
+ return 0;
674
+ }
675
+
676
+ function parseStartTag(/** @type {number} */ startPos) {
677
+ let tagName;
678
+ let consumed;
679
+ const scanned = scanAsciiTagName(fullHtml, startPos + 1);
680
+ if (scanned !== -1) {
681
+ tagName = fullHtml.slice(startPos + 1, startPos + 1 + scanned);
682
+ consumed = 1 + scanned;
683
+ } else {
684
+ startTagOpenY.lastIndex = startPos;
685
+ const start = startTagOpenY.exec(fullHtml);
686
+ if (!start) {
687
+ return undefined;
688
+ }
689
+ tagName = start[1] ?? '';
690
+ consumed = start[0].length;
691
+ }
692
+ /** @type {{tagName: string, attrs: Array<Array<string|undefined>>, advance: number, unarySlash?: string}} */
693
+ const match = {
694
+ tagName,
695
+ attrs: [],
696
+ advance: 0
697
+ };
698
+ let currentPos = startPos + consumed;
699
+ let close, attr;
700
+
701
+ // Safety limit: Max length of input to check for attributes
702
+ // Protects against catastrophic backtracking on massive attribute values
703
+ const MAX_ATTR_PARSE_LENGTH = 20000; // 20 KB should be enough for any reasonable tag
704
+
705
+ while (true) {
706
+ // Check for closing tag first (manual scan, regex only for the unusual)
707
+ close = matchTagClose(currentPos);
708
+ if (close) {
709
+ break;
710
+ }
711
+
712
+ // Limit the input length to pass to the regex to prevent catastrophic backtracking
713
+ const remainingLen = fullLength - currentPos;
714
+ const isLimited = remainingLen > MAX_ATTR_PARSE_LENGTH;
715
+
716
+ if (!isLimited) {
717
+ // Common case: Use sticky regex directly on full string (no slicing)
718
+ attributeY.lastIndex = currentPos;
719
+ attr = attributeY.exec(fullHtml);
720
+ } else {
721
+ const extractEndPos = currentPos + MAX_ATTR_PARSE_LENGTH;
722
+
723
+ // Create a temporary substring only for attribute parsing (limited for safety)
724
+ const searchStr = fullHtml.substring(currentPos, extractEndPos);
725
+ attr = searchStr.match(attribute);
726
+
727
+ // If input was limited and there’s a match, check if the value might be truncated
728
+ if (attr) {
729
+ // Check if the attribute value extends beyond our search window
730
+ const attrEnd = attr[0].length;
731
+ // If the match ends near the limit, the value might be truncated
732
+ if (attrEnd > MAX_ATTR_PARSE_LENGTH - 100) {
733
+ // Manually extract this attribute to handle potentially huge value
734
+ const manualMatch = searchStr.match(/^\s*([^\s"'<>/=]+)\s*=\s*/);
735
+ if (manualMatch) {
736
+ const quoteChar = searchStr[manualMatch[0].length];
737
+ if (quoteChar === '"' || quoteChar === "'") {
738
+ const closeQuote = searchStr.indexOf(quoteChar, manualMatch[0].length + 1);
739
+ if (closeQuote !== -1) {
740
+ const fullAttrLen = closeQuote + 1;
741
+ const numCustomParts = handler.customAttrSurround
742
+ ? handler.customAttrSurround.length * NCP
743
+ : 0;
744
+ const baseIndex = 1 + numCustomParts;
745
+
746
+ attr = [];
747
+ attr[0] = searchStr.substring(0, fullAttrLen);
748
+ attr[baseIndex] = manualMatch[1]; // Attribute name
749
+ attr[baseIndex + 1] = '='; // `customAssign` (falls back to "=" for huge attributes)
750
+ const value = searchStr.substring(manualMatch[0].length + 1, closeQuote);
751
+ // Place value at correct index based on quote type
752
+ if (quoteChar === '"') {
753
+ attr[baseIndex + 2] = value; // Double-quoted value
754
+ } else {
755
+ attr[baseIndex + 3] = value; // Single-quoted value
756
+ }
757
+ currentPos += fullAttrLen;
758
+ consumed += fullAttrLen;
759
+ match.attrs.push(attr);
760
+ continue;
761
+ }
762
+ }
763
+ // Note: Unquoted attribute values are intentionally not handled here
764
+ // Per HTML spec, unquoted values cannot contain spaces or special chars,
765
+ // making a 20 KB+ unquoted value practically impossible; if encountered,
766
+ // it’s malformed HTML and using the truncated regex match is acceptable
767
+ }
768
+ } else {
769
+ // If attr has no value assign but `=` follows in `fullHtml`,
770
+ // the value would be cut off—reset to trigger manual extraction below
771
+ const numCustomParts = handler.customAttrSurround
772
+ ? handler.customAttrSurround.length * NCP
773
+ : 0;
774
+ const baseIndex = 1 + numCustomParts;
775
+ if (attr[baseIndex + 1] === undefined) {
776
+ const posAfterName = currentPos + attrEnd;
777
+ if (/^\s*=/.test(fullHtml.slice(posAfterName, posAfterName + 50))) {
778
+ attr = null;
779
+ }
780
+ }
781
+ }
782
+ }
783
+
784
+ if (!attr) {
785
+ // If input was limited and there’s no match, try manual extraction
786
+ // This handles cases where quoted attributes exceed `MAX_ATTR_PARSE_LENGTH`
787
+ const manualMatch = searchStr.match(/^\s*([^\s"'<>/=]+)\s*=\s*/);
788
+ if (manualMatch) {
789
+ const quoteChar = searchStr[manualMatch[0].length];
790
+ if (quoteChar === '"' || quoteChar === "'") {
791
+ // Search in the full HTML (not limited substring) for closing quote
792
+ const closeQuote = fullHtml.indexOf(quoteChar, currentPos + manualMatch[0].length + 1);
793
+ if (closeQuote !== -1) {
794
+ const fullAttrLen = closeQuote - currentPos + 1;
795
+ const numCustomParts = handler.customAttrSurround
796
+ ? handler.customAttrSurround.length * NCP
797
+ : 0;
798
+ const baseIndex = 1 + numCustomParts;
799
+
800
+ attr = [];
801
+ attr[0] = fullHtml.substring(currentPos, closeQuote + 1);
802
+ attr[baseIndex] = manualMatch[1]; // Attribute name
803
+ attr[baseIndex + 1] = '='; // customAssign
804
+ const value = fullHtml.substring(currentPos + manualMatch[0].length + 1, closeQuote);
805
+ // Place value at correct index based on quote type
806
+ if (quoteChar === '"') {
807
+ attr[baseIndex + 2] = value; // Double-quoted value
808
+ } else {
809
+ attr[baseIndex + 3] = value; // Single-quoted value
810
+ }
811
+ currentPos += fullAttrLen;
812
+ consumed += fullAttrLen;
813
+ match.attrs.push(attr);
814
+ continue;
815
+ }
816
+ }
817
+ }
818
+ }
819
+ }
820
+
821
+ if (!attr) {
822
+ break;
823
+ }
824
+
825
+ const attrLen = attr[0].length;
826
+ currentPos += attrLen;
827
+ consumed += attrLen;
828
+ match.attrs.push(attr);
829
+ }
830
+
831
+ // Check for closing tag (manual scan, regex only for the unusual)
832
+ if (!close) {
833
+ close = matchTagClose(currentPos);
834
+ }
835
+ if (close) {
836
+ match.unarySlash = (close & 1) ? '/' : '';
837
+ consumed += close >> 1;
838
+ match.advance = consumed;
839
+ return match;
840
+ }
841
+ return undefined;
842
+ }
843
+
844
+ // `needle` must already be lowercase
845
+ function findTagInCurrentTable(/** @type {string} */ needle) {
846
+ let stackIndex;
847
+ for (stackIndex = stack.length - 1; stackIndex >= 0; stackIndex--) {
848
+ const entry = stack[stackIndex];
849
+ const currentTag = entry?.lowerTag;
850
+ if (currentTag === needle) {
851
+ return stackIndex;
852
+ }
853
+ // Stop searching if hitting a table boundary
854
+ if (currentTag === 'table') {
855
+ break;
856
+ }
857
+ }
858
+ return -1;
859
+ }
860
+
861
+ function parseEndTagAt(/** @type {number} */ stackIndex) {
862
+ // Close all open elements up to `stackIndex` (mirrors `parseEndTag`’s core branch);
863
+ // `end` handlers are synchronous—invoked without awaiting, as in `parseEndTag`
864
+ for (let i = stack.length - 1; i >= stackIndex; i--) {
865
+ const entry = /** @type {NonNullable<(typeof stack)[number]>} */ (stack[i]);
866
+ if (handler.end) {
867
+ handler.end(entry.tag, entry.attrs, true);
868
+ }
869
+ }
870
+ stack.length = stackIndex;
871
+ lastTag = stackIndex ? (stack[stackIndex - 1]?.tag ?? '') : '';
872
+ lastTagLower = stackIndex ? (stack[stackIndex - 1]?.lowerTag ?? '') : '';
873
+ }
874
+
875
+ function closeIfFoundInCurrentTable(/** @type {string} */ tagName) {
876
+ const stackIndex = findTagInCurrentTable(tagName);
877
+ if (stackIndex >= 0) {
878
+ // Close at the specific index to avoid re-searching
879
+ parseEndTagAt(stackIndex);
880
+ return true;
881
+ }
882
+ return false;
883
+ }
884
+
885
+ async function handleStartTag(/** @type {{tagName: string, attrs: Array<Array<string | undefined>>, advance: number, unarySlash?: string}} */ match) {
886
+ const tagName = match.tagName;
887
+ const lowerTagName = tagName.toLowerCase();
888
+ let unarySlash = match.unarySlash;
889
+
890
+ if (lastTagLower === 'p' && nonPhrasing.has(lowerTagName)) {
891
+ await parseEndTag('', lastTag);
892
+ }
893
+ // A row or cell start tag closes the row or cell still open in the same table,
894
+ // which may sit deeper down the stack than the element that was opened last
895
+ if (lowerTagName === 'tr') {
896
+ closeIfFoundInCurrentTable('tr');
897
+ } else if (lowerTagName === 'td' || lowerTagName === 'th') {
898
+ if (!closeIfFoundInCurrentTable('td')) {
899
+ closeIfFoundInCurrentTable('th');
900
+ }
901
+ }
902
+ if (lowerTagName === 'tbody') {
903
+ if (!closeIfFoundInCurrentTable('tfoot')) {
904
+ closeIfFoundInCurrentTable('thead');
905
+ }
906
+ } else if (lowerTagName === 'tfoot') {
907
+ if (!closeIfFoundInCurrentTable('tbody')) {
908
+ closeIfFoundInCurrentTable('thead');
909
+ }
910
+ } else if (lowerTagName === 'thead') {
911
+ // If a `tbody` or `tfoot` is open in the current table, close it
912
+ if (!closeIfFoundInCurrentTable('tbody')) {
913
+ closeIfFoundInCurrentTable('tfoot');
914
+ }
915
+ }
916
+ if (lowerTagName === 'col' && findTagInCurrentTable('colgroup') < 0) {
917
+ lastTag = 'colgroup';
918
+ lastTagLower = 'colgroup';
919
+ stack.push({ tag: lastTag, lowerTag: 'colgroup', attrs: [], namespace: namespaceInside(stack[stack.length - 1]) });
920
+ if (handler.start) {
921
+ await handler.start(lastTag, [], false, '', true);
922
+ }
923
+ } else if (lowerTagName !== 'col' && lastTagLower === 'colgroup') {
924
+ // Auto-close synthetic `<colgroup>` when a non-`col` element starts
925
+ await parseEndTag('', 'colgroup');
926
+ }
927
+
928
+ if (closeSelf.has(lowerTagName) && lastTagLower === lowerTagName) {
929
+ await parseEndTag('', tagName);
930
+ }
931
+
932
+ // Handle `dt`/`dd` cross-closing: `dt` followed by `dd`, or `dd` followed by `dt`
933
+ if ((lowerTagName === 'dt' || lowerTagName === 'dd') && (lastTagLower === 'dt' || lastTagLower === 'dd')) {
934
+ await parseEndTag('', lastTag);
935
+ }
936
+
937
+ // HTML ignores the slash on a start tag—only in SVG and MathML does it close the
938
+ // element, which `selfClosingSlash` extends back to every element
939
+ const selfClosed = !!unarySlash && (handler.selfClosingSlash || startsForeignContent(lowerTagName));
940
+ const unary = empty.has(lowerTagName) || (lowerTagName === 'html' && lastTagLower === 'head') || selfClosed;
941
+
942
+ const attrs = /** @type {HTMLAttribute[]} */ (match.attrs.map(function (/** @type {Array<string | undefined>} */ args) {
943
+ /** @type {string | undefined} */
944
+ let name, value, customOpen, customClose, customAssign, quote;
945
+
946
+ // Hackish workaround for Firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=369778
947
+ if (IS_REGEX_CAPTURING_BROKEN && (args[0] ?? '').indexOf('""') === -1) {
948
+ if (args[3] === '') { delete args[3]; }
949
+ if (args[4] === '') { delete args[4]; }
950
+ if (args[5] === '') { delete args[5]; }
951
+ }
952
+
953
+ function populate(/** @type {number} */ index) {
954
+ customAssign = args[index];
955
+ value = args[index + 1];
956
+ if (typeof value !== 'undefined') {
957
+ return '"';
958
+ }
959
+ value = args[index + 2];
960
+ if (typeof value !== 'undefined') {
961
+ return '\'';
962
+ }
963
+ value = args[index + 3];
964
+ if (typeof value === 'undefined' && name && fillAttrs.has(name.toLowerCase())) {
965
+ value = name;
966
+ }
967
+ return '';
968
+ }
969
+
970
+ let j = 1;
971
+ if (handler.customAttrSurround) {
972
+ for (let i = 0, l = handler.customAttrSurround.length; i < l; i++, j += NCP) {
973
+ name = args[j + 1];
974
+ if (name) {
975
+ quote = populate(j + 2);
976
+ customOpen = args[j];
977
+ customClose = args[j + 6];
978
+ break;
979
+ }
980
+ }
981
+ }
982
+
983
+ if (!name && (name = args[j])) {
984
+ quote = populate(j + 1);
985
+ }
986
+
987
+ return {
988
+ name: name ?? '',
989
+ value,
990
+ customAssign: customAssign || '=',
991
+ customOpen: customOpen || '',
992
+ customClose: customClose || '',
993
+ quote: quote || ''
994
+ };
995
+ }));
996
+
997
+ if (!unary) {
998
+ stack.push({ tag: tagName, lowerTag: lowerTagName, attrs, namespace: namespaceInside(stack[stack.length - 1]) });
999
+ lastTag = tagName;
1000
+ lastTagLower = lowerTagName;
1001
+ unarySlash = '';
1002
+ }
1003
+
1004
+ // Store attributes for `prevAttrs` tracking (used in whitespace collapsing)
1005
+ prevAttrs = attrs;
1006
+
1007
+ if (handler.start) {
1008
+ await handler.start(tagName, attrs, unary, unarySlash);
1009
+ }
1010
+ // Returned so the parse loop can skip lowercasing the name again
1011
+ return lowerTagName;
1012
+ }
1013
+
1014
+ // `needle` must already be lowercase
1015
+ function findTag(/** @type {string} */ needle) {
1016
+ let stackIndex;
1017
+ for (stackIndex = stack.length - 1; stackIndex >= 0; stackIndex--) {
1018
+ if (stack[stackIndex]?.lowerTag === needle) {
1019
+ break;
1020
+ }
1021
+ }
1022
+ return stackIndex;
1023
+ }
1024
+
1025
+ async function parseEndTag(/** @type {string} */ tag, /** @type {string} */ tagName) {
1026
+ let stackIndex;
1027
+ const lowerTagName = tagName ? tagName.toLowerCase() : '';
1028
+
1029
+ // Find the closest opened tag of the same type
1030
+ if (tagName) {
1031
+ stackIndex = findTag(lowerTagName);
1032
+ } else { // If no tag name is provided, clean shop
1033
+ stackIndex = 0;
1034
+ }
1035
+
1036
+ if (stackIndex >= 0) {
1037
+ // Close all the open elements, up the stack
1038
+ for (let i = stack.length - 1; i >= stackIndex; i--) {
1039
+ if (handler.end) {
1040
+ handler.end(stack[i]?.tag, stack[i]?.attrs, i > stackIndex || !tag);
1041
+ }
1042
+ }
1043
+
1044
+ // Remove the open elements from the stack
1045
+ stack.length = stackIndex;
1046
+ lastTag = stackIndex ? (stack[stackIndex - 1]?.tag ?? '') : '';
1047
+ lastTagLower = stackIndex ? (stack[stackIndex - 1]?.lowerTag ?? '') : '';
1048
+ } else if (handler.partialMarkup && tagName) {
1049
+ // In partial markup mode, preserve stray end tags
1050
+ if (handler.end) {
1051
+ handler.end(tagName, [], false);
1052
+ }
1053
+ } else if (lowerTagName === 'br') {
1054
+ if (handler.start) {
1055
+ await handler.start(tagName, [], true, '');
1056
+ }
1057
+ } else if (lowerTagName === 'p') {
1058
+ if (handler.start) {
1059
+ await handler.start(tagName, [], false, '', true);
1060
+ }
1061
+ if (handler.end) {
1062
+ handler.end(tagName, []);
1063
+ }
1064
+ }
1065
+ // Returned so the parse loop can skip lowercasing the name again
1066
+ return lowerTagName;
1067
+ }
1068
+ }
1069
+ }