Tokenizer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.QuoteType = void 0;
  4. var decode_js_1 = require("entities/lib/decode.js");
  5. var CharCodes;
  6. (function (CharCodes) {
  7. CharCodes[CharCodes["Tab"] = 9] = "Tab";
  8. CharCodes[CharCodes["NewLine"] = 10] = "NewLine";
  9. CharCodes[CharCodes["FormFeed"] = 12] = "FormFeed";
  10. CharCodes[CharCodes["CarriageReturn"] = 13] = "CarriageReturn";
  11. CharCodes[CharCodes["Space"] = 32] = "Space";
  12. CharCodes[CharCodes["ExclamationMark"] = 33] = "ExclamationMark";
  13. CharCodes[CharCodes["Number"] = 35] = "Number";
  14. CharCodes[CharCodes["Amp"] = 38] = "Amp";
  15. CharCodes[CharCodes["SingleQuote"] = 39] = "SingleQuote";
  16. CharCodes[CharCodes["DoubleQuote"] = 34] = "DoubleQuote";
  17. CharCodes[CharCodes["Dash"] = 45] = "Dash";
  18. CharCodes[CharCodes["Slash"] = 47] = "Slash";
  19. CharCodes[CharCodes["Zero"] = 48] = "Zero";
  20. CharCodes[CharCodes["Nine"] = 57] = "Nine";
  21. CharCodes[CharCodes["Semi"] = 59] = "Semi";
  22. CharCodes[CharCodes["Lt"] = 60] = "Lt";
  23. CharCodes[CharCodes["Eq"] = 61] = "Eq";
  24. CharCodes[CharCodes["Gt"] = 62] = "Gt";
  25. CharCodes[CharCodes["Questionmark"] = 63] = "Questionmark";
  26. CharCodes[CharCodes["UpperA"] = 65] = "UpperA";
  27. CharCodes[CharCodes["LowerA"] = 97] = "LowerA";
  28. CharCodes[CharCodes["UpperF"] = 70] = "UpperF";
  29. CharCodes[CharCodes["LowerF"] = 102] = "LowerF";
  30. CharCodes[CharCodes["UpperZ"] = 90] = "UpperZ";
  31. CharCodes[CharCodes["LowerZ"] = 122] = "LowerZ";
  32. CharCodes[CharCodes["LowerX"] = 120] = "LowerX";
  33. CharCodes[CharCodes["OpeningSquareBracket"] = 91] = "OpeningSquareBracket";
  34. })(CharCodes || (CharCodes = {}));
  35. /** All the states the tokenizer can be in. */
  36. var State;
  37. (function (State) {
  38. State[State["Text"] = 1] = "Text";
  39. State[State["BeforeTagName"] = 2] = "BeforeTagName";
  40. State[State["InTagName"] = 3] = "InTagName";
  41. State[State["InSelfClosingTag"] = 4] = "InSelfClosingTag";
  42. State[State["BeforeClosingTagName"] = 5] = "BeforeClosingTagName";
  43. State[State["InClosingTagName"] = 6] = "InClosingTagName";
  44. State[State["AfterClosingTagName"] = 7] = "AfterClosingTagName";
  45. // Attributes
  46. State[State["BeforeAttributeName"] = 8] = "BeforeAttributeName";
  47. State[State["InAttributeName"] = 9] = "InAttributeName";
  48. State[State["AfterAttributeName"] = 10] = "AfterAttributeName";
  49. State[State["BeforeAttributeValue"] = 11] = "BeforeAttributeValue";
  50. State[State["InAttributeValueDq"] = 12] = "InAttributeValueDq";
  51. State[State["InAttributeValueSq"] = 13] = "InAttributeValueSq";
  52. State[State["InAttributeValueNq"] = 14] = "InAttributeValueNq";
  53. // Declarations
  54. State[State["BeforeDeclaration"] = 15] = "BeforeDeclaration";
  55. State[State["InDeclaration"] = 16] = "InDeclaration";
  56. // Processing instructions
  57. State[State["InProcessingInstruction"] = 17] = "InProcessingInstruction";
  58. // Comments & CDATA
  59. State[State["BeforeComment"] = 18] = "BeforeComment";
  60. State[State["CDATASequence"] = 19] = "CDATASequence";
  61. State[State["InSpecialComment"] = 20] = "InSpecialComment";
  62. State[State["InCommentLike"] = 21] = "InCommentLike";
  63. // Special tags
  64. State[State["BeforeSpecialS"] = 22] = "BeforeSpecialS";
  65. State[State["SpecialStartSequence"] = 23] = "SpecialStartSequence";
  66. State[State["InSpecialTag"] = 24] = "InSpecialTag";
  67. State[State["BeforeEntity"] = 25] = "BeforeEntity";
  68. State[State["BeforeNumericEntity"] = 26] = "BeforeNumericEntity";
  69. State[State["InNamedEntity"] = 27] = "InNamedEntity";
  70. State[State["InNumericEntity"] = 28] = "InNumericEntity";
  71. State[State["InHexEntity"] = 29] = "InHexEntity";
  72. })(State || (State = {}));
  73. function isWhitespace(c) {
  74. return (c === CharCodes.Space ||
  75. c === CharCodes.NewLine ||
  76. c === CharCodes.Tab ||
  77. c === CharCodes.FormFeed ||
  78. c === CharCodes.CarriageReturn);
  79. }
  80. function isEndOfTagSection(c) {
  81. return c === CharCodes.Slash || c === CharCodes.Gt || isWhitespace(c);
  82. }
  83. function isNumber(c) {
  84. return c >= CharCodes.Zero && c <= CharCodes.Nine;
  85. }
  86. function isASCIIAlpha(c) {
  87. return ((c >= CharCodes.LowerA && c <= CharCodes.LowerZ) ||
  88. (c >= CharCodes.UpperA && c <= CharCodes.UpperZ));
  89. }
  90. function isHexDigit(c) {
  91. return ((c >= CharCodes.UpperA && c <= CharCodes.UpperF) ||
  92. (c >= CharCodes.LowerA && c <= CharCodes.LowerF));
  93. }
  94. var QuoteType;
  95. (function (QuoteType) {
  96. QuoteType[QuoteType["NoValue"] = 0] = "NoValue";
  97. QuoteType[QuoteType["Unquoted"] = 1] = "Unquoted";
  98. QuoteType[QuoteType["Single"] = 2] = "Single";
  99. QuoteType[QuoteType["Double"] = 3] = "Double";
  100. })(QuoteType = exports.QuoteType || (exports.QuoteType = {}));
  101. /**
  102. * Sequences used to match longer strings.
  103. *
  104. * We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End
  105. * sequences with an increased offset.
  106. */
  107. var Sequences = {
  108. Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]),
  109. CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]),
  110. CommentEnd: new Uint8Array([0x2d, 0x2d, 0x3e]),
  111. ScriptEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74]),
  112. StyleEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x74, 0x79, 0x6c, 0x65]),
  113. TitleEnd: new Uint8Array([0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65]), // `</title`
  114. };
  115. var Tokenizer = /** @class */ (function () {
  116. function Tokenizer(_a, cbs) {
  117. var _b = _a.xmlMode, xmlMode = _b === void 0 ? false : _b, _c = _a.decodeEntities, decodeEntities = _c === void 0 ? true : _c;
  118. this.cbs = cbs;
  119. /** The current state the tokenizer is in. */
  120. this.state = State.Text;
  121. /** The read buffer. */
  122. this.buffer = "";
  123. /** The beginning of the section that is currently being read. */
  124. this.sectionStart = 0;
  125. /** The index within the buffer that we are currently looking at. */
  126. this.index = 0;
  127. /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
  128. this.baseState = State.Text;
  129. /** For special parsing behavior inside of script and style tags. */
  130. this.isSpecial = false;
  131. /** Indicates whether the tokenizer has been paused. */
  132. this.running = true;
  133. /** The offset of the current buffer. */
  134. this.offset = 0;
  135. this.currentSequence = undefined;
  136. this.sequenceIndex = 0;
  137. this.trieIndex = 0;
  138. this.trieCurrent = 0;
  139. /** For named entities, the index of the value. For numeric entities, the code point. */
  140. this.entityResult = 0;
  141. this.entityExcess = 0;
  142. this.xmlMode = xmlMode;
  143. this.decodeEntities = decodeEntities;
  144. this.entityTrie = xmlMode ? decode_js_1.xmlDecodeTree : decode_js_1.htmlDecodeTree;
  145. }
  146. Tokenizer.prototype.reset = function () {
  147. this.state = State.Text;
  148. this.buffer = "";
  149. this.sectionStart = 0;
  150. this.index = 0;
  151. this.baseState = State.Text;
  152. this.currentSequence = undefined;
  153. this.running = true;
  154. this.offset = 0;
  155. };
  156. Tokenizer.prototype.write = function (chunk) {
  157. this.offset += this.buffer.length;
  158. this.buffer = chunk;
  159. this.parse();
  160. };
  161. Tokenizer.prototype.end = function () {
  162. if (this.running)
  163. this.finish();
  164. };
  165. Tokenizer.prototype.pause = function () {
  166. this.running = false;
  167. };
  168. Tokenizer.prototype.resume = function () {
  169. this.running = true;
  170. if (this.index < this.buffer.length + this.offset) {
  171. this.parse();
  172. }
  173. };
  174. /**
  175. * The current index within all of the written data.
  176. */
  177. Tokenizer.prototype.getIndex = function () {
  178. return this.index;
  179. };
  180. /**
  181. * The start of the current section.
  182. */
  183. Tokenizer.prototype.getSectionStart = function () {
  184. return this.sectionStart;
  185. };
  186. Tokenizer.prototype.stateText = function (c) {
  187. if (c === CharCodes.Lt ||
  188. (!this.decodeEntities && this.fastForwardTo(CharCodes.Lt))) {
  189. if (this.index > this.sectionStart) {
  190. this.cbs.ontext(this.sectionStart, this.index);
  191. }
  192. this.state = State.BeforeTagName;
  193. this.sectionStart = this.index;
  194. }
  195. else if (this.decodeEntities && c === CharCodes.Amp) {
  196. this.state = State.BeforeEntity;
  197. }
  198. };
  199. Tokenizer.prototype.stateSpecialStartSequence = function (c) {
  200. var isEnd = this.sequenceIndex === this.currentSequence.length;
  201. var isMatch = isEnd
  202. ? // If we are at the end of the sequence, make sure the tag name has ended
  203. isEndOfTagSection(c)
  204. : // Otherwise, do a case-insensitive comparison
  205. (c | 0x20) === this.currentSequence[this.sequenceIndex];
  206. if (!isMatch) {
  207. this.isSpecial = false;
  208. }
  209. else if (!isEnd) {
  210. this.sequenceIndex++;
  211. return;
  212. }
  213. this.sequenceIndex = 0;
  214. this.state = State.InTagName;
  215. this.stateInTagName(c);
  216. };
  217. /** Look for an end tag. For <title> tags, also decode entities. */
  218. Tokenizer.prototype.stateInSpecialTag = function (c) {
  219. if (this.sequenceIndex === this.currentSequence.length) {
  220. if (c === CharCodes.Gt || isWhitespace(c)) {
  221. var endOfText = this.index - this.currentSequence.length;
  222. if (this.sectionStart < endOfText) {
  223. // Spoof the index so that reported locations match up.
  224. var actualIndex = this.index;
  225. this.index = endOfText;
  226. this.cbs.ontext(this.sectionStart, endOfText);
  227. this.index = actualIndex;
  228. }
  229. this.isSpecial = false;
  230. this.sectionStart = endOfText + 2; // Skip over the `</`
  231. this.stateInClosingTagName(c);
  232. return; // We are done; skip the rest of the function.
  233. }
  234. this.sequenceIndex = 0;
  235. }
  236. if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) {
  237. this.sequenceIndex += 1;
  238. }
  239. else if (this.sequenceIndex === 0) {
  240. if (this.currentSequence === Sequences.TitleEnd) {
  241. // We have to parse entities in <title> tags.
  242. if (this.decodeEntities && c === CharCodes.Amp) {
  243. this.state = State.BeforeEntity;
  244. }
  245. }
  246. else if (this.fastForwardTo(CharCodes.Lt)) {
  247. // Outside of <title> tags, we can fast-forward.
  248. this.sequenceIndex = 1;
  249. }
  250. }
  251. else {
  252. // If we see a `<`, set the sequence index to 1; useful for eg. `<</script>`.
  253. this.sequenceIndex = Number(c === CharCodes.Lt);
  254. }
  255. };
  256. Tokenizer.prototype.stateCDATASequence = function (c) {
  257. if (c === Sequences.Cdata[this.sequenceIndex]) {
  258. if (++this.sequenceIndex === Sequences.Cdata.length) {
  259. this.state = State.InCommentLike;
  260. this.currentSequence = Sequences.CdataEnd;
  261. this.sequenceIndex = 0;
  262. this.sectionStart = this.index + 1;
  263. }
  264. }
  265. else {
  266. this.sequenceIndex = 0;
  267. this.state = State.InDeclaration;
  268. this.stateInDeclaration(c); // Reconsume the character
  269. }
  270. };
  271. /**
  272. * When we wait for one specific character, we can speed things up
  273. * by skipping through the buffer until we find it.
  274. *
  275. * @returns Whether the character was found.
  276. */
  277. Tokenizer.prototype.fastForwardTo = function (c) {
  278. while (++this.index < this.buffer.length + this.offset) {
  279. if (this.buffer.charCodeAt(this.index - this.offset) === c) {
  280. return true;
  281. }
  282. }
  283. /*
  284. * We increment the index at the end of the `parse` loop,
  285. * so set it to `buffer.length - 1` here.
  286. *
  287. * TODO: Refactor `parse` to increment index before calling states.
  288. */
  289. this.index = this.buffer.length + this.offset - 1;
  290. return false;
  291. };
  292. /**
  293. * Comments and CDATA end with `-->` and `]]>`.
  294. *
  295. * Their common qualities are:
  296. * - Their end sequences have a distinct character they start with.
  297. * - That character is then repeated, so we have to check multiple repeats.
  298. * - All characters but the start character of the sequence can be skipped.
  299. */
  300. Tokenizer.prototype.stateInCommentLike = function (c) {
  301. if (c === this.currentSequence[this.sequenceIndex]) {
  302. if (++this.sequenceIndex === this.currentSequence.length) {
  303. if (this.currentSequence === Sequences.CdataEnd) {
  304. this.cbs.oncdata(this.sectionStart, this.index, 2);
  305. }
  306. else {
  307. this.cbs.oncomment(this.sectionStart, this.index, 2);
  308. }
  309. this.sequenceIndex = 0;
  310. this.sectionStart = this.index + 1;
  311. this.state = State.Text;
  312. }
  313. }
  314. else if (this.sequenceIndex === 0) {
  315. // Fast-forward to the first character of the sequence
  316. if (this.fastForwardTo(this.currentSequence[0])) {
  317. this.sequenceIndex = 1;
  318. }
  319. }
  320. else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
  321. // Allow long sequences, eg. --->, ]]]>
  322. this.sequenceIndex = 0;
  323. }
  324. };
  325. /**
  326. * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name.
  327. *
  328. * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar).
  329. * We allow anything that wouldn't end the tag.
  330. */
  331. Tokenizer.prototype.isTagStartChar = function (c) {
  332. return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c);
  333. };
  334. Tokenizer.prototype.startSpecial = function (sequence, offset) {
  335. this.isSpecial = true;
  336. this.currentSequence = sequence;
  337. this.sequenceIndex = offset;
  338. this.state = State.SpecialStartSequence;
  339. };
  340. Tokenizer.prototype.stateBeforeTagName = function (c) {
  341. if (c === CharCodes.ExclamationMark) {
  342. this.state = State.BeforeDeclaration;
  343. this.sectionStart = this.index + 1;
  344. }
  345. else if (c === CharCodes.Questionmark) {
  346. this.state = State.InProcessingInstruction;
  347. this.sectionStart = this.index + 1;
  348. }
  349. else if (this.isTagStartChar(c)) {
  350. var lower = c | 0x20;
  351. this.sectionStart = this.index;
  352. if (!this.xmlM