parse-matches.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. import { alphaNumericAndMarksRe, digitRe } from '../regex-lib';
  2. import { UrlMatch } from '../match/url-match';
  3. import { remove, assertNever } from '../utils';
  4. import { httpSchemeRe, isDomainLabelChar, isDomainLabelStartChar, isPathChar, isSchemeChar, isSchemeStartChar, isUrlSuffixStartChar, isValidIpV4Address, isValidSchemeUrl, isValidTldMatch, urlSuffixedCharsNotAllowedAtEndRe, } from './uri-utils';
  5. import { isEmailLocalPartChar, isEmailLocalPartStartChar, isValidEmail, mailtoSchemePrefixRe, } from './email-utils';
  6. import { EmailMatch } from '../match/email-match';
  7. import { isHashtagTextChar, isValidHashtag } from './hashtag-utils';
  8. import { HashtagMatch } from '../match/hashtag-match';
  9. import { isMentionTextChar, isValidMention } from './mention-utils';
  10. import { MentionMatch } from '../match/mention-match';
  11. import { isPhoneNumberSeparatorChar, isPhoneNumberControlChar, isValidPhoneNumber, } from './phone-number-utils';
  12. import { PhoneMatch } from '../match/phone-match';
  13. // For debugging: search for and uncomment other "For debugging" lines
  14. // import CliTable from 'cli-table';
  15. /**
  16. * Parses URL, email, twitter, mention, and hashtag matches from the given
  17. * `text`.
  18. */
  19. export function parseMatches(text, args) {
  20. var tagBuilder = args.tagBuilder;
  21. var stripPrefix = args.stripPrefix;
  22. var stripTrailingSlash = args.stripTrailingSlash;
  23. var decodePercentEncoding = args.decodePercentEncoding;
  24. var hashtagServiceName = args.hashtagServiceName;
  25. var mentionServiceName = args.mentionServiceName;
  26. var matches = [];
  27. var textLen = text.length;
  28. // An array of all active state machines. Empty array means we're in the
  29. // "no url" state
  30. var stateMachines = [];
  31. // For debugging: search for and uncomment other "For debugging" lines
  32. // const table = new CliTable({
  33. // head: ['charIdx', 'char', 'states', 'charIdx', 'startIdx', 'reached accept state'],
  34. // });
  35. var charIdx = 0;
  36. for (; charIdx < textLen; charIdx++) {
  37. var char = text.charAt(charIdx);
  38. if (stateMachines.length === 0) {
  39. stateNoMatch(char);
  40. }
  41. else {
  42. // Must loop through the state machines backwards for when one
  43. // is removed
  44. for (var stateIdx = stateMachines.length - 1; stateIdx >= 0; stateIdx--) {
  45. var stateMachine = stateMachines[stateIdx];
  46. switch (stateMachine.state) {
  47. // Protocol-relative URL states
  48. case 11 /* ProtocolRelativeSlash1 */:
  49. stateProtocolRelativeSlash1(stateMachine, char);
  50. break;
  51. case 12 /* ProtocolRelativeSlash2 */:
  52. stateProtocolRelativeSlash2(stateMachine, char);
  53. break;
  54. case 0 /* SchemeChar */:
  55. stateSchemeChar(stateMachine, char);
  56. break;
  57. case 1 /* SchemeHyphen */:
  58. stateSchemeHyphen(stateMachine, char);
  59. break;
  60. case 2 /* SchemeColon */:
  61. stateSchemeColon(stateMachine, char);
  62. break;
  63. case 3 /* SchemeSlash1 */:
  64. stateSchemeSlash1(stateMachine, char);
  65. break;
  66. case 4 /* SchemeSlash2 */:
  67. stateSchemeSlash2(stateMachine, char);
  68. break;
  69. case 5 /* DomainLabelChar */:
  70. stateDomainLabelChar(stateMachine, char);
  71. break;
  72. case 6 /* DomainHyphen */:
  73. stateDomainHyphen(stateMachine, char);
  74. break;
  75. case 7 /* DomainDot */:
  76. stateDomainDot(stateMachine, char);
  77. break;
  78. case 13 /* IpV4Digit */:
  79. stateIpV4Digit(stateMachine, char);
  80. break;
  81. case 14 /* IpV4Dot */:
  82. stateIPv4Dot(stateMachine, char);
  83. break;
  84. case 8 /* PortColon */:
  85. statePortColon(stateMachine, char);
  86. break;
  87. case 9 /* PortNumber */:
  88. statePortNumber(stateMachine, char);
  89. break;
  90. case 10 /* Path */:
  91. statePath(stateMachine, char);
  92. break;
  93. // Email States
  94. case 15 /* EmailMailto_M */:
  95. stateEmailMailto_M(stateMachine, char);
  96. break;
  97. case 16 /* EmailMailto_A */:
  98. stateEmailMailto_A(stateMachine, char);
  99. break;
  100. case 17 /* EmailMailto_I */:
  101. stateEmailMailto_I(stateMachine, char);
  102. break;
  103. case 18 /* EmailMailto_L */:
  104. stateEmailMailto_L(stateMachine, char);
  105. break;
  106. case 19 /* EmailMailto_T */:
  107. stateEmailMailto_T(stateMachine, char);
  108. break;
  109. case 20 /* EmailMailto_O */:
  110. stateEmailMailto_O(stateMachine, char);
  111. break;
  112. case 21 /* EmailMailto_Colon */:
  113. stateEmailMailtoColon(stateMachine, char);
  114. break;
  115. case 22 /* EmailLocalPart */:
  116. stateEmailLocalPart(stateMachine, char);
  117. break;
  118. case 23 /* EmailLocalPartDot */:
  119. stateEmailLocalPartDot(stateMachine, char);
  120. break;
  121. case 24 /* EmailAtSign */:
  122. stateEmailAtSign(stateMachine, char);
  123. break;
  124. case 25 /* EmailDomainChar */:
  125. stateEmailDomainChar(stateMachine, char);
  126. break;
  127. case 26 /* EmailDomainHyphen */:
  128. stateEmailDomainHyphen(stateMachine, char);
  129. break;
  130. case 27 /* EmailDomainDot */:
  131. stateEmailDomainDot(stateMachine, char);
  132. break;
  133. // Hashtag states
  134. case 28 /* HashtagHashChar */:
  135. stateHashtagHashChar(stateMachine, char);
  136. break;
  137. case 29 /* HashtagTextChar */:
  138. stateHashtagTextChar(stateMachine, char);
  139. break;
  140. // Mention states
  141. case 30 /* MentionAtChar */:
  142. stateMentionAtChar(stateMachine, char);
  143. break;
  144. case 31 /* MentionTextChar */:
  145. stateMentionTextChar(stateMachine, char);
  146. break;
  147. // Phone number states
  148. case 32 /* PhoneNumberOpenParen */:
  149. statePhoneNumberOpenParen(stateMachine, char);
  150. break;
  151. case 33 /* PhoneNumberAreaCodeDigit1 */:
  152. statePhoneNumberAreaCodeDigit1(stateMachine, char);
  153. break;
  154. case 34 /* PhoneNumberAreaCodeDigit2 */:
  155. statePhoneNumberAreaCodeDigit2(stateMachine, char);
  156. break;
  157. case 35 /* PhoneNumberAreaCodeDigit3 */:
  158. statePhoneNumberAreaCodeDigit3(stateMachine, char);
  159. break;
  160. case 36 /* PhoneNumberCloseParen */:
  161. statePhoneNumberCloseParen(stateMachine, char);
  162. break;
  163. case 37 /* PhoneNumberPlus */:
  164. statePhoneNumberPlus(stateMachine, char);
  165. break;
  166. case 38 /* PhoneNumberDigit */:
  167. statePhoneNumberDigit(stateMachine, char);
  168. break;
  169. case 39 /* PhoneNumberSeparator */:
  170. statePhoneNumberSeparator(stateMachine, char);
  171. break;
  172. case 40 /* PhoneNumberControlChar */:
  173. statePhoneNumberControlChar(stateMachine, char);
  174. break;
  175. case 41 /* PhoneNumberPoundChar */:
  176. statePhoneNumberPoundChar(stateMachine, char);
  177. break;
  178. default:
  179. assertNever(stateMachine.state);
  180. }
  181. }
  182. }
  183. // For debugging: search for and uncomment other "For debugging" lines
  184. // table.push([
  185. // charIdx,
  186. // char,
  187. // stateMachines.map(machine => State[machine.state]).join('\n') || '(none)',
  188. // charIdx,
  189. // stateMachines.map(m => m.startIdx).join('\n'),
  190. // stateMachines.map(m => m.acceptStateReached).join('\n'),
  191. // ]);
  192. }
  193. // Capture any valid match at the end of the string
  194. // Note: this loop must happen in reverse because
  195. // captureMatchIfValidAndRemove() removes state machines from the array
  196. // and we'll end up skipping every other one if we remove while looping
  197. // forward
  198. for (var i = stateMachines.length - 1; i >= 0; i--) {
  199. stateMachines.forEach(function (stateMachine) { return captureMatchIfValidAndRemove(stateMachine); });
  200. }
  201. // For debugging: search for and uncomment other "For debugging" lines
  202. // console.log(`\nRead string:\n ${text}`);
  203. // console.log(table.toString());
  204. return matches;
  205. // Handles the state when we're not in a URL/email/etc. (i.e. when no state machines exist)
  206. function stateNoMatch(char) {
  207. if (char === '#') {
  208. // Hash char, start a Hashtag match
  209. stateMachines.push(createHashtagStateMachine(charIdx, 28 /* HashtagHashChar */));
  210. }
  211. else if (char === '@') {
  212. // '@' char, start a Mention match
  213. stateMachines.push(createMentionStateMachine(charIdx, 30 /* MentionAtChar */));
  214. }
  215. else if (char === '/') {
  216. // A slash could begin a protocol-relative URL
  217. stateMachines.push(createTldUrlStateMachine(charIdx, 11 /* ProtocolRelativeSlash1 */));
  218. }
  219. else if (char === '+') {
  220. // A '+' char can start a Phone number
  221. stateMachines.push(createPhoneNumberStateMachine(charIdx, 37 /* PhoneNumberPlus */));
  222. }
  223. else if (char === '(') {
  224. stateMachines.push(createPhoneNumberStateMachine(charIdx, 32 /* PhoneNumberOpenParen */));
  225. }
  226. else {
  227. if (digitRe.test(char)) {
  228. // A digit could start a phone number
  229. stateMachines.push(createPhoneNumberStateMachine(charIdx, 38 /* PhoneNumberDigit */));
  230. // A digit could start an IP address
  231. stateMachines.push(createIpV4UrlStateMachine(charIdx, 13 /* IpV4Digit */));
  232. }
  233. if (isEmailLocalPartStartChar(char)) {
  234. // Any email local part. An 'm' character in particular could
  235. // start a 'mailto:' match
  236. var startState = char.toLowerCase() === 'm' ? 15 /* EmailMailto_M */ : 22 /* EmailLocalPart */;
  237. stateMachines.push(createEmailStateMachine(charIdx, startState));
  238. }
  239. if (isSchemeStartChar(char)) {
  240. // An uppercase or lowercase letter may start a scheme match
  241. stateMachines.push(createSchemeUrlStateMachine(charIdx, 0 /* SchemeChar */));
  242. }
  243. if (alphaNumericAndMarksRe.test(char)) {
  244. // A unicode alpha character or digit could start a domain name
  245. // label for a TLD match
  246. stateMachines.push(createTldUrlStateMachine(charIdx, 5 /* DomainLabelChar */));
  247. }
  248. }
  249. // Anything else, remain in the "non-url" state by not creating any
  250. // state machines
  251. }
  252. // Implements ABNF: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  253. function stateSchemeChar(stateMachine, char) {
  254. if (char === ':') {
  255. stateMachine.state = 2 /* SchemeColon */;
  256. }
  257. else if (char === '-') {
  258. stateMachine.state = 1 /* SchemeHyphen */;
  259. }
  260. else if (isSchemeChar(char)) {
  261. // Stay in SchemeChar state
  262. }
  263. else {
  264. // Any other character, not a scheme
  265. remove(stateMachines, stateMachine);
  266. }
  267. }
  268. function stateSchemeHyphen(stateMachine, char) {
  269. if (char === '-') {
  270. // Stay in SchemeHyphen state
  271. // TODO: Should a colon following a dash be counted as the end of the scheme?
  272. // } else if (char === ':') {
  273. // stateMachine.state = State.SchemeColon;
  274. }
  275. else if (char === '/') {
  276. // Not a valid scheme match, but may be the start of a
  277. // protocol-relative match (such as //google.com)
  278. remove(stateMachines, stateMachine);
  279. stateMachines.push(createTldUrlStateMachine(charIdx, 11 /* ProtocolRelativeSlash1 */));
  280. }
  281. else if (isSchemeChar(char)) {
  282. stateMachine.state = 0 /* SchemeChar */;
  283. }
  284. else {
  285. // Any other character, not a scheme
  286. remove(stateMachines, stateMachine);
  287. }
  288. }
  289. function stateSchemeColon(stateMachine, char) {
  290. if (char === '/') {
  291. stateMachine.state = 3 /* SchemeSlash1 */;
  292. }
  293. else if (char === '.') {
  294. // We've read something like 'hello:.' - don't capture
  295. remove(stateMachines, stateMachine);
  296. }
  297. else if (isDomainLabelStartChar(char)) {
  298. stateMachine.state = 5 /* DomainLabelChar */;
  299. // It's possible that we read an "introduction" piece of text,
  300. // and the character after the current colon actually starts an
  301. // actual scheme. An example of this is:
  302. // "The link:http://google.com"
  303. // Hence, start a new machine to capture this match if so
  304. if (isSchemeStartChar(char)) {
  305. stateMachines.push(createSchemeUrlStateMachine(charIdx, 0 /* SchemeChar */));
  306. }
  307. }
  308. else {
  309. remove(stateMachines, stateMachine);
  310. }
  311. }
  312. function stateSchemeSlash1(stateMachine, char) {
  313. if (char === '/') {
  314. stateMachine.state = 4 /* SchemeSlash2 */;
  315. }
  316. else if (isPathChar(char)) {
  317. stateMachine.state = 10 /* Path */;
  318. stateMachine.acceptStateReached = true;
  319. }
  320. else {
  321. captureMatchIfValidAndRemove(stateMachine);
  322. }
  323. }
  324. function stateSchemeSlash2(stateMachine, char) {
  325. if (char === '/') {
  326. // 3rd slash, must be an absolute path (path-absolute in the
  327. // ABNF), such as in a file:///c:/windows/etc. See
  328. // https://tools.ietf.org/html/rfc3986#appendix-A
  329. stateMachine.state = 10 /* Path */;
  330. }
  331. else if (isDomainLabelStartChar(char)) {
  332. // start of "authority" section - see https://tools.ietf.org/html/rfc3986#appendix-A
  333. stateMachine.state = 5 /* DomainLabelChar */;
  334. stateMachine.acceptStateReached = true;
  335. }
  336. else {
  337. // not valid
  338. remove(stateMachines, stateMachine);
  339. }
  340. }
  341. // Handles reading a '/' from the NonUrl state
  342. function stateProtocolRelativeSlash1(stateMachine, char) {
  343. if (char === '/') {
  344. stateMachine.state = 12 /* ProtocolRelativeSlash2 */;
  345. }
  346. else {
  347. // Anything else, cannot be the start of a protocol-relative
  348. // URL.
  349. remove(stateMachines, stateMachine);
  350. }
  351. }
  352. // Handles reading a second '/', which could start a protocol-relative URL
  353. function stateProtocolRelativeSlash2(stateMachine, char) {
  354. if (isDomainLabelStartChar(char)) {
  355. stateMachine.state = 5 /* DomainLabelChar */;
  356. }
  357. else {
  358. // Anything else, not a URL
  359. remove(stateMachines, stateMachine);
  360. }
  361. }
  362. // Handles when we have read a domain label character
  363. function stateDomainLabelChar(stateMachine, char) {
  364. if (char === '.') {
  365. stateMachine.state = 7 /* DomainDot */;
  366. }
  367. else if (char === '-') {
  368. stateMachine.state = 6 /* DomainHyphen */;
  369. }
  370. else if (char === ':') {
  371. // Beginning of a port number, end the domain name
  372. stateMachine.state = 8 /* PortColon */;
  373. }
  374. else if (isUrlSuffixStartChar(char)) {
  375. // '/', '?', or '#'
  376. stateMachine.state = 10 /* Path */;
  377. }
  378. else if (isDomainLabelChar(char)) {
  379. // Stay in the DomainLabelChar state
  380. }
  381. else {
  382. // Anything else, end the domain name
  383. captureMatchIfValidAndRemove(stateMachine);
  384. }
  385. }
  386. function stateDomainHyphen(stateMachine, char) {
  387. if (char === '-') {
  388. // Remain in the DomainHyphen state
  389. }
  390. else if (char === '.') {
  391. // Not valid to have a '-.' in a domain label
  392. captureMatchIfValidAndRemove(stateMachine);
  393. }
  394. else if (isDomainLabelStartChar(char)) {
  395. stateMachine.state = 5 /* DomainLabelChar */;
  396. }
  397. else {
  398. captureMatchIfValidAndRemove(stateMachine);
  399. }
  400. }
  401. function stateDomainDot(stateMachine, char) {
  402. if (char === '.') {
  403. // domain names cannot have multiple '.'s next to each other.
  404. // It's possible we've already read a valid domain name though,
  405. // and that the '..' sequence just forms an ellipsis at the end
  406. // of a sentence
  407. captureMatchIfValidAndRemove(stateMachine);
  408. }
  409. else if (isDomainLabelStartChar(char)) {
  410. stateMachine.state = 5 /* DomainLabelChar */;
  411. stateMachine.acceptStateReached = true; // after hitting a dot, and then another domain label, we've reached an accept state
  412. }
  413. else {
  414. // Anything else, end the domain name
  415. captureMatchIfValidAndRemove(stateMachine);
  416. }
  417. }
  418. function stateIpV4Digit(stateMachine, char) {
  419. if (char === '.') {
  420. stateMachine.state = 14 /* IpV4Dot */;
  421. }
  422. else if (char === ':') {
  423. // Beginning of a port number
  424. stateMachine.state = 8 /* PortColon */;
  425. }
  426. else if (digitRe.test(char)) {
  427. // stay in the IPv4 digit state
  428. }
  429. else if (isUrlSuffixStartChar(char)) {
  430. stateMachine.state = 10 /* Path */;
  431. }
  432. else if (alphaNumericAndMarksRe.test(char)) {
  433. // If we hit an alpha character, must not be an IPv4
  434. // Example of this: 1.2.3.4abc
  435. remove(stateMachines, stateMachine);
  436. }
  437. else {
  438. captureMatchIfValidAndRemove(stateMachine);
  439. }
  440. }
  441. function stateIPv4Dot(stateMachine, char) {
  442. if (digitRe.test(char)) {
  443. stateMachine.octetsEncountered++;
  444. // Once we have encountered 4 octets, it's *potentially* a valid
  445. // IPv4 address. Our IPv4 regex will confirm the match later
  446. // though to make sure each octet is in the 0-255 range, and
  447. // there's exactly 4 octets (not 5 or more)
  448. if (stateMachine.octetsEncountered === 4) {
  449. stateMachine.acceptStateReached = true;
  450. }
  451. stateMachine.state = 13 /* IpV4Digit */;
  452. }
  453. else {
  454. captureMatchIfValidAndRemove(stateMachine);
  455. }
  456. }
  457. function statePortColon(stateMachine, char) {
  458. if (digitRe.test(char)) {
  459. stateMachine.state = 9 /* PortNumber */;
  460. }
  461. else {
  462. captureMatchIfValidAndRemove(stateMachine);
  463. }
  464. }
  465. function statePortNumber(stateMachine, char) {
  466. if (digitRe.test(char)) {
  467. // Stay in port number state
  468. }
  469. else if (isUrlSuffixStartChar(char)) {
  470. // '/', '?', or '#'
  471. stateMachine.state = 10 /* Path */;
  472. }
  473. else {
  474. captureMatchIfValidAndRemove(stateMachine);
  475. }
  476. }
  477. function statePath(stateMachine, char) {
  478. if (isPathChar(char)) {
  479. // Stay in the path state
  480. }
  481. else {
  482. captureMatchIfValidAndRemove(stateMachine);
  483. }
  484. }
  485. // Handles if we're reading a 'mailto:' prefix on the string
  486. function stateEmailMailto_M(stateMachine, char) {
  487. if (char.toLowerCase() === 'a') {
  488. stateMachine.state = 16 /* EmailMailto_A */;
  489. }
  490. else {
  491. stateEmailLocalPart(stateMachine, char);
  492. }
  493. }
  494. function stateEmailMailto_A(stateMachine, char) {
  495. if (char.toLowerCase() === 'i') {
  496. stateMachine.state = 17 /* EmailMailto_I */;
  497. }
  498. else {
  499. stateEmailLocalPart(stateMachine, char);
  500. }
  501. }
  502. function stateEmailMailto_I(stateMachine, char) {
  503. if (char.toLowerCase() === 'l') {
  504. stateMachine.state = 18 /* EmailMailto_L */;
  505. }
  506. else {
  507. stateEmailLocalPart(stateMachine, char);
  508. }
  509. }
  510. function stateEmailMailto_L(stateMachine, char) {
  511. if (char.toLowerCase() === 't') {
  512. stateMachine.state = 19 /* EmailMailto_T */;
  513. }
  514. else {
  515. stateEmailLocalPart(stateMachine, char);
  516. }
  517. }
  518. function stateEmailMailto_T(stateMachine, char) {
  519. if (char.toLowerCase() === 'o') {
  520. stateMachine.state = 20 /* EmailMailto_O */;
  521. }
  522. else {
  523. stateEmailLocalPart(stateMachine, char);
  524. }
  525. }
  526. function stateEmailMailto_O(stateMachine, char) {
  527. if (char.toLowerCase() === ':') {
  528. stateMachine.state = 21 /* EmailMailto_Colon */;
  529. }
  530. else {
  531. stateEmailLocalPart(stateMachine, char);
  532. }
  533. }
  534. function stateEmailMailtoColon(stateMachine, char) {
  535. if (isEmailLocalPartChar(char)) {
  536. stateMachine.state = 22 /* EmailLocalPart */;
  537. }
  538. else {
  539. remove(stateMachines, stateMachine);
  540. }
  541. }
  542. // Handles the state when we're currently in the "local part" of an
  543. // email address (as opposed to the "domain part")
  544. function stateEmailLocalPart(stateMachine, char) {
  545. if (char === '.') {
  546. stateMachine.state = 23 /* EmailLocalPartDot */;
  547. }
  548. else if (char === '@') {
  549. stateMachine.state = 24 /* EmailAtSign */;
  550. }
  551. else if (isEmailLocalPartChar(char)) {
  552. // stay in the "local part" of the email address
  553. // Note: because stateEmailLocalPart() is called from the
  554. // 'mailto' states (when the 'mailto' prefix itself has been
  555. // broken), make sure to set the state to EmailLocalPart
  556. stateMachine.state = 22 /* EmailLocalPart */;
  557. }
  558. else {
  559. // not an email address character
  560. remove(stateMachines, stateMachine);
  561. }
  562. }
  563. // Handles the state where we've read
  564. function stateEmailLocalPartDot(stateMachine, char) {
  565. if (char === '.') {
  566. // We read a second '.' in a row, not a valid email address
  567. // local part
  568. remove(stateMachines, stateMachine);
  569. }
  570. else if (char === '@') {
  571. // We read the '@' character immediately after a dot ('.'), not
  572. // an email address
  573. remove(stateMachines, stateMachine);
  574. }
  575. else if (isEmailLocalPartChar(char)) {
  576. stateMachine.state = 22 /* EmailLocalPart */;
  577. }
  578. else {
  579. // Anything else, not an email address
  580. remove(stateMachines, stateMachine);
  581. }
  582. }
  583. function stateEmailAtSign(stateMachine, char) {
  584. if (isDomainLabelStartChar(char)) {
  585. stateMachine.state = 25 /* EmailDomainChar */;
  586. }
  587. else {
  588. // Anything else, not an email address
  589. remove(stateMachines, stateMachine);
  590. }
  591. }
  592. function stateEmailDomainChar(stateMachine, char) {
  593. if (char === '.') {
  594. stateMachine.state = 27 /* EmailDomainDot */;
  595. }
  596. else if (char === '-') {
  597. stateMachine.state = 26 /* EmailDomainHyphen */;
  598. }
  599. else if (isDomainLabelChar(char)) {
  600. // Stay in the DomainChar state
  601. }
  602. else {
  603. // Anything else, we potentially matched if the criteria has
  604. // been met
  605. captureMatchIfValidAndRemove(stateMachine);
  606. }
  607. }
  608. function stateEmailDomainHyphen(stateMachine, char) {
  609. if (char === '-' || char === '.') {
  610. // Not valid to have two hyphens ("--") or hypen+dot ("-.")
  611. captureMatchIfValidAndRemove(stateMachine);
  612. }
  613. else if (isDomainLabelChar(char)) {
  614. stateMachine.state = 25 /* EmailDomainChar */;
  615. }
  616. else {
  617. // Anything else
  618. captureMatchIfValidAndRemove(stateMachine);
  619. }
  620. }
  621. function stateEmailDomainDot(stateMachine, char) {
  622. if (char === '.' || char === '-') {
  623. // not valid to have two dots ("..") or dot+hypen (".-")
  624. captureMatchIfValidAndRemove(stateMachine);
  625. }
  626. else if (isDomainLabelStartChar(char)) {
  627. stateMachine.state = 25 /* EmailDomainChar */;
  628. // After having read a '.' and then a valid domain character,
  629. // we now know that the domain part of the email is valid, and
  630. // we have found at least a partial EmailMatch (however, the
  631. // email address may have additional characters from this point)
  632. stateMachine.acceptStateReached = true;
  633. }
  634. else {
  635. // Anything else
  636. captureMatchIfValidAndRemove(stateMachine);
  637. }
  638. }
  639. // Handles the state when we've just encountered a '#' character
  640. function stateHashtagHashChar(stateMachine, char) {
  641. if (isHashtagTextChar(char)) {
  642. // '#' char with valid hash text char following
  643. stateMachine.state = 29 /* HashtagTextChar */;
  644. stateMachine.acceptStateReached = true;
  645. }
  646. else {
  647. remove(stateMachines, stateMachine);
  648. }
  649. }
  650. // Handles the state when we're currently in the hash tag's text chars
  651. function stateHashtagTextChar(stateMachine, char) {
  652. if (isHashtagTextChar(char)) {
  653. // Continue reading characters in the HashtagText state
  654. }
  655. else {
  656. captureMatchIfValidAndRemove(stateMachine);
  657. }
  658. }
  659. // Handles the state when we've just encountered a '@' character
  660. function stateMentionAtChar(stateMachine, char) {
  661. if (isMentionTextChar(char)) {
  662. // '@' char with valid mention text char following
  663. stateMachine.state = 31 /* MentionTextChar */;
  664. stateMachine.acceptStateReached = true;
  665. }
  666. else {
  667. remove(stateMachines, stateMachine);
  668. }
  669. }
  670. // Handles the state when we're currently in the mention's text chars
  671. function stateMentionTextChar(stateMachine, char) {
  672. if (isMentionTextChar(char)) {
  673. // Continue reading characters in the HashtagText state
  674. }
  675. else if (alphaNumericAndMarksRe.test(char)) {
  676. // Char is invalid for a mention text char, not a valid match.
  677. // Note that ascii alphanumeric chars are okay (which are tested
  678. // in the previous 'if' statement, but others are not)
  679. remove(stateMachines, stateMachine);
  680. }
  681. else {
  682. captureMatchIfValidAndRemove(stateMachine);
  683. }
  684. }
  685. function statePhoneNumberPlus(stateMachine, char) {
  686. if (digitRe.test(char)) {
  687. stateMachine.state = 38 /* PhoneNumberDigit */;
  688. }
  689. else {
  690. remove(stateMachines, stateMachine);
  691. // This character may start a new match. Add states for it
  692. stateNoMatch(char);
  693. }
  694. }
  695. function statePhoneNumberOpenParen(stateMachine, char) {
  696. if (digitRe.test(char)) {
  697. stateMachine.state = 33 /* PhoneNumberAreaCodeDigit1 */;
  698. }
  699. else {
  700. remove(stateMachines, stateMachine);
  701. }
  702. // It's also possible that the paren was just an open brace for
  703. // a piece of text. Start other machines
  704. stateNoMatch(char);
  705. }
  706. function statePhoneNumberAreaCodeDigit1(stateMachine, char) {
  707. if (digitRe.test(char)) {
  708. stateMachine.state = 34 /* PhoneNumberAreaCodeDigit2 */;
  709. }
  710. else {
  711. remove(stateMachines, stateMachine);
  712. }
  713. }
  714. function statePhoneNumberAreaCodeDigit2(stateMachine, char) {
  715. if (digitRe.test(char)) {
  716. stateMachine.state = 35 /* PhoneNumberAreaCodeDigit3 */;
  717. }
  718. else {
  719. remove(stateMachines, stateMachine);
  720. }
  721. }
  722. function statePhoneNumberAreaCodeDigit3(stateMachine, char) {
  723. if (char === ')') {
  724. stateMachine.state = 36 /* PhoneNumberCloseParen */;
  725. }
  726. else {
  727. remove(stateMachines, stateMachine);
  728. }
  729. }
  730. function statePhoneNumberCloseParen(stateMachine, char) {
  731. if (digitRe.test(char)) {
  732. stateMachine.state = 38 /* PhoneNumberDigit */;
  733. }
  734. else if (isPhoneNumberSeparatorChar(char)) {
  735. stateMachine.state = 39 /* PhoneNumberSeparator */;
  736. }
  737. else {
  738. remove(stateMachines, stateMachine);
  739. }
  740. }
  741. function statePhoneNumberDigit(stateMachine, char) {
  742. // For now, if we've reached any digits, we'll say that the machine
  743. // has reached its accept state. The phone regex will confirm the
  744. // match later.
  745. // Alternatively, we could count the number of digits to avoid
  746. // invoking the phone number regex
  747. stateMachine.acceptStateReached = true;
  748. if (isPhoneNumberControlChar(char)) {
  749. stateMachine.state = 40 /* PhoneNumberControlChar */;
  750. }
  751. else if (char === '#') {
  752. stateMachine.state = 41 /* PhoneNumberPoundChar */;
  753. }
  754. else if (digitRe.test(char)) {
  755. // Stay in the phone number digit state
  756. }
  757. else if (char === '(') {
  758. stateMachine.state = 32 /* PhoneNumberOpenParen */;
  759. }
  760. else if (isPhoneNumberSeparatorChar(char)) {
  761. stateMachine.state = 39 /* PhoneNumberSeparator */;
  762. }
  763. else {
  764. captureMatchIfValidAndRemove(stateMachine);
  765. // The transition from a digit character to a letter can be the
  766. // start of a new scheme URL match
  767. if (isSchemeStartChar(char)) {
  768. stateMachines.push(createSchemeUrlStateMachine(charIdx, 0 /* SchemeChar */));
  769. }
  770. }
  771. }
  772. function statePhoneNumberSeparator(stateMachine, char) {
  773. if (digitRe.test(char)) {
  774. stateMachine.state = 38 /* PhoneNumberDigit */;
  775. }
  776. else if (char === '(') {
  777. stateMachine.state = 32 /* PhoneNumberOpenParen */;
  778. }
  779. else {
  780. captureMatchIfValidAndRemove(stateMachine);
  781. // This character may start a new match. Add states for it
  782. stateNoMatch(char);
  783. }
  784. }
  785. // The ";" characters is "wait" in a phone number
  786. // The "," characters is "pause" in a phone number
  787. function statePhoneNumberControlChar(stateMachine, char) {
  788. if (isPhoneNumberControlChar(char)) {
  789. // Stay in the "control char" state
  790. }
  791. else if (char === '#') {
  792. stateMachine.state = 41 /* PhoneNumberPoundChar */;
  793. }
  794. else if (digitRe.test(char)) {
  795. stateMachine.state = 38 /* PhoneNumberDigit */;
  796. }
  797. else {
  798. captureMatchIfValidAndRemove(stateMachine);
  799. }
  800. }
  801. // The "#" characters is "pound" in a phone number
  802. function statePhoneNumberPoundChar(stateMachine, char) {
  803. if (isPhoneNumberControlChar(char)) {
  804. stateMachine.state = 40 /* PhoneNumberControlChar */;
  805. }
  806. else if (digitRe.test(char)) {
  807. // According to some of the older tests, if there's a digit
  808. // after a '#' sign, the match is invalid. TODO: Revisit if this is true
  809. remove(stateMachines, stateMachine);
  810. }
  811. else {
  812. captureMatchIfValidAndRemove(stateMachine);
  813. }
  814. }
  815. /*
  816. * Captures a match if it is valid (i.e. has a full domain name for a
  817. * TLD match). If a match is not valid, it is possible that we want to
  818. * keep reading characters in order to make a full match.
  819. */
  820. function captureMatchIfValidAndRemove(stateMachine) {
  821. // Remove the state machine first. There are a number of code paths
  822. // which return out of this function early, so make sure we have
  823. // this done
  824. remove(stateMachines, stateMachine);
  825. // Make sure the state machine being checked has actually reached an
  826. // "accept" state. If it hasn't reach one, it can't be a match
  827. if (!stateMachine.acceptStateReached) {
  828. return;
  829. }
  830. var startIdx = stateMachine.startIdx;
  831. var matchedText = text.slice(stateMachine.startIdx, charIdx);
  832. // Handle any unbalanced braces (parens, square brackets, or curly
  833. // brackets) inside the URL. This handles situations like:
  834. // The link (google.com)
  835. // and
  836. // Check out this link here (en.wikipedia.org/wiki/IANA_(disambiguation))
  837. //
  838. // And also remove any punctuation chars at the end such as:
  839. // '?', ',', ':', '.', etc.
  840. matchedText = excludeUnbalancedTrailingBracesAndPunctuation(matchedText);
  841. if (stateMachine.type === 'url') {
  842. // We don't want to accidentally match a URL that is preceded by an
  843. // '@' character, which would be an email address
  844. var charBeforeUrlMatch = text.charAt(stateMachine.startIdx - 1);
  845. if (charBeforeUrlMatch === '@') {
  846. return;
  847. }
  848. // For the purpose of this parser, we've generalized 'www'
  849. // matches as part of 'tld' matches. However, for backward
  850. // compatibility, we distinguish beween TLD matches and matches
  851. // that begin with 'www.' so that users may turn off 'www'
  852. // matches. As such, we need to correct for that now if the
  853. // URL begins with 'www.'
  854. var urlMatchType = stateMachine.matchType;
  855. if (urlMatchType === 'scheme') {
  856. // Autolinker accepts many characters in a url's scheme (like `fake://test.com`).
  857. // However, in cases where a URL is missing whitespace before an obvious link,
  858. // (for example: `nowhitespacehttp://www.test.com`), we only want the match to start
  859. // at the http:// part. We will check if the match contains a common scheme and then
  860. // shift the match to start from there.
  861. var httpSchemeMatch = httpSchemeRe.exec(matchedText);
  862. if (httpSchemeMatch) {
  863. // If we found an overmatched URL, we want to find the index
  864. // of where the match should start and shift the match to
  865. // start from the beginning of the common scheme
  866. startIdx = startIdx + httpSchemeMatch.index;
  867. matchedText = matchedText.slice(httpSchemeMatch.index);
  868. }
  869. if (!isValidSchemeUrl(matchedText)) {
  870. return; // not a valid match
  871. }
  872. }
  873. else if (urlMatchType === 'tld') {
  874. if (!isValidTldMatch(matchedText)) {
  875. return; // not a valid match
  876. }
  877. }
  878. else if (urlMatchType === 'ipV4') {
  879. if (!isValidIpV4Address(matchedText)) {
  880. return; // not a valid match
  881. }
  882. }
  883. else {
  884. assertNever(urlMatchType);
  885. }
  886. matches.push(new UrlMatch({
  887. tagBuilder: tagBuilder,
  888. matchedText: matchedText,
  889. offset: startIdx,
  890. urlMatchType: urlMatchType,
  891. url: matchedText,
  892. protocolRelativeMatch: matchedText.slice(0, 2) === '//',
  893. // TODO: Do these settings need to be passed to the match,
  894. // or should we handle them here in UrlMatcher?
  895. stripPrefix: stripPrefix,
  896. stripTrailingSlash: stripTrailingSlash,
  897. decodePercentEncoding: decodePercentEncoding,
  898. }));
  899. }
  900. else if (stateMachine.type === 'email') {
  901. // if the email address has a valid TLD, add it to the list of matches
  902. if (isValidEmail(matchedText)) {
  903. matches.push(new EmailMatch({
  904. tagBuilder: tagBuilder,
  905. matchedText: matchedText,
  906. offset: startIdx,
  907. email: matchedText.replace(mailtoSchemePrefixRe, ''),
  908. }));
  909. }
  910. }
  911. else if (stateMachine.type === 'hashtag') {
  912. if (isValidHashtag(matchedText)) {
  913. matches.push(new HashtagMatch({
  914. tagBuilder: tagBuilder,
  915. matchedText: matchedText,
  916. offset: startIdx,
  917. serviceName: hashtagServiceName,
  918. hashtag: matchedText.slice(1),
  919. }));
  920. }
  921. }
  922. else if (stateMachine.type === 'mention') {
  923. if (isValidMention(matchedText, mentionServiceName)) {
  924. matches.push(new MentionMatch({
  925. tagBuilder: tagBuilder,
  926. matchedText: matchedText,
  927. offset: startIdx,
  928. serviceName: mentionServiceName,
  929. mention: matchedText.slice(1), // strip off the '@' character at the beginning
  930. }));
  931. }
  932. }
  933. else if (stateMachine.type === 'phone') {
  934. // remove any trailing spaces that were considered as "separator"
  935. // chars by the state machine
  936. matchedText = matchedText.replace(/ +$/g, '');
  937. if (isValidPhoneNumber(matchedText)) {
  938. var cleanNumber = matchedText.replace(/[^0-9,;#]/g, ''); // strip out non-digit characters exclude comma semicolon and #
  939. matches.push(new PhoneMatch({
  940. tagBuilder: tagBuilder,
  941. matchedText: matchedText,
  942. offset: startIdx,
  943. number: cleanNumber,
  944. plusSign: matchedText.charAt(0) === '+',
  945. }));
  946. }
  947. }
  948. else {
  949. assertNever(stateMachine);
  950. }
  951. }
  952. }
  953. var openBraceRe = /[\(\{\[]/;
  954. var closeBraceRe = /[\)\}\]]/;
  955. var oppositeBrace = {
  956. ')': '(',
  957. '}': '{',
  958. ']': '[',
  959. };
  960. /**
  961. * Determines if a match found has unmatched closing parenthesis,
  962. * square brackets or curly brackets. If so, these unbalanced symbol(s) will be
  963. * removed from the URL match itself.
  964. *
  965. * A match may have an extra closing parenthesis/square brackets/curly brackets
  966. * at the end of the match because these are valid URL path characters. For
  967. * example, "wikipedia.com/something_(disambiguation)" should be auto-linked.
  968. *
  969. * However, an extra parenthesis *will* be included when the URL itself is
  970. * wrapped in parenthesis, such as in the case of:
  971. *
  972. * "(wikipedia.com/something_(disambiguation))"
  973. *
  974. * In this case, the last closing parenthesis should *not* be part of the
  975. * URL itself, and this method will exclude it from the returned URL.
  976. *
  977. * For square brackets in URLs such as in PHP arrays, the same behavior as
  978. * parenthesis discussed above should happen:
  979. *
  980. * "[http://www.example.com/foo.php?bar[]=1&bar[]=2&bar[]=3]"
  981. *
  982. * The very last closing square bracket should not be part of the URL itself,
  983. * and therefore this method will remove it.
  984. *
  985. * @param matchedText The full matched URL/email/hashtag/etc. from the state
  986. * machine parser.
  987. * @return The updated matched text with extraneous suffix characters removed.
  988. */
  989. export function excludeUnbalancedTrailingBracesAndPunctuation(matchedText) {
  990. var braceCounts = {
  991. '(': 0,
  992. '{': 0,
  993. '[': 0,
  994. };
  995. for (var i = 0; i < matchedText.length; i++) {
  996. var char_1 = matchedText.charAt(i);
  997. if (openBraceRe.test(char_1)) {
  998. braceCounts[char_1]++;
  999. }
  1000. else if (closeBraceRe.test(char_1)) {
  1001. braceCounts[oppositeBrace[char_1]]--;
  1002. }
  1003. }
  1004. var endIdx = matchedText.length - 1;
  1005. var char;
  1006. while (endIdx >= 0) {
  1007. char = matchedText.charAt(endIdx);
  1008. if (closeBraceRe.test(char)) {
  1009. var oppositeBraceChar = oppositeBrace[char];
  1010. if (braceCounts[oppositeBraceChar] < 0) {
  1011. braceCounts[oppositeBraceChar]++;
  1012. endIdx--;
  1013. }
  1014. else {
  1015. break;
  1016. }
  1017. }
  1018. else if (urlSuffixedCharsNotAllowedAtEndRe.test(char)) {
  1019. // Walk back a punctuation char like '?', ',', ':', '.', etc.
  1020. endIdx--;
  1021. }
  1022. else {
  1023. break;
  1024. }
  1025. }
  1026. return matchedText.slice(0, endIdx + 1);
  1027. }
  1028. function createSchemeUrlStateMachine(startIdx, state) {
  1029. return {
  1030. type: 'url',
  1031. startIdx: startIdx,
  1032. state: state,
  1033. acceptStateReached: false,
  1034. matchType: 'scheme',
  1035. };
  1036. }
  1037. function createTldUrlStateMachine(startIdx, state) {
  1038. return {
  1039. type: 'url',
  1040. startIdx: startIdx,
  1041. state: state,
  1042. acceptStateReached: false,
  1043. matchType: 'tld',
  1044. };
  1045. }
  1046. function createIpV4UrlStateMachine(startIdx, state) {
  1047. return {
  1048. type: 'url',
  1049. startIdx: startIdx,
  1050. state: state,
  1051. acceptStateReached: false,
  1052. matchType: 'ipV4',
  1053. octetsEncountered: 1, // starts at 1 because we create this machine when encountering the first octet
  1054. };
  1055. }
  1056. function createEmailStateMachine(startIdx, state) {
  1057. return {
  1058. type: 'email',
  1059. startIdx: startIdx,
  1060. state: state,
  1061. acceptStateReached: false,
  1062. };
  1063. }
  1064. function createHashtagStateMachine(startIdx, state) {
  1065. return {
  1066. type: 'hashtag',
  1067. startIdx: startIdx,
  1068. state: state,
  1069. acceptStateReached: false,
  1070. };
  1071. }
  1072. function createMentionStateMachine(startIdx, state) {
  1073. return {
  1074. type: 'mention',
  1075. startIdx: startIdx,
  1076. state: state,
  1077. acceptStateReached: false,
  1078. };
  1079. }
  1080. function createPhoneNumberStateMachine(startIdx, state) {
  1081. return {
  1082. type: 'phone',
  1083. startIdx: startIdx,
  1084. state: state,
  1085. acceptStateReached: false,
  1086. };
  1087. }
  1088. //# sourceMappingURL=parse-matches.js.map