marked.umd.js 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656
  1. /**
  2. * marked v7.0.1 - a markdown parser
  3. * Copyright (c) 2011-2023, Christopher Jeffrey. (MIT Licensed)
  4. * https://github.com/markedjs/marked
  5. */
  6. /**
  7. * DO NOT EDIT THIS FILE
  8. * The code in this file is generated from files in ./src/
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  12. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  13. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {}));
  14. })(this, (function (exports) { 'use strict';
  15. /**
  16. * Gets the original marked default options.
  17. */
  18. function _getDefaults() {
  19. return {
  20. async: false,
  21. baseUrl: null,
  22. breaks: false,
  23. extensions: null,
  24. gfm: true,
  25. headerIds: false,
  26. headerPrefix: '',
  27. highlight: null,
  28. hooks: null,
  29. langPrefix: 'language-',
  30. mangle: false,
  31. pedantic: false,
  32. renderer: null,
  33. sanitize: false,
  34. sanitizer: null,
  35. silent: false,
  36. smartypants: false,
  37. tokenizer: null,
  38. walkTokens: null,
  39. xhtml: false
  40. };
  41. }
  42. exports.defaults = _getDefaults();
  43. function changeDefaults(newDefaults) {
  44. exports.defaults = newDefaults;
  45. }
  46. /**
  47. * Helpers
  48. */
  49. const escapeTest = /[&<>"']/;
  50. const escapeReplace = new RegExp(escapeTest.source, 'g');
  51. const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
  52. const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
  53. const escapeReplacements = {
  54. '&': '&amp;',
  55. '<': '&lt;',
  56. '>': '&gt;',
  57. '"': '&quot;',
  58. "'": '&#39;'
  59. };
  60. const getEscapeReplacement = (ch) => escapeReplacements[ch];
  61. function escape(html, encode) {
  62. if (encode) {
  63. if (escapeTest.test(html)) {
  64. return html.replace(escapeReplace, getEscapeReplacement);
  65. }
  66. }
  67. else {
  68. if (escapeTestNoEncode.test(html)) {
  69. return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
  70. }
  71. }
  72. return html;
  73. }
  74. const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
  75. function unescape(html) {
  76. // explicitly match decimal, hex, and named HTML entities
  77. return html.replace(unescapeTest, (_, n) => {
  78. n = n.toLowerCase();
  79. if (n === 'colon')
  80. return ':';
  81. if (n.charAt(0) === '#') {
  82. return n.charAt(1) === 'x'
  83. ? String.fromCharCode(parseInt(n.substring(2), 16))
  84. : String.fromCharCode(+n.substring(1));
  85. }
  86. return '';
  87. });
  88. }
  89. const caret = /(^|[^\[])\^/g;
  90. function edit(regex, opt) {
  91. regex = typeof regex === 'string' ? regex : regex.source;
  92. opt = opt || '';
  93. const obj = {
  94. replace: (name, val) => {
  95. val = typeof val === 'object' && 'source' in val ? val.source : val;
  96. val = val.replace(caret, '$1');
  97. regex = regex.replace(name, val);
  98. return obj;
  99. },
  100. getRegex: () => {
  101. return new RegExp(regex, opt);
  102. }
  103. };
  104. return obj;
  105. }
  106. const nonWordAndColonTest = /[^\w:]/g;
  107. const originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
  108. function cleanUrl(sanitize, base, href) {
  109. if (sanitize) {
  110. let prot;
  111. try {
  112. prot = decodeURIComponent(unescape(href))
  113. .replace(nonWordAndColonTest, '')
  114. .toLowerCase();
  115. }
  116. catch (e) {
  117. return null;
  118. }
  119. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
  120. return null;
  121. }
  122. }
  123. if (base && !originIndependentUrl.test(href)) {
  124. href = resolveUrl(base, href);
  125. }
  126. try {
  127. href = encodeURI(href).replace(/%25/g, '%');
  128. }
  129. catch (e) {
  130. return null;
  131. }
  132. return href;
  133. }
  134. const baseUrls = {};
  135. const justDomain = /^[^:]+:\/*[^/]*$/;
  136. const protocol = /^([^:]+:)[\s\S]*$/;
  137. const domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
  138. function resolveUrl(base, href) {
  139. if (!baseUrls[' ' + base]) {
  140. // we can ignore everything in base after the last slash of its path component,
  141. // but we might need to add _that_
  142. // https://tools.ietf.org/html/rfc3986#section-3
  143. if (justDomain.test(base)) {
  144. baseUrls[' ' + base] = base + '/';
  145. }
  146. else {
  147. baseUrls[' ' + base] = rtrim(base, '/', true);
  148. }
  149. }
  150. base = baseUrls[' ' + base];
  151. const relativeBase = base.indexOf(':') === -1;
  152. if (href.substring(0, 2) === '//') {
  153. if (relativeBase) {
  154. return href;
  155. }
  156. return base.replace(protocol, '$1') + href;
  157. }
  158. else if (href.charAt(0) === '/') {
  159. if (relativeBase) {
  160. return href;
  161. }
  162. return base.replace(domain, '$1') + href;
  163. }
  164. else {
  165. return base + href;
  166. }
  167. }
  168. const noopTest = { exec: () => null };
  169. function splitCells(tableRow, count) {
  170. // ensure that every cell-delimiting pipe has a space
  171. // before it to distinguish it from an escaped pipe
  172. const row = tableRow.replace(/\|/g, (match, offset, str) => {
  173. let escaped = false, curr = offset;
  174. while (--curr >= 0 && str[curr] === '\\')
  175. escaped = !escaped;
  176. if (escaped) {
  177. // odd number of slashes means | is escaped
  178. // so we leave it alone
  179. return '|';
  180. }
  181. else {
  182. // add space before unescaped |
  183. return ' |';
  184. }
  185. }), cells = row.split(/ \|/);
  186. let i = 0;
  187. // First/last cell in a row cannot be empty if it has no leading/trailing pipe
  188. if (!cells[0].trim()) {
  189. cells.shift();
  190. }
  191. if (cells.length > 0 && !cells[cells.length - 1].trim()) {
  192. cells.pop();
  193. }
  194. if (count) {
  195. if (cells.length > count) {
  196. cells.splice(count);
  197. }
  198. else {
  199. while (cells.length < count)
  200. cells.push('');
  201. }
  202. }
  203. for (; i < cells.length; i++) {
  204. // leading or trailing whitespace is ignored per the gfm spec
  205. cells[i] = cells[i].trim().replace(/\\\|/g, '|');
  206. }
  207. return cells;
  208. }
  209. /**
  210. * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
  211. * /c*$/ is vulnerable to REDOS.
  212. *
  213. * @param str
  214. * @param c
  215. * @param invert Remove suffix of non-c chars instead. Default falsey.
  216. */
  217. function rtrim(str, c, invert) {
  218. const l = str.length;
  219. if (l === 0) {
  220. return '';
  221. }
  222. // Length of suffix matching the invert condition.
  223. let suffLen = 0;
  224. // Step left until we fail to match the invert condition.
  225. while (suffLen < l) {
  226. const currChar = str.charAt(l - suffLen - 1);
  227. if (currChar === c && !invert) {
  228. suffLen++;
  229. }
  230. else if (currChar !== c && invert) {
  231. suffLen++;
  232. }
  233. else {
  234. break;
  235. }
  236. }
  237. return str.slice(0, l - suffLen);
  238. }
  239. function findClosingBracket(str, b) {
  240. if (str.indexOf(b[1]) === -1) {
  241. return -1;
  242. }
  243. const l = str.length;
  244. let level = 0, i = 0;
  245. for (; i < l; i++) {
  246. if (str[i] === '\\') {
  247. i++;
  248. }
  249. else if (str[i] === b[0]) {
  250. level++;
  251. }
  252. else if (str[i] === b[1]) {
  253. level--;
  254. if (level < 0) {
  255. return i;
  256. }
  257. }
  258. }
  259. return -1;
  260. }
  261. function checkDeprecations(opt, callback) {
  262. if (!opt || opt.silent) {
  263. return;
  264. }
  265. if (callback) {
  266. console.warn('marked(): callback is deprecated since version 5.0.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/using_pro#async');
  267. }
  268. if (opt.sanitize || opt.sanitizer) {
  269. console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
  270. }
  271. if (opt.highlight || opt.langPrefix !== 'language-') {
  272. console.warn('marked(): highlight and langPrefix parameters are deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-highlight.');
  273. }
  274. if (opt.mangle) {
  275. console.warn('marked(): mangle parameter is enabled by default, but is deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-mangle, or disable by setting `{mangle: false}`.');
  276. }
  277. if (opt.baseUrl) {
  278. console.warn('marked(): baseUrl parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-base-url.');
  279. }
  280. if (opt.smartypants) {
  281. console.warn('marked(): smartypants parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-smartypants.');
  282. }
  283. if (opt.xhtml) {
  284. console.warn('marked(): xhtml parameter is deprecated since version 5.0.0, should not be used and will be removed in the future. Instead use https://www.npmjs.com/package/marked-xhtml.');
  285. }
  286. if (opt.headerIds || opt.headerPrefix) {
  287. console.warn('marked(): headerIds and headerPrefix parameters enabled by default, but are deprecated since version 5.0.0, and will be removed in the future. To clear this warning, install https://www.npmjs.com/package/marked-gfm-heading-id, or disable by setting `{headerIds: false}`.');
  288. }
  289. }
  290. function outputLink(cap, link, raw, lexer) {
  291. const href = link.href;
  292. const title = link.title ? escape(link.title) : null;
  293. const text = cap[1].replace(/\\([\[\]])/g, '$1');
  294. if (cap[0].charAt(0) !== '!') {
  295. lexer.state.inLink = true;
  296. const token = {
  297. type: 'link',
  298. raw,
  299. href,
  300. title,
  301. text,
  302. tokens: lexer.inlineTokens(text)
  303. };
  304. lexer.state.inLink = false;
  305. return token;
  306. }
  307. return {
  308. type: 'image',
  309. raw,
  310. href,
  311. title,
  312. text: escape(text)
  313. };
  314. }
  315. function indentCodeCompensation(raw, text) {
  316. const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
  317. if (matchIndentToCode === null) {
  318. return text;
  319. }
  320. const indentToCode = matchIndentToCode[1];
  321. return text
  322. .split('\n')
  323. .map(node => {
  324. const matchIndentInNode = node.match(/^\s+/);
  325. if (matchIndentInNode === null) {
  326. return node;
  327. }
  328. const [indentInNode] = matchIndentInNode;
  329. if (indentInNode.length >= indentToCode.length) {
  330. return node.slice(indentToCode.length);
  331. }
  332. return node;
  333. })
  334. .join('\n');
  335. }
  336. /**
  337. * Tokenizer
  338. */
  339. class _Tokenizer {
  340. options;
  341. rules;
  342. lexer;
  343. constructor(options) {
  344. this.options = options || exports.defaults;
  345. }
  346. space(src) {
  347. const cap = this.rules.block.newline.exec(src);
  348. if (cap && cap[0].length > 0) {
  349. return {
  350. type: 'space',
  351. raw: cap[0]
  352. };
  353. }
  354. }
  355. code(src) {
  356. const cap = this.rules.block.code.exec(src);
  357. if (cap) {
  358. const text = cap[0].replace(/^ {1,4}/gm, '');
  359. return {
  360. type: 'code',
  361. raw: cap[0],
  362. codeBlockStyle: 'indented',
  363. text: !this.options.pedantic
  364. ? rtrim(text, '\n')
  365. : text
  366. };
  367. }
  368. }
  369. fences(src) {
  370. const cap = this.rules.block.fences.exec(src);
  371. if (cap) {
  372. const raw = cap[0];
  373. const text = indentCodeCompensation(raw, cap[3] || '');
  374. return {
  375. type: 'code',
  376. raw,
  377. lang: cap[2] ? cap[2].trim().replace(this.rules.inline._escapes, '$1') : cap[2],
  378. text
  379. };
  380. }
  381. }
  382. heading(src) {
  383. const cap = this.rules.block.heading.exec(src);
  384. if (cap) {
  385. let text = cap[2].trim();
  386. // remove trailing #s
  387. if (/#$/.test(text)) {
  388. const trimmed = rtrim(text, '#');
  389. if (this.options.pedantic) {
  390. text = trimmed.trim();
  391. }
  392. else if (!trimmed || / $/.test(trimmed)) {
  393. // CommonMark requires space before trailing #s
  394. text = trimmed.trim();
  395. }
  396. }
  397. return {
  398. type: 'heading',
  399. raw: cap[0],
  400. depth: cap[1].length,
  401. text,
  402. tokens: this.lexer.inline(text)
  403. };
  404. }
  405. }
  406. hr(src) {
  407. const cap = this.rules.block.hr.exec(src);
  408. if (cap) {
  409. return {
  410. type: 'hr',
  411. raw: cap[0]
  412. };
  413. }
  414. }
  415. blockquote(src) {
  416. const cap = this.rules.block.blockquote.exec(src);
  417. if (cap) {
  418. const text = cap[0].replace(/^ *>[ \t]?/gm, '');
  419. const top = this.lexer.state.top;
  420. this.lexer.state.top = true;
  421. const tokens = this.lexer.blockTokens(text);
  422. this.lexer.state.top = top;
  423. return {
  424. type: 'blockquote',
  425. raw: cap[0],
  426. tokens,
  427. text
  428. };
  429. }
  430. }
  431. list(src) {
  432. let cap = this.rules.block.list.exec(src);
  433. if (cap) {
  434. let raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly;
  435. let bull = cap[1].trim();
  436. const isordered = bull.length > 1;
  437. const list = {
  438. type: 'list',
  439. raw: '',
  440. ordered: isordered,
  441. start: isordered ? +bull.slice(0, -1) : '',
  442. loose: false,
  443. items: []
  444. };
  445. bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
  446. if (this.options.pedantic) {
  447. bull = isordered ? bull : '[*+-]';
  448. }
  449. // Get next list item
  450. const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`);
  451. // Check if current bullet point can start a new List Item
  452. while (src) {
  453. endEarly = false;
  454. if (!(cap = itemRegex.exec(src))) {
  455. break;
  456. }
  457. if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)
  458. break;
  459. }
  460. raw = cap[0];
  461. src = src.substring(raw.length);
  462. line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length));
  463. nextLine = src.split('\n', 1)[0];
  464. if (this.options.pedantic) {
  465. indent = 2;
  466. itemContents = line.trimLeft();
  467. }
  468. else {
  469. indent = cap[2].search(/[^ ]/); // Find first non-space char
  470. indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent
  471. itemContents = line.slice(indent);
  472. indent += cap[1].length;
  473. }
  474. blankLine = false;
  475. if (!line && /^ *$/.test(nextLine)) { // Items begin with at most one blank line
  476. raw += nextLine + '\n';
  477. src = src.substring(nextLine.length + 1);
  478. endEarly = true;
  479. }
  480. if (!endEarly) {
  481. const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`);
  482. const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
  483. const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
  484. const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
  485. // Check if following lines should be included in List Item
  486. while (src) {
  487. rawLine = src.split('\n', 1)[0];
  488. nextLine = rawLine;
  489. // Re-align to follow commonmark nesting rules
  490. if (this.options.pedantic) {
  491. nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');
  492. }
  493. // End list item if found code fences
  494. if (fencesBeginRegex.test(nextLine)) {
  495. break;
  496. }
  497. // End list item if found start of new heading
  498. if (headingBeginRegex.test(nextLine)) {
  499. break;
  500. }
  501. // End list item if found start of new bullet
  502. if (nextBulletRegex.test(nextLine)) {
  503. break;
  504. }
  505. // Horizontal rule found
  506. if (hrRegex.test(src)) {
  507. break;
  508. }
  509. if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) { // Dedent if possible
  510. itemContents += '\n' + nextLine.slice(indent);
  511. }
  512. else {
  513. // not enough indentation
  514. if (blankLine) {
  515. break;
  516. }
  517. // paragraph continuation unless last line was a different block level element
  518. if (line.search(/[^ ]/) >= 4) { // indented code block
  519. break;
  520. }
  521. if (fencesBeginRegex.test(line)) {
  522. break;
  523. }
  524. if (headingBeginRegex.test(line)) {
  525. break;
  526. }
  527. if (hrRegex.test(line)) {
  528. break;
  529. }
  530. itemContents += '\n' + nextLine;
  531. }
  532. if (!blankLine && !nextLine.trim()) { // Check if current line is blank
  533. blankLine = true;
  534. }
  535. raw += rawLine + '\n';
  536. src = src.substring(rawLine.length + 1);
  537. line = nextLine.slice(indent);
  538. }
  539. }
  540. if (!list.loose) {
  541. // If the previous item ended with a blank line, the list is loose
  542. if (endsWithBlankLine) {
  543. list.loose = true;
  544. }
  545. else if (/\n *\n *$/.test(raw)) {
  546. endsWithBlankLine = true;
  547. }
  548. }
  549. // Check for task list items
  550. if (this.options.gfm) {
  551. istask = /^\[[ xX]\] /.exec(itemContents);
  552. if (istask) {
  553. ischecked = istask[0] !== '[ ] ';
  554. itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
  555. }
  556. }
  557. list.items.push({
  558. type: 'list_item',
  559. raw,
  560. task: !!istask,
  561. checked: ischecked,
  562. loose: false,
  563. text: itemContents
  564. });
  565. list.raw += raw;
  566. }
  567. // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
  568. list.items[list.items.length - 1].raw = raw.trimRight();
  569. list.items[list.items.length - 1].text = itemContents.trimRight();
  570. list.raw = list.raw.trimRight();
  571. const l = list.items.length;
  572. // Item child tokens handled here at end because we needed to have the final item to trim it first
  573. for (i = 0; i < l; i++) {
  574. this.lexer.state.top = false;
  575. list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
  576. if (!list.loose) {
  577. // Check if list should be loose
  578. const spacers = list.items[i].tokens.filter(t => t.type === 'space');
  579. const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw));
  580. list.loose = hasMultipleLineBreaks;
  581. }
  582. }
  583. // Set all items to loose if list is loose
  584. if (list.loose) {
  585. for (i = 0; i < l; i++) {
  586. list.items[i].loose = true;
  587. }
  588. }
  589. return list;
  590. }
  591. }
  592. html(src) {
  593. const cap = this.rules.block.html.exec(src);
  594. if (cap) {
  595. const token = {
  596. type: 'html',
  597. block: true,
  598. raw: cap[0],
  599. pre: !this.options.sanitizer
  600. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  601. text: cap[0]
  602. };
  603. if (this.options.sanitize) {
  604. const text = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]);
  605. const paragraph = token;
  606. paragraph.type = 'paragraph';
  607. paragraph.text = text;
  608. paragraph.tokens = this.lexer.inline(text);
  609. }
  610. return token;
  611. }
  612. }
  613. def(src) {
  614. const cap = this.rules.block.def.exec(src);
  615. if (cap) {
  616. const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
  617. const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline._escapes, '$1') : '';
  618. const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline._escapes, '$1') : cap[3];
  619. return {
  620. type: 'def',
  621. tag,
  622. raw: cap[0],
  623. href,
  624. title
  625. };
  626. }
  627. }
  628. table(src) {
  629. const cap = this.rules.block.table.exec(src);
  630. if (cap) {
  631. const item = {
  632. type: 'table',
  633. raw: cap[0],
  634. header: splitCells(cap[1]).map(c => {
  635. return { text: c };
  636. }),
  637. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  638. rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []
  639. };
  640. if (item.header.length === item.align.length) {
  641. let l = item.align.length;
  642. let i, j, k, row;
  643. for (i = 0; i < l; i++) {
  644. if (/^ *-+: *$/.test(item.align[i])) {
  645. item.align[i] = 'right';
  646. }
  647. else if (/^ *:-+: *$/.test(item.align[i])) {
  648. item.align[i] = 'center';
  649. }
  650. else if (/^ *:-+ *$/.test(item.align[i])) {
  651. item.align[i] = 'left';
  652. }
  653. else {
  654. item.align[i] = null;
  655. }
  656. }
  657. l = item.rows.length;
  658. for (i = 0; i < l; i++) {
  659. item.rows[i] = splitCells(item.rows[i], item.header.length).map(c => {
  660. return { text: c };
  661. });
  662. }
  663. // parse child tokens inside headers and cells
  664. // header child tokens
  665. l = item.header.length;
  666. for (j = 0; j < l; j++) {
  667. item.header[j].tokens = this.lexer.inline(item.header[j].text);
  668. }
  669. // cell child tokens
  670. l = item.rows.length;
  671. for (j = 0; j < l; j++) {
  672. row = item.rows[j];
  673. for (k = 0; k < row.length; k++) {
  674. row[k].tokens = this.lexer.inline(row[k].text);
  675. }
  676. }
  677. return item;
  678. }
  679. }
  680. }
  681. lheading(src) {
  682. const cap = this.rules.block.lheading.exec(src);
  683. if (cap) {
  684. return {
  685. type: 'heading',
  686. raw: cap[0],
  687. depth: cap[2].charAt(0) === '=' ? 1 : 2,
  688. text: cap[1],
  689. tokens: this.lexer.inline(cap[1])
  690. };
  691. }
  692. }
  693. paragraph(src) {
  694. const cap = this.rules.block.paragraph.exec(src);
  695. if (cap) {
  696. const text = cap[1].charAt(cap[1].length - 1) === '\n'
  697. ? cap[1].slice(0, -1)
  698. : cap[1];
  699. return {
  700. type: 'paragraph',
  701. raw: cap[0],
  702. text,
  703. tokens: this.lexer.inline(text)
  704. };
  705. }
  706. }
  707. text(src) {
  708. const cap = this.rules.block.text.exec(src);
  709. if (cap) {
  710. return {
  711. type: 'text',
  712. raw: cap[0],
  713. text: cap[0],
  714. tokens: this.lexer.inline(cap[0])
  715. };
  716. }
  717. }
  718. escape(src) {
  719. const cap = this.rules.inline.escape.exec(src);
  720. if (cap) {
  721. return {
  722. type: 'escape',
  723. raw: cap[0],
  724. text: escape(cap[1])
  725. };
  726. }
  727. }
  728. tag(src) {
  729. const cap = this.rules.inline.tag.exec(src);
  730. if (cap) {
  731. if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
  732. this.lexer.state.inLink = true;
  733. }
  734. else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
  735. this.lexer.state.inLink = false;
  736. }
  737. if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
  738. this.lexer.state.inRawBlock = true;
  739. }
  740. else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
  741. this.lexer.state.inRawBlock = false;
  742. }
  743. return {
  744. type: this.options.sanitize
  745. ? 'text'
  746. : 'html',
  747. raw: cap[0],
  748. inLink: this.lexer.state.inLink,
  749. inRawBlock: this.lexer.state.inRawBlock,
  750. block: false,
  751. text: this.options.sanitize
  752. ? (this.options.sanitizer
  753. ? this.options.sanitizer(cap[0])
  754. : escape(cap[0]))
  755. : cap[0]
  756. };
  757. }
  758. }
  759. link(src) {
  760. const cap = this.rules.inline.link.exec(src);
  761. if (cap) {
  762. const trimmedUrl = cap[2].trim();
  763. if (!this.options.pedantic && /^</.test(trimmedUrl)) {
  764. // commonmark requires matching angle brackets
  765. if (!(/>$/.test(trimmedUrl))) {
  766. return;
  767. }
  768. // ending angle bracket cannot be escaped
  769. const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
  770. if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
  771. return;
  772. }
  773. }
  774. else {
  775. // find closing parenthesis
  776. const lastParenIndex = findClosingBracket(cap[2], '()');
  777. if (lastParenIndex > -1) {
  778. const start = cap[0].indexOf('!') === 0 ? 5 : 4;
  779. const linkLen = start + cap[1].length + lastParenIndex;
  780. cap[2] = cap[2].substring(0, lastParenIndex);
  781. cap[0] = cap[0].substring(0, linkLen).trim();
  782. cap[3] = '';
  783. }
  784. }
  785. let href = cap[2];
  786. let title = '';
  787. if (this.options.pedantic) {
  788. // split pedantic href and title
  789. const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
  790. if (link) {
  791. href = link[1];
  792. title = link[3];
  793. }
  794. }
  795. else {
  796. title = cap[3] ? cap[3].slice(1, -1) : '';
  797. }
  798. href = href.trim();
  799. if (/^</.test(href)) {
  800. if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {
  801. // pedantic allows starting angle bracket without ending angle bracket
  802. href = href.slice(1);
  803. }
  804. else {
  805. href = href.slice(1, -1);
  806. }
  807. }
  808. return outputLink(cap, {
  809. href: href ? href.replace(this.rules.inline._escapes, '$1') : href,
  810. title: title ? title.replace(this.rules.inline._escapes, '$1') : title
  811. }, cap[0], this.lexer);
  812. }
  813. }
  814. reflink(src, links) {
  815. let cap;
  816. if ((cap = this.rules.inline.reflink.exec(src))
  817. || (cap = this.rules.inline.nolink.exec(src))) {
  818. let link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  819. link = links[link.toLowerCase()];
  820. if (!link) {
  821. const text = cap[0].charAt(0);
  822. return {
  823. type: 'text',
  824. raw: text,
  825. text
  826. };
  827. }
  828. return outputLink(cap, link, cap[0], this.lexer);
  829. }
  830. }
  831. emStrong(src, maskedSrc, prevChar = '') {
  832. let match = this.rules.inline.emStrong.lDelim.exec(src);
  833. if (!match)
  834. return;
  835. // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
  836. if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
  837. return;
  838. const nextChar = match[1] || match[2] || '';
  839. if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
  840. const lLength = match[0].length - 1;
  841. let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
  842. const endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
  843. endReg.lastIndex = 0;
  844. // Clip maskedSrc to same section of string as src (move to lexer?)
  845. maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
  846. while ((match = endReg.exec(maskedSrc)) != null) {
  847. rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
  848. if (!rDelim)
  849. continue; // skip single * in __abc*abc__
  850. rLength = rDelim.length;
  851. if (match[3] || match[4]) { // found another Left Delim
  852. delimTotal += rLength;
  853. continue;
  854. }
  855. else if (match[5] || match[6]) { // either Left or Right Delim
  856. if (lLength % 3 && !((lLength + rLength) % 3)) {
  857. midDelimTotal += rLength;
  858. continue; // CommonMark Emphasis Rules 9-10
  859. }
  860. }
  861. delimTotal -= rLength;
  862. if (delimTotal > 0)
  863. continue; // Haven't found enough closing delimiters
  864. // Remove extra characters. *a*** -> *a*
  865. rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
  866. const raw = src.slice(0, lLength + match.index + rLength + 1);
  867. // Create `em` if smallest delimiter has odd char count. *a***
  868. if (Math.min(lLength, rLength) % 2) {
  869. const text = raw.slice(1, -1);
  870. return {
  871. type: 'em',
  872. raw,
  873. text,
  874. tokens: this.lexer.inlineTokens(text)
  875. };
  876. }
  877. // Create 'strong' if smallest delimiter has even char count. **a***
  878. const text = raw.slice(2, -2);
  879. return {
  880. type: 'strong',
  881. raw,
  882. text,
  883. tokens: this.lexer.inlineTokens(text)
  884. };
  885. }
  886. }
  887. }
  888. codespan(src) {
  889. const cap = this.rules.inline.code.exec(src);
  890. if (cap) {
  891. let text = cap[2].replace(/\n/g, ' ');
  892. const hasNonSpaceChars = /[^ ]/.test(text);
  893. const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
  894. if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
  895. text = text.substring(1, text.length - 1);
  896. }
  897. text = escape(text, true);
  898. return {
  899. type: 'codespan',
  900. raw: cap[0],
  901. text
  902. };
  903. }
  904. }
  905. br(src) {
  906. const cap = this.rules.inline.br.exec(src);
  907. if (cap) {
  908. return {
  909. type: 'br',
  910. raw: cap[0]
  911. };
  912. }
  913. }
  914. del(src) {
  915. const cap = this.rules.inline.del.exec(src);
  916. if (cap) {
  917. return {
  918. type: 'del',
  919. raw: cap[0],
  920. text: cap[2],
  921. tokens: this.lexer.inlineTokens(cap[2])
  922. };
  923. }
  924. }
  925. autolink(src, mangle) {
  926. const cap = this.rules.inline.autolink.exec(src);
  927. if (cap) {
  928. let text, href;
  929. if (cap[2] === '@') {
  930. text = escape(this.options.mangle ? mangle(cap[1]) : cap[1]);
  931. href = 'mailto:' + text;
  932. }
  933. else {
  934. text = escape(cap[1]);
  935. href = text;
  936. }
  937. return {
  938. type: 'link',
  939. raw: cap[0],
  940. text,
  941. href,
  942. tokens: [
  943. {
  944. type: 'text',
  945. raw: text,
  946. text
  947. }
  948. ]
  949. };
  950. }
  951. }
  952. url(src, mangle) {
  953. let cap;
  954. if (cap = this.rules.inline.url.exec(src)) {
  955. let text, href;
  956. if (cap[2] === '@') {
  957. text = escape(this.options.mangle ? mangle(cap[0]) : cap[0]);
  958. href = 'mailto:' + text;
  959. }
  960. else {
  961. // do extended autolink path validation
  962. let prevCapZero;
  963. do {
  964. prevCapZero = cap[0];
  965. cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
  966. } while (prevCapZero !== cap[0]);
  967. text = escape(cap[0]);
  968. if (cap[1] === 'www.') {
  969. href = 'http://' + cap[0];
  970. }
  971. else {
  972. href = cap[0];
  973. }
  974. }
  975. return {
  976. type: 'link',
  977. raw: cap[0],
  978. text,
  979. href,
  980. tokens: [
  981. {
  982. type: 'text',
  983. raw: text,
  984. text
  985. }
  986. ]
  987. };
  988. }
  989. }
  990. inlineText(src, smartypants) {
  991. const cap = this.rules.inline.text.exec(src);
  992. if (cap) {
  993. let text;
  994. if (this.lexer.state.inRawBlock) {
  995. text = this.options.sanitize ? (this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0])) : cap[0];
  996. }
  997. else {
  998. text = escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);
  999. }
  1000. return {
  1001. type: 'text',
  1002. raw: cap[0],
  1003. text
  1004. };
  1005. }
  1006. }
  1007. }
  1008. /**
  1009. * Block-Level Grammar
  1010. */
  1011. // Not all rules are defined in the object literal
  1012. // @ts-expect-error
  1013. const block = {
  1014. newline: /^(?: *(?:\n|$))+/,
  1015. code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
  1016. fences: /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
  1017. hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
  1018. heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
  1019. blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
  1020. list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
  1021. html: '^ {0,3}(?:' // optional indentation
  1022. + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
  1023. + '|comment[^\\n]*(\\n+|$)' // (2)
  1024. + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
  1025. + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
  1026. + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
  1027. + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
  1028. + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
  1029. + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
  1030. + ')',
  1031. def: /^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
  1032. table: noopTest,
  1033. lheading: /^((?:(?!^bull ).|\n(?!\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  1034. // regex template, placeholders will be replaced according to different paragraph
  1035. // interruption rules of commonmark and the original markdown spec:
  1036. _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
  1037. text: /^[^\n]+/
  1038. };
  1039. block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
  1040. block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
  1041. block.def = edit(block.def)
  1042. .replace('label', block._label)
  1043. .replace('title', block._title)
  1044. .getRegex();
  1045. block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
  1046. block.listItemStart = edit(/^( *)(bull) */)
  1047. .replace('bull', block.bullet)
  1048. .getRegex();
  1049. block.list = edit(block.list)
  1050. .replace(/bull/g, block.bullet)
  1051. .replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))')
  1052. .replace('def', '\\n+(?=' + block.def.source + ')')
  1053. .getRegex();
  1054. block._tag = 'address|article|aside|base|basefont|blockquote|body|caption'
  1055. + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
  1056. + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
  1057. + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
  1058. + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
  1059. + '|track|ul';
  1060. block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
  1061. block.html = edit(block.html, 'i')
  1062. .replace('comment', block._comment)
  1063. .replace('tag', block._tag)
  1064. .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
  1065. .getRegex();
  1066. block.lheading = edit(block.lheading)
  1067. .replace(/bull/g, block.bullet) // lists can interrupt
  1068. .getRegex();
  1069. block.paragraph = edit(block._paragraph)
  1070. .replace('hr', block.hr)
  1071. .replace('heading', ' {0,3}#{1,6} ')
  1072. .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  1073. .replace('|table', '')
  1074. .replace('blockquote', ' {0,3}>')
  1075. .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
  1076. .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  1077. .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
  1078. .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  1079. .getRegex();
  1080. block.blockquote = edit(block.blockquote)
  1081. .replace('paragraph', block.paragraph)
  1082. .getRegex();
  1083. /**
  1084. * Normal Block Grammar
  1085. */
  1086. block.normal = { ...block };
  1087. /**
  1088. * GFM Block Grammar
  1089. */
  1090. block.gfm = {
  1091. ...block.normal,
  1092. table: '^ *([^\\n ].*\\|.*)\\n' // Header
  1093. + ' {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?' // Align
  1094. + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells
  1095. };
  1096. block.gfm.table = edit(block.gfm.table)
  1097. .replace('hr', block.hr)
  1098. .replace('heading', ' {0,3}#{1,6} ')
  1099. .replace('blockquote', ' {0,3}>')
  1100. .replace('code', ' {4}[^\\n]')
  1101. .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
  1102. .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  1103. .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
  1104. .replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
  1105. .getRegex();
  1106. block.gfm.paragraph = edit(block._paragraph)
  1107. .replace('hr', block.hr)
  1108. .replace('heading', ' {0,3}#{1,6} ')
  1109. .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  1110. .replace('table', block.gfm.table) // interrupt paragraphs with table
  1111. .replace('blockquote', ' {0,3}>')
  1112. .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
  1113. .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  1114. .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
  1115. .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  1116. .getRegex();
  1117. /**
  1118. * Pedantic grammar (original John Gruber's loose markdown specification)
  1119. */
  1120. block.pedantic = {
  1121. ...block.normal,
  1122. html: edit('^ *(?:comment *(?:\\n|\\s*$)'
  1123. + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
  1124. + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
  1125. .replace('comment', block._comment)
  1126. .replace(/tag/g, '(?!(?:'
  1127. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
  1128. + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
  1129. + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
  1130. .getRegex(),
  1131. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  1132. heading: /^(#{1,6})(.*)(?:\n+|$)/,
  1133. fences: noopTest,
  1134. lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  1135. paragraph: edit(block.normal._paragraph)
  1136. .replace('hr', block.hr)
  1137. .replace('heading', ' *#{1,6} *[^\n]')
  1138. .replace('lheading', block.lheading)
  1139. .replace('blockquote', ' {0,3}>')
  1140. .replace('|fences', '')
  1141. .replace('|list', '')
  1142. .replace('|html', '')
  1143. .getRegex()
  1144. };
  1145. /**
  1146. * Inline-Level Grammar
  1147. */
  1148. // Not all rules are defined in the object literal
  1149. // @ts-expect-error
  1150. const inline = {
  1151. escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
  1152. autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
  1153. url: noopTest,
  1154. tag: '^comment'
  1155. + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
  1156. + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
  1157. + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
  1158. + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
  1159. + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',
  1160. link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
  1161. reflink: /^!?\[(label)\]\[(ref)\]/,
  1162. nolink: /^!?\[(ref)\](?:\[\])?/,
  1163. reflinkSearch: 'reflink|nolink(?!\\()',
  1164. emStrong: {
  1165. lDelim: /^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,
  1166. // (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right.
  1167. // | Skip orphan inside strong | Consume to delim | (1) #*** | (2) a***#, a*** | (3) #***a, ***a | (4) ***# | (5) #***# | (6) a***a
  1168. rDelimAst: /^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\*)[punct](\*+)(?=[\s]|$)|[^punct\s](\*+)(?!\*)(?=[punct\s]|$)|(?!\*)[punct\s](\*+)(?=[^punct\s])|[\s](\*+)(?!\*)(?=[punct])|(?!\*)[punct](\*+)(?!\*)(?=[punct])|[^punct\s](\*+)(?=[^punct\s])/,
  1169. rDelimUnd: /^[^_*]*?\*\*[^_*]*?_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\s]|$)|[^punct\s](_+)(?!_)(?=[punct\s]|$)|(?!_)[punct\s](_+)(?=[^punct\s])|[\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])/ // ^- Not allowed for _
  1170. },
  1171. code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
  1172. br: /^( {2,}|\\)\n(?!\s*$)/,
  1173. del: noopTest,
  1174. text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
  1175. punctuation: /^((?![*_])[\spunctuation])/
  1176. };
  1177. // list of unicode punctuation marks, plus any missing characters from CommonMark spec
  1178. inline._punctuation = '\\p{P}$+<=>`^|~';
  1179. inline.punctuation = edit(inline.punctuation, 'u').replace(/punctuation/g, inline._punctuation).getRegex();
  1180. // sequences em should skip over [title](link), `code`, <html>
  1181. inline.blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
  1182. inline.anyPunctuation = /\\[punct]/g;
  1183. inline._escapes = /\\([punct])/g;
  1184. inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex();
  1185. inline.emStrong.lDelim = edit(inline.emStrong.lDelim, 'u')
  1186. .replace(/punct/g, inline._punctuation)
  1187. .getRegex();
  1188. inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, 'gu')
  1189. .replace(/punct/g, inline._punctuation)
  1190. .getRegex();
  1191. inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, 'gu')
  1192. .replace(/punct/g, inline._punctuation)
  1193. .getRegex();
  1194. inline.anyPunctuation = edit(inline.anyPunctuation, 'gu')
  1195. .replace(/punct/g, inline._punctuation)
  1196. .getRegex();
  1197. inline._escapes = edit(inline._escapes, 'gu')
  1198. .replace(/punct/g, inline._punctuation)
  1199. .getRegex();
  1200. inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
  1201. inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
  1202. inline.autolink = edit(inline.autolink)
  1203. .replace('scheme', inline._scheme)
  1204. .replace('email', inline._email)
  1205. .getRegex();
  1206. inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
  1207. inline.tag = edit(inline.tag)
  1208. .replace('comment', inline._comment)
  1209. .replace('attribute', inline._attribute)
  1210. .getRegex();
  1211. inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
  1212. inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
  1213. inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
  1214. inline.link = edit(inline.link)
  1215. .replace('label', inline._label)
  1216. .replace('href', inline._href)
  1217. .replace('title', inline._title)
  1218. .getRegex();
  1219. inline.reflink = edit(inline.reflink)
  1220. .replace('label', inline._label)
  1221. .replace('ref', block._label)
  1222. .getRegex();
  1223. inline.nolink = edit(inline.nolink)
  1224. .replace('ref', block._label)
  1225. .getRegex();
  1226. inline.reflinkSearch = edit(inline.reflinkSearch, 'g')
  1227. .replace('reflink', inline.reflink)
  1228. .replace('nolink', inline.nolink)
  1229. .getRegex();
  1230. /**
  1231. * Normal Inline Grammar
  1232. */
  1233. inline.normal = { ...inline };
  1234. /**
  1235. * Pedantic Inline Grammar
  1236. */
  1237. inline.pedantic = {
  1238. ...inline.normal,
  1239. strong: {
  1240. start: /^__|\*\*/,
  1241. middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  1242. endAst: /\*\*(?!\*)/g,
  1243. endUnd: /__(?!_)/g
  1244. },
  1245. em: {
  1246. start: /^_|\*/,
  1247. middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
  1248. endAst: /\*(?!\*)/g,
  1249. endUnd: /_(?!_)/g
  1250. },
  1251. link: edit(/^!?\[(label)\]\((.*?)\)/)
  1252. .replace('label', inline._label)
  1253. .getRegex(),
  1254. reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
  1255. .replace('label', inline._label)
  1256. .getRegex()
  1257. };
  1258. /**
  1259. * GFM Inline Grammar
  1260. */
  1261. inline.gfm = {
  1262. ...inline.normal,
  1263. escape: edit(inline.escape).replace('])', '~|])').getRegex(),
  1264. _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
  1265. url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
  1266. _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  1267. del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
  1268. text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
  1269. };
  1270. inline.gfm.url = edit(inline.gfm.url, 'i')
  1271. .replace('email', inline.gfm._extended_email)
  1272. .getRegex();
  1273. /**
  1274. * GFM + Line Breaks Inline Grammar
  1275. */
  1276. inline.breaks = {
  1277. ...inline.gfm,
  1278. br: edit(inline.br).replace('{2,}', '*').getRegex(),
  1279. text: edit(inline.gfm.text)
  1280. .replace('\\b_', '\\b_| {2,}\\n')
  1281. .replace(/\{2,\}/g, '*')
  1282. .getRegex()
  1283. };
  1284. /**
  1285. * smartypants text replacement
  1286. */
  1287. function smartypants(text) {
  1288. return text
  1289. // em-dashes
  1290. .replace(/---/g, '\u2014')
  1291. // en-dashes
  1292. .replace(/--/g, '\u2013')
  1293. // opening singles
  1294. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  1295. // closing singles & apostrophes
  1296. .replace(/'/g, '\u2019')
  1297. // opening doubles
  1298. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  1299. // closing doubles
  1300. .replace(/"/g, '\u201d')
  1301. // ellipses
  1302. .replace(/\.{3}/g, '\u2026');
  1303. }
  1304. /**
  1305. * mangle email addresses
  1306. */
  1307. function mangle(text) {
  1308. let out = '', i, ch;
  1309. const l = text.length;
  1310. for (i = 0; i < l; i++) {
  1311. ch = text.charCodeAt(i);
  1312. if (Math.random() > 0.5) {
  1313. ch = 'x' + ch.toString(16);
  1314. }
  1315. out += '&#' + ch + ';';
  1316. }
  1317. return out;
  1318. }
  1319. /**
  1320. * Block Lexer
  1321. */
  1322. class _Lexer {
  1323. tokens;
  1324. options;
  1325. state;
  1326. tokenizer;
  1327. inlineQueue;
  1328. constructor(options) {
  1329. // TokenList cannot be created in one go
  1330. // @ts-expect-error
  1331. this.tokens = [];
  1332. this.tokens.links = Object.create(null);
  1333. this.options = options || exports.defaults;
  1334. this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
  1335. this.tokenizer = this.options.tokenizer;
  1336. this.tokenizer.options = this.options;
  1337. this.tokenizer.lexer = this;
  1338. this.inlineQueue = [];
  1339. this.state = {
  1340. inLink: false,
  1341. inRawBlock: false,
  1342. top: true
  1343. };
  1344. const rules = {
  1345. block: block.normal,
  1346. inline: inline.normal
  1347. };
  1348. if (this.options.pedantic) {
  1349. rules.block = block.pedantic;
  1350. rules.inline = inline.pedantic;
  1351. }
  1352. else if (this.options.gfm) {
  1353. rules.block = block.gfm;
  1354. if (this.options.breaks) {
  1355. rules.inline = inline.breaks;
  1356. }
  1357. else {
  1358. rules.inline = inline.gfm;
  1359. }
  1360. }
  1361. this.tokenizer.rules = rules;
  1362. }
  1363. /**
  1364. * Expose Rules
  1365. */
  1366. static get rules() {
  1367. return {
  1368. block,
  1369. inline
  1370. };
  1371. }
  1372. /**
  1373. * Static Lex Method
  1374. */
  1375. static lex(src, options) {
  1376. const lexer = new _Lexer(options);
  1377. return lexer.lex(src);
  1378. }
  1379. /**
  1380. * Static Lex Inline Method
  1381. */
  1382. static lexInline(src, options) {
  1383. const lexer = new _Lexer(options);
  1384. return lexer.inlineTokens(src);
  1385. }
  1386. /**
  1387. * Preprocessing
  1388. */
  1389. lex(src) {
  1390. src = src
  1391. .replace(/\r\n|\r/g, '\n');
  1392. this.blockTokens(src, this.tokens);
  1393. let next;
  1394. while (next = this.inlineQueue.shift()) {
  1395. this.inlineTokens(next.src, next.tokens);
  1396. }
  1397. return this.tokens;
  1398. }
  1399. blockTokens(src, tokens = []) {
  1400. if (this.options.pedantic) {
  1401. src = src.replace(/\t/g, ' ').replace(/^ +$/gm, '');
  1402. }
  1403. else {
  1404. src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
  1405. return leading + ' '.repeat(tabs.length);
  1406. });
  1407. }
  1408. let token;
  1409. let lastToken;
  1410. let cutSrc;
  1411. let lastParagraphClipped;
  1412. while (src) {
  1413. if (this.options.extensions
  1414. && this.options.extensions.block
  1415. && this.options.extensions.block.some((extTokenizer) => {
  1416. if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
  1417. src = src.substring(token.raw.length);
  1418. tokens.push(token);
  1419. return true;
  1420. }
  1421. return false;
  1422. })) {
  1423. continue;
  1424. }
  1425. // newline
  1426. if (token = this.tokenizer.space(src)) {
  1427. src = src.substring(token.raw.length);
  1428. if (token.raw.length === 1 && tokens.length > 0) {
  1429. // if there's a single \n as a spacer, it's terminating the last line,
  1430. // so move it there so that we don't get unecessary paragraph tags
  1431. tokens[tokens.length - 1].raw += '\n';
  1432. }
  1433. else {
  1434. tokens.push(token);
  1435. }
  1436. continue;
  1437. }
  1438. // code
  1439. if (token = this.tokenizer.code(src)) {
  1440. src = src.substring(token.raw.length);
  1441. lastToken = tokens[tokens.length - 1];
  1442. // An indented code block cannot interrupt a paragraph.
  1443. if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
  1444. lastToken.raw += '\n' + token.raw;
  1445. lastToken.text += '\n' + token.text;
  1446. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1447. }
  1448. else {
  1449. tokens.push(token);
  1450. }
  1451. continue;
  1452. }
  1453. // fences
  1454. if (token = this.tokenizer.fences(src)) {
  1455. src = src.substring(token.raw.length);
  1456. tokens.push(token);
  1457. continue;
  1458. }
  1459. // heading
  1460. if (token = this.tokenizer.heading(src)) {
  1461. src = src.substring(token.raw.length);
  1462. tokens.push(token);
  1463. continue;
  1464. }
  1465. // hr
  1466. if (token = this.tokenizer.hr(src)) {
  1467. src = src.substring(token.raw.length);
  1468. tokens.push(token);
  1469. continue;
  1470. }
  1471. // blockquote
  1472. if (token = this.tokenizer.blockquote(src)) {
  1473. src = src.substring(token.raw.length);
  1474. tokens.push(token);
  1475. continue;
  1476. }
  1477. // list
  1478. if (token = this.tokenizer.list(src)) {
  1479. src = src.substring(token.raw.length);
  1480. tokens.push(token);
  1481. continue;
  1482. }
  1483. // html
  1484. if (token = this.tokenizer.html(src)) {
  1485. src = src.substring(token.raw.length);
  1486. tokens.push(token);
  1487. continue;
  1488. }
  1489. // def
  1490. if (token = this.tokenizer.def(src)) {
  1491. src = src.substring(token.raw.length);
  1492. lastToken = tokens[tokens.length - 1];
  1493. if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
  1494. lastToken.raw += '\n' + token.raw;
  1495. lastToken.text += '\n' + token.raw;
  1496. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1497. }
  1498. else if (!this.tokens.links[token.tag]) {
  1499. this.tokens.links[token.tag] = {
  1500. href: token.href,
  1501. title: token.title
  1502. };
  1503. }
  1504. continue;
  1505. }
  1506. // table (gfm)
  1507. if (token = this.tokenizer.table(src)) {
  1508. src = src.substring(token.raw.length);
  1509. tokens.push(token);
  1510. continue;
  1511. }
  1512. // lheading
  1513. if (token = this.tokenizer.lheading(src)) {
  1514. src = src.substring(token.raw.length);
  1515. tokens.push(token);
  1516. continue;
  1517. }
  1518. // top-level paragraph
  1519. // prevent paragraph consuming extensions by clipping 'src' to extension start
  1520. cutSrc = src;
  1521. if (this.options.extensions && this.options.extensions.startBlock) {
  1522. let startIndex = Infinity;
  1523. const tempSrc = src.slice(1);
  1524. let tempStart;
  1525. this.options.extensions.startBlock.forEach((getStartIndex) => {
  1526. tempStart = getStartIndex.call({ lexer: this }, tempSrc);
  1527. if (typeof tempStart === 'number' && tempStart >= 0) {
  1528. startIndex = Math.min(startIndex, tempStart);
  1529. }
  1530. });
  1531. if (startIndex < Infinity && startIndex >= 0) {
  1532. cutSrc = src.substring(0, startIndex + 1);
  1533. }
  1534. }
  1535. if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
  1536. lastToken = tokens[tokens.length - 1];
  1537. if (lastParagraphClipped && lastToken.type === 'paragraph') {
  1538. lastToken.raw += '\n' + token.raw;
  1539. lastToken.text += '\n' + token.text;
  1540. this.inlineQueue.pop();
  1541. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1542. }
  1543. else {
  1544. tokens.push(token);
  1545. }
  1546. lastParagraphClipped = (cutSrc.length !== src.length);
  1547. src = src.substring(token.raw.length);
  1548. continue;
  1549. }
  1550. // text
  1551. if (token = this.tokenizer.text(src)) {
  1552. src = src.substring(token.raw.length);
  1553. lastToken = tokens[tokens.length - 1];
  1554. if (lastToken && lastToken.type === 'text') {
  1555. lastToken.raw += '\n' + token.raw;
  1556. lastToken.text += '\n' + token.text;
  1557. this.inlineQueue.pop();
  1558. this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
  1559. }
  1560. else {
  1561. tokens.push(token);
  1562. }
  1563. continue;
  1564. }
  1565. if (src) {
  1566. const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
  1567. if (this.options.silent) {
  1568. console.error(errMsg);
  1569. break;
  1570. }
  1571. else {
  1572. throw new Error(errMsg);
  1573. }
  1574. }
  1575. }
  1576. this.state.top = true;
  1577. return tokens;
  1578. }
  1579. inline(src, tokens = []) {
  1580. this.inlineQueue.push({ src, tokens });
  1581. return tokens;
  1582. }
  1583. /**
  1584. * Lexing/Compiling
  1585. */
  1586. inlineTokens(src, tokens = []) {
  1587. let token, lastToken, cutSrc;
  1588. // String with links masked to avoid interference with em and strong
  1589. let maskedSrc = src;
  1590. let match;
  1591. let keepPrevChar, prevChar;
  1592. // Mask out reflinks
  1593. if (this.tokens.links) {
  1594. const links = Object.keys(this.tokens.links);
  1595. if (links.length > 0) {
  1596. while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
  1597. if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
  1598. maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
  1599. }
  1600. }
  1601. }
  1602. }
  1603. // Mask out other blocks
  1604. while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
  1605. maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
  1606. }
  1607. // Mask out escaped characters
  1608. while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
  1609. maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
  1610. }
  1611. while (src) {
  1612. if (!keepPrevChar) {
  1613. prevChar = '';
  1614. }
  1615. keepPrevChar = false;
  1616. // extensions
  1617. if (this.options.extensions
  1618. && this.options.extensions.inline
  1619. && this.options.extensions.inline.some((extTokenizer) => {
  1620. if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
  1621. src = src.substring(token.raw.length);
  1622. tokens.push(token);
  1623. return true;
  1624. }
  1625. return false;
  1626. })) {
  1627. continue;
  1628. }
  1629. // escape
  1630. if (token = this.tokenizer.escape(src)) {
  1631. src = src.substring(token.raw.length);
  1632. tokens.push(token);
  1633. continue;
  1634. }
  1635. // tag
  1636. if (token = this.tokenizer.tag(src)) {
  1637. src = src.substring(token.raw.length);
  1638. lastToken = tokens[tokens.length - 1];
  1639. if (lastToken && token.type === 'text' && lastToken.type === 'text') {
  1640. lastToken.raw += token.raw;
  1641. lastToken.text += token.text;
  1642. }
  1643. else {
  1644. tokens.push(token);
  1645. }
  1646. continue;
  1647. }
  1648. // link
  1649. if (token = this.tokenizer.link(src)) {
  1650. src = src.substring(token.raw.length);
  1651. tokens.push(token);
  1652. continue;
  1653. }
  1654. // reflink, nolink
  1655. if (token = this.tokenizer.reflink(src, this.tokens.links)) {
  1656. src = src.substring(token.raw.length);
  1657. lastToken = tokens[tokens.length - 1];
  1658. if (lastToken && token.type === 'text' && lastToken.type === 'text') {
  1659. lastToken.raw += token.raw;
  1660. lastToken.text += token.text;
  1661. }
  1662. else {
  1663. tokens.push(token);
  1664. }
  1665. continue;
  1666. }
  1667. // em & strong
  1668. if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
  1669. src = src.substring(token.raw.length);
  1670. tokens.push(token);
  1671. continue;
  1672. }
  1673. // code
  1674. if (token = this.tokenizer.codespan(src)) {
  1675. src = src.substring(token.raw.length);
  1676. tokens.push(token);
  1677. continue;
  1678. }
  1679. // br
  1680. if (token = this.tokenizer.br(src)) {
  1681. src = src.substring(token.raw.length);
  1682. tokens.push(token);
  1683. continue;
  1684. }
  1685. // del (gfm)
  1686. if (token = this.tokenizer.del(src)) {
  1687. src = src.substring(token.raw.length);
  1688. tokens.push(token);
  1689. continue;
  1690. }
  1691. // autolink
  1692. if (token = this.tokenizer.autolink(src, mangle)) {
  1693. src = src.substring(token.raw.length);
  1694. tokens.push(token);
  1695. continue;
  1696. }
  1697. // url (gfm)
  1698. if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
  1699. src = src.substring(token.raw.length);
  1700. tokens.push(token);
  1701. continue;
  1702. }
  1703. // text
  1704. // prevent inlineText consuming extensions by clipping 'src' to extension start
  1705. cutSrc = src;
  1706. if (this.options.extensions && this.options.extensions.startInline) {
  1707. let startIndex = Infinity;
  1708. const tempSrc = src.slice(1);
  1709. let tempStart;
  1710. this.options.extensions.startInline.forEach((getStartIndex) => {
  1711. tempStart = getStartIndex.call({ lexer: this }, tempSrc);
  1712. if (typeof tempStart === 'number' && tempStart >= 0) {
  1713. startIndex = Math.min(startIndex, tempStart);
  1714. }
  1715. });
  1716. if (startIndex < Infinity && startIndex >= 0) {
  1717. cutSrc = src.substring(0, startIndex + 1);
  1718. }
  1719. }
  1720. if (token = this.tokenizer.inlineText(cutSrc, smartypants)) {
  1721. src = src.substring(token.raw.length);
  1722. if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started
  1723. prevChar = token.raw.slice(-1);
  1724. }
  1725. keepPrevChar = true;
  1726. lastToken = tokens[tokens.length - 1];
  1727. if (lastToken && lastToken.type === 'text') {
  1728. lastToken.raw += token.raw;
  1729. lastToken.text += token.text;
  1730. }
  1731. else {
  1732. tokens.push(token);
  1733. }
  1734. continue;
  1735. }
  1736. if (src) {
  1737. const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
  1738. if (this.options.silent) {
  1739. console.error(errMsg);
  1740. break;
  1741. }
  1742. else {
  1743. throw new Error(errMsg);
  1744. }
  1745. }
  1746. }
  1747. return tokens;
  1748. }
  1749. }
  1750. /**
  1751. * Renderer
  1752. */
  1753. class _Renderer {
  1754. options;
  1755. constructor(options) {
  1756. this.options = options || exports.defaults;
  1757. }
  1758. code(code, infostring, escaped) {
  1759. const lang = (infostring || '').match(/\S*/)[0];
  1760. if (this.options.highlight) {
  1761. const out = this.options.highlight(code, lang);
  1762. if (out != null && out !== code) {
  1763. escaped = true;
  1764. code = out;
  1765. }
  1766. }
  1767. code = code.replace(/\n$/, '') + '\n';
  1768. if (!lang) {
  1769. return '<pre><code>'
  1770. + (escaped ? code : escape(code, true))
  1771. + '</code></pre>\n';
  1772. }
  1773. return '<pre><code class="'
  1774. + this.options.langPrefix
  1775. + escape(lang)
  1776. + '">'
  1777. + (escaped ? code : escape(code, true))
  1778. + '</code></pre>\n';
  1779. }
  1780. blockquote(quote) {
  1781. return `<blockquote>\n${quote}</blockquote>\n`;
  1782. }
  1783. html(html, block) {
  1784. return html;
  1785. }
  1786. heading(text, level, raw, slugger) {
  1787. if (this.options.headerIds) {
  1788. const id = this.options.headerPrefix + slugger.slug(raw);
  1789. return `<h${level} id="${id}">${text}</h${level}>\n`;
  1790. }
  1791. // ignore IDs
  1792. return `<h${level}>${text}</h${level}>\n`;
  1793. }
  1794. hr() {
  1795. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  1796. }
  1797. list(body, ordered, start) {
  1798. const type = ordered ? 'ol' : 'ul', startatt = (ordered && start !== 1) ? (' start="' + start + '"') : '';
  1799. return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
  1800. }
  1801. listitem(text, task, checked) {
  1802. return `<li>${text}</li>\n`;
  1803. }
  1804. checkbox(checked) {
  1805. return '<input '
  1806. + (checked ? 'checked="" ' : '')
  1807. + 'disabled="" type="checkbox"'
  1808. + (this.options.xhtml ? ' /' : '')
  1809. + '> ';
  1810. }
  1811. paragraph(text) {
  1812. return `<p>${text}</p>\n`;
  1813. }
  1814. table(header, body) {
  1815. if (body)
  1816. body = `<tbody>${body}</tbody>`;
  1817. return '<table>\n'
  1818. + '<thead>\n'
  1819. + header
  1820. + '</thead>\n'
  1821. + body
  1822. + '</table>\n';
  1823. }
  1824. tablerow(content) {
  1825. return `<tr>\n${content}</tr>\n`;
  1826. }
  1827. tablecell(content, flags) {
  1828. const type = flags.header ? 'th' : 'td';
  1829. const tag = flags.align
  1830. ? `<${type} align="${flags.align}">`
  1831. : `<${type}>`;
  1832. return tag + content + `</${type}>\n`;
  1833. }
  1834. /**
  1835. * span level renderer
  1836. */
  1837. strong(text) {
  1838. return `<strong>${text}</strong>`;
  1839. }
  1840. em(text) {
  1841. return `<em>${text}</em>`;
  1842. }
  1843. codespan(text) {
  1844. return `<code>${text}</code>`;
  1845. }
  1846. br() {
  1847. return this.options.xhtml ? '<br/>' : '<br>';
  1848. }
  1849. del(text) {
  1850. return `<del>${text}</del>`;
  1851. }
  1852. link(href, title, text) {
  1853. href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
  1854. if (href === null) {
  1855. return text;
  1856. }
  1857. let out = '<a href="' + href + '"';
  1858. if (title) {
  1859. out += ' title="' + title + '"';
  1860. }
  1861. out += '>' + text + '</a>';
  1862. return out;
  1863. }
  1864. image(href, title, text) {
  1865. href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
  1866. if (href === null) {
  1867. return text;
  1868. }
  1869. let out = `<img src="${href}" alt="${text}"`;
  1870. if (title) {
  1871. out += ` title="${title}"`;
  1872. }
  1873. out += this.options.xhtml ? '/>' : '>';
  1874. return out;
  1875. }
  1876. text(text) {
  1877. return text;
  1878. }
  1879. }
  1880. /**
  1881. * TextRenderer
  1882. * returns only the textual part of the token
  1883. */
  1884. class _TextRenderer {
  1885. // no need for block level renderers
  1886. strong(text) {
  1887. return text;
  1888. }
  1889. em(text) {
  1890. return text;
  1891. }
  1892. codespan(text) {
  1893. return text;
  1894. }
  1895. del(text) {
  1896. return text;
  1897. }
  1898. html(text) {
  1899. return text;
  1900. }
  1901. text(text) {
  1902. return text;
  1903. }
  1904. link(href, title, text) {
  1905. return '' + text;
  1906. }
  1907. image(href, title, text) {
  1908. return '' + text;
  1909. }
  1910. br() {
  1911. return '';
  1912. }
  1913. }
  1914. /**
  1915. * Slugger generates header id
  1916. */
  1917. class _Slugger {
  1918. seen;
  1919. constructor() {
  1920. this.seen = {};
  1921. }
  1922. serialize(value) {
  1923. return value
  1924. .toLowerCase()
  1925. .trim()
  1926. // remove html tags
  1927. .replace(/<[!\/a-z].*?>/ig, '')
  1928. // remove unwanted chars
  1929. .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
  1930. .replace(/\s/g, '-');
  1931. }
  1932. /**
  1933. * Finds the next safe (unique) slug to use
  1934. */
  1935. getNextSafeSlug(originalSlug, isDryRun) {
  1936. let slug = originalSlug;
  1937. let occurenceAccumulator = 0;
  1938. if (this.seen.hasOwnProperty(slug)) {
  1939. occurenceAccumulator = this.seen[originalSlug];
  1940. do {
  1941. occurenceAccumulator++;
  1942. slug = originalSlug + '-' + occurenceAccumulator;
  1943. } while (this.seen.hasOwnProperty(slug));
  1944. }
  1945. if (!isDryRun) {
  1946. this.seen[originalSlug] = occurenceAccumulator;
  1947. this.seen[slug] = 0;
  1948. }
  1949. return slug;
  1950. }
  1951. /**
  1952. * Convert string to unique id
  1953. */
  1954. slug(value, options = {}) {
  1955. const slug = this.serialize(value);
  1956. return this.getNextSafeSlug(slug, options.dryrun);
  1957. }
  1958. }
  1959. /**
  1960. * Parsing & Compiling
  1961. */
  1962. class _Parser {
  1963. options;
  1964. renderer;
  1965. textRenderer;
  1966. slugger;
  1967. constructor(options) {
  1968. this.options = options || exports.defaults;
  1969. this.options.renderer = this.options.renderer || new _Renderer();
  1970. this.renderer = this.options.renderer;
  1971. this.renderer.options = this.options;
  1972. this.textRenderer = new _TextRenderer();
  1973. this.slugger = new _Slugger();
  1974. }
  1975. /**
  1976. * Static Parse Method
  1977. */
  1978. static parse(tokens, options) {
  1979. const parser = new _Parser(options);
  1980. return parser.parse(tokens);
  1981. }
  1982. /**
  1983. * Static Parse Inline Method
  1984. */
  1985. static parseInline(tokens, options) {
  1986. const parser = new _Parser(options);
  1987. return parser.parseInline(tokens);
  1988. }
  1989. /**
  1990. * Parse Loop
  1991. */
  1992. parse(tokens, top = true) {
  1993. let out = '', i, j, k, l2, l3, row, cell, header, body, token, ordered, start, loose, itemBody, item, checked, task, checkbox, ret;
  1994. const l = tokens.length;
  1995. for (i = 0; i < l; i++) {
  1996. token = tokens[i];
  1997. // Run any renderer extensions
  1998. if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
  1999. ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
  2000. if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(token.type)) {
  2001. out += ret || '';
  2002. continue;
  2003. }
  2004. }
  2005. switch (token.type) {
  2006. case 'space': {
  2007. continue;
  2008. }
  2009. case 'hr': {
  2010. out += this.renderer.hr();
  2011. continue;
  2012. }
  2013. case 'heading': {
  2014. out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape(this.parseInline(token.tokens, this.textRenderer)), this.slugger);
  2015. continue;
  2016. }
  2017. case 'code': {
  2018. out += this.renderer.code(token.text, token.lang, !!token.escaped);
  2019. continue;
  2020. }
  2021. case 'table': {
  2022. header = '';
  2023. // header
  2024. cell = '';
  2025. l2 = token.header.length;
  2026. for (j = 0; j < l2; j++) {
  2027. cell += this.renderer.tablecell(this.parseInline(token.header[j].tokens), { header: true, align: token.align[j] });
  2028. }
  2029. header += this.renderer.tablerow(cell);
  2030. body = '';
  2031. l2 = token.rows.length;
  2032. for (j = 0; j < l2; j++) {
  2033. row = token.rows[j];
  2034. cell = '';
  2035. l3 = row.length;
  2036. for (k = 0; k < l3; k++) {
  2037. cell += this.renderer.tablecell(this.parseInline(row[k].tokens), { header: false, align: token.align[k] });
  2038. }
  2039. body += this.renderer.tablerow(cell);
  2040. }
  2041. out += this.renderer.table(header, body);
  2042. continue;
  2043. }
  2044. case 'blockquote': {
  2045. body = this.parse(token.tokens);
  2046. out += this.renderer.blockquote(body);
  2047. continue;
  2048. }
  2049. case 'list': {
  2050. ordered = token.ordered;
  2051. start = token.start;
  2052. loose = token.loose;
  2053. l2 = token.items.length;
  2054. body = '';
  2055. for (j = 0; j < l2; j++) {
  2056. item = token.items[j];
  2057. checked = item.checked;
  2058. task = item.task;
  2059. itemBody = '';
  2060. if (item.task) {
  2061. checkbox = this.renderer.checkbox(!!checked);
  2062. if (loose) {
  2063. if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
  2064. item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
  2065. if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
  2066. item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
  2067. }
  2068. }
  2069. else {
  2070. item.tokens.unshift({
  2071. type: 'text',
  2072. text: checkbox
  2073. });
  2074. }
  2075. }
  2076. else {
  2077. itemBody += checkbox;
  2078. }
  2079. }
  2080. itemBody += this.parse(item.tokens, loose);
  2081. body += this.renderer.listitem(itemBody, task, !!checked);
  2082. }
  2083. out += this.renderer.list(body, ordered, start);
  2084. continue;
  2085. }
  2086. case 'html': {
  2087. out += this.renderer.html(token.text, token.block);
  2088. continue;
  2089. }
  2090. case 'paragraph': {
  2091. out += this.renderer.paragraph(this.parseInline(token.tokens));
  2092. continue;
  2093. }
  2094. case 'text': {
  2095. body = token.tokens ? this.parseInline(token.tokens) : token.text;
  2096. while (i + 1 < l && tokens[i + 1].type === 'text') {
  2097. token = tokens[++i];
  2098. body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text);
  2099. }
  2100. out += top ? this.renderer.paragraph(body) : body;
  2101. continue;
  2102. }
  2103. default: {
  2104. const errMsg = 'Token with "' + token.type + '" type was not found.';
  2105. if (this.options.silent) {
  2106. console.error(errMsg);
  2107. return '';
  2108. }
  2109. else {
  2110. throw new Error(errMsg);
  2111. }
  2112. }
  2113. }
  2114. }
  2115. return out;
  2116. }
  2117. /**
  2118. * Parse Inline Tokens
  2119. */
  2120. parseInline(tokens, renderer) {
  2121. renderer = renderer || this.renderer;
  2122. let out = '', i, token, ret;
  2123. const l = tokens.length;
  2124. for (i = 0; i < l; i++) {
  2125. token = tokens[i];
  2126. // Run any renderer extensions
  2127. if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
  2128. ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
  2129. if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {
  2130. out += ret || '';
  2131. continue;
  2132. }
  2133. }
  2134. switch (token.type) {
  2135. case 'escape': {
  2136. out += renderer.text(token.text);
  2137. break;
  2138. }
  2139. case 'html': {
  2140. out += renderer.html(token.text);
  2141. break;
  2142. }
  2143. case 'link': {
  2144. out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));
  2145. break;
  2146. }
  2147. case 'image': {
  2148. out += renderer.image(token.href, token.title, token.text);
  2149. break;
  2150. }
  2151. case 'strong': {
  2152. out += renderer.strong(this.parseInline(token.tokens, renderer));
  2153. break;
  2154. }
  2155. case 'em': {
  2156. out += renderer.em(this.parseInline(token.tokens, renderer));
  2157. break;
  2158. }
  2159. case 'codespan': {
  2160. out += renderer.codespan(token.text);
  2161. break;
  2162. }
  2163. case 'br': {
  2164. out += renderer.br();
  2165. break;
  2166. }
  2167. case 'del': {
  2168. out += renderer.del(this.parseInline(token.tokens, renderer));
  2169. break;
  2170. }
  2171. case 'text': {
  2172. out += renderer.text(token.text);
  2173. break;
  2174. }
  2175. default: {
  2176. const errMsg = 'Token with "' + token.type + '" type was not found.';
  2177. if (this.options.silent) {
  2178. console.error(errMsg);
  2179. return '';
  2180. }
  2181. else {
  2182. throw new Error(errMsg);
  2183. }
  2184. }
  2185. }
  2186. }
  2187. return out;
  2188. }
  2189. }
  2190. class _Hooks {
  2191. options;
  2192. constructor(options) {
  2193. this.options = options || exports.defaults;
  2194. }
  2195. static passThroughHooks = new Set([
  2196. 'preprocess',
  2197. 'postprocess'
  2198. ]);
  2199. /**
  2200. * Process markdown before marked
  2201. */
  2202. preprocess(markdown) {
  2203. return markdown;
  2204. }
  2205. /**
  2206. * Process HTML after marked is finished
  2207. */
  2208. postprocess(html) {
  2209. return html;
  2210. }
  2211. }
  2212. class Marked {
  2213. defaults = _getDefaults();
  2214. options = this.setOptions;
  2215. parse = this.#parseMarkdown(_Lexer.lex, _Parser.parse);
  2216. parseInline = this.#parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
  2217. Parser = _Parser;
  2218. parser = _Parser.parse;
  2219. Renderer = _Renderer;
  2220. TextRenderer = _TextRenderer;
  2221. Lexer = _Lexer;
  2222. lexer = _Lexer.lex;
  2223. Tokenizer = _Tokenizer;
  2224. Slugger = _Slugger;
  2225. Hooks = _Hooks;
  2226. constructor(...args) {
  2227. this.use(...args);
  2228. }
  2229. /**
  2230. * Run callback for every token
  2231. */
  2232. walkTokens(tokens, callback) {
  2233. let values = [];
  2234. for (const token of tokens) {
  2235. values = values.concat(callback.call(this, token));
  2236. switch (token.type) {
  2237. case 'table': {
  2238. for (const cell of token.header) {
  2239. values = values.concat(this.walkTokens(cell.tokens, callback));
  2240. }
  2241. for (const row of token.rows) {
  2242. for (const cell of row) {
  2243. values = values.concat(this.walkTokens(cell.tokens, callback));
  2244. }
  2245. }
  2246. break;
  2247. }
  2248. case 'list': {
  2249. values = values.concat(this.walkTokens(token.items, callback));
  2250. break;
  2251. }
  2252. default: {
  2253. if (this.defaults.extensions && this.defaults.extensions.childTokens && this.defaults.extensions.childTokens[token.type]) { // Walk any extensions
  2254. this.defaults.extensions.childTokens[token.type].forEach((childTokens) => {
  2255. // @ts-expect-error we assume token[childToken] is an array of tokens but we can't be sure
  2256. values = values.concat(this.walkTokens(token[childTokens], callback));
  2257. });
  2258. }
  2259. else if (token.tokens) {
  2260. values = values.concat(this.walkTokens(token.tokens, callback));
  2261. }
  2262. }
  2263. }
  2264. }
  2265. return values;
  2266. }
  2267. use(...args) {
  2268. const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
  2269. args.forEach((pack) => {
  2270. // copy options to new object
  2271. const opts = { ...pack };
  2272. // set async to true if it was set to true before
  2273. opts.async = this.defaults.async || opts.async || false;
  2274. // ==-- Parse "addon" extensions --== //
  2275. if (pack.extensions) {
  2276. pack.extensions.forEach((ext) => {
  2277. if (!ext.name) {
  2278. throw new Error('extension name required');
  2279. }
  2280. if ('renderer' in ext) { // Renderer extensions
  2281. const prevRenderer = extensions.renderers[ext.name];
  2282. if (prevRenderer) {
  2283. // Replace extension with func to run new extension but fall back if false
  2284. extensions.renderers[ext.name] = function (...args) {
  2285. let ret = ext.renderer.apply(this, args);
  2286. if (ret === false) {
  2287. ret = prevRenderer.apply(this, args);
  2288. }
  2289. return ret;
  2290. };
  2291. }
  2292. else {
  2293. extensions.renderers[ext.name] = ext.renderer;
  2294. }
  2295. }
  2296. if ('tokenizer' in ext) { // Tokenizer Extensions
  2297. if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {
  2298. throw new Error("extension level must be 'block' or 'inline'");
  2299. }
  2300. if (extensions[ext.level]) {
  2301. extensions[ext.level].unshift(ext.tokenizer);
  2302. }
  2303. else {
  2304. extensions[ext.level] = [ext.tokenizer];
  2305. }
  2306. if (ext.start) { // Function to check for start of token
  2307. if (ext.level === 'block') {
  2308. if (extensions.startBlock) {
  2309. extensions.startBlock.push(ext.start);
  2310. }
  2311. else {
  2312. extensions.startBlock = [ext.start];
  2313. }
  2314. }
  2315. else if (ext.level === 'inline') {
  2316. if (extensions.startInline) {
  2317. extensions.startInline.push(ext.start);
  2318. }
  2319. else {
  2320. extensions.startInline = [ext.start];
  2321. }
  2322. }
  2323. }
  2324. }
  2325. if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens
  2326. extensions.childTokens[ext.name] = ext.childTokens;
  2327. }
  2328. });
  2329. opts.extensions = extensions;
  2330. }
  2331. // ==-- Parse "overwrite" extensions --== //
  2332. if (pack.renderer) {
  2333. const renderer = this.defaults.renderer || new _Renderer(this.defaults);
  2334. for (const prop in pack.renderer) {
  2335. const rendererFunc = pack.renderer[prop];
  2336. const rendererKey = prop;
  2337. const prevRenderer = renderer[rendererKey];
  2338. // Replace renderer with func to run extension, but fall back if false
  2339. renderer[rendererKey] = (...args) => {
  2340. let ret = rendererFunc.apply(renderer, args);
  2341. if (ret === false) {
  2342. ret = prevRenderer.apply(renderer, args);
  2343. }
  2344. return ret || '';
  2345. };
  2346. }
  2347. opts.renderer = renderer;
  2348. }
  2349. if (pack.tokenizer) {
  2350. const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
  2351. for (const prop in pack.tokenizer) {
  2352. const tokenizerFunc = pack.tokenizer[prop];
  2353. const tokenizerKey = prop;
  2354. const prevTokenizer = tokenizer[tokenizerKey];
  2355. // Replace tokenizer with func to run extension, but fall back if false
  2356. tokenizer[tokenizerKey] = (...args) => {
  2357. let ret = tokenizerFunc.apply(tokenizer, args);
  2358. if (ret === false) {
  2359. ret = prevTokenizer.apply(tokenizer, args);
  2360. }
  2361. return ret;
  2362. };
  2363. }
  2364. opts.tokenizer = tokenizer;
  2365. }
  2366. // ==-- Parse Hooks extensions --== //
  2367. if (pack.hooks) {
  2368. const hooks = this.defaults.hooks || new _Hooks();
  2369. for (const prop in pack.hooks) {
  2370. const hooksFunc = pack.hooks[prop];
  2371. const hooksKey = prop;
  2372. const prevHook = hooks[hooksKey];
  2373. if (_Hooks.passThroughHooks.has(prop)) {
  2374. hooks[hooksKey] = (arg) => {
  2375. if (this.defaults.async) {
  2376. return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
  2377. return prevHook.call(hooks, ret);
  2378. });
  2379. }
  2380. const ret = hooksFunc.call(hooks, arg);
  2381. return prevHook.call(hooks, ret);
  2382. };
  2383. }
  2384. else {
  2385. hooks[hooksKey] = (...args) => {
  2386. let ret = hooksFunc.apply(hooks, args);
  2387. if (ret === false) {
  2388. ret = prevHook.apply(hooks, args);
  2389. }
  2390. return ret;
  2391. };
  2392. }
  2393. }
  2394. opts.hooks = hooks;
  2395. }
  2396. // ==-- Parse WalkTokens extensions --== //
  2397. if (pack.walkTokens) {
  2398. const walkTokens = this.defaults.walkTokens;
  2399. opts.walkTokens = function (token) {
  2400. let values = [];
  2401. values.push(pack.walkTokens.call(this, token));
  2402. if (walkTokens) {
  2403. values = values.concat(walkTokens.call(this, token));
  2404. }
  2405. return values;
  2406. };
  2407. }
  2408. this.defaults = { ...this.defaults, ...opts };
  2409. });
  2410. return this;
  2411. }
  2412. setOptions(opt) {
  2413. this.defaults = { ...this.defaults, ...opt };
  2414. return this;
  2415. }
  2416. #parseMarkdown(lexer, parser) {
  2417. return (src, optOrCallback, callback) => {
  2418. if (typeof optOrCallback === 'function') {
  2419. callback = optOrCallback;
  2420. optOrCallback = null;
  2421. }
  2422. const origOpt = { ...optOrCallback };
  2423. const opt = { ...this.defaults, ...origOpt };
  2424. const throwError = this.#onError(!!opt.silent, !!opt.async, callback);
  2425. // throw error in case of non string input
  2426. if (typeof src === 'undefined' || src === null) {
  2427. return throwError(new Error('marked(): input parameter is undefined or null'));
  2428. }
  2429. if (typeof src !== 'string') {
  2430. return throwError(new Error('marked(): input parameter is of type '
  2431. + Object.prototype.toString.call(src) + ', string expected'));
  2432. }
  2433. checkDeprecations(opt, callback);
  2434. if (opt.hooks) {
  2435. opt.hooks.options = opt;
  2436. }
  2437. if (callback) {
  2438. const highlight = opt.highlight;
  2439. let tokens;
  2440. try {
  2441. if (opt.hooks) {
  2442. src = opt.hooks.preprocess(src);
  2443. }
  2444. tokens = lexer(src, opt);
  2445. }
  2446. catch (e) {
  2447. return throwError(e);
  2448. }
  2449. const done = (err) => {
  2450. let out;
  2451. if (!err) {
  2452. try {
  2453. if (opt.walkTokens) {
  2454. this.walkTokens(tokens, opt.walkTokens);
  2455. }
  2456. out = parser(tokens, opt);
  2457. if (opt.hooks) {
  2458. out = opt.hooks.postprocess(out);
  2459. }
  2460. }
  2461. catch (e) {
  2462. err = e;
  2463. }
  2464. }
  2465. opt.highlight = highlight;
  2466. return err
  2467. ? throwError(err)
  2468. : callback(null, out);
  2469. };
  2470. if (!highlight || highlight.length < 3) {
  2471. return done();
  2472. }
  2473. delete opt.highlight;
  2474. if (!tokens.length)
  2475. return done();
  2476. let pending = 0;
  2477. this.walkTokens(tokens, (token) => {
  2478. if (token.type === 'code') {
  2479. pending++;
  2480. setTimeout(() => {
  2481. highlight(token.text, token.lang, (err, code) => {
  2482. if (err) {
  2483. return done(err);
  2484. }
  2485. if (code != null && code !== token.text) {
  2486. token.text = code;
  2487. token.escaped = true;
  2488. }
  2489. pending--;
  2490. if (pending === 0) {
  2491. done();
  2492. }
  2493. });
  2494. }, 0);
  2495. }
  2496. });
  2497. if (pending === 0) {
  2498. done();
  2499. }
  2500. return;
  2501. }
  2502. if (opt.async) {
  2503. return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)
  2504. .then(src => lexer(src, opt))
  2505. .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)
  2506. .then(tokens => parser(tokens, opt))
  2507. .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)
  2508. .catch(throwError);
  2509. }
  2510. try {
  2511. if (opt.hooks) {
  2512. src = opt.hooks.preprocess(src);
  2513. }
  2514. const tokens = lexer(src, opt);
  2515. if (opt.walkTokens) {
  2516. this.walkTokens(tokens, opt.walkTokens);
  2517. }
  2518. let html = parser(tokens, opt);
  2519. if (opt.hooks) {
  2520. html = opt.hooks.postprocess(html);
  2521. }
  2522. return html;
  2523. }
  2524. catch (e) {
  2525. return throwError(e);
  2526. }
  2527. };
  2528. }
  2529. #onError(silent, async, callback) {
  2530. return (e) => {
  2531. e.message += '\nPlease report this to https://github.com/markedjs/marked.';
  2532. if (silent) {
  2533. const msg = '<p>An error occurred:</p><pre>'
  2534. + escape(e.message + '', true)
  2535. + '</pre>';
  2536. if (async) {
  2537. return Promise.resolve(msg);
  2538. }
  2539. if (callback) {
  2540. callback(null, msg);
  2541. return;
  2542. }
  2543. return msg;
  2544. }
  2545. if (async) {
  2546. return Promise.reject(e);
  2547. }
  2548. if (callback) {
  2549. callback(e);
  2550. return;
  2551. }
  2552. throw e;
  2553. };
  2554. }
  2555. }
  2556. const markedInstance = new Marked();
  2557. function marked(src, opt, callback) {
  2558. return markedInstance.parse(src, opt, callback);
  2559. }
  2560. /**
  2561. * Sets the default options.
  2562. *
  2563. * @param options Hash of options
  2564. */
  2565. marked.options =
  2566. marked.setOptions = function (options) {
  2567. markedInstance.setOptions(options);
  2568. marked.defaults = markedInstance.defaults;
  2569. changeDefaults(marked.defaults);
  2570. return marked;
  2571. };
  2572. /**
  2573. * Gets the original marked default options.
  2574. */
  2575. marked.getDefaults = _getDefaults;
  2576. marked.defaults = exports.defaults;
  2577. /**
  2578. * Use Extension
  2579. */
  2580. marked.use = function (...args) {
  2581. markedInstance.use(...args);
  2582. marked.defaults = markedInstance.defaults;
  2583. changeDefaults(marked.defaults);
  2584. return marked;
  2585. };
  2586. /**
  2587. * Run callback for every token
  2588. */
  2589. marked.walkTokens = function (tokens, callback) {
  2590. return markedInstance.walkTokens(tokens, callback);
  2591. };
  2592. /**
  2593. * Compiles markdown to HTML without enclosing `p` tag.
  2594. *
  2595. * @param src String of markdown source to be compiled
  2596. * @param options Hash of options
  2597. * @return String of compiled HTML
  2598. */
  2599. marked.parseInline = markedInstance.parseInline;
  2600. /**
  2601. * Expose
  2602. */
  2603. marked.Parser = _Parser;
  2604. marked.parser = _Parser.parse;
  2605. marked.Renderer = _Renderer;
  2606. marked.TextRenderer = _TextRenderer;
  2607. marked.Lexer = _Lexer;
  2608. marked.lexer = _Lexer.lex;
  2609. marked.Tokenizer = _Tokenizer;
  2610. marked.Slugger = _Slugger;
  2611. marked.Hooks = _Hooks;
  2612. marked.parse = marked;
  2613. const options = marked.options;
  2614. const setOptions = marked.setOptions;
  2615. const use = marked.use;
  2616. const walkTokens = marked.walkTokens;
  2617. const parseInline = marked.parseInline;
  2618. const parse = marked;
  2619. const parser = _Parser.parse;
  2620. const lexer = _Lexer.lex;
  2621. exports.Hooks = _Hooks;
  2622. exports.Lexer = _Lexer;
  2623. exports.Marked = Marked;
  2624. exports.Parser = _Parser;
  2625. exports.Renderer = _Renderer;
  2626. exports.Slugger = _Slugger;
  2627. exports.TextRenderer = _TextRenderer;
  2628. exports.Tokenizer = _Tokenizer;
  2629. exports.getDefaults = _getDefaults;
  2630. exports.lexer = lexer;
  2631. exports.marked = marked;
  2632. exports.options = options;
  2633. exports.parse = parse;
  2634. exports.parseInline = parseInline;
  2635. exports.parser = parser;
  2636. exports.setOptions = setOptions;
  2637. exports.use = use;
  2638. exports.walkTokens = walkTokens;
  2639. }));
  2640. //# sourceMappingURL=marked.umd.js.map