@simon_he/vue-tui 1.1.12 → 1.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/markdown.cjs CHANGED
@@ -853,6 +853,19 @@ function sliceByCellsRange(text2, startCells, endCells, provider = currentTextWi
853
853
  out.push(g), cells = next;
854
854
  }), out.length ? out.join("") : "";
855
855
  }
856
+ function sliceByCellsRangeForSelection(text2, startCells, endCells, provider = currentTextWidthProvider()) {
857
+ if (startCells = Math.max(0, Math.floor(startCells)), endCells = Math.max(0, Math.floor(endCells)), endCells <= startCells || !text2)
858
+ return "";
859
+ if (hasAsciiFastPath(provider) && isAscii(text2))
860
+ return text2.slice(startCells, endCells);
861
+ let out = [], cells = 0;
862
+ return forEachGrapheme(text2, (g) => {
863
+ let leadingCell = cells;
864
+ if (cells += charCellWidth(g, provider), leadingCell >= endCells)
865
+ return !1;
866
+ leadingCell >= startCells && out.push(g);
867
+ }), out.join("");
868
+ }
856
869
  var textWidthCache = /* @__PURE__ */ new Map(), MAX_TEXT_WIDTH_CACHE = 1024;
857
870
  function textWidthCacheGet(text2) {
858
871
  let cached = textWidthCache.get(text2);
@@ -1279,7 +1292,7 @@ function loadBuiltinMathRasterizer() {
1279
1292
  })()), builtinRasterizerLoad;
1280
1293
  }
1281
1294
 
1282
- // node_modules/.pnpm/stream-markdown-parser@1.2.12/node_modules/stream-markdown-parser/dist/index.js
1295
+ // node_modules/.pnpm/stream-markdown-parser@1.2.20/node_modules/stream-markdown-parser/dist/index.js
1283
1296
  var __create2 = Object.create, __defProp$1 = Object.defineProperty, __getOwnPropDesc2 = Object.getOwnPropertyDescriptor, __getOwnPropNames2 = Object.getOwnPropertyNames, __getProtoOf2 = Object.getPrototypeOf, __hasOwnProp2 = Object.prototype.hasOwnProperty, __commonJS = (cb, mod) => function() {
1284
1297
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
1285
1298
  }, __export$1 = (all) => {
@@ -1662,7 +1675,756 @@ var require_markdown_it_task_checkbox = /* @__PURE__ */ __commonJS({ "../../node
1662
1675
  function startsWithTodoMarkdown(token) {
1663
1676
  return /^\[[xX \u00A0]\][ \u00A0]/.test(token.content);
1664
1677
  }
1665
- } }), decodeMap = /* @__PURE__ */ new Map([
1678
+ } }), import_markdown_it_task_checkbox = /* @__PURE__ */ __toESM2(require_markdown_it_task_checkbox(), 1), ambiguousMinimalCodePoint = 161, ambiguousMaximumCodePoint = 1114109, ambiguousRanges = [
1679
+ 161,
1680
+ 161,
1681
+ 164,
1682
+ 164,
1683
+ 167,
1684
+ 168,
1685
+ 170,
1686
+ 170,
1687
+ 173,
1688
+ 174,
1689
+ 176,
1690
+ 180,
1691
+ 182,
1692
+ 186,
1693
+ 188,
1694
+ 191,
1695
+ 198,
1696
+ 198,
1697
+ 208,
1698
+ 208,
1699
+ 215,
1700
+ 216,
1701
+ 222,
1702
+ 225,
1703
+ 230,
1704
+ 230,
1705
+ 232,
1706
+ 234,
1707
+ 236,
1708
+ 237,
1709
+ 240,
1710
+ 240,
1711
+ 242,
1712
+ 243,
1713
+ 247,
1714
+ 250,
1715
+ 252,
1716
+ 252,
1717
+ 254,
1718
+ 254,
1719
+ 257,
1720
+ 257,
1721
+ 273,
1722
+ 273,
1723
+ 275,
1724
+ 275,
1725
+ 283,
1726
+ 283,
1727
+ 294,
1728
+ 295,
1729
+ 299,
1730
+ 299,
1731
+ 305,
1732
+ 307,
1733
+ 312,
1734
+ 312,
1735
+ 319,
1736
+ 322,
1737
+ 324,
1738
+ 324,
1739
+ 328,
1740
+ 331,
1741
+ 333,
1742
+ 333,
1743
+ 338,
1744
+ 339,
1745
+ 358,
1746
+ 359,
1747
+ 363,
1748
+ 363,
1749
+ 462,
1750
+ 462,
1751
+ 464,
1752
+ 464,
1753
+ 466,
1754
+ 466,
1755
+ 468,
1756
+ 468,
1757
+ 470,
1758
+ 470,
1759
+ 472,
1760
+ 472,
1761
+ 474,
1762
+ 474,
1763
+ 476,
1764
+ 476,
1765
+ 593,
1766
+ 593,
1767
+ 609,
1768
+ 609,
1769
+ 708,
1770
+ 708,
1771
+ 711,
1772
+ 711,
1773
+ 713,
1774
+ 715,
1775
+ 717,
1776
+ 717,
1777
+ 720,
1778
+ 720,
1779
+ 728,
1780
+ 731,
1781
+ 733,
1782
+ 733,
1783
+ 735,
1784
+ 735,
1785
+ 768,
1786
+ 879,
1787
+ 913,
1788
+ 929,
1789
+ 931,
1790
+ 937,
1791
+ 945,
1792
+ 961,
1793
+ 963,
1794
+ 969,
1795
+ 1025,
1796
+ 1025,
1797
+ 1040,
1798
+ 1103,
1799
+ 1105,
1800
+ 1105,
1801
+ 8208,
1802
+ 8208,
1803
+ 8211,
1804
+ 8214,
1805
+ 8216,
1806
+ 8217,
1807
+ 8220,
1808
+ 8221,
1809
+ 8224,
1810
+ 8226,
1811
+ 8228,
1812
+ 8231,
1813
+ 8240,
1814
+ 8240,
1815
+ 8242,
1816
+ 8243,
1817
+ 8245,
1818
+ 8245,
1819
+ 8251,
1820
+ 8251,
1821
+ 8254,
1822
+ 8254,
1823
+ 8308,
1824
+ 8308,
1825
+ 8319,
1826
+ 8319,
1827
+ 8321,
1828
+ 8324,
1829
+ 8364,
1830
+ 8364,
1831
+ 8451,
1832
+ 8451,
1833
+ 8453,
1834
+ 8453,
1835
+ 8457,
1836
+ 8457,
1837
+ 8467,
1838
+ 8467,
1839
+ 8470,
1840
+ 8470,
1841
+ 8481,
1842
+ 8482,
1843
+ 8486,
1844
+ 8486,
1845
+ 8491,
1846
+ 8491,
1847
+ 8531,
1848
+ 8532,
1849
+ 8539,
1850
+ 8542,
1851
+ 8544,
1852
+ 8555,
1853
+ 8560,
1854
+ 8569,
1855
+ 8585,
1856
+ 8585,
1857
+ 8592,
1858
+ 8601,
1859
+ 8632,
1860
+ 8633,
1861
+ 8658,
1862
+ 8658,
1863
+ 8660,
1864
+ 8660,
1865
+ 8679,
1866
+ 8679,
1867
+ 8704,
1868
+ 8704,
1869
+ 8706,
1870
+ 8707,
1871
+ 8711,
1872
+ 8712,
1873
+ 8715,
1874
+ 8715,
1875
+ 8719,
1876
+ 8719,
1877
+ 8721,
1878
+ 8721,
1879
+ 8725,
1880
+ 8725,
1881
+ 8730,
1882
+ 8730,
1883
+ 8733,
1884
+ 8736,
1885
+ 8739,
1886
+ 8739,
1887
+ 8741,
1888
+ 8741,
1889
+ 8743,
1890
+ 8748,
1891
+ 8750,
1892
+ 8750,
1893
+ 8756,
1894
+ 8759,
1895
+ 8764,
1896
+ 8765,
1897
+ 8776,
1898
+ 8776,
1899
+ 8780,
1900
+ 8780,
1901
+ 8786,
1902
+ 8786,
1903
+ 8800,
1904
+ 8801,
1905
+ 8804,
1906
+ 8807,
1907
+ 8810,
1908
+ 8811,
1909
+ 8814,
1910
+ 8815,
1911
+ 8834,
1912
+ 8835,
1913
+ 8838,
1914
+ 8839,
1915
+ 8853,
1916
+ 8853,
1917
+ 8857,
1918
+ 8857,
1919
+ 8869,
1920
+ 8869,
1921
+ 8895,
1922
+ 8895,
1923
+ 8978,
1924
+ 8978,
1925
+ 9312,
1926
+ 9449,
1927
+ 9451,
1928
+ 9547,
1929
+ 9552,
1930
+ 9587,
1931
+ 9600,
1932
+ 9615,
1933
+ 9618,
1934
+ 9621,
1935
+ 9632,
1936
+ 9633,
1937
+ 9635,
1938
+ 9641,
1939
+ 9650,
1940
+ 9651,
1941
+ 9654,
1942
+ 9655,
1943
+ 9660,
1944
+ 9661,
1945
+ 9664,
1946
+ 9665,
1947
+ 9670,
1948
+ 9672,
1949
+ 9675,
1950
+ 9675,
1951
+ 9678,
1952
+ 9681,
1953
+ 9698,
1954
+ 9701,
1955
+ 9711,
1956
+ 9711,
1957
+ 9733,
1958
+ 9734,
1959
+ 9737,
1960
+ 9737,
1961
+ 9742,
1962
+ 9743,
1963
+ 9756,
1964
+ 9756,
1965
+ 9758,
1966
+ 9758,
1967
+ 9792,
1968
+ 9792,
1969
+ 9794,
1970
+ 9794,
1971
+ 9824,
1972
+ 9825,
1973
+ 9827,
1974
+ 9829,
1975
+ 9831,
1976
+ 9834,
1977
+ 9836,
1978
+ 9837,
1979
+ 9839,
1980
+ 9839,
1981
+ 9886,
1982
+ 9887,
1983
+ 9919,
1984
+ 9919,
1985
+ 9926,
1986
+ 9933,
1987
+ 9935,
1988
+ 9939,
1989
+ 9941,
1990
+ 9953,
1991
+ 9955,
1992
+ 9955,
1993
+ 9960,
1994
+ 9961,
1995
+ 9963,
1996
+ 9969,
1997
+ 9972,
1998
+ 9972,
1999
+ 9974,
2000
+ 9977,
2001
+ 9979,
2002
+ 9980,
2003
+ 9982,
2004
+ 9983,
2005
+ 10045,
2006
+ 10045,
2007
+ 10102,
2008
+ 10111,
2009
+ 11094,
2010
+ 11097,
2011
+ 12872,
2012
+ 12879,
2013
+ 57344,
2014
+ 63743,
2015
+ 65024,
2016
+ 65039,
2017
+ 65533,
2018
+ 65533,
2019
+ 127232,
2020
+ 127242,
2021
+ 127248,
2022
+ 127277,
2023
+ 127280,
2024
+ 127337,
2025
+ 127344,
2026
+ 127373,
2027
+ 127375,
2028
+ 127376,
2029
+ 127387,
2030
+ 127404,
2031
+ 917760,
2032
+ 917999,
2033
+ 983040,
2034
+ 1048573,
2035
+ 1048576,
2036
+ 1114109
2037
+ ], fullwidthMinimalCodePoint = 12288, fullwidthMaximumCodePoint = 65510, fullwidthRanges = [
2038
+ 12288,
2039
+ 12288,
2040
+ 65281,
2041
+ 65376,
2042
+ 65504,
2043
+ 65510
2044
+ ], halfwidthMinimalCodePoint = 8361, halfwidthMaximumCodePoint = 65518, halfwidthRanges = [
2045
+ 8361,
2046
+ 8361,
2047
+ 65377,
2048
+ 65470,
2049
+ 65474,
2050
+ 65479,
2051
+ 65482,
2052
+ 65487,
2053
+ 65490,
2054
+ 65495,
2055
+ 65498,
2056
+ 65500,
2057
+ 65512,
2058
+ 65518
2059
+ ], narrowMinimalCodePoint = 32, narrowMaximumCodePoint = 10630, narrowRanges = [
2060
+ 32,
2061
+ 126,
2062
+ 162,
2063
+ 163,
2064
+ 165,
2065
+ 166,
2066
+ 172,
2067
+ 172,
2068
+ 175,
2069
+ 175,
2070
+ 10214,
2071
+ 10221,
2072
+ 10629,
2073
+ 10630
2074
+ ], wideMinimalCodePoint = 4352, wideMaximumCodePoint = 262141, wideRanges = [
2075
+ 4352,
2076
+ 4447,
2077
+ 8986,
2078
+ 8987,
2079
+ 9001,
2080
+ 9002,
2081
+ 9193,
2082
+ 9196,
2083
+ 9200,
2084
+ 9200,
2085
+ 9203,
2086
+ 9203,
2087
+ 9725,
2088
+ 9726,
2089
+ 9748,
2090
+ 9749,
2091
+ 9776,
2092
+ 9783,
2093
+ 9800,
2094
+ 9811,
2095
+ 9855,
2096
+ 9855,
2097
+ 9866,
2098
+ 9871,
2099
+ 9875,
2100
+ 9875,
2101
+ 9889,
2102
+ 9889,
2103
+ 9898,
2104
+ 9899,
2105
+ 9917,
2106
+ 9918,
2107
+ 9924,
2108
+ 9925,
2109
+ 9934,
2110
+ 9934,
2111
+ 9940,
2112
+ 9940,
2113
+ 9962,
2114
+ 9962,
2115
+ 9970,
2116
+ 9971,
2117
+ 9973,
2118
+ 9973,
2119
+ 9978,
2120
+ 9978,
2121
+ 9981,
2122
+ 9981,
2123
+ 9989,
2124
+ 9989,
2125
+ 9994,
2126
+ 9995,
2127
+ 10024,
2128
+ 10024,
2129
+ 10060,
2130
+ 10060,
2131
+ 10062,
2132
+ 10062,
2133
+ 10067,
2134
+ 10069,
2135
+ 10071,
2136
+ 10071,
2137
+ 10133,
2138
+ 10135,
2139
+ 10160,
2140
+ 10160,
2141
+ 10175,
2142
+ 10175,
2143
+ 11035,
2144
+ 11036,
2145
+ 11088,
2146
+ 11088,
2147
+ 11093,
2148
+ 11093,
2149
+ 11904,
2150
+ 11929,
2151
+ 11931,
2152
+ 12019,
2153
+ 12032,
2154
+ 12245,
2155
+ 12272,
2156
+ 12287,
2157
+ 12289,
2158
+ 12350,
2159
+ 12353,
2160
+ 12438,
2161
+ 12441,
2162
+ 12543,
2163
+ 12549,
2164
+ 12591,
2165
+ 12593,
2166
+ 12686,
2167
+ 12688,
2168
+ 12773,
2169
+ 12783,
2170
+ 12830,
2171
+ 12832,
2172
+ 12871,
2173
+ 12880,
2174
+ 42124,
2175
+ 42128,
2176
+ 42182,
2177
+ 43360,
2178
+ 43388,
2179
+ 44032,
2180
+ 55203,
2181
+ 63744,
2182
+ 64255,
2183
+ 65040,
2184
+ 65049,
2185
+ 65072,
2186
+ 65106,
2187
+ 65108,
2188
+ 65126,
2189
+ 65128,
2190
+ 65131,
2191
+ 94176,
2192
+ 94180,
2193
+ 94192,
2194
+ 94198,
2195
+ 94208,
2196
+ 101589,
2197
+ 101631,
2198
+ 101662,
2199
+ 101760,
2200
+ 101874,
2201
+ 110576,
2202
+ 110579,
2203
+ 110581,
2204
+ 110587,
2205
+ 110589,
2206
+ 110590,
2207
+ 110592,
2208
+ 110882,
2209
+ 110898,
2210
+ 110898,
2211
+ 110928,
2212
+ 110930,
2213
+ 110933,
2214
+ 110933,
2215
+ 110948,
2216
+ 110951,
2217
+ 110960,
2218
+ 111355,
2219
+ 119552,
2220
+ 119638,
2221
+ 119648,
2222
+ 119670,
2223
+ 126980,
2224
+ 126980,
2225
+ 127183,
2226
+ 127183,
2227
+ 127374,
2228
+ 127374,
2229
+ 127377,
2230
+ 127386,
2231
+ 127488,
2232
+ 127490,
2233
+ 127504,
2234
+ 127547,
2235
+ 127552,
2236
+ 127560,
2237
+ 127568,
2238
+ 127569,
2239
+ 127584,
2240
+ 127589,
2241
+ 127744,
2242
+ 127776,
2243
+ 127789,
2244
+ 127797,
2245
+ 127799,
2246
+ 127868,
2247
+ 127870,
2248
+ 127891,
2249
+ 127904,
2250
+ 127946,
2251
+ 127951,
2252
+ 127955,
2253
+ 127968,
2254
+ 127984,
2255
+ 127988,
2256
+ 127988,
2257
+ 127992,
2258
+ 128062,
2259
+ 128064,
2260
+ 128064,
2261
+ 128066,
2262
+ 128252,
2263
+ 128255,
2264
+ 128317,
2265
+ 128331,
2266
+ 128334,
2267
+ 128336,
2268
+ 128359,
2269
+ 128378,
2270
+ 128378,
2271
+ 128405,
2272
+ 128406,
2273
+ 128420,
2274
+ 128420,
2275
+ 128507,
2276
+ 128591,
2277
+ 128640,
2278
+ 128709,
2279
+ 128716,
2280
+ 128716,
2281
+ 128720,
2282
+ 128722,
2283
+ 128725,
2284
+ 128728,
2285
+ 128732,
2286
+ 128735,
2287
+ 128747,
2288
+ 128748,
2289
+ 128756,
2290
+ 128764,
2291
+ 128992,
2292
+ 129003,
2293
+ 129008,
2294
+ 129008,
2295
+ 129292,
2296
+ 129338,
2297
+ 129340,
2298
+ 129349,
2299
+ 129351,
2300
+ 129535,
2301
+ 129648,
2302
+ 129660,
2303
+ 129664,
2304
+ 129674,
2305
+ 129678,
2306
+ 129734,
2307
+ 129736,
2308
+ 129736,
2309
+ 129741,
2310
+ 129756,
2311
+ 129759,
2312
+ 129770,
2313
+ 129775,
2314
+ 129784,
2315
+ 131072,
2316
+ 196605,
2317
+ 196608,
2318
+ 262141
2319
+ ], isInRange = (ranges, codePoint) => {
2320
+ let low = 0, high = Math.floor(ranges.length / 2) - 1;
2321
+ for (; low <= high; ) {
2322
+ let mid = Math.floor((low + high) / 2), i = mid * 2;
2323
+ if (codePoint < ranges[i])
2324
+ high = mid - 1;
2325
+ else if (codePoint > ranges[i + 1])
2326
+ low = mid + 1;
2327
+ else
2328
+ return !0;
2329
+ }
2330
+ return !1;
2331
+ }, commonCjkCodePoint = 19968, [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
2332
+ function findWideFastPathRange(ranges) {
2333
+ let fastPathStart = ranges[0], fastPathEnd = ranges[1];
2334
+ for (let index = 0; index < ranges.length; index += 2) {
2335
+ let start = ranges[index], end = ranges[index + 1];
2336
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end)
2337
+ return [start, end];
2338
+ end - start > fastPathEnd - fastPathStart && (fastPathStart = start, fastPathEnd = end);
2339
+ }
2340
+ return [fastPathStart, fastPathEnd];
2341
+ }
2342
+ var isAmbiguous = (codePoint) => codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint ? !1 : isInRange(ambiguousRanges, codePoint), isFullWidth = (codePoint) => codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint ? !1 : isInRange(fullwidthRanges, codePoint), isHalfWidth = (codePoint) => codePoint < halfwidthMinimalCodePoint || codePoint > halfwidthMaximumCodePoint ? !1 : isInRange(halfwidthRanges, codePoint), isNarrow = (codePoint) => codePoint < narrowMinimalCodePoint || codePoint > narrowMaximumCodePoint ? !1 : isInRange(narrowRanges, codePoint), isWide = (codePoint) => codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd ? !0 : codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint ? !1 : isInRange(wideRanges, codePoint);
2343
+ function getCategory(codePoint) {
2344
+ return isAmbiguous(codePoint) ? "ambiguous" : isFullWidth(codePoint) ? "fullwidth" : isHalfWidth(codePoint) ? "halfwidth" : isNarrow(codePoint) ? "narrow" : isWide(codePoint) ? "wide" : "neutral";
2345
+ }
2346
+ function validate(codePoint) {
2347
+ if (!Number.isSafeInteger(codePoint))
2348
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
2349
+ }
2350
+ function eastAsianWidthType(codePoint) {
2351
+ return validate(codePoint), getCategory(codePoint);
2352
+ }
2353
+ function isEmoji(uc) {
2354
+ return /^\p{Emoji_Presentation}/u.test(String.fromCodePoint(uc));
2355
+ }
2356
+ function isCjkBase(uc) {
2357
+ if (uc < 4352)
2358
+ return !1;
2359
+ switch (eastAsianWidthType(uc)) {
2360
+ case "fullwidth":
2361
+ case "halfwidth":
2362
+ return !0;
2363
+ case "wide":
2364
+ return !isEmoji(uc);
2365
+ case "narrow":
2366
+ return !1;
2367
+ case "ambiguous":
2368
+ return null;
2369
+ case "neutral":
2370
+ return /^\p{sc=Hangul}/u.test(String.fromCodePoint(uc));
2371
+ }
2372
+ }
2373
+ function is2PreviousCjk(uc, prev) {
2374
+ return isCjkBase(uc) ?? (prev === 65025 && isQuotationMark(uc));
2375
+ function isQuotationMark(uc$1) {
2376
+ return uc$1 === 8216 || uc$1 === 8217 || uc$1 === 8220 || uc$1 === 8221;
2377
+ }
2378
+ }
2379
+ function isPreviousCjk(uc) {
2380
+ return isCjkBase(uc) ?? (917760 <= uc && uc <= 917999);
2381
+ }
2382
+ function isNextCjk(uc) {
2383
+ return isCjkBase(uc) ?? !1;
2384
+ }
2385
+ function nonEmojiGeneralUseVS(uc) {
2386
+ return uc >= 65024 && uc <= 65038;
2387
+ }
2388
+ function markdownItCjkFriendlyPlugin(md) {
2389
+ let PreviousState = md.inline.State;
2390
+ class CjkFriendlyState extends PreviousState {
2391
+ scanDelims(start, canSplitWord) {
2392
+ let max = this.posMax, marker = this.src.charCodeAt(start), [lastChar, lastCharPos] = getLastCharCode(this.src, start), lastMainChar = lastChar, twoPrevChar = null;
2393
+ nonEmojiGeneralUseVS(lastChar) && (twoPrevChar = getLastCharCode(this.src, lastCharPos)[0], /^\p{Zs}/u.test(String.fromCodePoint(twoPrevChar)) || (lastMainChar = twoPrevChar));
2394
+ let pos = start;
2395
+ for (; pos < max && this.src.charCodeAt(pos) === marker; )
2396
+ pos++;
2397
+ let count = pos - start, nextChar = pos < max ? this.src.codePointAt(pos) : 32, isLastWhiteSpace = md.utils.isWhiteSpace(lastMainChar), isNextWhiteSpace = md.utils.isWhiteSpace(nextChar);
2398
+ if (isLastWhiteSpace || isNextWhiteSpace)
2399
+ return {
2400
+ can_open: !isNextWhiteSpace,
2401
+ can_close: !isLastWhiteSpace,
2402
+ length: count
2403
+ };
2404
+ let isLastPunctChar = md.utils.isMdAsciiPunct(lastMainChar) || md.utils.isPunctChar(String.fromCodePoint(lastMainChar)), isNextPunctChar = md.utils.isMdAsciiPunct(nextChar) || md.utils.isPunctChar(String.fromCodePoint(nextChar)), left_flanking = isLastPunctChar, right_flanking = isNextPunctChar;
2405
+ if (canSplitWord) {
2406
+ let isEitherCJKChar = isNextCjk(nextChar) || (twoPrevChar !== null ? is2PreviousCjk(twoPrevChar, lastChar) : isPreviousCjk(lastChar));
2407
+ left_flanking || (left_flanking = isEitherCJKChar || !isNextPunctChar), right_flanking || (right_flanking = isEitherCJKChar || !isLastPunctChar);
2408
+ }
2409
+ return {
2410
+ can_open: left_flanking,
2411
+ can_close: right_flanking,
2412
+ length: count
2413
+ };
2414
+ function getLastCharCode(str, pos$1) {
2415
+ if (pos$1 <= 0)
2416
+ return [32, -1];
2417
+ let charCode = str.charCodeAt(pos$1 - 1);
2418
+ if ((charCode & 64512) !== 56320)
2419
+ return [charCode, pos$1 - 1];
2420
+ let codePoint = str.codePointAt(pos$1 - 2);
2421
+ return codePoint > 65535 ? [codePoint, pos$1 - 2] : [charCode, pos$1 - 1];
2422
+ }
2423
+ }
2424
+ }
2425
+ md.inline.State = CjkFriendlyState;
2426
+ }
2427
+ var decodeMap = /* @__PURE__ */ new Map([
1666
2428
  [0, 65533],
1667
2429
  [128, 8364],
1668
2430
  [130, 8218],
@@ -1984,7 +2746,7 @@ var htmlDecoder = /* @__PURE__ */ getDecoder(htmlDecodeTree);
1984
2746
  function decodeHTML(htmlString, mode = DecodingMode.Legacy) {
1985
2747
  return htmlDecoder(htmlString, mode);
1986
2748
  }
1987
- var import_markdown_it_task_checkbox = /* @__PURE__ */ __toESM2(require_markdown_it_task_checkbox(), 1), decodeCache = {};
2749
+ var decodeCache = {};
1988
2750
  function getDecodeCache(exclude) {
1989
2751
  let cache = decodeCache[exclude];
1990
2752
  if (cache)
@@ -4453,6 +5215,13 @@ var ParserInline = class {
4453
5215
  constructor() {
4454
5216
  __publicField(this, "ruler");
4455
5217
  __publicField(this, "ruler2");
5218
+ /**
5219
+ * State class used for inline parsing, mirroring `ParserInline.prototype.State` in
5220
+ * markdown-it. Plugins subclass it (`scanDelims`, `push`, `pushPending`, ...) and assign
5221
+ * the subclass back to `md.inline.State`; the parser then constructs it with
5222
+ * `new this.State(...)`.
5223
+ */
5224
+ __publicField(this, "State", StateInline);
4456
5225
  __publicField(this, "cachedRulesVersion", -1);
4457
5226
  __publicField(this, "cachedRules", []);
4458
5227
  __publicField(this, "cachedRules2Version", -1);
@@ -4559,13 +5328,20 @@ var ParserInline = class {
4559
5328
  isDefaultRuleset() {
4560
5329
  return this.ruler.version === this.defaultRulerVersion && this.ruler2.version === this.defaultRuler2Version;
4561
5330
  }
5331
+ /**
5332
+ * Whether inline parsing still uses the stock `StateInline`. The plain-text fast paths
5333
+ * construct no state at all, so they must stand down once a plugin replaces `State`.
5334
+ */
5335
+ usesDefaultState() {
5336
+ return this.State === StateInline;
5337
+ }
4562
5338
  parseSource(src, md, env, outTokens) {
4563
- if (typeof src == "string" && src.length > 0 && this.isDefaultRuleset() && isPlainInlineText$1(src)) {
5339
+ if (typeof src == "string" && src.length > 0 && this.isDefaultRuleset() && this.usesDefaultState() && isPlainInlineText$1(src)) {
4564
5340
  let token = new Token("text", "", 0);
4565
5341
  token.content = src, outTokens.push(token);
4566
5342
  return;
4567
5343
  }
4568
- let state = new StateInline(src, md, env, outTokens);
5344
+ let state = new this.State(src, md, env, outTokens);
4569
5345
  this.tokenize(state);
4570
5346
  let rules2 = this.getRules2(), len = rules2.length;
4571
5347
  if (!(state.env && (Object.prototype.hasOwnProperty.call(state.env, "__mdtsRuleProfile") || Object.prototype.hasOwnProperty.call(state.env, "__mdtsProfileRules")))) {
@@ -4592,7 +5368,7 @@ var ParserInline = class {
4592
5368
  }
4593
5369
  };
4594
5370
  function inline(state) {
4595
- let tokens = state.tokens, canUsePlainTextFastPath = !!state.md?.inline?.isDefaultRuleset?.();
5371
+ let tokens = state.tokens, inlineParser = state.md?.inline, canUsePlainTextFastPath = !!inlineParser?.isDefaultRuleset?.() && inlineParser?.usesDefaultState?.() !== !1;
4596
5372
  for (let i = 0, l = tokens.length; i < l; i++) {
4597
5373
  let tok = tokens[i];
4598
5374
  if (tok.type === "inline" && state.md) {
@@ -4606,6 +5382,30 @@ function inline(state) {
4606
5382
  }
4607
5383
  }
4608
5384
  var CJK_CHAR_RE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u, ASCII_DOMAIN_START_RE = /[0-9a-z]/i;
5385
+ function hasLinkifySeed(text$1) {
5386
+ return text$1.includes(".") || text$1.includes("@") || text$1.includes(":");
5387
+ }
5388
+ var linkifySeedSafety = /* @__PURE__ */ new WeakMap();
5389
+ function isLinkifySeedSafe(linkify$2) {
5390
+ let schemaSearch = linkify$2.re?.get_schema_search?.();
5391
+ if (!schemaSearch)
5392
+ return !1;
5393
+ let cached = linkifySeedSafety.get(linkify$2);
5394
+ if (cached && cached.schemaSearch === schemaSearch)
5395
+ return cached.safe;
5396
+ let schemas = linkify$2.__schemas__, safe = !0;
5397
+ if (schemas) {
5398
+ for (let name in schemas)
5399
+ if (name.charCodeAt(name.length - 1) !== 58) {
5400
+ safe = !1;
5401
+ break;
5402
+ }
5403
+ }
5404
+ return linkifySeedSafety.set(linkify$2, {
5405
+ schemaSearch,
5406
+ safe
5407
+ }), safe;
5408
+ }
4609
5409
  function isLinkOpen(str) {
4610
5410
  return /^<a[>\s]/i.test(str);
4611
5411
  }
@@ -4631,55 +5431,57 @@ function trimCjkPrefixFromFuzzyLink(linkify$2, link$1) {
4631
5431
  }
4632
5432
  function linkify(state) {
4633
5433
  let blockTokens = state.tokens;
4634
- if (state.md?.options?.linkify)
4635
- for (let j = 0; j < blockTokens.length; j++) {
4636
- let blockToken$1 = blockTokens[j];
4637
- if (blockToken$1.type !== "inline" || !state.md.linkify.test(blockToken$1.content))
5434
+ if (!state.md?.options?.linkify)
5435
+ return;
5436
+ let seedSafe = isLinkifySeedSafe(state.md.linkify), mayMatch = (text$1) => seedSafe ? hasLinkifySeed(text$1) : !0;
5437
+ for (let j = 0; j < blockTokens.length; j++) {
5438
+ let blockToken$1 = blockTokens[j];
5439
+ if (blockToken$1.type !== "inline" || !mayMatch(blockToken$1.content))
5440
+ continue;
5441
+ let tokens = blockToken$1.children;
5442
+ tokens || (tokens = [], blockToken$1.children = tokens);
5443
+ let htmlLinkLevel = 0;
5444
+ for (let i = tokens.length - 1; i >= 0; i--) {
5445
+ let currentToken = tokens[i];
5446
+ if (currentToken.type === "link_close") {
5447
+ for (i--; i >= 0 && tokens[i].level !== currentToken.level && tokens[i].type !== "link_open"; )
5448
+ i--;
4638
5449
  continue;
4639
- let tokens = blockToken$1.children;
4640
- tokens || (tokens = [], blockToken$1.children = tokens);
4641
- let htmlLinkLevel = 0;
4642
- for (let i = tokens.length - 1; i >= 0; i--) {
4643
- let currentToken = tokens[i];
4644
- if (currentToken.type === "link_close") {
4645
- for (i--; i >= 0 && tokens[i].level !== currentToken.level && tokens[i].type !== "link_open"; )
4646
- i--;
4647
- continue;
4648
- }
4649
- if (currentToken.type === "html_inline" && (isLinkOpen(currentToken.content) && htmlLinkLevel > 0 && htmlLinkLevel--, isLinkClose(currentToken.content) && htmlLinkLevel++), htmlLinkLevel > 0 || currentToken.type !== "text" || !state.md.linkify.test(currentToken.content))
4650
- continue;
4651
- let text$1 = currentToken.content, links = (state.md.linkify.match(text$1) || []).map((link$1) => trimCjkPrefixFromFuzzyLink(state.md.linkify, link$1));
4652
- if (links.length === 0)
5450
+ }
5451
+ if (currentToken.type === "html_inline" && (isLinkOpen(currentToken.content) && htmlLinkLevel > 0 && htmlLinkLevel--, isLinkClose(currentToken.content) && htmlLinkLevel++), htmlLinkLevel > 0 || currentToken.type !== "text" || !mayMatch(currentToken.content))
5452
+ continue;
5453
+ let text$1 = currentToken.content, links = (state.md.linkify.match(text$1) || []).map((link$1) => trimCjkPrefixFromFuzzyLink(state.md.linkify, link$1));
5454
+ if (links.length === 0)
5455
+ continue;
5456
+ let nodes = [], level = currentToken.level, lastPos = 0;
5457
+ links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === "text_special" && (links = links.slice(1));
5458
+ for (let ln = 0; ln < links.length; ln++) {
5459
+ let link$1 = links[ln], fullUrl = state.md.normalizeLink(link$1.url);
5460
+ if (!state.md.validateLink(fullUrl))
4653
5461
  continue;
4654
- let nodes = [], level = currentToken.level, lastPos = 0;
4655
- links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === "text_special" && (links = links.slice(1));
4656
- for (let ln = 0; ln < links.length; ln++) {
4657
- let link$1 = links[ln], fullUrl = state.md.normalizeLink(link$1.url);
4658
- if (!state.md.validateLink(fullUrl))
4659
- continue;
4660
- let urlText = link$1.text;
4661
- link$1.schema ? link$1.schema === "mailto:" && !/^mailto:/i.test(urlText) ? urlText = state.md.normalizeLinkText(`mailto:${urlText}`).replace(/^mailto:/, "") : urlText = state.md.normalizeLinkText(urlText) : urlText = state.md.normalizeLinkText(`http://${urlText}`).replace(/^http:\/\//, "");
4662
- let pos = link$1.index;
4663
- if (pos > lastPos) {
4664
- let textToken$1 = new Token("text", "", 0);
4665
- textToken$1.content = text$1.slice(lastPos, pos), textToken$1.level = level, nodes.push(textToken$1);
4666
- }
4667
- let tokenOpen = new Token("link_open", "a", 1);
4668
- tokenOpen.attrs = [["href", fullUrl]], tokenOpen.level = level++, tokenOpen.markup = "linkify", tokenOpen.info = "auto", nodes.push(tokenOpen);
4669
- let tokenText = new Token("text", "", 0);
4670
- tokenText.content = urlText, tokenText.level = level, nodes.push(tokenText);
4671
- let tokenClose = new Token("link_close", "a", -1);
4672
- tokenClose.level = --level, tokenClose.markup = "linkify", tokenClose.info = "auto", nodes.push(tokenClose), lastPos = link$1.lastIndex;
5462
+ let urlText = link$1.text;
5463
+ link$1.schema ? link$1.schema === "mailto:" && !/^mailto:/i.test(urlText) ? urlText = state.md.normalizeLinkText(`mailto:${urlText}`).replace(/^mailto:/, "") : urlText = state.md.normalizeLinkText(urlText) : urlText = state.md.normalizeLinkText(`http://${urlText}`).replace(/^http:\/\//, "");
5464
+ let pos = link$1.index;
5465
+ if (pos > lastPos) {
5466
+ let textToken$1 = new Token("text", "", 0);
5467
+ textToken$1.content = text$1.slice(lastPos, pos), textToken$1.level = level, nodes.push(textToken$1);
4673
5468
  }
4674
- if (lastPos !== 0) {
4675
- if (lastPos < text$1.length) {
4676
- let textToken$1 = new Token("text", "", 0);
4677
- textToken$1.content = text$1.slice(lastPos), textToken$1.level = level, nodes.push(textToken$1);
4678
- }
4679
- tokens.splice(i, 1, ...nodes);
5469
+ let tokenOpen = new Token("link_open", "a", 1);
5470
+ tokenOpen.attrs = [["href", fullUrl]], tokenOpen.level = level++, tokenOpen.markup = "linkify", tokenOpen.info = "auto", nodes.push(tokenOpen);
5471
+ let tokenText = new Token("text", "", 0);
5472
+ tokenText.content = urlText, tokenText.level = level, nodes.push(tokenText);
5473
+ let tokenClose = new Token("link_close", "a", -1);
5474
+ tokenClose.level = --level, tokenClose.markup = "linkify", tokenClose.info = "auto", nodes.push(tokenClose), lastPos = link$1.lastIndex;
5475
+ }
5476
+ if (lastPos !== 0) {
5477
+ if (lastPos < text$1.length) {
5478
+ let textToken$1 = new Token("text", "", 0);
5479
+ textToken$1.content = text$1.slice(lastPos), textToken$1.level = level, nodes.push(textToken$1);
4680
5480
  }
5481
+ tokens.splice(i, 1, ...nodes);
4681
5482
  }
4682
5483
  }
5484
+ }
4683
5485
  }
4684
5486
  var NEWLINES_RE = /\r\n?|\n/g, NULL_RE = /\0/g;
4685
5487
  function normalize(state) {
@@ -4855,7 +5657,7 @@ function process_inlines(tokens, state) {
4855
5657
  nextChar = tokens[j].content.charCodeAt(0);
4856
5658
  break;
4857
5659
  }
4858
- let isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)), isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)), isLastWhiteSpace = isWhiteSpace(lastChar), isNextWhiteSpace = isWhiteSpace(nextChar);
5660
+ let isLastPunctChar = isPunctCode(lastChar), isNextPunctChar = isPunctCode(nextChar), isLastWhiteSpace = isWhiteSpace(lastChar), isNextWhiteSpace = isWhiteSpace(nextChar);
4859
5661
  if (isNextWhiteSpace ? canOpen = !1 : isNextPunctChar && (isLastWhiteSpace || isLastPunctChar || (canOpen = !1)), isLastWhiteSpace ? canClose = !1 : isLastPunctChar && (isNextWhiteSpace || isNextPunctChar || (canClose = !1)), nextChar === 34 && t[0] === '"' && lastChar >= 48 && lastChar <= 57 && (canClose = canOpen = !1), canOpen && canClose && (canOpen = isLastPunctChar, canClose = isNextPunctChar), !canOpen && !canClose) {
4860
5662
  isSingle && (token.content = replaceAt(token.content, t.index, APOSTROPHE));
4861
5663
  continue;
@@ -4910,28 +5712,30 @@ var BAD_PROTO_RE = /^(?:vbscript|javascript|file|data):/, GOOD_DATA_RE = /^data:
4910
5712
  "http:",
4911
5713
  "https:",
4912
5714
  "mailto:"
4913
- ];
5715
+ ], NON_ASCII_RE = /[^\0-\x7F]/, PUNYCODE_LABEL_RE = /xn--/, ENCODE_IDENTITY_RE = /%(?![0-9a-f]{2})|[^\w;/?:@&=+$,\-.!~*'()#%]/i, DECODE_SCAN_RE = /%[0-9a-f]{2}/i;
4914
5716
  function validateLink(url) {
4915
5717
  let str = url.trim().toLowerCase();
4916
5718
  return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : !0;
4917
5719
  }
4918
5720
  function normalizeLink(url) {
4919
5721
  let parsed = parse_default(url, !0);
4920
- if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)))
5722
+ if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)) && NON_ASCII_RE.test(parsed.hostname))
4921
5723
  try {
4922
5724
  parsed.hostname = import_punycode.default.toASCII(parsed.hostname);
4923
5725
  } catch {
4924
5726
  }
4925
- return encode_default(format(parsed));
5727
+ let formatted = format(parsed);
5728
+ return ENCODE_IDENTITY_RE.test(formatted) ? encode_default(formatted) : formatted;
4926
5729
  }
4927
5730
  function normalizeLinkText(url) {
4928
5731
  let parsed = parse_default(url, !0);
4929
- if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)))
5732
+ if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)) && (NON_ASCII_RE.test(parsed.hostname) || PUNYCODE_LABEL_RE.test(parsed.hostname)))
4930
5733
  try {
4931
5734
  parsed.hostname = import_punycode.default.toUnicode(parsed.hostname);
4932
5735
  } catch {
4933
5736
  }
4934
- return decode_default(format(parsed), `${decode_default.defaultChars}%`);
5737
+ let formatted = format(parsed);
5738
+ return DECODE_SCAN_RE.test(formatted) ? decode_default(formatted, `${decode_default.defaultChars}%`) : formatted;
4935
5739
  }
4936
5740
  function isSpace$7(code$1) {
4937
5741
  switch (code$1) {
@@ -8330,6 +9134,37 @@ var Renderer = class {
8330
9134
  return output;
8331
9135
  }
8332
9136
  }, renderer_default = Renderer, EMPTY_TOKENS = [], GLOBAL_STATE_APPEND_SCAN_WINDOW = 4096;
9137
+ function copyOptions(options) {
9138
+ let copy = { ...options };
9139
+ return Array.isArray(options.quotes) && (copy.quotes = [...options.quotes]), options.experimental && (copy.experimental = { ...options.experimental }), copy;
9140
+ }
9141
+ function optionsEqual(left, right) {
9142
+ let keys = Object.keys(right);
9143
+ return Object.keys(left).length !== keys.length ? !1 : keys.every((key) => {
9144
+ if (!Object.hasOwn(left, key))
9145
+ return !1;
9146
+ let leftValue = left[key], rightValue = right[key];
9147
+ if (Array.isArray(leftValue) && Array.isArray(rightValue))
9148
+ return leftValue.length === rightValue.length && leftValue.every((value, index) => Object.is(value, rightValue[index]));
9149
+ if (key === "experimental" && leftValue && rightValue) {
9150
+ let leftExperimental = leftValue, rightExperimental = rightValue, experimentalKeys = Object.keys(rightExperimental);
9151
+ return Object.keys(leftExperimental).length === experimentalKeys.length && experimentalKeys.every((option) => Object.hasOwn(leftExperimental, option) && Object.is(leftExperimental[option], rightExperimental[option]));
9152
+ }
9153
+ return Object.is(leftValue, rightValue);
9154
+ });
9155
+ }
9156
+ function copyParserConfig(md) {
9157
+ return {
9158
+ options: copyOptions(md.options),
9159
+ coreVersion: md.core.ruler.version,
9160
+ blockVersion: md.block.ruler.version,
9161
+ inlineVersion: md.inline.ruler.version,
9162
+ inline2Version: md.inline.ruler2.version
9163
+ };
9164
+ }
9165
+ function parserConfigEqual(config$1, md) {
9166
+ return optionsEqual(config$1.options, md.options) && config$1.coreVersion === md.core.ruler.version && config$1.blockVersion === md.block.ruler.version && config$1.inlineVersion === md.inline.ruler.version && config$1.inline2Version === md.inline.ruler2.version;
9167
+ }
8333
9168
  function appendedHasBlockConstructs(s) {
8334
9169
  let len = s.length, lineStart = 0;
8335
9170
  for (; lineStart <= len; ) {
@@ -8472,9 +9307,9 @@ var StreamParser = class {
8472
9307
  __publicField(this, "core");
8473
9308
  __publicField(this, "anchorBlock", new ParserBlock());
8474
9309
  __publicField(this, "cache", null);
9310
+ __publicField(this, "snapshots", /* @__PURE__ */ new WeakSet());
8475
9311
  __publicField(this, "stats", makeEmptyStats());
8476
9312
  __publicField(this, "normalizeLineEndings", !0);
8477
- __publicField(this, "coreRulerVersion", -1);
8478
9313
  __publicField(this, "tokenMapsTrusted", !0);
8479
9314
  __publicField(this, "allowUntrustedTailReuse", !1);
8480
9315
  __publicField(this, "MIN_SIZE_FOR_OPTIMIZATION", 1e3);
@@ -8497,19 +9332,46 @@ var StreamParser = class {
8497
9332
  let { resets } = this.stats;
8498
9333
  this.stats = makeEmptyStats(), this.stats.resets = resets;
8499
9334
  }
8500
- parse(src, env, md) {
8501
- let priorEnv = this.cache?.env;
8502
- this.coreRulerVersion >= 0 && this.coreRulerVersion !== md.core.ruler.version && (this.cache = null), this.coreRulerVersion = md.core.ruler.version;
8503
- let coreRules = md.core.ruler.getNamedRules(""), lineNormalizerIndex = coreRules.findIndex((rule) => rule.fn === normalize), blockRuleIndex = coreRules.findIndex((rule) => rule.fn === block), namedNormalizeRule = coreRules.find((rule) => rule.name === "normalize");
9335
+ snapshot() {
9336
+ let cache = this.cache;
9337
+ if (!cache)
9338
+ return null;
9339
+ let state = cache.snapshotState ?? { cache };
9340
+ cache.snapshotState = state;
9341
+ let snapshot = {
9342
+ state,
9343
+ get sourceLength() {
9344
+ return this.state.cache.src.length;
9345
+ },
9346
+ get tokenCount() {
9347
+ return this.state.cache.tokens.length;
9348
+ }
9349
+ };
9350
+ return this.snapshots.add(snapshot), snapshot;
9351
+ }
9352
+ restore(snapshot, md) {
9353
+ if (!this.snapshots.has(snapshot))
9354
+ throw new TypeError("Invalid stream snapshot");
9355
+ let cache = snapshot.state.cache;
9356
+ return this.cache = cache, parserConfigEqual(cache.config, md) ? cache.tokens : this.parse(cache.src, cache.env, md);
9357
+ }
9358
+ append(segment, env, md) {
9359
+ let cached = this.cache;
9360
+ if (!cached)
9361
+ throw new Error("Stream append requires cached history; call stream.parse(fullSource) first");
9362
+ return this.ensureBoundaryState(cached), this.parse(cached.src + segment, env, md, segment);
9363
+ }
9364
+ parse(src, env, md, knownAppend) {
9365
+ let previousCache = this.cache, priorEnv = previousCache?.env, coreRules = md.core.ruler.getNamedRules(""), lineNormalizerIndex = coreRules.findIndex((rule) => rule.fn === normalize), blockRuleIndex = coreRules.findIndex((rule) => rule.fn === block), namedNormalizeRule = coreRules.find((rule) => rule.name === "normalize");
8504
9366
  this.normalizeLineEndings = lineNormalizerIndex >= 0 && blockRuleIndex >= 0 && lineNormalizerIndex < blockRuleIndex;
8505
- let envProvided = env, previousCache = this.cache, customNormalize = namedNormalizeRule && namedNormalizeRule.fn !== normalize, nonstandardBuiltinNormalize = namedNormalizeRule && !this.normalizeLineEndings && src.includes("\r"), unknownPreBlockRule = blockRuleIndex < 0 || coreRules.slice(0, blockRuleIndex).some((rule) => rule.fn !== normalize);
9367
+ let envProvided = env, configChanged = !!previousCache && !parserConfigEqual(previousCache.config, md), customNormalize = namedNormalizeRule && namedNormalizeRule.fn !== normalize, nonstandardBuiltinNormalize = namedNormalizeRule && !this.normalizeLineEndings && src.includes("\r"), unknownPreBlockRule = blockRuleIndex < 0 || coreRules.slice(0, blockRuleIndex).some((rule) => rule.fn !== normalize);
8506
9368
  this.tokenMapsTrusted = !(blockRuleIndex < 0 || coreRules.slice(blockRuleIndex + 1).some((rule) => rule.fn !== inline && rule.fn !== linkify && rule.fn !== replacements && rule.fn !== smartquotes && rule.fn !== text_join)), this.allowUntrustedTailReuse = this.tokenMapsTrusted || md.options?.streamTailLocalPostBlockRules === !0;
8507
- let cached = customNormalize || nonstandardBuiltinNormalize || unknownPreBlockRule ? null : previousCache;
9369
+ let cached = configChanged || customNormalize || nonstandardBuiltinNormalize || unknownPreBlockRule ? null : previousCache;
8508
9370
  if (beginParseDiagnostics(envProvided ?? previousCache?.env ?? priorEnv), !cached || envProvided && envProvided !== cached.env) {
8509
9371
  let workingEnv = envProvided ?? previousCache?.env ?? priorEnv ?? {}, explicitChunkFallbackSetting$1 = !!md.__explicitStreamChunkFallbackSetting, canImplicitLargeInput$1 = typeof md.__canUseImplicitLargeInputStrategy == "function" ? md.__canUseImplicitLargeInputStrategy() : !0, wantsChunking$1 = !!md.options?.streamChunkedFallback, allowImplicitChunk$1 = !explicitChunkFallbackSetting$1 && canImplicitLargeInput$1, chunkedEnabled$1 = wantsChunking$1 || allowImplicitChunk$1, chunkAdaptive$1 = md.options?.streamChunkAdaptive !== !1, targetChunks$1 = md.options?.streamChunkTargetChunks ?? 8, chunkSizeCharsCfg$1 = md.options?.streamChunkSizeChars, chunkSizeLinesCfg$1 = md.options?.streamChunkSizeLines, chunkMaxChunksCfg$1 = md.options?.streamChunkMaxChunks, explicitChunkConfig$1 = !!md.__explicitStreamChunkConfig, auto$1 = md.options?.autoTuneChunks !== !1, chunkFenceAware$1 = md.options?.streamChunkFenceAware ?? !0, largeCachePolicy = md.options?.streamLargeCachePolicy ?? "retain", skipCacheChars = md.options?.streamSkipCacheAboveChars ?? this.DEFAULT_SKIP_CACHE_CHARS, skipCacheLines = md.options?.streamSkipCacheAboveLines ?? this.DEFAULT_SKIP_CACHE_LINES, srcLineCount, shouldSkipLargeCache = !1;
8510
- if (largeCachePolicy === "skip" && (shouldSkipLargeCache = src.length >= skipCacheChars, !shouldSkipLargeCache && skipCacheLines !== void 0 && (srcLineCount = countLines(src), shouldSkipLargeCache = srcLineCount >= skipCacheLines)), shouldSkipLargeCache) {
9372
+ if (largeCachePolicy === "skip" && (shouldSkipLargeCache = src.length >= skipCacheChars, !shouldSkipLargeCache && skipCacheLines !== void 0 && (srcLineCount = countLines(src), shouldSkipLargeCache = srcLineCount >= skipCacheLines)), shouldSkipLargeCache && knownAppend === void 0 && !previousCache?.snapshotState) {
8511
9373
  let parsed$2 = this.parseFullDocument(src, workingEnv, md, srcLineCount, !1);
8512
- return this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
9374
+ return this.cache = null, this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
8513
9375
  area: "stream",
8514
9376
  path: "stream-full",
8515
9377
  reason: "skip-cache-large-one-shot",
@@ -8525,26 +9387,28 @@ var StreamParser = class {
8525
9387
  maxChunkLines: useLines,
8526
9388
  fenceAware: recommendation?.fenceAware ?? chunkFenceAware$1,
8527
9389
  maxChunks: useMaxChunks
8528
- });
8529
- return this.cache = {
9390
+ }), globalStateReason = getParseDiagnostics(workingEnv)?.chunk?.globalStateDetected ?? null, cache$2 = this.setCache({
8530
9391
  src,
8531
9392
  tokens,
8532
9393
  env: workingEnv,
8533
9394
  lineCount: srcLineCount,
8534
9395
  lastSegment: void 0,
8535
- globalStateReason: detectGlobalMarkdownState(src)
8536
- }, this.updateCacheLineCount(this.cache, srcLineCount), this.recordChunkedParseResult(workingEnv, wantsChunking$1 ? "explicit-initial-large-doc" : "default-initial-large-doc"), tokens;
9396
+ globalStateReason
9397
+ }, md);
9398
+ return this.updateCacheLineCount(cache$2, srcLineCount), this.recordChunkedParseResult(workingEnv, wantsChunking$1 ? "explicit-initial-large-doc" : "default-initial-large-doc"), tokens;
8537
9399
  }
8538
9400
  }
8539
9401
  let parsed$1 = this.parseFullDocument(src, workingEnv, md, srcLineCount);
8540
- return srcLineCount = parsed$1.lineCount, this.cache = {
9402
+ srcLineCount = parsed$1.lineCount;
9403
+ let cache$1 = this.setCache({
8541
9404
  src,
8542
9405
  tokens: parsed$1.tokens,
8543
9406
  env: workingEnv,
8544
9407
  lineCount: srcLineCount,
8545
9408
  lastSegment: void 0,
8546
- globalStateReason: detectGlobalMarkdownState(src)
8547
- }, this.updateCacheLineCount(this.cache, srcLineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
9409
+ globalStateReason: parsed$1.globalStateReason
9410
+ }, md);
9411
+ return this.updateCacheLineCount(cache$1, srcLineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
8548
9412
  area: "stream",
8549
9413
  path: "stream-full",
8550
9414
  reason: "initial-parse",
@@ -8557,21 +9421,21 @@ var StreamParser = class {
8557
9421
  path: "stream-cache",
8558
9422
  reason: "same-source"
8559
9423
  }), cached.tokens;
8560
- let appendDelta = src.startsWith(cached.src) ? src.slice(cached.src.length) : null, cachedGlobalStateReason = cached.globalStateReason;
9424
+ let appendDelta = knownAppend !== void 0 ? knownAppend : src.startsWith(cached.src) ? src.slice(cached.src.length) : null, cachedGlobalStateReason = cached.globalStateReason;
8561
9425
  cachedGlobalStateReason === void 0 && (cachedGlobalStateReason = detectGlobalMarkdownState(cached.src), cached.globalStateReason = cachedGlobalStateReason);
8562
9426
  let currentGlobalStateReason = cachedGlobalStateReason ? null : appendDelta !== null ? this.detectGlobalStateForAppend(cached, appendDelta) : detectGlobalMarkdownState(src), nextGlobalStateReason = cachedGlobalStateReason || currentGlobalStateReason;
8563
9427
  if (nextGlobalStateReason) {
8564
9428
  let fallbackEnv$1 = envProvided ?? cached.env;
8565
9429
  resetKnownGlobalMarkdownState(fallbackEnv$1);
8566
- let fallbackGlobalStateReason = detectGlobalMarkdownState(src), parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount;
8567
- return this.cache = {
9430
+ let parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount, cache$1 = this.setCache({
8568
9431
  src,
8569
9432
  tokens: nextTokens$1,
8570
9433
  env: fallbackEnv$1,
8571
9434
  lineCount,
8572
9435
  lastSegment: void 0,
8573
- globalStateReason: fallbackGlobalStateReason
8574
- }, this.updateCacheLineCount(this.cache, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
9436
+ globalStateReason: parsed$1.globalStateReason
9437
+ }, md);
9438
+ return this.updateCacheLineCount(cache$1, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
8575
9439
  area: "stream",
8576
9440
  path: "stream-full",
8577
9441
  reason: `global-state:${nextGlobalStateReason}`,
@@ -8579,23 +9443,23 @@ var StreamParser = class {
8579
9443
  }), nextTokens$1;
8580
9444
  }
8581
9445
  let threshold = md.options?.streamOptimizationMinSize ?? this.MIN_SIZE_FOR_OPTIMIZATION;
8582
- if (cached.src.length < threshold && src.length < threshold * 1.5 && !src.startsWith(cached.src)) {
8583
- let fallbackEnv$1 = envProvided ?? cached.env, parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount;
8584
- return this.cache = {
9446
+ if (cached.src.length < threshold && src.length < threshold * 1.5 && appendDelta === null) {
9447
+ let fallbackEnv$1 = envProvided ?? cached.env, parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount, cache$1 = this.setCache({
8585
9448
  src,
8586
9449
  tokens: nextTokens$1,
8587
9450
  env: fallbackEnv$1,
8588
9451
  lineCount,
8589
9452
  lastSegment: void 0,
8590
- globalStateReason: detectGlobalMarkdownState(src)
8591
- }, this.updateCacheLineCount(this.cache, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
9453
+ globalStateReason: parsed$1.globalStateReason
9454
+ }, md);
9455
+ return this.updateCacheLineCount(cache$1, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
8592
9456
  area: "stream",
8593
9457
  path: "stream-full",
8594
9458
  reason: "small-non-append",
8595
9459
  unbounded: !!getParseDiagnostics(fallbackEnv$1)?.unbounded
8596
9460
  }), nextTokens$1;
8597
9461
  }
8598
- let cachedLastSegment = this.ensureLastSegment(cached), verifiedUntrustedTail = this.tokenMapsTrusted || this.allowUntrustedTailReuse && (cached.lastSegmentVerified === !0 || !!(cachedLastSegment && this.hasVerifiedSegmentAnchor(cached, cachedLastSegment, md))), appended = appendDelta !== null && this.shouldPreferTailReparseForAppend(cached, verifiedUntrustedTail) || !this.tokenMapsTrusted ? null : this.getAppendedSegment(cached, src, appendDelta);
9462
+ let cachedLastSegment = this.ensureLastSegment(cached, knownAppend !== void 0), verifiedUntrustedTail = this.tokenMapsTrusted || this.allowUntrustedTailReuse && (cached.lastSegmentVerified === !0 || !!(cachedLastSegment && this.hasVerifiedSegmentAnchor(cached, cachedLastSegment, md))), appended = appendDelta !== null && this.shouldPreferTailReparseForAppend(cached, verifiedUntrustedTail) || !this.tokenMapsTrusted ? null : this.getAppendedSegment(cached, src, appendDelta);
8599
9463
  if (appended) {
8600
9464
  let cachedLineCount = cached.lineCount ?? countLines(cached.src), ctxLines = 3;
8601
9465
  appended.length > 5e3 ? ctxLines = 8 : appended.length > 1e3 ? ctxLines = 6 : appended.length > 200 && (ctxLines = 4), ctxLines = Math.min(ctxLines, cachedLineCount);
@@ -8670,11 +9534,16 @@ var StreamParser = class {
8670
9534
  }
8671
9535
  dup > 0 && (appendedTokenStart += dup), a.length > appendedTokenStart && this.appendTokens(cached.tokens, a, appendedTokenStart);
8672
9536
  }
8673
- if (this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.globalStateReason = null, cached.lineCount = cachedLineCount + (appendedLineCount ?? countAppendedLines()), cached.tokens.length > appendStart) {
9537
+ if (cached.boundary ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.globalStateReason = null, cached.lineCount = cachedLineCount + (appendedLineCount ?? countAppendedLines()), cached.tokens.length > appendStart) {
8674
9538
  let appendedLastSegment = this.getLastSegment(cached.tokens, src, appendStart, cached.tokens.length, src.length - appended.length, cachedLineCount);
8675
- appendedLastSegment ? cached.lastSegment = appendedLastSegment : cached.lastSegment = void 0;
9539
+ if (appendedLastSegment) {
9540
+ cached.lastSegment = appendedLastSegment;
9541
+ let appendedOffset = src.length - appended.length;
9542
+ cached.lastSegmentSource = appended.slice(Math.max(0, appendedLastSegment.srcOffset - appendedOffset));
9543
+ } else
9544
+ cached.lastSegment = void 0, cached.lastSegmentSource = void 0;
8676
9545
  } else
8677
- cached.lastSegment = void 0;
9546
+ cached.lastSegment = void 0, cached.lastSegmentSource = void 0;
8678
9547
  return cached.lastSegmentVerified = void 0, this.stats.total += 1, this.stats.appendHits += 1, useUnboundedAppend && (this.stats.unboundedAppendHits = (this.stats.unboundedAppendHits || 0) + 1), this.stats.lastMode = "append", setStrategyDiagnostics(cached.env, {
8679
9548
  area: "stream",
8680
9549
  path: useUnboundedAppend ? "stream-unbounded-append" : "stream-append",
@@ -8682,7 +9551,7 @@ var StreamParser = class {
8682
9551
  unbounded: useUnboundedAppend
8683
9552
  }), cached.tokens;
8684
9553
  }
8685
- let fallbackEnv = envProvided ?? cached.env, tailReparsed = verifiedUntrustedTail ? this.tryTailSegmentReparse(src, cached, fallbackEnv, md, cachedLastSegment ?? void 0) : this.allowUntrustedTailReuse ? this.tryUntrustedParagraphTailReparse(src, cached, fallbackEnv, md) : null;
9554
+ let fallbackEnv = envProvided ?? cached.env, tailReparsed = verifiedUntrustedTail ? this.tryTailSegmentReparse(src, cached, fallbackEnv, md, cachedLastSegment ?? void 0, appendDelta ?? void 0) : this.allowUntrustedTailReuse ? this.tryUntrustedParagraphTailReparse(src, cached, fallbackEnv, md) : null;
8686
9555
  if (tailReparsed)
8687
9556
  return this.stats.total += 1, this.stats.tailHits += 1, this.stats.lastMode = "tail", setStrategyDiagnostics(fallbackEnv, {
8688
9557
  area: "stream",
@@ -8699,26 +9568,28 @@ var StreamParser = class {
8699
9568
  maxChunkLines: useLines,
8700
9569
  fenceAware: recommendation?.fenceAware ?? chunkFenceAware,
8701
9570
  maxChunks: useMaxChunks
8702
- });
8703
- return this.cache = {
9571
+ }), globalStateReason = getParseDiagnostics(fallbackEnv)?.chunk?.globalStateDetected ?? null, cache$1 = this.setCache({
8704
9572
  src,
8705
9573
  tokens,
8706
9574
  env: fallbackEnv,
8707
9575
  lineCount: srcLineCount2,
8708
9576
  lastSegment: void 0,
8709
- globalStateReason: detectGlobalMarkdownState(src)
8710
- }, this.updateCacheLineCount(this.cache, srcLineCount2), this.recordChunkedParseResult(fallbackEnv, wantsChunking ? "explicit-fallback-large-doc" : "default-fallback-large-doc"), tokens;
9577
+ globalStateReason
9578
+ }, md);
9579
+ return this.updateCacheLineCount(cache$1, srcLineCount2), this.recordChunkedParseResult(fallbackEnv, wantsChunking ? "explicit-fallback-large-doc" : "default-fallback-large-doc"), tokens;
8711
9580
  }
8712
9581
  }
8713
9582
  let parsed = this.parseFullDocument(src, fallbackEnv, md, srcLineCount2), nextTokens = parsed.tokens;
8714
- return srcLineCount2 = parsed.lineCount, this.cache = {
9583
+ srcLineCount2 = parsed.lineCount;
9584
+ let cache = this.setCache({
8715
9585
  src,
8716
9586
  tokens: nextTokens,
8717
9587
  env: fallbackEnv,
8718
9588
  lineCount: srcLineCount2,
8719
9589
  lastSegment: void 0,
8720
- globalStateReason: detectGlobalMarkdownState(src)
8721
- }, this.updateCacheLineCount(this.cache, srcLineCount2), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv, {
9590
+ globalStateReason: parsed.globalStateReason
9591
+ }, md);
9592
+ return this.updateCacheLineCount(cache, srcLineCount2), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv, {
8722
9593
  area: "stream",
8723
9594
  path: "stream-full",
8724
9595
  reason: "fallback-full",
@@ -8744,11 +9615,10 @@ var StreamParser = class {
8744
9615
  });
8745
9616
  }
8746
9617
  parseFullDocument(src, env, md, knownLineCount, needLineCount = !0) {
8747
- let currentGlobalStateReason = detectGlobalMarkdownState(src);
8748
9618
  getKnownGlobalMarkdownState(env) && resetKnownGlobalMarkdownState(env);
8749
9619
  let autoUnboundedDecision = typeof md.__canUseImplicitLargeInputStrategy != "function" || md.__canUseImplicitLargeInputStrategy() ? getAutoUnboundedDecision(md, src.length, knownLineCount) : "no";
8750
9620
  if (autoUnboundedDecision === "yes") {
8751
- let tokens = parseStringUnbounded(md, src, env);
9621
+ let tokens = parseStringUnbounded(md, src, env), globalStateReason = getParseDiagnostics(env)?.unbounded?.globalStateDetected ?? null;
8752
9622
  return setStrategyDiagnostics(env, {
8753
9623
  area: "stream",
8754
9624
  path: "stream-full",
@@ -8756,12 +9626,13 @@ var StreamParser = class {
8756
9626
  unbounded: !0
8757
9627
  }), {
8758
9628
  tokens,
8759
- lineCount: knownLineCount ?? (needLineCount ? countLines(src) : 0)
9629
+ lineCount: knownLineCount ?? (needLineCount ? countLines(src) : 0),
9630
+ globalStateReason
8760
9631
  };
8761
9632
  }
8762
9633
  let lineCount = knownLineCount;
8763
9634
  if (autoUnboundedDecision === "need-lines" && (lineCount = countLines(src), shouldAutoUseUnbounded(md, src.length, lineCount))) {
8764
- let tokens = parseStringUnbounded(md, src, env);
9635
+ let tokens = parseStringUnbounded(md, src, env), globalStateReason = getParseDiagnostics(env)?.unbounded?.globalStateDetected ?? null;
8765
9636
  return setStrategyDiagnostics(env, {
8766
9637
  area: "stream",
8767
9638
  path: "stream-full",
@@ -8769,12 +9640,16 @@ var StreamParser = class {
8769
9640
  unbounded: !0
8770
9641
  }), {
8771
9642
  tokens,
8772
- lineCount
9643
+ lineCount,
9644
+ globalStateReason
8773
9645
  };
8774
9646
  }
8775
- return lineCount === void 0 && (lineCount = needLineCount ? countLines(src) : 0), {
9647
+ lineCount === void 0 && (lineCount = needLineCount ? countLines(src) : 0);
9648
+ let currentGlobalStateReason = detectGlobalMarkdownState(src);
9649
+ return {
8776
9650
  tokens: runWithKnownGlobalMarkdownState(env, currentGlobalStateReason, () => this.core.parse(src, env, md).tokens),
8777
- lineCount
9651
+ lineCount,
9652
+ globalStateReason: currentGlobalStateReason
8778
9653
  };
8779
9654
  }
8780
9655
  shouldUseUnboundedAppend(src, _cached, appended) {
@@ -8782,8 +9657,8 @@ var StreamParser = class {
8782
9657
  }
8783
9658
  getAppendedSegment(cache, next, knownAppend) {
8784
9659
  let prev = cache.src;
8785
- if (knownAppend === null || knownAppend === void 0 && !next.startsWith(prev) || !prev.endsWith(`
8786
- `))
9660
+ if (knownAppend === null || knownAppend === void 0 && !next.startsWith(prev) || (knownAppend !== void 0 ? !this.ensureBoundaryState(cache).endsWithNewline : !prev.endsWith(`
9661
+ `)))
8787
9662
  return null;
8788
9663
  let segment = knownAppend ?? next.slice(prev.length);
8789
9664
  if (!segment)
@@ -8800,47 +9675,69 @@ var StreamParser = class {
8800
9675
  if (trimmedFirstLine.length === 0)
8801
9676
  return null;
8802
9677
  if (/^[-=]+$/.test(trimmedFirstLine)) {
8803
- let prevWithoutTrailingNewline = prev.slice(0, -1), lastBreak = prevWithoutTrailingNewline.lastIndexOf(`
9678
+ let previousLineNonBlank;
9679
+ if (knownAppend !== void 0)
9680
+ previousLineNonBlank = this.ensureBoundaryState(cache).previousLineNonBlank;
9681
+ else {
9682
+ let prevWithoutTrailingNewline = prev.slice(0, -1), lastBreak = prevWithoutTrailingNewline.lastIndexOf(`
8804
9683
  `);
8805
- if (prevWithoutTrailingNewline.slice(lastBreak + 1).trim().length > 0)
9684
+ previousLineNonBlank = prevWithoutTrailingNewline.slice(lastBreak + 1).trim().length > 0;
9685
+ }
9686
+ if (previousLineNonBlank)
9687
+ return null;
9688
+ }
9689
+ if (knownAppend !== void 0) {
9690
+ let lastSegment = this.ensureLastSegment(cache);
9691
+ if (lastSegment && this.segmentHasFence(cache, lastSegment)) {
9692
+ let scanStart = this.tokenMapsTrusted ? this.ensureSegmentSourceOffset(cache, lastSegment) : 0;
9693
+ if (this.endsInsideOpenFence(prev, scanStart))
9694
+ return null;
9695
+ }
9696
+ } else {
9697
+ let scanStart = this.tokenMapsTrusted ? this.ensureLastSegment(cache)?.srcOffset ?? 0 : 0;
9698
+ if ((this.tokenMapsTrusted || this.cacheHasFenceMarker(cache)) && this.endsInsideOpenFence(prev, scanStart))
8806
9699
  return null;
8807
9700
  }
8808
- let scanStart = this.tokenMapsTrusted ? this.ensureLastSegment(cache)?.srcOffset ?? 0 : 0;
8809
- return (this.tokenMapsTrusted || this.cacheHasFenceMarker(cache)) && this.endsInsideOpenFence(prev, scanStart) || this.mayContainReferenceDefinition(segment) ? null : segment;
9701
+ return this.mayContainReferenceDefinition(segment) ? null : segment;
8810
9702
  }
8811
- tryTailSegmentReparse(src, cached, env, md, segmentOverride) {
9703
+ tryTailSegmentReparse(src, cached, env, md, segmentOverride, knownAppend) {
8812
9704
  let lastSegment = segmentOverride ?? this.ensureLastSegment(cached);
8813
- if (!lastSegment || lastSegment.srcOffset <= 0 && lastSegment.tokenStart <= 0)
9705
+ if (!lastSegment)
8814
9706
  return null;
8815
- let stablePrefix = cached.src.slice(0, lastSegment.srcOffset);
8816
- if (!src.startsWith(stablePrefix))
9707
+ let directAppend = knownAppend !== void 0;
9708
+ if (directAppend && this.ensureSegmentSourceOffset(cached, lastSegment), lastSegment.srcOffset <= 0 && lastSegment.tokenStart <= 0)
8817
9709
  return null;
8818
- let prevTail = cached.src.slice(lastSegment.srcOffset), nextTail = src.slice(lastSegment.srcOffset);
9710
+ if (!directAppend) {
9711
+ let stablePrefix = cached.src.slice(0, lastSegment.srcOffset);
9712
+ if (!src.startsWith(stablePrefix))
9713
+ return null;
9714
+ }
9715
+ let prevTail = directAppend ? cached.lastSegmentSource ?? cached.src.slice(lastSegment.srcOffset) : cached.src.slice(lastSegment.srcOffset), nextTail = directAppend ? prevTail + knownAppend : src.slice(lastSegment.srcOffset);
8819
9716
  if (nextTail === prevTail)
8820
9717
  return null;
8821
- let appended = src.startsWith(cached.src) ? src.slice(cached.src.length) : null, postBlockSrc = this.getNormalizedUpdatedSource(cached, src);
9718
+ let appended = directAppend ? knownAppend : src.startsWith(cached.src) ? src.slice(cached.src.length) : null, postBlockSrc = directAppend && this.tokenMapsTrusted ? src : this.getNormalizedUpdatedSource(cached, src, knownAppend);
8822
9719
  if (appended) {
8823
9720
  let merged = this.tryContainerTailAppendMerge(src, cached, env, md, lastSegment, appended, postBlockSrc);
8824
9721
  if (merged)
8825
- return merged;
9722
+ return cached.lastSegmentSource = directAppend ? nextTail : void 0, merged;
8826
9723
  }
8827
9724
  if (this.mayContainReferenceDefinition(prevTail) || this.mayContainReferenceDefinition(nextTail))
8828
9725
  return null;
8829
9726
  try {
8830
9727
  let parsedTail = this.parseAtLineOffset(nextTail, env, md, lastSegment.lineStart, postBlockSrc), tailState = parsedTail.state, localLastSegment = this.getLastSegment(tailState.tokens, nextTail, 0, tailState.tokens.length, parsedTail.mapsShifted ? 0 : void 0, parsedTail.mapsShifted ? lastSegment.lineStart : void 0);
8831
- return lastSegment.lineStart > 0 && !parsedTail.mapsShifted && this.shiftTokenLines(tailState.tokens, lastSegment.lineStart), appended ? this.updateFenceMarkerCacheForAppend(cached, appended) : cached.hasFenceMarker = void 0, cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null, cached.globalStateCarry = void 0, cached.tokens.length = lastSegment.tokenStart, this.appendTokens(cached.tokens, tailState.tokens), cached.lineCount = lastSegment.lineStart + countLines(nextTail), localLastSegment ? cached.lastSegment = {
9728
+ return lastSegment.lineStart > 0 && !parsedTail.mapsShifted && this.shiftTokenLines(tailState.tokens, lastSegment.lineStart), appended ? directAppend ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended) : (cached.boundary = void 0, cached.hasFenceMarker = void 0), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null, (!directAppend || !appended) && (cached.globalStateCarry = void 0), cached.tokens.length = lastSegment.tokenStart, this.appendTokens(cached.tokens, tailState.tokens), cached.lineCount = lastSegment.lineStart + countLines(nextTail), localLastSegment ? (cached.lastSegment = {
8832
9729
  tokenStart: lastSegment.tokenStart + localLastSegment.tokenStart,
8833
9730
  tokenEnd: lastSegment.tokenStart + localLastSegment.tokenEnd,
8834
9731
  lineStart: parsedTail.mapsShifted ? localLastSegment.lineStart : lastSegment.lineStart + localLastSegment.lineStart,
8835
9732
  lineEnd: parsedTail.mapsShifted ? localLastSegment.lineEnd : lastSegment.lineStart + localLastSegment.lineEnd,
8836
9733
  srcOffset: lastSegment.srcOffset + localLastSegment.srcOffset
8837
- } : cached.lastSegment = null, cached.lastSegmentVerified = void 0, cached.tokens;
9734
+ }, cached.lastSegmentSource = directAppend ? nextTail.slice(localLastSegment.srcOffset) : void 0) : (cached.lastSegment = null, cached.lastSegmentSource = void 0), cached.lastSegmentVerified = void 0, cached.tokens;
8838
9735
  } catch {
8839
9736
  return null;
8840
9737
  }
8841
9738
  }
8842
9739
  tryUntrustedParagraphTailReparse(src, cached, env, md) {
8843
- if (this.endsWithBlankLine(cached.src))
9740
+ if (cached.boundary ? cached.boundary.endsWithBlankLine : this.endsWithBlankLine(cached.src))
8844
9741
  return null;
8845
9742
  let lastSegment = this.ensureLastSegment(cached);
8846
9743
  if (!lastSegment || cached.tokens[lastSegment.tokenStart]?.type !== "paragraph_open")
@@ -8871,6 +9768,7 @@ var StreamParser = class {
8871
9768
  return count;
8872
9769
  }
8873
9770
  hasVerifiedSegmentAnchor(cache, segment, md) {
9771
+ segment.srcOffset < 0 && this.ensureSegmentSourceOffset(cache, segment);
8874
9772
  let lineCount = cache.lineCount ?? countLines(cache.src), docLineCount = this.getDocLineCount(cache.src, lineCount);
8875
9773
  if (!(segment.lineStart >= 0 && segment.lineStart <= segment.lineEnd && segment.lineEnd <= docLineCount && segment.srcOffset < cache.src.length))
8876
9774
  return !1;
@@ -8897,6 +9795,10 @@ var StreamParser = class {
8897
9795
  return !1;
8898
9796
  }
8899
9797
  }
9798
+ normalizeSource(src) {
9799
+ return src.replace(/\r\n?/g, `
9800
+ `).replace(/\0/g, "\uFFFD");
9801
+ }
8900
9802
  cacheHasFenceMarker(cache) {
8901
9803
  return cache.hasFenceMarker === void 0 && (cache.hasFenceMarker = cache.src.includes("```") || cache.src.includes("~~~")), cache.hasFenceMarker;
8902
9804
  }
@@ -8906,16 +9808,12 @@ var StreamParser = class {
8906
9808
  let boundary = cache.src.slice(-2) + appended;
8907
9809
  cache.hasFenceMarker = boundary.includes("```") || boundary.includes("~~~");
8908
9810
  }
8909
- normalizeSource(src) {
8910
- return src.replace(/\r\n?/g, `
8911
- `).replace(/\0/g, "\uFFFD");
8912
- }
8913
- getNormalizedUpdatedSource(cache, next) {
9811
+ getNormalizedUpdatedSource(cache, next, knownAppend) {
8914
9812
  if (!this.normalizeLineEndings)
8915
9813
  return next;
8916
- if (!next.startsWith(cache.src))
9814
+ if (knownAppend === void 0 && !next.startsWith(cache.src))
8917
9815
  return this.normalizeSource(next);
8918
- let normalizedCached = cache.normalizedSrc ?? this.normalizeSource(cache.src), appended = next.slice(cache.src.length), normalizedAppend = this.normalizeSource(appended);
9816
+ let normalizedCached = cache.normalizedSrc ?? this.normalizeSource(cache.src), appended = knownAppend ?? next.slice(cache.src.length), normalizedAppend = this.normalizeSource(appended);
8919
9817
  return cache.src.endsWith("\r") && appended.startsWith(`
8920
9818
  `) && (normalizedAppend = normalizedAppend.slice(1)), normalizedCached + normalizedAppend;
8921
9819
  }
@@ -9002,15 +9900,26 @@ var StreamParser = class {
9002
9900
  peek() {
9003
9901
  return this.cache?.tokens ?? EMPTY_TOKENS;
9004
9902
  }
9903
+ hasCache() {
9904
+ return this.cache !== null;
9905
+ }
9005
9906
  getStats() {
9006
9907
  return { ...this.stats };
9007
9908
  }
9909
+ setCache(cache, md) {
9910
+ let snapshotState = this.cache?.snapshotState, nextCache = {
9911
+ ...cache,
9912
+ config: copyParserConfig(md),
9913
+ snapshotState
9914
+ };
9915
+ return snapshotState && (snapshotState.cache = nextCache), this.cache = nextCache, nextCache;
9916
+ }
9008
9917
  appendTokens(target, source, start = 0, end = source.length) {
9009
9918
  for (let i = start; i < end; i++)
9010
9919
  target.push(source[i]);
9011
9920
  }
9012
9921
  updateCacheLineCount(cache, lineCount) {
9013
- cache.lineCount = lineCount ?? countLines(cache.src), cache.lastSegment = void 0, cache.lastSegmentVerified = void 0, cache.normalizedSrc = void 0, cache.globalStateCarry = void 0;
9922
+ cache.lineCount = lineCount ?? countLines(cache.src), cache.lastSegment = void 0, cache.lastSegmentVerified = void 0, cache.normalizedSrc = void 0, cache.globalStateCarry = cache.src.slice(-GLOBAL_STATE_APPEND_SCAN_WINDOW), cache.boundary = void 0, cache.lastSegmentSource = void 0;
9014
9923
  }
9015
9924
  detectGlobalStateForAppend(cache, appended) {
9016
9925
  if (cache.globalStateReason)
@@ -9018,10 +9927,10 @@ var StreamParser = class {
9018
9927
  let text$1 = (cache.globalStateCarry ?? cache.src.slice(-GLOBAL_STATE_APPEND_SCAN_WINDOW)) + appended, reason = detectGlobalMarkdownState(text$1);
9019
9928
  return cache.globalStateCarry = text$1.length > GLOBAL_STATE_APPEND_SCAN_WINDOW ? text$1.slice(text$1.length - GLOBAL_STATE_APPEND_SCAN_WINDOW) : text$1, reason && (cache.globalStateReason = reason), reason;
9020
9929
  }
9021
- ensureLastSegment(cache) {
9022
- return cache.lastSegment !== void 0 || (cache.lastSegment = this.getLastSegment(cache.tokens, cache.src)), cache.lastSegment;
9930
+ ensureLastSegment(cache, skipSourceOffset = !1) {
9931
+ return cache.lastSegment !== void 0 || (cache.lastSegment = this.getLastSegment(cache.tokens, cache.src, 0, cache.tokens.length, void 0, void 0, skipSourceOffset)), cache.lastSegment;
9023
9932
  }
9024
- getLastSegment(tokens, src, tokenStart = 0, tokenEnd = tokens.length, knownSrcOffset, knownLineStart) {
9933
+ getLastSegment(tokens, src, tokenStart = 0, tokenEnd = tokens.length, knownSrcOffset, knownLineStart, skipSourceOffset = !1) {
9025
9934
  if (tokenEnd <= tokenStart)
9026
9935
  return null;
9027
9936
  let lineStart = Number.POSITIVE_INFINITY, lineEnd$2 = -1, depth = 0;
@@ -9039,7 +9948,7 @@ var StreamParser = class {
9039
9948
  tokenEnd,
9040
9949
  lineStart: resolvedStart,
9041
9950
  lineEnd: resolvedEnd,
9042
- srcOffset: this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
9951
+ srcOffset: skipSourceOffset ? -1 : this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
9043
9952
  };
9044
9953
  }
9045
9954
  continue;
@@ -9051,12 +9960,38 @@ var StreamParser = class {
9051
9960
  tokenEnd,
9052
9961
  lineStart: resolvedStart,
9053
9962
  lineEnd: resolvedEnd,
9054
- srcOffset: this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
9963
+ srcOffset: skipSourceOffset ? -1 : this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
9055
9964
  };
9056
9965
  }
9057
9966
  }
9058
9967
  return null;
9059
9968
  }
9969
+ segmentHasFence(cache, segment) {
9970
+ let end = Math.min(segment.tokenEnd, cache.tokens.length);
9971
+ for (let i = segment.tokenStart; i < end; i++)
9972
+ if (cache.tokens[i].type === "fence")
9973
+ return !0;
9974
+ return !1;
9975
+ }
9976
+ ensureSegmentSourceOffset(cache, segment) {
9977
+ if (segment.srcOffset < 0) {
9978
+ let lineCount = cache.lineCount;
9979
+ segment.srcOffset = lineCount !== void 0 && segment.lineStart <= lineCount && segment.lineEnd <= lineCount + 1 ? this.getLineStartOffsetFromEnd(cache.src, segment.lineStart, lineCount) : this.getLineStartOffset(cache.src, segment.lineStart);
9980
+ }
9981
+ return segment.srcOffset;
9982
+ }
9983
+ getLineStartOffsetFromEnd(src, line, lineCount) {
9984
+ if (line <= 0)
9985
+ return 0;
9986
+ let remaining = lineCount - line + 1, pos = src.length;
9987
+ for (; remaining > 0; ) {
9988
+ if (pos = src.lastIndexOf(`
9989
+ `, pos - 1), pos < 0)
9990
+ return 0;
9991
+ remaining--;
9992
+ }
9993
+ return pos + 1;
9994
+ }
9060
9995
  getLineStartOffset(src, line, knownSrcOffset, knownLineStart) {
9061
9996
  return knownSrcOffset !== void 0 && knownLineStart !== void 0 && line >= knownLineStart ? this.getLineStartOffsetFrom(src, knownSrcOffset, line - knownLineStart) : this.getLineStartOffsetFrom(src, 0, line);
9062
9997
  }
@@ -9083,7 +10018,7 @@ var StreamParser = class {
9083
10018
  return src.includes("]:") ? /(?:^|\n)[ \t]{0,3}\[[^\]\n]+\]:/.test(src) : !1;
9084
10019
  }
9085
10020
  canDirectlyParseAppend(cache) {
9086
- if (!this.tokenMapsTrusted || !this.endsWithBlankLine(cache.src))
10021
+ if (!this.tokenMapsTrusted || !(cache.boundary ? cache.boundary.endsWithBlankLine : this.endsWithBlankLine(cache.src)))
9087
10022
  return !1;
9088
10023
  let lastSegment = this.ensureLastSegment(cache);
9089
10024
  if (!lastSegment)
@@ -9116,8 +10051,9 @@ var StreamParser = class {
9116
10051
  }
9117
10052
  }
9118
10053
  tryListTailAppendMerge(src, cached, env, md, lastSegment, appended, listOpen, postBlockSrc) {
9119
- if (cached.src.length === 0 || cached.src.charCodeAt(cached.src.length - 1) !== 10)
10054
+ if (cached.src.length === 0 || !(cached.boundary ? cached.boundary.endsWithNewline : cached.src.charCodeAt(cached.src.length - 1) === 10))
9120
10055
  return null;
10056
+ this.ensureSegmentSourceOffset(cached, lastSegment);
9121
10057
  let segmentLineSpan = lastSegment.lineEnd - lastSegment.lineStart, segmentChars = cached.src.length - lastSegment.srcOffset;
9122
10058
  if (segmentLineSpan < this.MIN_LIST_LINES_FOR_MERGE && segmentChars < this.MIN_LIST_CHARS_FOR_MERGE)
9123
10059
  return null;
@@ -9135,10 +10071,10 @@ var StreamParser = class {
9135
10071
  return null;
9136
10072
  lineOffset > 0 && !mapsShifted && this.shiftTokenLines(inserted, lineOffset);
9137
10073
  let existingMode = this.getListParagraphMode(cached.tokens, lastSegment.tokenStart, cached.tokens.length, listOpen.level), appendedMode = this.getListParagraphMode(parsed, 0, parsed.length, 0);
9138
- (existingMode === "loose" || appendedMode === "loose" || this.endsWithBlankLine(cached.src) || (parsed[0]?.map?.[0] ?? 0) - (mapsShifted ? lineOffset : 0) > 0) && (this.setListParagraphVisibility(cached.tokens, lastSegment.tokenStart, cached.tokens.length, listOpen.level, !1), this.setListParagraphVisibility(inserted, 0, inserted.length, listOpen.level, !1)), cached.tokens.splice(cached.tokens.length - 1, 0, ...inserted), this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
10074
+ (existingMode === "loose" || appendedMode === "loose" || (cached.boundary ? cached.boundary.endsWithBlankLine : this.endsWithBlankLine(cached.src)) || (parsed[0]?.map?.[0] ?? 0) - (mapsShifted ? lineOffset : 0) > 0) && (this.setListParagraphVisibility(cached.tokens, lastSegment.tokenStart, cached.tokens.length, listOpen.level, !1), this.setListParagraphVisibility(inserted, 0, inserted.length, listOpen.level, !1)), cached.tokens.splice(cached.tokens.length - 1, 0, ...inserted), cached.boundary ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
9139
10075
  let nextLineCount = lineOffset + countLines(appended);
9140
10076
  cached.lineCount = nextLineCount;
9141
- let nextDocLineCount = this.getDocLineCount(src, nextLineCount);
10077
+ let nextDocLineCount = this.getCachedDocLineCount(cached, nextLineCount);
9142
10078
  return listOpen.map && (listOpen.map[1] = nextDocLineCount), cached.lastSegment = {
9143
10079
  tokenStart: lastSegment.tokenStart,
9144
10080
  tokenEnd: cached.tokens.length,
@@ -9148,8 +10084,9 @@ var StreamParser = class {
9148
10084
  }, cached.lastSegmentVerified = !0, cached.tokens;
9149
10085
  }
9150
10086
  tryTableTailAppendMerge(src, cached, env, md, lastSegment, appended, tableOpen, postBlockSrc) {
9151
- if (cached.src.length === 0 || cached.src.charCodeAt(cached.src.length - 1) !== 10 || /(?:^|\n)[ \t]*\n/.test(appended))
10087
+ if (cached.src.length === 0 || !(cached.boundary ? cached.boundary.endsWithNewline : cached.src.charCodeAt(cached.src.length - 1) === 10) || /(?:^|\n)[ \t]*\n/.test(appended))
9152
10088
  return null;
10089
+ this.ensureSegmentSourceOffset(cached, lastSegment);
9153
10090
  let segmentLineSpan = lastSegment.lineEnd - lastSegment.lineStart, segmentChars = cached.src.length - lastSegment.srcOffset;
9154
10091
  if (segmentLineSpan < this.MIN_TABLE_LINES_FOR_MERGE && segmentChars < this.MIN_TABLE_CHARS_FOR_MERGE)
9155
10092
  return null;
@@ -9173,10 +10110,10 @@ var StreamParser = class {
9173
10110
  return null;
9174
10111
  lineOffset !== 0 && !mapsShifted && this.shiftTokenLines(inserted, lineOffset);
9175
10112
  let insertAt = cachedSection.tbodyCloseIndex >= 0 ? cachedSection.tbodyCloseIndex : cachedSection.tableCloseIndex, previousLineCount = cached.lineCount ?? countLines(cached.src);
9176
- cached.tokens.splice(insertAt, 0, ...inserted), this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
10113
+ cached.tokens.splice(insertAt, 0, ...inserted), cached.boundary ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
9177
10114
  let nextLineCount = previousLineCount + countLines(appended);
9178
10115
  cached.lineCount = nextLineCount;
9179
- let nextDocLineCount = this.getDocLineCount(src, nextLineCount);
10116
+ let nextDocLineCount = this.getCachedDocLineCount(cached, nextLineCount);
9180
10117
  if (tableOpen.map && (tableOpen.map[1] = nextDocLineCount), cachedSection.tbodyOpenIndex >= 0) {
9181
10118
  let tbodyOpen = cached.tokens[cachedSection.tbodyOpenIndex];
9182
10119
  tbodyOpen?.map && (tbodyOpen.map[1] = nextDocLineCount);
@@ -9283,7 +10220,7 @@ var StreamParser = class {
9283
10220
  case "paragraph_open":
9284
10221
  case "code_block":
9285
10222
  case "html_block":
9286
- return !this.endsWithBlankLine(cache.src);
10223
+ return !(cache.boundary ? cache.boundary.endsWithBlankLine : this.endsWithBlankLine(cache.src));
9287
10224
  default:
9288
10225
  return lastToken?.nesting === 1;
9289
10226
  }
@@ -9303,9 +10240,41 @@ var StreamParser = class {
9303
10240
  }
9304
10241
  return !0;
9305
10242
  }
10243
+ ensureBoundaryState(cache) {
10244
+ if (cache.boundary)
10245
+ return cache.boundary;
10246
+ let src = cache.src, len = src.length, endsWithNewline = len > 0 && src.charCodeAt(len - 1) === 10, lineEnd$2 = endsWithNewline ? len - 1 : len, lineStart = lineEnd$2 - 1;
10247
+ for (; lineStart >= 0 && src.charCodeAt(lineStart) !== 10; )
10248
+ lineStart--;
10249
+ let lineNonBlank = !1;
10250
+ for (let i = lineStart + 1; i < lineEnd$2; i++) {
10251
+ let ch = src.charCodeAt(i);
10252
+ if (ch !== 32 && ch !== 9) {
10253
+ lineNonBlank = !0;
10254
+ break;
10255
+ }
10256
+ }
10257
+ return cache.boundary = {
10258
+ currentLineNonBlank: endsWithNewline ? !1 : lineNonBlank,
10259
+ previousLineNonBlank: endsWithNewline ? lineNonBlank : !1,
10260
+ endsWithNewline,
10261
+ endsWithBlankLine: this.endsWithBlankLine(src)
10262
+ }, cache.boundary;
10263
+ }
10264
+ updateBoundaryStateForAppend(cache, appended) {
10265
+ let boundary = this.ensureBoundaryState(cache), currentLineNonBlank = boundary.currentLineNonBlank, previousLineNonBlank = boundary.previousLineNonBlank;
10266
+ for (let i = 0; i < appended.length; i++) {
10267
+ let ch = appended.charCodeAt(i);
10268
+ ch === 10 ? (previousLineNonBlank = currentLineNonBlank, currentLineNonBlank = !1) : ch !== 32 && ch !== 9 && (currentLineNonBlank = !0);
10269
+ }
10270
+ boundary.currentLineNonBlank = currentLineNonBlank, boundary.previousLineNonBlank = previousLineNonBlank, boundary.endsWithNewline = appended.length > 0 ? appended.charCodeAt(appended.length - 1) === 10 : boundary.endsWithNewline, boundary.endsWithBlankLine = cache.src.length + appended.length >= 2 && boundary.endsWithNewline && !previousLineNonBlank;
10271
+ }
9306
10272
  getDocLineCount(src, lineCount = countLines(src)) {
9307
10273
  return src.length === 0 ? 0 : src.charCodeAt(src.length - 1) === 10 ? lineCount : lineCount + 1;
9308
10274
  }
10275
+ getCachedDocLineCount(cache, lineCount) {
10276
+ return cache.src.length === 0 ? 0 : cache.boundary ? cache.boundary.endsWithNewline ? lineCount : lineCount + 1 : this.getDocLineCount(cache.src, lineCount);
10277
+ }
9309
10278
  shiftTokenLines(tokens, offset) {
9310
10279
  if (offset === 0)
9311
10280
  return;
@@ -9335,11 +10304,12 @@ function getParserRuleVersions(md) {
9335
10304
  core: md.core.ruler.version,
9336
10305
  block: md.block.ruler.version,
9337
10306
  inline: md.inline.ruler.version,
9338
- inline2: md.inline.ruler2.version
10307
+ inline2: md.inline.ruler2.version,
10308
+ inlineState: md.inline.State
9339
10309
  };
9340
10310
  }
9341
10311
  function hasParserRuleChanges(md, initial) {
9342
- return md.core.ruler.version !== initial.core || md.block.ruler.version !== initial.block || md.inline.ruler.version !== initial.inline || md.inline.ruler2.version !== initial.inline2;
10312
+ return md.core.ruler.version !== initial.core || md.block.ruler.version !== initial.block || md.inline.ruler.version !== initial.inline || md.inline.ruler2.version !== initial.inline2 || md.inline.State !== initial.inlineState;
9343
10313
  }
9344
10314
  function applyExperimentalOptions(options) {
9345
10315
  return options.experimental ? {
@@ -9692,9 +10662,25 @@ function markdownIt(presetName, options) {
9692
10662
  parse(src, env) {
9693
10663
  return md.stream.enabled ? getStreamParser().parse(src, env, md) : md.parse(src, env ?? {});
9694
10664
  },
10665
+ append(segment, env) {
10666
+ if (!md.stream.enabled)
10667
+ throw new Error("Stream append requires stream mode");
10668
+ return getStreamParser().append(segment, env, md);
10669
+ },
10670
+ snapshot() {
10671
+ return streamParser ? streamParser.snapshot() : null;
10672
+ },
10673
+ restore(snapshot) {
10674
+ if (!md.stream.enabled)
10675
+ throw new Error("Stream restore requires stream mode");
10676
+ return getStreamParser().restore(snapshot, md);
10677
+ },
9695
10678
  reset() {
9696
10679
  getStreamParser().reset();
9697
10680
  },
10681
+ hasCache() {
10682
+ return streamParser?.hasCache() ?? !1;
10683
+ },
9698
10684
  peek() {
9699
10685
  return streamParser ? streamParser.peek() : [];
9700
10686
  },
@@ -10012,7 +10998,7 @@ function container_plugin(md, name, options) {
10012
10998
  return tokens[idx].nesting === 1 && tokens[idx].attrJoin("class", name), slf.renderToken(tokens, idx, _options, env, slf);
10013
10999
  }
10014
11000
  options = options || {};
10015
- let min_markers = 3, marker_str = options.marker || ":", marker_char = marker_str.charCodeAt(0), marker_len = marker_str.length, validate = options.validate || validateDefault, render = options.render || renderDefault;
11001
+ let min_markers = 3, marker_str = options.marker || ":", marker_char = marker_str.charCodeAt(0), marker_len = marker_str.length, validate$1 = options.validate || validateDefault, render = options.render || renderDefault;
10016
11002
  function container(state, startLine, endLine, silent) {
10017
11003
  let pos, auto_closed = !1, start = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine];
10018
11004
  if (marker_char !== state.src.charCodeAt(start))
@@ -10024,7 +11010,7 @@ function container_plugin(md, name, options) {
10024
11010
  return !1;
10025
11011
  pos -= (pos - start) % marker_len;
10026
11012
  let markup = state.src.slice(start, pos), params = state.src.slice(pos, max);
10027
- if (!validate(params, markup))
11013
+ if (!validate$1(params, markup))
10028
11014
  return !1;
10029
11015
  if (silent)
10030
11016
  return !0;
@@ -10247,9 +11233,9 @@ function applyContainers(md) {
10247
11233
  function escapeTagForRegExp(tag) {
10248
11234
  return tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10249
11235
  }
10250
- function findTagCloseIndexOutsideQuotes(input) {
11236
+ function findTagCloseIndexOutsideQuotes(input, start = 0) {
10251
11237
  let inSingle = !1, inDouble = !1;
10252
- for (let i = 0; i < input.length; i++) {
11238
+ for (let i = start; i < input.length; i++) {
10253
11239
  let ch = input[i];
10254
11240
  if (ch === "\\") {
10255
11241
  i++;
@@ -11120,7 +12106,7 @@ function createChildParseContext(parent, options = parent, overrides = {}) {
11120
12106
  ...overrides
11121
12107
  });
11122
12108
  }
11123
- var FILENAMEISH_EXTENSION_RE = /\.([a-z0-9]{1,15})$/i, FILENAMEISH_SEGMENT_RE = /[_()[\]{}<>]/u, URL_PREFIX_HINT_RE = /^(?:https?:\/\/|ftp:\/\/|mailto:|www\.)/i, URL_QUERY_OR_AUTH_HINT_RE = /[?#@]/u, PATH_SEPARATOR_RE = /[\\/]/u, DOMAINISH_TEXT_RE = /^[\p{L}\p{N}./\\-]+$/u, DOMAIN_LABEL_RE = /^[A-Za-z0-9-]{1,63}$/u, PUNYCODE_TLD_RE = /^xn--[a-z0-9-]{2,59}$/i, MARKET_TICKER_SYMBOL_RE = /^(?:[A-Z]{1,6}|\d{1,8})$/u, MARKET_TICKER_CONTEXT_SYMBOL_RE = /^(?=.{1,12}$)[A-Z0-9]+(?:[-.][A-Z0-9]+)*$/iu, EXPLICIT_FILENAME_CONTEXT_RE = /文件名\s*[::]?|附件\s*[::]?|路径\s*[::]?|路徑\s*[::]?|文件列表\s*[::]?|文档列表\s*[::]?|文檔列表\s*[::]?|\bfile\s*names?\b\s*[::]?|\battachments?\b\s*[::]?|\bpaths?\b\s*[::]?|\bfile\s+lists?\b\s*[::]?|\bdocument\s+lists?\b\s*[::]?/iu, FILENAME_CONTEXT_RE = /文件名\s*[::]?|文件\s*[::]?|附件\s*[::]?|档案\s*[::]?|檔案\s*[::]?|文档\s*[::]?|文檔\s*[::]?|资料\s*[::]?|資料\s*[::]?|路径\s*[::]?|路徑\s*[::]?|\bfile\s*name\b\s*[::]?|\battachments?\b\s*[::]?|\bfiles?\b\s*[::]?|\bdocuments?\b\s*[::]?|\bdocs?\b\s*[::]?|\bpaths?\b\s*[::]?/iu, MARKET_TICKER_CONTEXT_RE = /股票代码|股票代碼|证券代码|證券代碼|(?:代码|代碼|交易所|后缀|後綴|市场|市場)(?=$|[\s::/|,,、()()])|\btickers?\b|\bsymbols?\b|\bexchanges?\b/iu, LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT = 2e3, LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TEXT_LENGTH = 512, EMPTY_LINKIFY_DEMOTION_CONTEXT = {}, AMBIGUOUS_BARE_DOMAIN_EXTENSIONS = /* @__PURE__ */ new Set([
12109
+ var FILENAMEISH_EXTENSION_RE = /\.([a-z0-9]{1,15})$/i, FILENAMEISH_SEGMENT_RE = /[_()[\]{}<>]/u, URL_PREFIX_HINT_RE = /^(?:https?:\/\/|ftp:\/\/|mailto:|www\.)/i, URL_QUERY_OR_AUTH_HINT_RE = /[?#@]/u, PATH_SEPARATOR_RE = /[\\/]/u, DOMAINISH_TEXT_RE = /^[\p{L}\p{N}./\\-]+$/u, DOMAIN_LABEL_RE = /^[A-Za-z0-9-]{1,63}$/u, PUNYCODE_TLD_RE = /^xn--[a-z0-9-]{2,59}$/i, MARKET_TICKER_SYMBOL_RE = /^(?:[A-Z]{1,6}|\d{1,8})$/u, MARKET_TICKER_CONTEXT_SYMBOL_RE = /^(?=.{1,12}$)[A-Z0-9]+(?:[-.][A-Z0-9]+)*$/iu, EXPLICIT_FILENAME_CONTEXT_RE = /文件名\s*[::]?|附件\s*[::]?|路径\s*[::]?|路徑\s*[::]?|文件列表\s*[::]?|文档列表\s*[::]?|文檔列表\s*[::]?|\bfile\s*names?\b\s*[::]?|\battachments?\b\s*[::]?|\bpaths?\b\s*[::]?|\bfile\s+lists?\b\s*[::]?|\bdocument\s+lists?\b\s*[::]?/iu, FILENAME_CONTEXT_RE = /文件名\s*[::]?|文件\s*[::]?|附件\s*[::]?|档案\s*[::]?|檔案\s*[::]?|文档\s*[::]?|文檔\s*[::]?|资料\s*[::]?|資料\s*[::]?|路径\s*[::]?|路徑\s*[::]?|\bfile\s*name\b\s*[::]?|\battachments?\b\s*[::]?|\bfiles?\b\s*[::]?|\bdocuments?\b\s*[::]?|\bdocs?\b\s*[::]?|\bpaths?\b\s*[::]?/iu, MARKET_TICKER_CONTEXT_RE = /股票代码|股票代碼|证券代码|證券代碼|(?:代码|代碼|交易所|后缀|後綴|市场|市場)(?=$|[\s::/|,,、()()])|\btickers?\b|\bsymbols?\b|\bexchanges?\b/iu, LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT = 2e3, LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TEXT_LENGTH = 16384, LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TOTAL_TEXT_LENGTH = 512 * LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT, EMPTY_LINKIFY_DEMOTION_CONTEXT = {}, AMBIGUOUS_BARE_DOMAIN_EXTENSIONS = /* @__PURE__ */ new Set([
11124
12110
  "ai",
11125
12111
  "md",
11126
12112
  "py",
@@ -11240,15 +12226,15 @@ var FILENAMEISH_EXTENSION_RE = /\.([a-z0-9]{1,15})$/i, FILENAMEISH_SEGMENT_RE =
11240
12226
  "yml",
11241
12227
  "zip",
11242
12228
  "zsh"
11243
- ]), linkifyDemotionContextCache = /* @__PURE__ */ new Map();
12229
+ ]), linkifyDemotionContextCache = /* @__PURE__ */ new Map(), linkifyDemotionContextCacheTextLength = 0;
11244
12230
  function rememberLinkifyDemotionContext(text$1, context) {
11245
12231
  if (!text$1 || text$1.length > LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TEXT_LENGTH)
11246
12232
  return context;
11247
- for (linkifyDemotionContextCache.set(text$1, context); linkifyDemotionContextCache.size > LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT; ) {
12233
+ for (linkifyDemotionContextCache.has(text$1) || (linkifyDemotionContextCacheTextLength += text$1.length), linkifyDemotionContextCache.set(text$1, context); linkifyDemotionContextCache.size > LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT || linkifyDemotionContextCacheTextLength > LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TOTAL_TEXT_LENGTH; ) {
11248
12234
  let oldestKey = linkifyDemotionContextCache.keys().next().value;
11249
12235
  if (!oldestKey)
11250
12236
  break;
11251
- linkifyDemotionContextCache.delete(oldestKey);
12237
+ linkifyDemotionContextCache.delete(oldestKey), linkifyDemotionContextCacheTextLength -= oldestKey.length;
11252
12238
  }
11253
12239
  return context;
11254
12240
  }
@@ -11296,7 +12282,7 @@ function inferContinuationLinkifyContext(raw, inherited) {
11296
12282
  })) && (continuation.filename = !0), inherited?.explicitFilename && continuation.filename && (continuation.explicitFilename = !0), inherited?.marketTicker && parts.every((part) => shouldDemoteFilenameLikeLinkify(part, { marketTicker: !0 })) && (continuation.marketTicker = !0), hasLinkifyDemotionContext(continuation) ? continuation : void 0;
11297
12283
  }
11298
12284
  function createLinkifyDemotionContextTracker(options, sticky = !1) {
11299
- let context;
12285
+ let context = ensureParseContext(options).linkifyDemotionSeedContext;
11300
12286
  return {
11301
12287
  options(raw) {
11302
12288
  return sticky || raw == null ? withLinkifyDemotionContext(options, context) : withLinkifyDemotionContext(options, mergeLinkifyDemotionContext(inferNextBlockLinkifyContext(raw), inferContinuationLinkifyContext(raw, context)));
@@ -11307,6 +12293,9 @@ function createLinkifyDemotionContextTracker(options, sticky = !1) {
11307
12293
  },
11308
12294
  reset() {
11309
12295
  context = void 0;
12296
+ },
12297
+ snapshot() {
12298
+ return context;
11310
12299
  }
11311
12300
  };
11312
12301
  }
@@ -11343,11 +12332,11 @@ function mayContainLinkifyDemotionContext(text$1) {
11343
12332
  }
11344
12333
  function inferLinkifyDemotionContext(contextText) {
11345
12334
  let text$1 = String(contextText ?? ""), cached = linkifyDemotionContextCache.get(text$1);
11346
- return cached ? (linkifyDemotionContextCache.delete(text$1), linkifyDemotionContextCache.set(text$1, cached), cached) : mayContainLinkifyDemotionContext(text$1) ? rememberLinkifyDemotionContext(text$1, {
12335
+ return cached || (mayContainLinkifyDemotionContext(text$1) ? rememberLinkifyDemotionContext(text$1, {
11347
12336
  explicitFilename: EXPLICIT_FILENAME_CONTEXT_RE.test(text$1),
11348
12337
  filename: FILENAME_CONTEXT_RE.test(text$1),
11349
12338
  marketTicker: MARKET_TICKER_CONTEXT_RE.test(text$1)
11350
- }) : rememberLinkifyDemotionContext(text$1, EMPTY_LINKIFY_DEMOTION_CONTEXT);
12339
+ }) : rememberLinkifyDemotionContext(text$1, EMPTY_LINKIFY_DEMOTION_CONTEXT));
11351
12340
  }
11352
12341
  function hasDomainAuthorityPrefix(text$1) {
11353
12342
  return isPlausibleBareDomain(text$1.split(/[\\/]/)[0] ?? "");
@@ -11386,6 +12375,21 @@ function setSyntheticLinkOrigin(token, origin) {
11386
12375
  function readSyntheticLinkOrigin(token) {
11387
12376
  return syntheticLinkOrigins.get(token);
11388
12377
  }
12378
+ function resolveLinkMarkup(token) {
12379
+ if (!token)
12380
+ return "";
12381
+ let origin = readSyntheticLinkOrigin(token);
12382
+ if (origin === "linkify" || origin === "autolink")
12383
+ return origin;
12384
+ let markup = typeof token.markup == "string" ? token.markup : "";
12385
+ return markup === "linkify" || markup === "autolink" ? markup : "";
12386
+ }
12387
+ function copySyntheticLinkOrigin(from, to) {
12388
+ if (!from || !to)
12389
+ return;
12390
+ let origin = readSyntheticLinkOrigin(from);
12391
+ origin && syntheticLinkOrigins.set(to, origin);
12392
+ }
11389
12393
  function registerCacheStableLinkValidator(validateLink$1) {
11390
12394
  cacheStableLinkValidators.add(validateLink$1);
11391
12395
  }
@@ -11623,7 +12627,7 @@ function fixLinkToken(tokens, raw) {
11623
12627
  } else if (curToken?.type === "text" && curToken.content?.endsWith("(") && tokens[i + 1]?.type === "link_open") {
11624
12628
  let match = curToken.content.match(/\[([^\]]+)\]/);
11625
12629
  if (match) {
11626
- let beforeText = curToken.content.slice(0, match.index), emphasisMatch = beforeText.match(/(\*+)$/), origin = getSyntheticLinkOrigin(tokens[i + 1]?.markup), replacerTokens = [];
12630
+ let beforeText = curToken.content.slice(0, match.index), emphasisMatch = beforeText.match(/(\*+)$/), linkOpenMarkup = tokens[i + 1]?.markup, origin = (linkOpenMarkup === "linkify" || linkOpenMarkup === "autolink") && (match.index ?? 0) + match[0].length === curToken.content.length - 1 ? "explicit" : getSyntheticLinkOrigin(linkOpenMarkup), replacerTokens = [];
11627
12631
  if (emphasisMatch) {
11628
12632
  beforeText = beforeText.slice(0, emphasisMatch.index), beforeText && replacerTokens.push(textToken(beforeText));
11629
12633
  let text$1 = match[1], type = emphasisMatch[1].length;
@@ -11852,7 +12856,7 @@ function fixStrongTokens(tokens) {
11852
12856
  for (; k < tokens.length && tokens[k].type === "text" && tokens[k].content === ""; )
11853
12857
  k++;
11854
12858
  let postToken = tokens[k];
11855
- markup === "__" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_") || postToken?.markup?.includes("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansStrong.add(strongIndex));
12859
+ markup === "__" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansStrong.add(strongIndex));
11856
12860
  } else if (type === "strong_close")
11857
12861
  cleansStrong.has(strongIndex) && t.markup === "__" && (t.type = "text", t.content = t.markup, t.raw = String(t.markup ?? ""), t.tag = "", t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null), strongIndex--, strongIndex < 0 && (strongIndex = 0);
11858
12862
  else if (type === "em_open") {
@@ -11864,7 +12868,7 @@ function fixStrongTokens(tokens) {
11864
12868
  for (; k < tokens.length && tokens[k].type === "text" && tokens[k].content === ""; )
11865
12869
  k++;
11866
12870
  let postToken = tokens[k];
11867
- markup === "_" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_") || postToken?.markup?.includes("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansEm.add(emIndex));
12871
+ markup === "_" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansEm.add(emIndex));
11868
12872
  } else
11869
12873
  type === "em_close" && (cleansEm.has(emIndex) && t.markup === "_" && (t.type = "text", t.content = t.markup, t.raw = String(t.markup ?? ""), t.tag = "", t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null), emIndex--, emIndex < 0 && (emIndex = 0));
11870
12874
  }
@@ -12173,36 +13177,35 @@ function hasTrailingPipeHeaderRowWithoutColon(line) {
12173
13177
  return cells !== null && cells.every((cell) => !cell.includes(":"));
12174
13178
  }
12175
13179
  function fixTableTokens(tokens, final = !1, source = "") {
12176
- let fixedTokens = [...tokens];
12177
13180
  if (tokens.length < 3)
12178
- return fixedTokens;
13181
+ return tokens;
12179
13182
  let i = tokens.length - 2, token = tokens[i];
12180
- if (token.type === "inline") {
12181
- let sourceMap = tokens[i - 1]?.map, tcontent = String(token.content ?? ""), headerContent = tcontent.split(`
13183
+ if (token.type !== "inline")
13184
+ return tokens;
13185
+ let sourceMap = tokens[i - 1]?.map, tcontent = String(token.content ?? ""), headerContent = tcontent.split(`
12182
13186
  `)[0] ?? "", [headerLine = "", separatorLine = "", ...rest] = tcontent.split(`
12183
13187
  `), hasTrailingNewlineSeparatorStart = !final && !tcontent.includes(`
12184
- `) && /\r?\n$/.test(source) && hasTrailingPipeHeaderRow(tcontent);
12185
- if (!final && (tcontent.includes(`
13188
+ `) && /\r?\n$/.test(source) && hasTrailingPipeHeaderRow(tcontent), fixedTokens = null;
13189
+ if (!final && (tcontent.includes(`
12186
13190
  `) && rest.length === 0 && hasTrailingPipeHeaderRow(headerLine) && isTableSeparatorRowWithPartialTail(separatorLine) || hasTrailingNewlineSeparatorStart)) {
12187
- let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
12188
- ...createStart(sourceMap),
12189
- ...body,
12190
- ...createEnd()
12191
- ];
12192
- fixedTokens.splice(i - 1, 3, ...insert);
12193
- } else if (tcontent.includes(`
13191
+ let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
13192
+ ...createStart(sourceMap),
13193
+ ...body,
13194
+ ...createEnd()
13195
+ ];
13196
+ fixedTokens = [...tokens], fixedTokens.splice(i - 1, 3, ...insert);
13197
+ } else if (tcontent.includes(`
12194
13198
  `) && rest.length === 0 && hasTrailingPipeHeaderRow(headerLine) && isTableSeparatorRow(separatorLine)) {
12195
- let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
12196
- ...createStart(sourceMap),
12197
- ...body,
12198
- ...createEnd()
12199
- ];
12200
- fixedTokens.splice(i - 1, 3, ...insert);
12201
- } else
12202
- tcontent.includes(`
12203
- `) && rest.length === 0 && hasTrailingPipeHeaderRowWithoutColon(headerLine) && isTruncatedSeparatorRow(separatorLine) && (token.content = tcontent.slice(0, -2), token.children.splice(2, 1));
12204
- }
12205
- return fixedTokens;
13199
+ let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
13200
+ ...createStart(sourceMap),
13201
+ ...body,
13202
+ ...createEnd()
13203
+ ];
13204
+ fixedTokens = [...tokens], fixedTokens.splice(i - 1, 3, ...insert);
13205
+ } else if (tcontent.includes(`
13206
+ `) && rest.length === 0 && hasTrailingPipeHeaderRowWithoutColon(headerLine) && isTruncatedSeparatorRow(separatorLine))
13207
+ return token.content = tcontent.slice(0, -2), token.children.splice(2, 1), tokens;
13208
+ return fixedTokens ?? tokens;
12206
13209
  }
12207
13210
  function findMatchingClose(src, startIdx, open, close) {
12208
13211
  let len = src.length;
@@ -12693,27 +13696,36 @@ function hashTolerantBoundaryContent(content) {
12693
13696
  hash = hash * 31 + content.charCodeAt(index) | 0;
12694
13697
  return hash.toString(36);
12695
13698
  }
12696
- function getTolerantBoundaryScanWindow(source) {
13699
+ function getTolerantBoundaryScanWindow(source, cache) {
12697
13700
  if (source.length <= TOLERANT_BOUNDARY_SCAN_TAIL_CHARS)
12698
13701
  return {
12699
13702
  source,
12700
13703
  lineOffset: 0
12701
13704
  };
13705
+ if (cache) {
13706
+ let cut = source.length - TOLERANT_BOUNDARY_SCAN_TAIL_CHARS, start$1 = source.indexOf(`
13707
+ `, cut);
13708
+ start$1 = start$1 === -1 ? source.length : start$1 + 1;
13709
+ let lineOffset$1 = cache.lineOffset + countLineBreaks(source.slice(cache.windowStart, start$1));
13710
+ return cache.lineOffset = lineOffset$1, cache.windowStart = start$1, {
13711
+ source: source.slice(start$1),
13712
+ lineOffset: lineOffset$1
13713
+ };
13714
+ }
12702
13715
  let start = source.length - TOLERANT_BOUNDARY_SCAN_TAIL_CHARS, nextLineBreak = source.indexOf(`
12703
13716
  `, start);
12704
- return nextLineBreak === -1 ? {
12705
- source: "",
12706
- lineOffset: countLineBreaks(source)
12707
- } : (start = nextLineBreak + 1, {
13717
+ start = nextLineBreak === -1 ? source.length : nextLineBreak + 1;
13718
+ let lineOffset = countLineBreaks(source.slice(0, start));
13719
+ return {
12708
13720
  source: source.slice(start),
12709
- lineOffset: countLineBreaks(source.slice(0, start))
12710
- });
13721
+ lineOffset
13722
+ };
12711
13723
  }
12712
- function mayContainTolerantMathBlockBoundaryOpener(markdown) {
13724
+ function mayContainTolerantMathBlockBoundaryOpener(markdown, scanWindowCache) {
12713
13725
  let fullSource = String(markdown ?? "");
12714
13726
  if (!fullSource || !fullSource.includes("$$") && !fullSource.includes("\\["))
12715
13727
  return !1;
12716
- let { source } = getTolerantBoundaryScanWindow(fullSource);
13728
+ let { source } = getTolerantBoundaryScanWindow(fullSource, scanWindowCache);
12717
13729
  if (!source)
12718
13730
  return !1;
12719
13731
  let lines = source.split(/\r?\n/), startLine = Math.max(0, lines.length - TOLERANT_BOUNDARY_SCAN_MAX_LINES - 2), delimiters = [["$$", "$$"], ["\\[", "\\]"]];
@@ -12727,11 +13739,11 @@ function mayContainTolerantMathBlockBoundaryOpener(markdown) {
12727
13739
  }
12728
13740
  return !1;
12729
13741
  }
12730
- function getTolerantMathBlockBoundaryStreamKey(markdown) {
13742
+ function getTolerantMathBlockBoundaryStreamKey(markdown, scanWindowCache) {
12731
13743
  let fullSource = String(markdown ?? "");
12732
13744
  if (!fullSource || !fullSource.includes("$$") && !fullSource.includes("\\["))
12733
13745
  return null;
12734
- let { source, lineOffset } = getTolerantBoundaryScanWindow(fullSource);
13746
+ let { source, lineOffset } = getTolerantBoundaryScanWindow(fullSource, scanWindowCache);
12735
13747
  if (!source)
12736
13748
  return null;
12737
13749
  let lines = source.split(/\r?\n/), startLine = Math.max(0, lines.length - TOLERANT_BOUNDARY_SCAN_MAX_LINES - 2), delimiters = [["$$", "$$"], ["\\[", "\\]"]];
@@ -13225,7 +14237,7 @@ function applyRenderRules(md) {
13225
14237
  return `<pre class="${info ? `language-${md.utils.escapeHtml(info.split(/\s+/g)[0])}` : ""}"><code>${md.utils.escapeHtml(String(tokenShape.content ?? ""))}</code></pre>`;
13226
14238
  });
13227
14239
  }
13228
- var HTML_LINK_OPEN_RE = /^<a[>\s]/i, HTML_LINK_CLOSE_RE = /^<\/a\s*>/i;
14240
+ var HTML_LINK_OPEN_RE = /^<a[>\s]/i, HTML_LINK_CLOSE_RE = /^<\/a\s*>/i, LINKIFY_SEED_RE = /[@:]|\/\/|\.\S/;
13229
14241
  function inlineTokenMayNeedLinkify(token, linkify$2) {
13230
14242
  if (token?.type !== "inline")
13231
14243
  return !1;
@@ -13251,13 +14263,33 @@ function inlineTokenMayNeedLinkify(token, linkify$2) {
13251
14263
  }
13252
14264
  function applyLinkifyCandidateFilter(md) {
13253
14265
  let ruler = md.core?.ruler, original = ruler.getNamedRules?.().find((rule) => rule.name === "linkify")?.fn;
13254
- typeof original == "function" && ruler.at("linkify", (state) => {
14266
+ if (typeof original != "function")
14267
+ return;
14268
+ let nativeLinkify = md.options.linkify ? md.linkify : void 0, nativeTest = nativeLinkify?.test, nativeMatch = nativeLinkify?.match, nativeBuilderPrototype = nativeLinkify?.re && Object.getPrototypeOf(nativeLinkify.re), screenedCache, seedSafe = !1;
14269
+ ruler.at("linkify", (state) => {
13255
14270
  if (!state.md?.options?.linkify)
13256
14271
  return;
13257
14272
  let tokens = Array.isArray(state.tokens) ? state.tokens : [], linkify$2 = state.md.linkify;
13258
- if (!linkify$2)
14273
+ if (!linkify$2 || !tokens.some((token) => token?.type === "inline"))
13259
14274
  return;
13260
- let candidates = tokens.filter((token) => inlineTokenMayNeedLinkify(token, linkify$2));
14275
+ let re = linkify$2.re, nativeBuilder = re && Object.getPrototypeOf(re) === nativeBuilderPrototype && !Object.values(re).some((value) => typeof value == "function"), nativeMethods = linkify$2.test === nativeTest && linkify$2.match === nativeMatch;
14276
+ if (nativeMethods && nativeBuilder && screenedCache !== re.cache) {
14277
+ screenedCache = re.cache;
14278
+ let { schema_names: schemas = [], tlds = [] } = re.opts;
14279
+ seedSafe = schemas.every((name) => name === "//" || name.endsWith(":")) && tlds.every((tld) => /^[\p{L}\p{N}-]+$/u.test(tld));
14280
+ }
14281
+ let canScreen = !!nativeMethods && !!nativeBuilder && seedSafe && (state.env?.__markstreamFinal !== !1 || !!re?.cache.link_fuzzy_search), candidates = tokens.filter((token) => {
14282
+ if (canScreen && token?.type === "inline") {
14283
+ let children = token.children;
14284
+ if (Array.isArray(children) && children.length > 0) {
14285
+ if (!children.some((child) => child?.type === "text" && LINKIFY_SEED_RE.test(String(child.content ?? ""))))
14286
+ return !1;
14287
+ } else if (!LINKIFY_SEED_RE.test(String(token.content ?? "")))
14288
+ return !1;
14289
+ canScreen = !1;
14290
+ }
14291
+ return inlineTokenMayNeedLinkify(token, linkify$2);
14292
+ });
13261
14293
  if (candidates.length)
13262
14294
  return original(Object.assign(Object.create(Object.getPrototypeOf(state)), state, { tokens: candidates }));
13263
14295
  });
@@ -13309,12 +14341,22 @@ function factory(opts = {}) {
13309
14341
  });
13310
14342
  registerCacheStableLinkValidator(validateLink$1), md.set({ validateLink: validateLink$1 });
13311
14343
  }
13312
- return applyInlineUrlValidation(md), applyLinkifyCandidateFilter(md), (opts.enableMath ?? !0) && applyMath(md, {
14344
+ return applyInlineUrlValidation(md), applyLinkifyCandidateFilter(md), (opts.cjkFriendly ?? !0) && md.use(markdownItCjkFriendlyPlugin), (opts.enableMath ?? !0) && applyMath(md, {
13313
14345
  ...getDefaultMathOptions() ?? {},
13314
14346
  ...opts.mathOptions ?? {}
13315
14347
  }), (opts.enableContainers ?? !0) && applyContainers(md), opts.enableFixIndentedCodeBlock !== !1 && applyFixIndentedCodeBlock(md), applyFixLinkTokens(md), applyFixStrongTokens(md), applyFixListItem(md), applyFixTableTokens(md), applyRenderRules(md), applyFixHtmlInlineTokens(md, { customHtmlTags: opts.customHtmlTags }), md;
13316
14348
  }
13317
- var NOT_WHITESPACE = /\S/;
14349
+ var regexCache = /* @__PURE__ */ new Map();
14350
+ function getCachedRegex(pattern, flags) {
14351
+ let key = flags ? `${pattern}:::${flags}` : pattern, regex = regexCache.get(key);
14352
+ if (!regex && (regex = new RegExp(pattern, flags), regexCache.set(key, regex), regexCache.size > 200)) {
14353
+ let keysToDelete = Array.from(regexCache.keys()).slice(0, 50);
14354
+ for (let keyToDelete of keysToDelete)
14355
+ regexCache.delete(keyToDelete);
14356
+ }
14357
+ return regex.lastIndex = 0, regex;
14358
+ }
14359
+ var NOT_WHITESPACE = /\S/, STARTS_LIKE_HTML_DOCUMENT_RE = /^(?:<!doctype\s+html[^>]*>\s*)?<html(?:\s[^>]*)?>/i, ENDS_WITH_HTML_CLOSE_RE = /<\/html>\s*$/i, NON_ELEMENT_MARKUP_START_RE = /^<\s*[!?]/, MARKUP_TAG_NAME_RE = /^([A-Z][\w:-]*)/i, SELF_CLOSING_END_RE$1 = /\/\s*>$/;
13318
14360
  function parseStandaloneHtmlDocument(markdown) {
13319
14361
  let firstNonWhitespace = markdown.search(NOT_WHITESPACE);
13320
14362
  if (firstNonWhitespace === -1 || markdown.charCodeAt(firstNonWhitespace) !== 60)
@@ -13322,7 +14364,7 @@ function parseStandaloneHtmlDocument(markdown) {
13322
14364
  let trimmed = markdown.trim();
13323
14365
  if (!trimmed)
13324
14366
  return null;
13325
- let startsLikeHtmlDocument = /^(?:<!doctype\s+html[^>]*>\s*)?<html(?:\s[^>]*)?>/i.test(trimmed), endsWithHtmlClose = /<\/html>\s*$/i.test(trimmed);
14367
+ let startsLikeHtmlDocument = STARTS_LIKE_HTML_DOCUMENT_RE.test(trimmed), endsWithHtmlClose = ENDS_WITH_HTML_CLOSE_RE.test(trimmed);
13326
14368
  return !startsLikeHtmlDocument || !endsWithHtmlClose ? null : [{
13327
14369
  type: "html_block",
13328
14370
  tag: "html",
@@ -13342,7 +14384,7 @@ function isCloseOnlyHtmlBlockForTag(node, tag) {
13342
14384
  if (node.type !== "html_block" || !tag)
13343
14385
  return !1;
13344
14386
  let raw = String(node.raw ?? node.content ?? "");
13345
- return new RegExp(String.raw`^\s*<\s*\/\s*${escapeTagForRegExp(tag)}\s*>\s*$`, "i").test(raw);
14387
+ return getCachedRegex(String.raw`^\s*<\s*\/\s*${escapeTagForRegExp(tag)}\s*>\s*$`, "i").test(raw);
13346
14388
  }
13347
14389
  var RAW_TEXT_HTML_TAGS = /* @__PURE__ */ new Set([
13348
14390
  "iframe",
@@ -13373,11 +14415,11 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
13373
14415
  tag: ""
13374
14416
  };
13375
14417
  }
13376
- let endRel = findTagCloseIndexOutsideQuotes(source.slice(start$1));
13377
- if (endRel === -1)
14418
+ let closeIndex = findTagCloseIndexOutsideQuotes(source, start$1);
14419
+ if (closeIndex === -1)
13378
14420
  return null;
13379
- let end = start$1 + endRel + 1, raw = source.slice(start$1, end);
13380
- if (/^<\s*[!?]/.test(raw))
14421
+ let end = closeIndex + 1, raw = source.slice(start$1, end);
14422
+ if (NON_ELEMENT_MARKUP_START_RE.test(raw))
13381
14423
  return {
13382
14424
  closing: !1,
13383
14425
  end,
@@ -13386,11 +14428,11 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
13386
14428
  };
13387
14429
  let body = raw.slice(1).trimStart(), closing = body.startsWith("/");
13388
14430
  closing && (body = body.slice(1).trimStart());
13389
- let tagMatch = body.match(/^([A-Z][\w:-]*)/i);
14431
+ let tagMatch = body.match(MARKUP_TAG_NAME_RE);
13390
14432
  return tagMatch?.[1] ? {
13391
14433
  closing,
13392
14434
  end,
13393
- selfClosing: /\/\s*>$/.test(raw),
14435
+ selfClosing: SELF_CLOSING_END_RE$1.test(raw),
13394
14436
  tag: tagMatch[1].toLowerCase()
13395
14437
  } : {
13396
14438
  closing: !1,
@@ -13399,7 +14441,7 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
13399
14441
  tag: ""
13400
14442
  };
13401
14443
  }, findRawTextClose = (rawTextTag, from) => {
13402
- let closeRe = new RegExp(String.raw`<\s*\/\s*${escapeTagForRegExp(rawTextTag)}(?=\s|>)`, "gi");
14444
+ let closeRe = getCachedRegex(String.raw`<\s*\/\s*${escapeTagForRegExp(rawTextTag)}(?=\s|>)`, "gi");
13403
14445
  closeRe.lastIndex = from;
13404
14446
  let match = closeRe.exec(source);
13405
14447
  if (!match || match.index == null)
@@ -13430,7 +14472,7 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
13430
14472
  if (start === -1 || openEnd === -1)
13431
14473
  return null;
13432
14474
  let openTag = source.slice(start, openEnd + 1);
13433
- if (VOID_HTML_TAGS.has(lowerTag) || /\/\s*>$/.test(openTag))
14475
+ if (VOID_HTML_TAGS.has(lowerTag) || SELF_CLOSING_END_RE$1.test(openTag))
13434
14476
  return {
13435
14477
  raw: openTag,
13436
14478
  start,
@@ -13534,13 +14576,14 @@ function extendHtmlBlockCloseToLineEnding(source, startIndex) {
13534
14576
  ` ? end + 1 : startIndex;
13535
14577
  }
13536
14578
  function findLastClosingTagStart(raw, tag) {
13537
- let closeRe = new RegExp(String.raw`<\s*\/\s*${escapeTagForRegExp(tag)}(?=\s|>)`, "gi"), last = -1, match;
14579
+ let closeRe = getCachedRegex(String.raw`<\s*\/\s*${escapeTagForRegExp(tag)}(?=\s|>)`, "gi"), last = -1, match;
13538
14580
  for (; (match = closeRe.exec(raw)) !== null; )
13539
14581
  last = match.index;
13540
14582
  return last;
13541
14583
  }
14584
+ var NON_ELEMENT_HTML_BLOCK_START_RE = /^\s*(?:<!--|<!|<\?)/, FIRST_TAG_NAME_RE = /^\s*<([A-Z][\w:-]*)/i, SELF_CLOSING_END_RE = /\/\s*>$/, TRAILING_UNCLOSED_TAG_RE = /<[^>]*$/;
13542
14585
  function findMatchingCloseTagEnd(rawHtml, tag, startIndex) {
13543
- let lowerTag = tag.toLowerCase(), openTagRe = new RegExp(String.raw`^<\s*${lowerTag}(?=\s|>|/)`, "i"), closeTagRe = new RegExp(String.raw`^<\s*\/\s*${lowerTag}(?=\s|>)`, "i"), depth = 0, index = Math.max(0, startIndex);
14586
+ let lowerTag = tag.toLowerCase(), openTagRe = getCachedRegex(String.raw`^<\s*${lowerTag}(?=\s|>|/)`, "i"), closeTagRe = getCachedRegex(String.raw`^<\s*\/\s*${lowerTag}(?=\s|>)`, "i"), depth = 0, index = Math.max(0, startIndex);
13544
14587
  for (; index < rawHtml.length; ) {
13545
14588
  let lt = rawHtml.indexOf("<", index);
13546
14589
  if (lt === -1)
@@ -13560,7 +14603,7 @@ function findMatchingCloseTagEnd(rawHtml, tag, startIndex) {
13560
14603
  if (endRel === -1)
13561
14604
  return -1;
13562
14605
  let rawTag = slice.slice(0, endRel + 1);
13563
- /\/\s*>$/.test(rawTag) || depth++, index = lt + endRel + 1;
14606
+ SELF_CLOSING_END_RE.test(rawTag) || depth++, index = lt + endRel + 1;
13564
14607
  continue;
13565
14608
  }
13566
14609
  index = lt + 1;
@@ -13569,7 +14612,7 @@ function findMatchingCloseTagEnd(rawHtml, tag, startIndex) {
13569
14612
  }
13570
14613
  function parseHtmlBlock(token) {
13571
14614
  let raw = String(token.content ?? "");
13572
- if (/^\s*<!--/.test(raw) || /^\s*<!/.test(raw) || /^\s*<\?/.test(raw))
14615
+ if (NON_ELEMENT_HTML_BLOCK_START_RE.test(raw))
13573
14616
  return {
13574
14617
  type: "html_block",
13575
14618
  content: raw,
@@ -13577,7 +14620,7 @@ function parseHtmlBlock(token) {
13577
14620
  tag: "",
13578
14621
  loading: !1
13579
14622
  };
13580
- let tag = (raw.match(/^\s*<([A-Z][\w:-]*)/i)?.[1] || "").toLowerCase();
14623
+ let tag = (raw.match(FIRST_TAG_NAME_RE)?.[1] || "").toLowerCase();
13581
14624
  if (!tag)
13582
14625
  return {
13583
14626
  type: "html_block",
@@ -13586,10 +14629,10 @@ function parseHtmlBlock(token) {
13586
14629
  tag: "",
13587
14630
  loading: !1
13588
14631
  };
13589
- let openEnd = findTagCloseIndexOutsideQuotes(raw), openTag = openEnd === -1 ? raw : raw.slice(0, openEnd + 1), selfClosing = openEnd !== -1 && /\/\s*>$/.test(openTag), isVoid = VOID_HTML_TAGS.has(tag), attrs = parseTagAttrs(openTag), hasClosing = (openEnd === -1 ? -1 : findMatchingCloseTagEnd(raw, tag, openEnd + 1)) !== -1, loading = !(isVoid || selfClosing || hasClosing);
14632
+ let openEnd = findTagCloseIndexOutsideQuotes(raw), openTag = openEnd === -1 ? raw : raw.slice(0, openEnd + 1), selfClosing = openEnd !== -1 && SELF_CLOSING_END_RE.test(openTag), isVoid = VOID_HTML_TAGS.has(tag), attrs = parseTagAttrs(openTag), hasClosing = (openEnd === -1 ? -1 : findMatchingCloseTagEnd(raw, tag, openEnd + 1)) !== -1, loading = !(isVoid || selfClosing || hasClosing);
13590
14633
  return {
13591
14634
  type: "html_block",
13592
- content: loading ? `${raw.replace(/<[^>]*$/, "")}
14635
+ content: loading ? `${raw.replace(TRAILING_UNCLOSED_TAG_RE, "")}
13593
14636
  </${tag}>` : raw,
13594
14637
  raw,
13595
14638
  tag,
@@ -13659,7 +14702,7 @@ function applyNodeSourceMapRange(node, token, endLine, options) {
13659
14702
  }
13660
14703
  function cloneTokenWithMutableChildren(token) {
13661
14704
  let copy = Object.assign(Object.create(Object.getPrototypeOf(token)), token);
13662
- return Array.isArray(token.attrs) && (copy.attrs = token.attrs.map((attr) => [...attr])), Array.isArray(token.map) && (copy.map = [...token.map]), Array.isArray(token.children) && (copy.children = token.children.map((child) => cloneTokenWithMutableChildren(child))), copy;
14705
+ return Array.isArray(token.attrs) && (copy.attrs = token.attrs.map((attr) => [...attr])), Array.isArray(token.map) && (copy.map = [...token.map]), Array.isArray(token.children) && (copy.children = token.children.map((child) => cloneTokenWithMutableChildren(child))), copySyntheticLinkOrigin(token, copy), copy;
13663
14706
  }
13664
14707
  function isPlainObject(value) {
13665
14708
  if (!value || typeof value != "object")
@@ -13750,6 +14793,10 @@ function canCloneMarkdownTokenFast(token, enumerableKeys) {
13750
14793
  return !0;
13751
14794
  }
13752
14795
  function cloneMarkdownToken(token, cloneObjectFields = !0) {
14796
+ let cloned = cloneMarkdownTokenValue(token, cloneObjectFields);
14797
+ return copySyntheticLinkOrigin(token, cloned), cloned;
14798
+ }
14799
+ function cloneMarkdownTokenValue(token, cloneObjectFields = !0) {
13753
14800
  if (!cloneObjectFields)
13754
14801
  return cloneTokenWithMutableChildren(token);
13755
14802
  let allKeys = Reflect.ownKeys(token), enumerableKeys = Object.keys(token);
@@ -13943,12 +14990,16 @@ function createExplicitBracketMathContext() {
13943
14990
  function cloneExplicitBracketMathContext(context) {
13944
14991
  return { ...context };
13945
14992
  }
13946
- function setTolerantMathBoundaryStreamCache(runtime, source, key, explicitBracketMath = scanExplicitBracketMathStreamState(source).state) {
14993
+ function setTolerantMathBoundaryStreamCache(runtime, source, key, explicitBracketMath = scanExplicitBracketMathStreamState(source).state, scanWindow = {
14994
+ lineOffset: 0,
14995
+ windowStart: 0
14996
+ }) {
13947
14997
  runtime.tolerantMathBoundary = {
13948
14998
  explicitBracketMath,
13949
14999
  source,
13950
15000
  key,
13951
- pendingCandidate: key === null && mayContainTolerantMathBlockBoundaryOpener(source)
15001
+ pendingCandidate: key === null && mayContainTolerantMathBlockBoundaryOpener(source, scanWindow),
15002
+ scanWindow
13952
15003
  };
13953
15004
  }
13954
15005
  function sourceEndsWithSplitTolerantBoundaryPrefix(source) {
@@ -14197,7 +15248,7 @@ function stripPendingExplicitMathTail(markdown, runtime, useCache = !0) {
14197
15248
  let md = runtime.markdownIt;
14198
15249
  if (!hasMarkstreamMathPlugin(md))
14199
15250
  return markdown;
14200
- let previous = useCache ? runtime.pendingExplicitMathTail : void 0, state = previous?.source === markdown ? previous.state : previous && markdown.startsWith(previous.source) ? updateExplicitBracketMathStreamState(previous.state, markdown.slice(previous.source.length), previous.source.length - previous.state.lineBuffer.length).state : scanExplicitBracketMathStreamState(markdown).state;
15251
+ let previous = useCache ? runtime.pendingExplicitMathTail : void 0, state = previous?.source === markdown ? previous.state : previous && runtime.sourceExtends(previous.source, markdown) ? updateExplicitBracketMathStreamState(previous.state, markdown.slice(previous.source.length), previous.source.length - previous.state.lineBuffer.length).state : scanExplicitBracketMathStreamState(markdown).state;
14201
15252
  useCache && (runtime.pendingExplicitMathTail = {
14202
15253
  source: markdown,
14203
15254
  state
@@ -14257,13 +15308,16 @@ function syncTolerantMathBoundaryStreamCache(runtime, source) {
14257
15308
  let previous = runtime.tolerantMathBoundary;
14258
15309
  if (previous?.source === source)
14259
15310
  return;
14260
- let sourceExtendsPrevious = previous ? source.startsWith(previous.source) : !1, appended = sourceExtendsPrevious && previous ? source.slice(previous.source.length) : "", explicitBracketMathUpdate = sourceExtendsPrevious && previous ? updateExplicitBracketMathStreamState(previous.explicitBracketMath, appended, previous.source.length - previous.explicitBracketMath.lineBuffer.length) : scanExplicitBracketMathStreamState(source), nextExplicitBracketMath = explicitBracketMathUpdate.state, completesExplicitBracketMathClose = sourceExtendsPrevious && previous ? explicitBracketMathUpdate.closedOpenMath : !1;
15311
+ let sourceExtendsPrevious = previous ? runtime.sourceExtends(previous.source, source) : !1, appended = sourceExtendsPrevious && previous ? source.slice(previous.source.length) : "", explicitBracketMathUpdate = sourceExtendsPrevious && previous ? updateExplicitBracketMathStreamState(previous.explicitBracketMath, appended, previous.source.length - previous.explicitBracketMath.lineBuffer.length) : scanExplicitBracketMathStreamState(source), nextExplicitBracketMath = explicitBracketMathUpdate.state, completesExplicitBracketMathClose = sourceExtendsPrevious && previous ? explicitBracketMathUpdate.closedOpenMath : !1;
14261
15312
  if (previous && sourceExtendsPrevious && previous.key === null && previous.pendingCandidate === !1 && !completesExplicitBracketMathClose && !appendedChunkMayAffectTolerantMathBoundary(previous.source, appended) && !sourceEndsWithSplitTolerantBoundaryPrefix(source)) {
14262
15313
  previous.source = source, previous.explicitBracketMath = nextExplicitBracketMath;
14263
15314
  return;
14264
15315
  }
14265
- let nextKey = getTolerantMathBlockBoundaryStreamKey(source);
14266
- (previous && (previous && !sourceExtendsPrevious || previous.key !== nextKey || completesExplicitBracketMathClose) || !previous && nextKey) && runtime.resetStreamOnly(), setTolerantMathBoundaryStreamCache(runtime, source, nextKey, nextExplicitBracketMath);
15316
+ let scanWindow = sourceExtendsPrevious && previous ? previous.scanWindow : {
15317
+ lineOffset: 0,
15318
+ windowStart: 0
15319
+ }, nextKey = getTolerantMathBlockBoundaryStreamKey(source, scanWindow);
15320
+ (previous && (previous && !sourceExtendsPrevious || previous.key !== nextKey || completesExplicitBracketMathClose) || !previous && nextKey) && runtime.resetStreamOnly(), setTolerantMathBoundaryStreamCache(runtime, source, nextKey, nextExplicitBracketMath, scanWindow);
14267
15321
  }
14268
15322
  function shouldUseSyncParseForPendingTolerantMathBoundary(runtime) {
14269
15323
  let cache = runtime.tolerantMathBoundary;
@@ -14431,6 +15485,7 @@ var REUSABLE_INLINE_TOKEN_TYPES = /* @__PURE__ */ new Set([
14431
15485
  "code_block",
14432
15486
  "fence",
14433
15487
  "hr",
15488
+ "html_block",
14434
15489
  "inline",
14435
15490
  "math_block"
14436
15491
  ]);
@@ -14533,7 +15588,7 @@ function sameTokenAttrs(left, right) {
14533
15588
  function isSameTokenShapeForReuse(left, right) {
14534
15589
  return !!left && !!right && left.type === right.type && left.tag === right.tag && left.nesting === right.nesting && left.level === right.level && left.markup === right.markup && left.content === right.content && left.info === right.info && sameTokenMap(left, right) && sameTokenAttrs(left, right);
14535
15590
  }
14536
- function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, options, previousSeed) {
15591
+ function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, options, linkifyDemotionContexts, linkifyDemotionContextOffset = 0, fallbackLinkifyDemotionContext) {
14537
15592
  let groupStarts = groups.starts;
14538
15593
  if (groupStarts.length === 0 || nodes.length !== groupStarts.length) {
14539
15594
  runtime.structuredStream = void 0;
@@ -14546,7 +15601,7 @@ function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, opt
14546
15601
  lastToken: tokens[end - 1],
14547
15602
  tokenCount: end - start
14548
15603
  };
14549
- }), stableGroupCount = groups.mixed ? Math.max(0, groupStarts.length - 1) : sourceEndsWithBlankLine(source) ? groupStarts.length : Math.max(0, groupStarts.length - 1), seed = previousSeed && previousSeed.length >= stableGroupCount ? previousSeed.slice(0, stableGroupCount).concat(nodes.slice(stableGroupCount).map((node) => String(node.raw ?? ""))) : nodes.map((node) => String(node.raw ?? ""));
15604
+ }), stableGroupCount = groups.mixed ? Math.max(0, groupStarts.length - 1) : sourceEndsWithBlankLine(source) ? groupStarts.length : Math.max(0, groupStarts.length - 1), linkifyContextIndex = stableGroupCount - linkifyDemotionContextOffset - 1, linkifyDemotionContext = linkifyContextIndex >= 0 ? linkifyDemotionContexts?.[linkifyContextIndex] : fallbackLinkifyDemotionContext;
14550
15605
  runtime.structuredStream = {
14551
15606
  groupBoundaries,
14552
15607
  groupStarts,
@@ -14555,7 +15610,7 @@ function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, opt
14555
15610
  mixed: groups.mixed,
14556
15611
  source,
14557
15612
  nodes,
14558
- seed,
15613
+ linkifyDemotionContext,
14559
15614
  stableGroupCount,
14560
15615
  requireClosingStrong: options.requireClosingStrong,
14561
15616
  validateLink: options.validateLink
@@ -14592,18 +15647,18 @@ function processTopLevelTokensWithReuse(runtime, source, tokens, options, callba
14592
15647
  if (!groups)
14593
15648
  return runtime.structuredStream = void 0, callbacks.processTokens(tokens, options);
14594
15649
  let groupStarts = groups.starts, stableGroupCount = previous && groups.mixed ? Math.min(previous.stableGroupCount, Math.max(0, previous.groupBoundaries.length - 1)) : previous?.stableGroupCount ?? 0;
14595
- if (previous && stableGroupCount > 0 && previous.requireClosingStrong === options.requireClosingStrong && previous.validateLink === options.validateLink && source.startsWith(previous.source) && groupStarts.length >= stableGroupCount && (mode === "append" || mode === "tail") && hasStableStructuredStreamGroupBoundaries(previous, tokens, groupStarts, stableGroupCount)) {
14596
- let tailStart = groupStarts[stableGroupCount] ?? tokens.length, tailNodes = callbacks.processTokens(tokens.slice(tailStart), {
15650
+ if (previous && stableGroupCount > 0 && previous.requireClosingStrong === options.requireClosingStrong && previous.validateLink === options.validateLink && runtime.sourceExtends(previous.source, source) && groupStarts.length >= stableGroupCount && (mode === "append" || mode === "tail") && hasStableStructuredStreamGroupBoundaries(previous, tokens, groupStarts, stableGroupCount)) {
15651
+ let tailStart = groupStarts[stableGroupCount] ?? tokens.length, tailOptions = {
14597
15652
  ...options,
14598
- linkifyDemotionSeed: previous.seed.slice(0, stableGroupCount)
14599
- }), expectedTailNodes = groupStarts.length - stableGroupCount;
15653
+ linkifyDemotionSeedContext: previous.linkifyDemotionContext
15654
+ }, tailNodes = callbacks.processTokens(tokens.slice(tailStart), tailOptions), expectedTailNodes = groupStarts.length - stableGroupCount;
14600
15655
  if (tailNodes.length === expectedTailNodes) {
14601
15656
  let result$1 = previous.nodes.slice(0, stableGroupCount).concat(tailNodes);
14602
- return runtime.structuredReuseTailStart = stableGroupCount, callbacks.recordReusedTopLevelNodes?.(stableGroupCount), updateStructuredStreamCache(runtime, source, tokens, groups, result$1, options, previous.seed), result$1;
15657
+ return runtime.structuredReuseTailStart = stableGroupCount, callbacks.recordReusedTopLevelNodes?.(stableGroupCount), updateStructuredStreamCache(runtime, source, tokens, groups, result$1, options, tailOptions.linkifyDemotionResultContexts, stableGroupCount, previous.linkifyDemotionContext), result$1;
14603
15658
  }
14604
15659
  }
14605
15660
  let result = callbacks.processTokens(tokens, options);
14606
- return updateStructuredStreamCache(runtime, source, tokens, groups, result, options), result;
15661
+ return updateStructuredStreamCache(runtime, source, tokens, groups, result, options, options.linkifyDemotionResultContexts), result;
14607
15662
  }
14608
15663
  function isDetailsOpenHtmlBlock(node) {
14609
15664
  if (node.type !== "html_block" || String(node.tag ?? "").toLowerCase() !== "details")
@@ -14688,7 +15743,7 @@ function parseSiblingHtmlBlockChildren(blocks, context, options, final, useCache
14688
15743
  validateLink: options.validateLink
14689
15744
  }), children.flat();
14690
15745
  }
14691
- function structureGenericHtmlBlockChildren(nodes, context, options, final, tailStart = 0) {
15746
+ function structureGenericHtmlBlockChildren(nodes, context, options, final) {
14692
15747
  let processNode = (node) => {
14693
15748
  if (node?.type !== "html_block")
14694
15749
  return node;
@@ -14705,12 +15760,9 @@ function structureGenericHtmlBlockChildren(nodes, context, options, final, tailS
14705
15760
  if (!innerRaw.trim() || !hasStructuredHtmlWrapperMarkers(innerRaw))
14706
15761
  return node;
14707
15762
  let childOptions = buildDetailsChildParseOptions(options, final), siblingHtmlBlocks = hasClose ? null : splitSiblingHtmlBlockFragments(innerRaw), useSiblingCache = !options.isFragment && typeof options.preTransformTokens != "function" && typeof options.postTransformTokens != "function" && typeof options.postTransformNodes != "function" && context.markdownIt.__markstreamHasCustomParserExtensions === !1 && isCacheStableLinkValidator(options.validateLink), children = siblingHtmlBlocks ? parseSiblingHtmlBlockChildren(siblingHtmlBlocks, context, childOptions, final, useSiblingCache) : parseDetailsFragmentChildren(innerRaw, context, childOptions);
14708
- return shouldStructureGenericHtmlBlockChildren(children) ? {
14709
- ...node,
14710
- children
14711
- } : node;
15763
+ return shouldStructureGenericHtmlBlockChildren(children) && (fields.children = children), node;
14712
15764
  };
14713
- return tailStart <= 0 ? nodes.map(processNode) : nodes.slice(0, tailStart).concat(nodes.slice(tailStart).map(processNode));
15765
+ return nodes.map(processNode);
14714
15766
  }
14715
15767
  function hasTopLevelHtmlBlock(nodes, start = 0) {
14716
15768
  for (let i = start; i < nodes.length; i++)
@@ -14821,12 +15873,18 @@ function combineStructuredDetailsHtmlBlocks(nodes, source, context, options, fin
14821
15873
  }
14822
15874
  return [merged, cursor];
14823
15875
  }
14824
- function mergeSplitTopLevelHtmlBlocks(nodes, final, source, context, options) {
15876
+ function findNodeRawPosition(node, nodeRaw, source, cursor, context) {
15877
+ if (!nodeRaw)
15878
+ return -1;
15879
+ let anchor = context.getInternalNodeSourceRange(node)?.start ?? -1, anchored = anchor >= cursor && source.startsWith(nodeRaw, anchor);
15880
+ return node?.type === "html_block" ? anchored && anchor === cursor ? anchor : source.indexOf(nodeRaw, cursor) : anchor < 0 ? source.indexOf(nodeRaw, cursor) : anchored ? anchor : -1;
15881
+ }
15882
+ function mergeSplitTopLevelHtmlBlocks(nodes, final, source, context, options, initialSourceCursor = 0) {
14825
15883
  if (!source)
14826
15884
  return nodes;
14827
- let merged = nodes.slice(), sourceHtmlCursor = 0;
15885
+ let merged = nodes.slice(), sourceHtmlCursor = initialSourceCursor;
14828
15886
  for (let i = 0; i < merged.length; i++) {
14829
- let node = merged[i], nodeRaw = getMergeableNodeRaw(node), nodePos = nodeRaw ? source.indexOf(nodeRaw, sourceHtmlCursor) : -1;
15887
+ let node = merged[i], nodeRaw = getMergeableNodeRaw(node), nodePos = findNodeRawPosition(node, nodeRaw, source, sourceHtmlCursor, context);
14830
15888
  if (node?.type !== "html_block") {
14831
15889
  nodePos !== -1 && (sourceHtmlCursor = nodePos + nodeRaw.length);
14832
15890
  continue;
@@ -14934,7 +15992,7 @@ function parseEmphasisToken(tokens, startIndex, parseInlineTokens$1, options) {
14934
15992
  };
14935
15993
  }
14936
15994
  function TRAILING_OWN_FENCE_CANDIDATE_LINE_RE(marker) {
14937
- return /* @__PURE__ */ new RegExp(`(?:^|\\r\\n|\\n|\\r) {0,3}${marker}+[ \\t]*$`);
15995
+ return getCachedRegex(`(?:^|\\r\\n|\\n|\\r) {0,3}${marker}+[ \\t]*$`);
14938
15996
  }
14939
15997
  var DIFF_HEADER_PREFIXES = [
14940
15998
  "diff ",
@@ -15216,7 +16274,8 @@ function parseHtmlInlineCodeToken(token, tokens, i, parseInlineTokens$1, raw, pP
15216
16274
  attrs: normalizedAttrs,
15217
16275
  children: normalizedChildren$1,
15218
16276
  loading: !fragment$1.closed,
15219
- raw: fragment$1.html || code$1
16277
+ raw: fragment$1.html || code$1,
16278
+ markup: "html"
15220
16279
  }, fragment$1.nextIndex];
15221
16280
  }
15222
16281
  if (selfClosing)
@@ -15367,7 +16426,8 @@ function parseLinkToken(tokens, startIndex, parseInlineTokens$1, options) {
15367
16426
  children,
15368
16427
  raw: `[${linkText}](${href}${title ? ` "${title}"` : ""})`,
15369
16428
  loading,
15370
- attrs: normalizedAttrs
16429
+ attrs: normalizedAttrs,
16430
+ markup: resolveLinkMarkup(openToken)
15371
16431
  },
15372
16432
  nextIndex: i < tokens.length ? i + 1 : tokens.length
15373
16433
  };
@@ -15597,7 +16657,8 @@ function recoverMarkdownLinkFromTrailingText(state, token) {
15597
16657
  content: label,
15598
16658
  raw: label
15599
16659
  }],
15600
- raw: `[${label}](${href}${linkToken.title ? ` "${linkToken.title}"` : ""})`
16660
+ raw: `[${label}](${href}${linkToken.title ? ` "${linkToken.title}"` : ""})`,
16661
+ markup: resolveLinkMarkup(token)
15601
16662
  }), !0;
15602
16663
  }
15603
16664
  function recoverMarkdownImageFromLoadingImageTail(state, token) {
@@ -15660,7 +16721,8 @@ function buildLoadingOuterImageLinkNode(imageNode, href = "", title = null) {
15660
16721
  text: text$1,
15661
16722
  children: [imageNode],
15662
16723
  raw: `[${text$1}](${href}${title ? ` "${title}"` : ""})`,
15663
- loading: !0
16724
+ loading: !0,
16725
+ markup: ""
15664
16726
  };
15665
16727
  }
15666
16728
  function buildLoadingImageNodeFromRaw(raw) {
@@ -15784,7 +16846,8 @@ function handleInlineLinkContent(state, content, _token) {
15784
16846
  content: text$1,
15785
16847
  raw: text$1
15786
16848
  }],
15787
- loading: loading$1
16849
+ loading: loading$1,
16850
+ markup: ""
15788
16851
  }), state.index += index, !0;
15789
16852
  }
15790
16853
  let linkContentEnd = content.indexOf(")", linkEnd), href = linkContentEnd !== -1 ? content.slice(linkEnd + 2, linkContentEnd) : "", loading = linkContentEnd === -1, emphasisMatch = textNodeContent.match(/\*+$/);
@@ -15818,7 +16881,8 @@ function handleInlineLinkContent(state, content, _token) {
15818
16881
  content: text$1,
15819
16882
  raw: text$1
15820
16883
  }],
15821
- loading
16884
+ loading,
16885
+ markup: ""
15822
16886
  }), type === 1) {
15823
16887
  newTokens.push({
15824
16888
  type: "em_close",
@@ -15862,7 +16926,8 @@ function handleInlineLinkContent(state, content, _token) {
15862
16926
  content: text$1,
15863
16927
  raw: text$1
15864
16928
  }],
15865
- loading
16929
+ loading,
16930
+ markup: ""
15866
16931
  });
15867
16932
  let afterText = linkContentEnd !== -1 ? content.slice(linkContentEnd + 1) : "";
15868
16933
  return afterText && (state.dispatchToken({
@@ -16473,7 +17538,7 @@ function handleTextToken(state, token) {
16473
17538
  }
16474
17539
  trailingTextStart < state.result.length && (content.startsWith(trailingTextContent) ? (state.currentTextNode = null, state.result.length = trailingTextStart) : state.currentTextNode = state.result[state.result.length - 1]);
16475
17540
  let nextToken = state.tokens[state.index + 1];
16476
- if ((content === "`" || content === "|" || content === "$") && !hasEscapedMarkup(token, `\\${content}`) || /^\*+$/.test(content) && !hasEscapedMarkup(token, "\\*")) {
17541
+ if (state.options?.final !== !0 && ((content === "`" || content === "|" || content === "$") && !hasEscapedMarkup(token, `\\${content}`) || /^\*+$/.test(content) && !hasEscapedMarkup(token, "\\*"))) {
16477
17542
  state.index++;
16478
17543
  return;
16479
17544
  }
@@ -16673,9 +17738,20 @@ function dispatchInlineToken(state, token) {
16673
17738
  function handleReference(state, token) {
16674
17739
  state.resetCurrentTextNode(), state.pushParsed(parseReferenceToken(token)), state.index++;
16675
17740
  }
17741
+ var TEXT_RECOVERY_MARKER_RE = /[!$(*[\\\]_`|~]/;
16676
17742
  function parseInlineTokens(tokens, raw, pPreToken, options) {
16677
17743
  if (!tokens || tokens.length === 0)
16678
17744
  return [];
17745
+ if (tokens.length === 1 && tokens[0].type === "text") {
17746
+ let content = tokens[0].content;
17747
+ if (typeof content == "string" && content && content !== "<" && !content.endsWith("undefined") && !TEXT_RECOVERY_MARKER_RE.test(content))
17748
+ return [{
17749
+ type: "text",
17750
+ content,
17751
+ raw: content,
17752
+ center: !1
17753
+ }];
17754
+ }
16679
17755
  let parseContext = ensureParseContext(options), inheritedContext = parseContext.linkifyDemotionContext, inferredContext = inferLinkifyDemotionContext(raw), linkifyDemotionContext = {
16680
17756
  filename: inheritedContext?.filename || inferredContext.filename,
16681
17757
  explicitFilename: inheritedContext?.explicitFilename || inferredContext.explicitFilename,
@@ -16714,7 +17790,7 @@ function parseInlineTokens(tokens, raw, pPreToken, options) {
16714
17790
  function pushToken(token) {
16715
17791
  resetCurrentTextNode();
16716
17792
  let node = cloneTokenWithMutableChildren(token);
16717
- state.result.push(node);
17793
+ node.type === "link" && (node.markup = resolveLinkMarkup(token)), state.result.push(node);
16718
17794
  }
16719
17795
  function pushText(content, raw$1) {
16720
17796
  state.currentTextNode ? (state.currentTextNode.content += content, state.currentTextNode.raw += raw$1 ?? content) : (state.currentTextNode = {
@@ -17463,7 +18539,7 @@ function parseBasicBlockToken(tokens, index, options, parseInlineTokens$1) {
17463
18539
  return includeSourceMap && applyNodeSourceMap(paragraphNode, token, options), [paragraphNode, index + 1];
17464
18540
  }
17465
18541
  if (htmlBlockNode.tag && tagSets?.customTagSet?.has(htmlBlockNode.tag)) {
17466
- let tag = htmlBlockNode.tag, context = isParseContext(options) ? options : void 0, source = String(context?.sourceMarkdown ?? ""), cursor = Number(context?.customHtmlBlockCursor ?? 0), mappedLineStart = Array.isArray(token.map) ? lineToIndex(source, Number(token.map?.[0] ?? 0)) : 0, fromSource = findNextCustomHtmlBlockFromSource(source, tag, Math.max(clampNonNegative(cursor), clampNonNegative(mappedLineStart)));
18542
+ let tag = htmlBlockNode.tag, context = isParseContext(options) ? options : void 0, source = String(context?.sourceMarkdown ?? ""), cursor = Number(context?.customHtmlBlockCursor ?? 0), mappedLine = Number(token.map?.[0] ?? 0), mappedLineStart = Array.isArray(token.map) ? context?.sourceLineOffsets?.[mappedLine] ?? lineToIndex(source, mappedLine) : 0, fromSource = findNextCustomHtmlBlockFromSource(source, tag, Math.max(clampNonNegative(cursor), clampNonNegative(mappedLineStart)));
17467
18543
  fromSource && context && (context.customHtmlBlockCursor = fromSource.end);
17468
18544
  let rawHtml = String(fromSource?.raw ?? htmlBlockNode.raw ?? ""), openEnd = findTagCloseIndexOutsideQuotes(rawHtml), openTag = openEnd !== -1 ? rawHtml.slice(0, openEnd + 1) : rawHtml, selfClosing = openEnd !== -1 && /\/\s*>\s*$/.test(openTag), closeRange = openEnd === -1 ? null : findMatchingCloseTagRange(rawHtml, tag, openEnd + 1), closeIndex = closeRange?.start ?? -1, inner = "";
17469
18545
  openEnd !== -1 && (closeIndex !== -1 && openEnd < closeIndex ? inner = rawHtml.slice(openEnd + 1, closeIndex) : inner = rawHtml.slice(openEnd + 1)), closeIndex === -1 && (inner = stripTrailingPartialClosingTag(inner, tag));
@@ -17643,15 +18719,11 @@ function maybePromoteCustomNodeFromParagraph(node, options) {
17643
18719
  function processTokensWithContext(tokens, options, parseInlineTokens$1) {
17644
18720
  if (!tokens || !Array.isArray(tokens))
17645
18721
  return [];
17646
- let result = [], linkifyContext = createLinkifyDemotionContextTracker(options), seedRaws = options.linkifyDemotionSeed;
17647
- if (Array.isArray(seedRaws) && seedRaws.length)
17648
- for (let raw of seedRaws)
17649
- linkifyContext.remember(String(raw ?? ""));
17650
- let includeSourceMap = options?.includeSourceMap === !0, i = 0;
18722
+ let result = [], resultContexts = [], linkifyContext = createLinkifyDemotionContextTracker(options), includeSourceMap = options?.includeSourceMap === !0, i = 0;
17651
18723
  for (; i < tokens.length; ) {
17652
18724
  let handled = parseCommonBlockToken(tokens, i, linkifyContext.options(), containerTokenHandlers, parseInlineTokens$1);
17653
18725
  if (handled) {
17654
- recordInternalNodeSourceRange(handled[0], tokens[i], options), result.push(handled[0]), linkifyContext.remember(handled[0].raw), i = handled[1];
18726
+ recordInternalNodeSourceRange(handled[0], tokens[i], options), result.push(handled[0]), linkifyContext.remember(handled[0].raw), resultContexts.push(linkifyContext.snapshot()), i = handled[1];
17655
18727
  continue;
17656
18728
  }
17657
18729
  let token = tokens[i];
@@ -17741,42 +18813,52 @@ function processTokensWithContext(tokens, options, parseInlineTokens$1) {
17741
18813
  i += 1;
17742
18814
  break;
17743
18815
  }
18816
+ let context = linkifyContext.snapshot();
18817
+ for (; resultContexts.length < result.length; )
18818
+ resultContexts.push(context);
17744
18819
  }
17745
- return result;
18820
+ return options.linkifyDemotionResultContexts = resultContexts, result;
17746
18821
  }
17747
18822
  function getCachedSourceLineOffsets(runtime, source) {
17748
18823
  let cached = runtime.sourceLineOffsets;
17749
- if (cached && cached.source === source)
18824
+ if (cached?.source === source)
17750
18825
  return cached.offsets;
17751
- if (cached && source.length > cached.source.length && source.startsWith(cached.source)) {
18826
+ if (cached && source.length > cached.source.length && runtime.sourceExtends(cached.source, source)) {
17752
18827
  let offsets$1 = cached.offsets;
17753
18828
  for (let i = cached.source.length; i < source.length; i++)
17754
18829
  source.charCodeAt(i) === 10 && offsets$1.push(i + 1);
17755
18830
  return cached.source = source, offsets$1;
17756
18831
  }
17757
- let offsets = [0];
17758
- for (let i = 0; i < source.length; i++)
17759
- source.charCodeAt(i) === 10 && offsets.push(i + 1);
18832
+ let offsets = computeSourceLineOffsets(source);
17760
18833
  return runtime.sourceLineOffsets = {
17761
18834
  source,
17762
18835
  offsets
17763
18836
  }, offsets;
17764
18837
  }
18838
+ function computeSourceLineOffsets(source) {
18839
+ let offsets = [0];
18840
+ for (let i = 0; i < source.length; i++)
18841
+ source.charCodeAt(i) === 10 && offsets.push(i + 1);
18842
+ return offsets;
18843
+ }
17765
18844
  var parserRuntimes = /* @__PURE__ */ new WeakMap(), wrappedMarkdownItInstances = /* @__PURE__ */ new WeakSet(), wrappedStreamInstances = /* @__PURE__ */ new WeakSet();
17766
18845
  function sameSemantics(left, right) {
17767
18846
  return left.customHtmlTags === right.customHtmlTags && left.hasCustomParserExtensions === right.hasCustomParserExtensions && left.includeSourceMap === right.includeSourceMap && left.postTransformNodes === right.postTransformNodes && left.postTransformTokens === right.postTransformTokens && left.preTransformTokens === right.preTransformTokens && left.requireClosingStrong === right.requireClosingStrong && left.reuseStableTopLevelNodes === right.reuseStableTopLevelNodes && left.streamParse === right.streamParse && left.validateLink === right.validateLink;
17768
18847
  }
17769
18848
  var ParserRuntime = class {
17770
18849
  constructor(markdownIt$1) {
17771
- this.streamParseEnvs = /* @__PURE__ */ new Map(), this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.finalized = !1, this.resettingStream = !1, this.streamStateActive = !1, this.streamResetInCurrentRootParse = !1, this.markdownIt = markdownIt$1;
18850
+ this.streamParseEnvs = /* @__PURE__ */ new Map(), this.htmlPassIdentityPreserving = !1, this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.finalized = !1, this.resettingStream = !1, this.streamStateActive = !1, this.streamResetInCurrentRootParse = !1, this.markdownIt = markdownIt$1;
18851
+ }
18852
+ sourceExtends(previousSource, currentSource) {
18853
+ return this.sourceRelationPrevious === previousSource && this.sourceRelationCurrent === currentSource ? !0 : currentSource.startsWith(previousSource) ? (this.sourceRelationPrevious = previousSource, this.sourceRelationCurrent = currentSource, !0) : !1;
17772
18854
  }
17773
18855
  beginRootParse(source, semantics) {
17774
18856
  this.streamResetInCurrentRootParse = !1;
17775
- let sourceChangedNonAppend = this.documentSource !== void 0 && source !== this.documentSource && !source.startsWith(this.documentSource), semanticsChanged = this.semantics !== void 0 && !sameSemantics(this.semantics, semantics);
18857
+ let sourceChangedNonAppend = this.documentSource !== void 0 && source !== this.documentSource && !this.sourceExtends(this.documentSource, source), semanticsChanged = this.semantics !== void 0 && !sameSemantics(this.semantics, semantics);
17776
18858
  (this.finalized || sourceChangedNonAppend || semanticsChanged) && this.resetDocument(this.streamStateActive), this.finalized = !1, this.documentSource = source, this.semantics = semantics;
17777
18859
  }
17778
18860
  finishRootParse(final) {
17779
- final && (this.clearDocumentCaches(), this.documentSource = void 0, this.semantics = void 0, this.finalized = !0);
18861
+ this.sourceRelationPrevious = void 0, this.sourceRelationCurrent = void 0, final && (this.clearDocumentCaches(), this.documentSource = void 0, this.semantics = void 0, this.finalized = !0);
17780
18862
  }
17781
18863
  resetForFinalAutoParse() {
17782
18864
  this.streamResetInCurrentRootParse || this.resetStreamOnly(), this.clearDocumentCaches();
@@ -17811,7 +18893,7 @@ var ParserRuntime = class {
17811
18893
  this.resetDocument(!0), parserRuntimes.delete(this.markdownIt);
17812
18894
  }
17813
18895
  clearDocumentCaches() {
17814
- this.safeMarkdown = void 0, this.tolerantMathBoundary = void 0, this.pendingExplicitMathTail = void 0, this.streamParseEnvs.clear(), this.topLevelStreamParseMode = void 0, this.structuredStream = void 0, this.siblingHtmlChildren = void 0, this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.sourceLineOffsets = void 0;
18896
+ this.safeMarkdown = void 0, this.tolerantMathBoundary = void 0, this.pendingExplicitMathTail = void 0, this.streamParseEnvs.clear(), this.topLevelStreamParseMode = void 0, this.structuredStream = void 0, this.htmlPassIdentityPreserving = !1, this.siblingHtmlChildren = void 0, this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.sourceLineOffsets = void 0, this.sourceRelationPrevious = void 0, this.sourceRelationCurrent = void 0;
17815
18897
  }
17816
18898
  };
17817
18899
  function wrapMarkdownItBoundaries(md) {
@@ -17950,6 +19032,11 @@ function createSourceLineMapper(source, parsedSource) {
17950
19032
  };
17951
19033
  };
17952
19034
  }
19035
+ var closingTagBlankLineReCache = /* @__PURE__ */ new Map();
19036
+ function getClosingTagBlankLineRe(tag) {
19037
+ let re = closingTagBlankLineReCache.get(tag);
19038
+ return re || (re = new RegExp(String.raw`(^[\t ]*<\s*\/\s*${tag}\s*>[\t ]*)(\r?\n)(?![\t ]*\r?\n|$)`, "gim"), closingTagBlankLineReCache.size >= 64 && closingTagBlankLineReCache.clear(), closingTagBlankLineReCache.set(tag, re)), re;
19039
+ }
17953
19040
  function stripDanglingHtmlLikeTail(markdown) {
17954
19041
  let isWs = (ch) => ch === " " || ch === " " || ch === `
17955
19042
  ` || ch === "\r", isLikelyHtmlTagPrefix = (tail$1) => {
@@ -18010,8 +19097,8 @@ function stripDanglingHtmlLikeTail(markdown) {
18010
19097
  }
18011
19098
  }
18012
19099
  return !0;
18013
- }, isInsideFencedCodeBlock = (src, pos) => isInsideOpenMarkdownFenceBeforeOffset(src, pos), s = String(markdown ?? ""), lastLt = s.lastIndexOf("<");
18014
- if (lastLt === -1 || isInsideFencedCodeBlock(s, lastLt))
19100
+ }, s = String(markdown ?? ""), lastLt = s.lastIndexOf("<");
19101
+ if (lastLt === -1)
18015
19102
  return s;
18016
19103
  if (lastLt > 0) {
18017
19104
  let prev = s[lastLt - 1], prevIsWs = prev === " " || prev === " " || prev === `
@@ -18021,7 +19108,7 @@ function stripDanglingHtmlLikeTail(markdown) {
18021
19108
  }
18022
19109
  let tail = s.slice(lastLt);
18023
19110
  return tail.includes(">") || tail.length > 1 && (tail[1] === " " || tail[1] === " " || tail[1] === `
18024
- ` || tail[1] === "\r") || !isLikelyHtmlTagPrefix(tail) ? s : s.slice(0, lastLt);
19111
+ ` || tail[1] === "\r") || !isLikelyHtmlTagPrefix(tail) || isInsideOpenMarkdownFenceBeforeOffset(s, lastLt) ? s : s.slice(0, lastLt);
18025
19112
  }
18026
19113
  function ensureBlankLineBeforeInlineMultilineCustomHtmlBlocks(markdown, tags) {
18027
19114
  if (!markdown || !tags.length)
@@ -18567,10 +19654,8 @@ function normalizeStreamingCustomHtmlSource(markdown, customHtmlTags, isFinal) {
18567
19654
  if (customHtmlTags?.length && safeMarkdown.includes("<")) {
18568
19655
  let tags = normalizeCustomHtmlTags(customHtmlTags);
18569
19656
  if (tags.length && (safeMarkdown = ensureBlankLineBeforeInlineMultilineCustomHtmlBlocks(safeMarkdown, tags), safeMarkdown = normalizeCustomHtmlOpeningTagSameLine(safeMarkdown, tags), safeMarkdown = ensureBlankLineBeforeCustomHtmlBlocks(safeMarkdown, tags), safeMarkdown = ensureBlankLineAfterCustomHtmlCloseBeforeBlockMarkerSameLine(safeMarkdown, tags), safeMarkdown.includes("</")))
18570
- for (let tag of tags) {
18571
- let re = new RegExp(String.raw`(^[\t ]*<\s*\/\s*${tag}\s*>[\t ]*)(\r?\n)(?![\t ]*\r?\n|$)`, "gim");
18572
- safeMarkdown = safeMarkdown.replace(re, "$1$2$2");
18573
- }
19657
+ for (let tag of tags)
19658
+ safeMarkdown = safeMarkdown.replace(getClosingTagBlankLineRe(tag), "$1$2$2");
18574
19659
  }
18575
19660
  return isFinal || (safeMarkdown = stripDanglingHtmlLikeTail(safeMarkdown)), safeMarkdown;
18576
19661
  }
@@ -18597,7 +19682,7 @@ function transformStreamingSafeMarkdown(source, isFinal, options) {
18597
19682
  }
18598
19683
  function getSafeMarkdown(runtime, sourceMarkdown, isFinal, options) {
18599
19684
  let mode = `${isFinal ? "final" : "stream"}:${(options.customHtmlTags ?? []).join(",")}`, previous = options.isFragment ? void 0 : runtime.safeMarkdown, safeMarkdown;
18600
- if (!isFinal && !options.customHtmlTags?.length && previous && previous.mode === mode && sourceMarkdown.length >= previous.source.length && sourceMarkdown.startsWith(previous.source)) {
19685
+ if (!isFinal && !options.customHtmlTags?.length && previous && previous.mode === mode && sourceMarkdown.length >= previous.source.length && runtime.sourceExtends(previous.source, sourceMarkdown)) {
18601
19686
  let windowStart = Math.max(0, previous.source.length - SAFE_MARKDOWN_WINDOW_MARGIN - SAFE_MARKDOWN_WINDOW_OVERLAP), transformed = transformStreamingSafeMarkdown(sourceMarkdown.slice(windowStart), isFinal, options), overlapLength = previous.source.length - windowStart;
18602
19687
  safeMarkdown = transformed.length >= overlapLength && transformed.slice(0, overlapLength) === previous.safeMarkdown.slice(-overlapLength) ? previous.safeMarkdown.slice(0, previous.safeMarkdown.length - overlapLength) + transformed : transformStreamingSafeMarkdown(sourceMarkdown, isFinal, options);
18603
19688
  } else
@@ -18668,7 +19753,7 @@ function parseMarkdownWithContext(markdown, inputContext) {
18668
19753
  ...options,
18669
19754
  sourceLineMapper: options.includeSourceMap === !0 ? createSourceLineMapper(sourceMarkdown, safeMarkdown) : void 0,
18670
19755
  sourceMarkdown: safeMarkdown,
18671
- sourceLineOffsets: getCachedSourceLineOffsets(runtime, safeMarkdown),
19756
+ sourceLineOffsets: options.isFragment ? computeSourceLineOffsets(safeMarkdown) : getCachedSourceLineOffsets(runtime, safeMarkdown),
18672
19757
  customHtmlBlockCursor: 0
18673
19758
  }, result = processTopLevelTokensWithReuse(runtime, safeMarkdown, transformedTokens, internalOptions, {
18674
19759
  processTokens: (nextTokens, nextOptions) => processTokensWithTiming(nextTokens, nextOptions, timing),
@@ -18690,9 +19775,18 @@ function parseMarkdownWithContext(markdown, inputContext) {
18690
19775
  getInternalNodeSourceRange: (node) => getInternalNodeSourceRange(node, runtime),
18691
19776
  markdownIt: md,
18692
19777
  parseFragment: (fragment, fragmentOptions) => parseMarkdownWithContext(fragment, fragmentOptions)
18693
- };
18694
- result = mergeSplitTopLevelHtmlBlocks(result, isFinal, safeMarkdown, htmlStructureContext, internalOptions), result = combineStructuredDetailsHtmlBlocks(result, safeMarkdown, htmlStructureContext, internalOptions, isFinal)[0], result = structureGenericHtmlBlockChildren(result, htmlStructureContext, internalOptions, isFinal, tailStart), timing && addTiming(timing, "htmlBlockPassesMs", getParserNow() - htmlPassesStartedAt);
18695
- }
19778
+ }, canReuseHtmlPrefix = tailStart > 0 && runtime.htmlPassIdentityPreserving, tailSourceStart = canReuseHtmlPrefix ? getInternalNodeSourceRange(result[tailStart], runtime)?.start : void 0, hasDetailsInput = !1;
19779
+ for (let i = canReuseHtmlPrefix ? tailStart : 0; i < result.length; i++) {
19780
+ let node = result[i];
19781
+ if (node.type === "html_block" && String(node.tag ?? "").toLowerCase() === "details") {
19782
+ hasDetailsInput = !0;
19783
+ break;
19784
+ }
19785
+ }
19786
+ let useHtmlTail = canReuseHtmlPrefix && !hasDetailsInput && tailSourceStart != null, prefix = useHtmlTail ? result.slice(0, tailStart) : [], htmlInput = useHtmlTail ? result.slice(tailStart) : result, htmlSourceStart = useHtmlTail ? tailSourceStart : 0, htmlResult = mergeSplitTopLevelHtmlBlocks(htmlInput, isFinal, safeMarkdown, htmlStructureContext, internalOptions, htmlSourceStart), mergeIdentityPreserving = htmlResult.length === htmlInput.length && htmlResult.every((node, index) => node === htmlInput[index]);
19787
+ hasDetailsInput && (htmlResult = combineStructuredDetailsHtmlBlocks(htmlResult, safeMarkdown, htmlStructureContext, internalOptions, isFinal, htmlSourceStart)[0]), htmlResult = structureGenericHtmlBlockChildren(htmlResult, htmlStructureContext, internalOptions, isFinal), result = useHtmlTail ? prefix.concat(htmlResult) : htmlResult, runtime.htmlPassIdentityPreserving = !hasDetailsInput && mergeIdentityPreserving, timing && addTiming(timing, "htmlBlockPassesMs", getParserNow() - htmlPassesStartedAt);
19788
+ } else
19789
+ runtime.htmlPassIdentityPreserving = !0;
18696
19790
  return isFinal && finalizeHtmlBlockLoading(result), result = applyPostTransformNodes(result, options), options.debug && console.log("Parsed Markdown Tree Structure:", result), finishTimedParse(result, timing, parseStartedAt);
18697
19791
  }
18698
19792
  function parseMarkdownToStructure(markdown, md, options = {}) {
@@ -18830,11 +19924,13 @@ function getMarkdown(msgId = `editor-${Date.now()}`, options = {}) {
18830
19924
  md.use(applyInlinePairs), md.use(sup_plugin), md.use(ins_plugin$1);
18831
19925
  let checkboxModule = import_markdown_it_task_checkbox, markdownItCheckboxPlugin = checkboxModule.default ?? checkboxModule;
18832
19926
  md.use(markdownItCheckboxPlugin), md.use(ins_plugin), md.use(footnote_plugin), md.core.ruler.after("block", "mark_fence_closed", (state) => {
18833
- let s = state, src = s.src, envFinal = !!s.env?.__markstreamFinal, lines = src.split(/\r?\n/);
19927
+ let s = state, src = s.src, envFinal = !!s.env?.__markstreamFinal, lines;
18834
19928
  for (let token of s.tokens) {
18835
19929
  if (token.type !== "fence" || !token.map || !token.markup)
18836
19930
  continue;
18837
- let openLine = token.map[0], endLine = token.map[1], markup = token.markup, marker = markup[0], minLen = markup.length, line = lines[Math.max(0, endLine - 1)] ?? "", i = 0;
19931
+ let openLine = token.map[0], endLine = token.map[1], markup = token.markup, marker = markup[0], minLen = markup.length, lineIdx = Math.max(0, endLine - 1);
19932
+ lines ?? (lines = src.split(/\r?\n/));
19933
+ let line = lines[lineIdx] ?? "", i = 0;
18838
19934
  for (; i < line.length && (line[i] === " " || line[i] === " "); )
18839
19935
  i++;
18840
19936
  let count = 0;
@@ -21777,7 +22873,11 @@ var TVirtualMarkdown = (0, import_vue10.defineComponent)({
21777
22873
  return withTextWidthProvider(
21778
22874
  widthProvider,
21779
22875
  () => terminalSelectionRowSpans(range, cols, rows.value.length).map((span) => {
21780
- let text2 = sliceByCellsRange(rows.value[span.y]?.plainText ?? "", span.x0, span.x1);
22876
+ let text2 = sliceByCellsRangeForSelection(
22877
+ rows.value[span.y]?.plainText ?? "",
22878
+ span.x0,
22879
+ span.x1
22880
+ );
21781
22881
  return span.x1 >= cols ? text2.trimEnd() : text2;
21782
22882
  }).join(`
21783
22883
  `)