svelte-streamdown 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +58 -0
  2. package/dist/Block.svelte +34 -0
  3. package/dist/Block.svelte.d.ts +6 -0
  4. package/dist/Elements/A.svelte +48 -0
  5. package/dist/Elements/A.svelte.d.ts +4 -0
  6. package/dist/Elements/Alert.svelte +78 -0
  7. package/dist/Elements/Alert.svelte.d.ts +4 -0
  8. package/dist/Elements/Blockquote.svelte +26 -0
  9. package/dist/Elements/Blockquote.svelte.d.ts +4 -0
  10. package/dist/Elements/Code.svelte +123 -0
  11. package/dist/Elements/Code.svelte.d.ts +4 -0
  12. package/dist/Elements/Del.svelte +24 -0
  13. package/dist/Elements/Del.svelte.d.ts +4 -0
  14. package/dist/Elements/Element.svelte +122 -0
  15. package/dist/Elements/Element.svelte.d.ts +12 -0
  16. package/dist/Elements/Em.svelte +23 -0
  17. package/dist/Elements/Em.svelte.d.ts +4 -0
  18. package/dist/Elements/H1.svelte +23 -0
  19. package/dist/Elements/H1.svelte.d.ts +4 -0
  20. package/dist/Elements/H2.svelte +23 -0
  21. package/dist/Elements/H2.svelte.d.ts +4 -0
  22. package/dist/Elements/H3.svelte +23 -0
  23. package/dist/Elements/H3.svelte.d.ts +4 -0
  24. package/dist/Elements/H4.svelte +23 -0
  25. package/dist/Elements/H4.svelte.d.ts +4 -0
  26. package/dist/Elements/H5.svelte +23 -0
  27. package/dist/Elements/H5.svelte.d.ts +4 -0
  28. package/dist/Elements/H6.svelte +23 -0
  29. package/dist/Elements/H6.svelte.d.ts +4 -0
  30. package/dist/Elements/Hr.svelte +20 -0
  31. package/dist/Elements/Hr.svelte.d.ts +4 -0
  32. package/dist/Elements/Image.svelte +49 -0
  33. package/dist/Elements/Image.svelte.d.ts +4 -0
  34. package/dist/Elements/InlineCode.svelte +23 -0
  35. package/dist/Elements/InlineCode.svelte.d.ts +4 -0
  36. package/dist/Elements/Li.svelte +23 -0
  37. package/dist/Elements/Li.svelte.d.ts +4 -0
  38. package/dist/Elements/Math.svelte +73 -0
  39. package/dist/Elements/Math.svelte.d.ts +5 -0
  40. package/dist/Elements/Mermaid.svelte +80 -0
  41. package/dist/Elements/Mermaid.svelte.d.ts +4 -0
  42. package/dist/Elements/Ol.svelte +23 -0
  43. package/dist/Elements/Ol.svelte.d.ts +4 -0
  44. package/dist/Elements/P.svelte +23 -0
  45. package/dist/Elements/P.svelte.d.ts +4 -0
  46. package/dist/Elements/Slot.svelte +19 -0
  47. package/dist/Elements/Slot.svelte.d.ts +9 -0
  48. package/dist/Elements/Strong.svelte +23 -0
  49. package/dist/Elements/Strong.svelte.d.ts +4 -0
  50. package/dist/Elements/Sub.svelte +23 -0
  51. package/dist/Elements/Sub.svelte.d.ts +4 -0
  52. package/dist/Elements/Sup.svelte +23 -0
  53. package/dist/Elements/Sup.svelte.d.ts +4 -0
  54. package/dist/Elements/Table.svelte +25 -0
  55. package/dist/Elements/Table.svelte.d.ts +4 -0
  56. package/dist/Elements/Tbody.svelte +23 -0
  57. package/dist/Elements/Tbody.svelte.d.ts +4 -0
  58. package/dist/Elements/Td.svelte +23 -0
  59. package/dist/Elements/Td.svelte.d.ts +4 -0
  60. package/dist/Elements/Th.svelte +23 -0
  61. package/dist/Elements/Th.svelte.d.ts +4 -0
  62. package/dist/Elements/Thead.svelte +23 -0
  63. package/dist/Elements/Thead.svelte.d.ts +4 -0
  64. package/dist/Elements/Tr.svelte +23 -0
  65. package/dist/Elements/Tr.svelte.d.ts +4 -0
  66. package/dist/Elements/Ul.svelte +23 -0
  67. package/dist/Elements/Ul.svelte.d.ts +4 -0
  68. package/dist/Elements/element.d.ts +8 -0
  69. package/dist/Elements/element.js +1 -0
  70. package/dist/Elements/index.d.ts +34 -0
  71. package/dist/Elements/index.js +34 -0
  72. package/dist/Streamdown.d.ts +83 -0
  73. package/dist/Streamdown.js +1 -0
  74. package/dist/Streamdown.svelte +128 -0
  75. package/dist/Streamdown.svelte.d.ts +18 -0
  76. package/dist/hightlighter.svelte.d.ts +25 -0
  77. package/dist/hightlighter.svelte.js +413 -0
  78. package/dist/index.d.ts +2 -0
  79. package/dist/index.js +2 -0
  80. package/dist/theme.d.ts +247 -0
  81. package/dist/theme.js +138 -0
  82. package/dist/utils/alerts.d.ts +12 -0
  83. package/dist/utils/alerts.js +207 -0
  84. package/dist/utils/bind.d.ts +1 -0
  85. package/dist/utils/bind.js +6 -0
  86. package/dist/utils/copy.svelte.d.ts +7 -0
  87. package/dist/utils/copy.svelte.js +35 -0
  88. package/dist/utils/parse-blocks.d.ts +1 -0
  89. package/dist/utils/parse-blocks.js +40 -0
  90. package/dist/utils/parse-incomplete-markdown.d.ts +1 -0
  91. package/dist/utils/parse-incomplete-markdown.js +442 -0
  92. package/dist/utils/parse.d.ts +3 -0
  93. package/dist/utils/parse.js +144 -0
  94. package/dist/utils/save.d.ts +1 -0
  95. package/dist/utils/save.js +11 -0
  96. package/dist/utils/url.d.ts +2 -0
  97. package/dist/utils/url.js +71 -0
  98. package/package.json +92 -0
@@ -0,0 +1,442 @@
1
+ const linkImagePattern = /(!?\[)([^\]]*?)$/;
2
+ const boldPattern = /(\*\*)([^*]*?)$/;
3
+ const italicPattern = /(__)([^_]*?)$/;
4
+ const boldItalicPattern = /(\*\*\*)([^*]*?)$/;
5
+ const singleAsteriskPattern = /(\*)([^*]*?)$/;
6
+ const singleUnderscorePattern = /(_)([^_]*?)$/;
7
+ const inlineCodePattern = /(`)([^`]*?)$/;
8
+ const strikethroughPattern = /(~~)([^~]*?)$/;
9
+ // Helper function to check if we have a complete code block
10
+ const hasCompleteCodeBlock = (text) => {
11
+ const tripleBackticks = (text.match(/```/g) || []).length;
12
+ return tripleBackticks > 0 && tripleBackticks % 2 === 0 && text.includes('\n');
13
+ };
14
+ // Handles incomplete links and images by preserving them with a special marker
15
+ const handleIncompleteLinksAndImages = (text) => {
16
+ const linkMatch = text.match(linkImagePattern);
17
+ if (linkMatch) {
18
+ const isImage = linkMatch[1].startsWith('!');
19
+ // For images, we still remove them as they can't show skeleton
20
+ if (isImage) {
21
+ const startIndex = text.lastIndexOf(linkMatch[1]);
22
+ return text.substring(0, startIndex);
23
+ }
24
+ // For links, preserve the text and close the link with a
25
+ // special placeholder URL that indicates it's incomplete
26
+ return `${text}](streamdown:incomplete-link)`;
27
+ }
28
+ return text;
29
+ };
30
+ // Completes incomplete bold formatting (**)
31
+ const handleIncompleteBold = (text) => {
32
+ // Don't process if inside a complete code block
33
+ if (hasCompleteCodeBlock(text)) {
34
+ return text;
35
+ }
36
+ const boldMatch = text.match(boldPattern);
37
+ if (boldMatch) {
38
+ // Don't close if there's no meaningful content after the opening markers
39
+ // boldMatch[2] contains the content after **
40
+ // Check if content is only whitespace or other emphasis markers
41
+ const contentAfterMarker = boldMatch[2];
42
+ if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) {
43
+ return text;
44
+ }
45
+ // Check if the bold marker is in a list item context
46
+ // Find the position of the matched bold marker
47
+ const markerIndex = text.lastIndexOf(boldMatch[1]);
48
+ const beforeMarker = text.substring(0, markerIndex);
49
+ const lastNewlineBeforeMarker = beforeMarker.lastIndexOf('\n');
50
+ const lineStart = lastNewlineBeforeMarker === -1 ? 0 : lastNewlineBeforeMarker + 1;
51
+ const lineBeforeMarker = text.substring(lineStart, markerIndex);
52
+ // Check if this line is a list item with just the bold marker
53
+ if (/^[\s]*[-*+][\s]+$/.test(lineBeforeMarker)) {
54
+ // This is a list item with just emphasis markers
55
+ // Check if content after marker spans multiple lines
56
+ const hasNewlineInContent = contentAfterMarker.includes('\n');
57
+ if (hasNewlineInContent) {
58
+ // Don't complete if the content spans to another line
59
+ return text;
60
+ }
61
+ }
62
+ const asteriskPairs = (text.match(/\*\*/g) || []).length;
63
+ if (asteriskPairs % 2 === 1) {
64
+ return `${text}**`;
65
+ }
66
+ }
67
+ return text;
68
+ };
69
+ // Completes incomplete italic formatting with double underscores (__)
70
+ const handleIncompleteDoubleUnderscoreItalic = (text) => {
71
+ const italicMatch = text.match(italicPattern);
72
+ if (italicMatch) {
73
+ // Don't close if there's no meaningful content after the opening markers
74
+ // italicMatch[2] contains the content after __
75
+ // Check if content is only whitespace or other emphasis markers
76
+ const contentAfterMarker = italicMatch[2];
77
+ if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) {
78
+ return text;
79
+ }
80
+ // Check if the underscore marker is in a list item context
81
+ // Find the position of the matched underscore marker
82
+ const markerIndex = text.lastIndexOf(italicMatch[1]);
83
+ const beforeMarker = text.substring(0, markerIndex);
84
+ const lastNewlineBeforeMarker = beforeMarker.lastIndexOf('\n');
85
+ const lineStart = lastNewlineBeforeMarker === -1 ? 0 : lastNewlineBeforeMarker + 1;
86
+ const lineBeforeMarker = text.substring(lineStart, markerIndex);
87
+ // Check if this line is a list item with just the underscore marker
88
+ if (/^[\s]*[-*+][\s]+$/.test(lineBeforeMarker)) {
89
+ // This is a list item with just emphasis markers
90
+ // Check if content after marker spans multiple lines
91
+ const hasNewlineInContent = contentAfterMarker.includes('\n');
92
+ if (hasNewlineInContent) {
93
+ // Don't complete if the content spans to another line
94
+ return text;
95
+ }
96
+ }
97
+ const underscorePairs = (text.match(/__/g) || []).length;
98
+ if (underscorePairs % 2 === 1) {
99
+ return `${text}__`;
100
+ }
101
+ }
102
+ return text;
103
+ };
104
+ // Counts single asterisks that are not part of double asterisks, not escaped, and not list markers
105
+ const countSingleAsterisks = (text) => {
106
+ return text.split('').reduce((acc, char, index) => {
107
+ if (char === '*') {
108
+ const prevChar = text[index - 1];
109
+ const nextChar = text[index + 1];
110
+ // Skip if escaped with backslash
111
+ if (prevChar === '\\') {
112
+ return acc;
113
+ }
114
+ // Check if this is a list marker (asterisk at start of line followed by space)
115
+ // Look backwards to find the start of the current line
116
+ let lineStartIndex = index;
117
+ for (let i = index - 1; i >= 0; i--) {
118
+ if (text[i] === '\n') {
119
+ lineStartIndex = i + 1;
120
+ break;
121
+ }
122
+ if (i === 0) {
123
+ lineStartIndex = 0;
124
+ break;
125
+ }
126
+ }
127
+ // Check if this asterisk is at the beginning of a line (with optional whitespace)
128
+ const beforeAsterisk = text.substring(lineStartIndex, index);
129
+ if (beforeAsterisk.trim() === '' && (nextChar === ' ' || nextChar === '\t')) {
130
+ // This is likely a list marker, don't count it
131
+ return acc;
132
+ }
133
+ if (prevChar !== '*' && nextChar !== '*') {
134
+ return acc + 1;
135
+ }
136
+ }
137
+ return acc;
138
+ }, 0);
139
+ };
140
+ // Completes incomplete italic formatting with single asterisks (*)
141
+ const handleIncompleteSingleAsteriskItalic = (text) => {
142
+ // Don't process if inside a complete code block
143
+ if (hasCompleteCodeBlock(text)) {
144
+ return text;
145
+ }
146
+ const singleAsteriskMatch = text.match(singleAsteriskPattern);
147
+ if (singleAsteriskMatch) {
148
+ // Find the first single asterisk position (not part of **)
149
+ let firstSingleAsteriskIndex = -1;
150
+ for (let i = 0; i < text.length; i++) {
151
+ if (text[i] === '*' && text[i - 1] !== '*' && text[i + 1] !== '*') {
152
+ firstSingleAsteriskIndex = i;
153
+ break;
154
+ }
155
+ }
156
+ if (firstSingleAsteriskIndex === -1) {
157
+ return text;
158
+ }
159
+ // Get content after the first single asterisk
160
+ const contentAfterFirstAsterisk = text.substring(firstSingleAsteriskIndex + 1);
161
+ // Check if there's meaningful content after the asterisk
162
+ // Don't close if content is only whitespace or emphasis markers
163
+ if (!contentAfterFirstAsterisk || /^[\s_~*`]*$/.test(contentAfterFirstAsterisk)) {
164
+ return text;
165
+ }
166
+ const singleAsterisks = countSingleAsterisks(text);
167
+ if (singleAsterisks % 2 === 1) {
168
+ return `${text}*`;
169
+ }
170
+ }
171
+ return text;
172
+ };
173
+ // Check if a position is within a math block (between $ or $$)
174
+ const isWithinMathBlock = (text, position) => {
175
+ // Count dollar signs before this position
176
+ let inInlineMath = false;
177
+ let inBlockMath = false;
178
+ for (let i = 0; i < text.length && i < position; i++) {
179
+ // Skip escaped dollar signs
180
+ if (text[i] === '\\' && text[i + 1] === '$') {
181
+ i++; // Skip the next character
182
+ continue;
183
+ }
184
+ if (text[i] === '$') {
185
+ // Check for block math ($$)
186
+ if (text[i + 1] === '$') {
187
+ inBlockMath = !inBlockMath;
188
+ i++; // Skip the second $
189
+ inInlineMath = false; // Block math takes precedence
190
+ }
191
+ else if (!inBlockMath) {
192
+ // Only toggle inline math if not in block math
193
+ inInlineMath = !inInlineMath;
194
+ }
195
+ }
196
+ }
197
+ return inInlineMath || inBlockMath;
198
+ };
199
+ // Counts single underscores that are not part of double underscores, not escaped, and not in math blocks
200
+ const countSingleUnderscores = (text) => {
201
+ return text.split('').reduce((acc, char, index) => {
202
+ if (char === '_') {
203
+ const prevChar = text[index - 1];
204
+ const nextChar = text[index + 1];
205
+ // Skip if escaped with backslash
206
+ if (prevChar === '\\') {
207
+ return acc;
208
+ }
209
+ // Skip if within math block
210
+ if (isWithinMathBlock(text, index)) {
211
+ return acc;
212
+ }
213
+ if (prevChar !== '_' && nextChar !== '_') {
214
+ return acc + 1;
215
+ }
216
+ }
217
+ return acc;
218
+ }, 0);
219
+ };
220
+ // Completes incomplete italic formatting with single underscores (_)
221
+ const handleIncompleteSingleUnderscoreItalic = (text) => {
222
+ // Don't process if inside a complete code block
223
+ if (hasCompleteCodeBlock(text)) {
224
+ return text;
225
+ }
226
+ const singleUnderscoreMatch = text.match(singleUnderscorePattern);
227
+ if (singleUnderscoreMatch) {
228
+ // Find the first single underscore position (not part of __)
229
+ let firstSingleUnderscoreIndex = -1;
230
+ for (let i = 0; i < text.length; i++) {
231
+ if (text[i] === '_' &&
232
+ text[i - 1] !== '_' &&
233
+ text[i + 1] !== '_' &&
234
+ !isWithinMathBlock(text, i)) {
235
+ firstSingleUnderscoreIndex = i;
236
+ break;
237
+ }
238
+ }
239
+ if (firstSingleUnderscoreIndex === -1) {
240
+ return text;
241
+ }
242
+ // Get content after the first single underscore
243
+ const contentAfterFirstUnderscore = text.substring(firstSingleUnderscoreIndex + 1);
244
+ // Check if there's meaningful content after the underscore
245
+ // Don't close if content is only whitespace or emphasis markers
246
+ if (!contentAfterFirstUnderscore || /^[\s_~*`]*$/.test(contentAfterFirstUnderscore)) {
247
+ return text;
248
+ }
249
+ const singleUnderscores = countSingleUnderscores(text);
250
+ if (singleUnderscores % 2 === 1) {
251
+ return `${text}_`;
252
+ }
253
+ }
254
+ return text;
255
+ };
256
+ // Checks if a backtick at position i is part of a triple backtick sequence
257
+ const isPartOfTripleBacktick = (text, i) => {
258
+ const isTripleStart = text.substring(i, i + 3) === '```';
259
+ const isTripleMiddle = i > 0 && text.substring(i - 1, i + 2) === '```';
260
+ const isTripleEnd = i > 1 && text.substring(i - 2, i + 1) === '```';
261
+ return isTripleStart || isTripleMiddle || isTripleEnd;
262
+ };
263
+ // Counts single backticks that are not part of triple backticks
264
+ const countSingleBackticks = (text) => {
265
+ let count = 0;
266
+ for (let i = 0; i < text.length; i++) {
267
+ if (text[i] === '`' && !isPartOfTripleBacktick(text, i)) {
268
+ count++;
269
+ }
270
+ }
271
+ return count;
272
+ };
273
+ // Completes incomplete inline code formatting (`)
274
+ // Avoids completing if inside an incomplete code block
275
+ const handleIncompleteInlineCode = (text) => {
276
+ // Check if we have inline triple backticks (starts with ``` and should end with ```)
277
+ // This pattern should ONLY match truly inline code (no newlines)
278
+ // Examples: ```code``` or ```python code```
279
+ const inlineTripleBacktickMatch = text.match(/^```[^`\n]*```?$/);
280
+ if (inlineTripleBacktickMatch && !text.includes('\n')) {
281
+ // Check if it ends with exactly 2 backticks (incomplete)
282
+ if (text.endsWith('``') && !text.endsWith('```')) {
283
+ return `${text}\``;
284
+ }
285
+ // Already complete inline triple backticks
286
+ return text;
287
+ }
288
+ // Check if we're inside a multi-line code block (complete or incomplete)
289
+ const allTripleBackticks = (text.match(/```/g) || []).length;
290
+ const insideIncompleteCodeBlock = allTripleBackticks % 2 === 1;
291
+ // Don't modify text if we have complete multi-line code blocks (even pairs of ```)
292
+ if (allTripleBackticks > 0 && allTripleBackticks % 2 === 0 && text.includes('\n')) {
293
+ // We have complete multi-line code blocks, don't add any backticks
294
+ return text;
295
+ }
296
+ // Special case: if text ends with ```\n (triple backticks followed by newline)
297
+ // This is actually a complete code block, not incomplete
298
+ if (text.endsWith('```\n') || text.endsWith('```')) {
299
+ // Count all triple backticks - if even, it's complete
300
+ if (allTripleBackticks % 2 === 0) {
301
+ return text;
302
+ }
303
+ }
304
+ const inlineCodeMatch = text.match(inlineCodePattern);
305
+ if (inlineCodeMatch && !insideIncompleteCodeBlock) {
306
+ // Don't close if there's no meaningful content after the opening marker
307
+ // inlineCodeMatch[2] contains the content after `
308
+ // Check if content is only whitespace or other emphasis markers
309
+ const contentAfterMarker = inlineCodeMatch[2];
310
+ if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) {
311
+ return text;
312
+ }
313
+ const singleBacktickCount = countSingleBackticks(text);
314
+ if (singleBacktickCount % 2 === 1) {
315
+ return `${text}\``;
316
+ }
317
+ }
318
+ return text;
319
+ };
320
+ // Completes incomplete strikethrough formatting (~~)
321
+ const handleIncompleteStrikethrough = (text) => {
322
+ const strikethroughMatch = text.match(strikethroughPattern);
323
+ if (strikethroughMatch) {
324
+ // Don't close if there's no meaningful content after the opening markers
325
+ // strikethroughMatch[2] contains the content after ~~
326
+ // Check if content is only whitespace or other emphasis markers
327
+ const contentAfterMarker = strikethroughMatch[2];
328
+ if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) {
329
+ return text;
330
+ }
331
+ const tildePairs = (text.match(/~~/g) || []).length;
332
+ if (tildePairs % 2 === 1) {
333
+ return `${text}~~`;
334
+ }
335
+ }
336
+ return text;
337
+ };
338
+ // Counts single dollar signs that are not part of double dollar signs and not escaped
339
+ const _countSingleDollarSigns = (text) => {
340
+ return text.split('').reduce((acc, char, index) => {
341
+ if (char === '$') {
342
+ const prevChar = text[index - 1];
343
+ const nextChar = text[index + 1];
344
+ // Skip if escaped with backslash
345
+ if (prevChar === '\\') {
346
+ return acc;
347
+ }
348
+ if (prevChar !== '$' && nextChar !== '$') {
349
+ return acc + 1;
350
+ }
351
+ }
352
+ return acc;
353
+ }, 0);
354
+ };
355
+ // Completes incomplete block KaTeX formatting ($$)
356
+ const handleIncompleteBlockKatex = (text) => {
357
+ // Count all $$ pairs in the text
358
+ const dollarPairs = (text.match(/\$\$/g) || []).length;
359
+ // If we have an even number of $$, the block is complete
360
+ if (dollarPairs % 2 === 0) {
361
+ return text;
362
+ }
363
+ // If we have an odd number, add closing $$
364
+ // Check if this looks like a multi-line math block (contains newlines after opening $$)
365
+ const firstDollarIndex = text.indexOf('$$');
366
+ const hasNewlineAfterStart = firstDollarIndex !== -1 && text.indexOf('\n', firstDollarIndex) !== -1;
367
+ // For multi-line blocks, add newline before closing $$ if not present
368
+ if (hasNewlineAfterStart && !text.endsWith('\n')) {
369
+ return `${text}\n$$`;
370
+ }
371
+ // For inline blocks or when already ending with newline, just add $$
372
+ return `${text}$$`;
373
+ };
374
+ // Counts triple asterisks that are not part of quadruple or more asterisks
375
+ const countTripleAsterisks = (text) => {
376
+ let count = 0;
377
+ const matches = text.match(/\*+/g) || [];
378
+ for (const match of matches) {
379
+ // Count how many complete triple asterisks are in this sequence
380
+ const asteriskCount = match.length;
381
+ if (asteriskCount >= 3) {
382
+ // Each group of exactly 3 asterisks counts as one triple asterisk marker
383
+ count += Math.floor(asteriskCount / 3);
384
+ }
385
+ }
386
+ return count;
387
+ };
388
+ // Completes incomplete bold-italic formatting (***)
389
+ const handleIncompleteBoldItalic = (text) => {
390
+ // Don't process if inside a complete code block
391
+ if (hasCompleteCodeBlock(text)) {
392
+ return text;
393
+ }
394
+ // Don't process if text is only asterisks and has 4 or more consecutive asterisks
395
+ // This prevents cases like **** from being treated as incomplete ***
396
+ if (/^\*{4,}$/.test(text)) {
397
+ return text;
398
+ }
399
+ const boldItalicMatch = text.match(boldItalicPattern);
400
+ if (boldItalicMatch) {
401
+ // Don't close if there's no meaningful content after the opening markers
402
+ // boldItalicMatch[2] contains the content after ***
403
+ // Check if content is only whitespace or other emphasis markers
404
+ const contentAfterMarker = boldItalicMatch[2];
405
+ if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) {
406
+ return text;
407
+ }
408
+ const tripleAsteriskCount = countTripleAsterisks(text);
409
+ if (tripleAsteriskCount % 2 === 1) {
410
+ return `${text}***`;
411
+ }
412
+ }
413
+ return text;
414
+ };
415
+ // Parses markdown text and removes incomplete tokens to prevent partial rendering
416
+ export const parseIncompleteMarkdown = (text) => {
417
+ if (!text || typeof text !== 'string') {
418
+ return text;
419
+ }
420
+ let result = text;
421
+ // Handle incomplete links and images first
422
+ const processedResult = handleIncompleteLinksAndImages(result);
423
+ // If we added an incomplete link marker, don't process other formatting
424
+ // as the content inside the link should be preserved as-is
425
+ if (processedResult.endsWith('](streamdown:incomplete-link)')) {
426
+ return processedResult;
427
+ }
428
+ result = processedResult;
429
+ // Handle various formatting completions
430
+ // Handle triple asterisks first (most specific)
431
+ result = handleIncompleteBoldItalic(result);
432
+ result = handleIncompleteBold(result);
433
+ result = handleIncompleteDoubleUnderscoreItalic(result);
434
+ result = handleIncompleteSingleAsteriskItalic(result);
435
+ result = handleIncompleteSingleUnderscoreItalic(result);
436
+ result = handleIncompleteInlineCode(result);
437
+ result = handleIncompleteStrikethrough(result);
438
+ // Handle KaTeX formatting (only block math with $$)
439
+ result = handleIncompleteBlockKatex(result);
440
+ // Note: We don't handle inline KaTeX with single $ as they're likely currency symbols
441
+ return result;
442
+ };
@@ -0,0 +1,3 @@
1
+ import type { StreamdownContext } from '../Streamdown.svelte';
2
+ import type { Root } from 'hast';
3
+ export declare function parseMarkdown(context: StreamdownContext, content: string): Root;
@@ -0,0 +1,144 @@
1
+ import { urlAttributes } from 'html-url-attributes';
2
+ import remarkParse from 'remark-parse';
3
+ import remarkRehype from 'remark-rehype';
4
+ import { unified } from 'unified';
5
+ import { visit } from 'unist-util-visit';
6
+ import { VFile } from 'vfile';
7
+ import remarkGfm from 'remark-gfm';
8
+ import remarkMath from 'remark-math';
9
+ import { rehypeGithubAlerts } from './alerts.js';
10
+ import { squeezeParagraphs } from 'mdast-squeeze-paragraphs';
11
+ const emptyPlugins = [];
12
+ const emptyRemarkRehypeOptions = { allowDangerousHtml: true };
13
+ const safeProtocol = /^(https?|ircs?|mailto|xmpp)$/i;
14
+ function createFile(content) {
15
+ const file = new VFile();
16
+ if (typeof content === 'string') {
17
+ file.value = content;
18
+ }
19
+ else {
20
+ throw new Error('Unexpected value `' + content + '` for content, expected `string`');
21
+ }
22
+ return file;
23
+ }
24
+ export function parseMarkdown(context, content) {
25
+ const rehypePlugins = context.rehypePlugins || emptyPlugins;
26
+ const remarkPlugins = context.remarkPlugins || emptyPlugins;
27
+ const remarkRehypeOptions = context.remarkRehypeOptions
28
+ ? { ...context.remarkRehypeOptions, ...emptyRemarkRehypeOptions }
29
+ : emptyRemarkRehypeOptions;
30
+ const processor = unified()
31
+ .use(remarkParse)
32
+ .use(remarkPlugins)
33
+ .use(remarkMath)
34
+ .use(remarkGfm)
35
+ .use(remarkRehype, remarkRehypeOptions)
36
+ .use(rehypePlugins)
37
+ .use([rehypeGithubAlerts]);
38
+ const file = createFile(content);
39
+ const tree = processor.parse(file);
40
+ return post(processor.runSync(tree, file), {
41
+ allowElement: context.allowElement,
42
+ allowedElements: context.allowedElements,
43
+ disallowedElements: context.disallowedElements,
44
+ skipHtml: context.skipHtml,
45
+ unwrapDisallowed: context.unwrapDisallowed,
46
+ urlTransform: context.urlTransform
47
+ });
48
+ }
49
+ /**
50
+ * Process the HAST tree with filtering and transformations
51
+ */
52
+ function post(tree, options) {
53
+ const allowedElements = options.allowedElements;
54
+ const allowElement = options.allowElement;
55
+ const disallowedElements = options.disallowedElements;
56
+ const skipHtml = options.skipHtml;
57
+ const unwrapDisallowed = options.unwrapDisallowed;
58
+ const urlTransform = options.urlTransform || defaultUrlTransform;
59
+ if (allowedElements && disallowedElements) {
60
+ throw new Error('Unexpected combined `allowedElements` and `disallowedElements`, expected one or the other');
61
+ }
62
+ visit(tree, transform);
63
+ return tree;
64
+ /** @type {import('unist-util-visit').BuildVisitor<Root>} */
65
+ function transform(node, index, parent) {
66
+ if (node.type === 'raw' && parent && typeof index === 'number') {
67
+ if (skipHtml) {
68
+ parent.children.splice(index, 1);
69
+ }
70
+ else {
71
+ parent.children[index] = { type: 'text', value: node.value };
72
+ }
73
+ return index;
74
+ }
75
+ if (node.type === 'element') {
76
+ const element = node;
77
+ // Transform URLs
78
+ for (const key in urlAttributes) {
79
+ if (Object.hasOwn(urlAttributes, key) && Object.hasOwn(element.properties, key)) {
80
+ const value = element.properties[key];
81
+ const test = urlAttributes[key];
82
+ if (test === null || test.includes(element.tagName)) {
83
+ element.properties[key] = urlTransform(String(value || ''), key, element);
84
+ }
85
+ }
86
+ }
87
+ const className = node.properties.className;
88
+ if (node.tagName === 'code') {
89
+ const LANGUAGE_REGEX = /language-([^\s]+)/;
90
+ const match = (Array.isArray(className) ? className : [className])?.reduce((acc, c) => {
91
+ const match = String(c).match(LANGUAGE_REGEX);
92
+ const lang = match?.[1];
93
+ if (lang) {
94
+ acc = lang;
95
+ }
96
+ return acc;
97
+ }, '');
98
+ const language = (match ?? 'plaintext');
99
+ node.properties.language = language;
100
+ }
101
+ }
102
+ if (node.type === 'element') {
103
+ const element = node;
104
+ let remove = allowedElements
105
+ ? !allowedElements.includes(element.tagName)
106
+ : disallowedElements
107
+ ? disallowedElements.includes(element.tagName)
108
+ : false;
109
+ if (!remove && allowElement && typeof index === 'number') {
110
+ remove = !allowElement(element, index, parent);
111
+ }
112
+ if (remove && parent && typeof index === 'number') {
113
+ if (unwrapDisallowed && element.children) {
114
+ parent.children.splice(index, 1, ...element.children);
115
+ }
116
+ else {
117
+ parent.children.splice(index, 1);
118
+ }
119
+ return index;
120
+ }
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * Make a URL safe (GitHub-style)
126
+ */
127
+ function defaultUrlTransform(value) {
128
+ const colon = value.indexOf(':');
129
+ const questionMark = value.indexOf('?');
130
+ const numberSign = value.indexOf('#');
131
+ const slash = value.indexOf('/');
132
+ if (
133
+ // If there is no protocol, it's relative
134
+ colon === -1 ||
135
+ // If the first colon is after a `?`, `#`, or `/`, it's not a protocol
136
+ (slash !== -1 && colon > slash) ||
137
+ (questionMark !== -1 && colon > questionMark) ||
138
+ (numberSign !== -1 && colon > numberSign) ||
139
+ // It is a protocol, it should be allowed
140
+ safeProtocol.test(value.slice(0, colon))) {
141
+ return value;
142
+ }
143
+ return '';
144
+ }
@@ -0,0 +1 @@
1
+ export declare const save: (filename: string, content: string, mimeType: string) => void;
@@ -0,0 +1,11 @@
1
+ export const save = (filename, content, mimeType) => {
2
+ const blob = new Blob([content], { type: mimeType });
3
+ const url = URL.createObjectURL(blob);
4
+ const link = document.createElement('a');
5
+ link.href = url;
6
+ link.download = filename;
7
+ document.body.appendChild(link);
8
+ link.click();
9
+ document.body.removeChild(link);
10
+ URL.revokeObjectURL(url);
11
+ };
@@ -0,0 +1,2 @@
1
+ export declare const parseUrl: (url: unknown, defaultOrigin?: string) => URL | null;
2
+ export declare const transformUrl: (url: unknown, allowedPrefixes: string[], defaultOrigin?: string) => string | null;
@@ -0,0 +1,71 @@
1
+ export const parseUrl = (url, defaultOrigin) => {
2
+ if (typeof url !== 'string')
3
+ return null;
4
+ try {
5
+ // Try to parse as absolute URL first
6
+ const urlObject = new URL(url);
7
+ return urlObject;
8
+ }
9
+ catch (error) {
10
+ // If that fails and we have a defaultOrigin, try with it
11
+ if (defaultOrigin) {
12
+ try {
13
+ const urlObject = new URL(url, defaultOrigin);
14
+ return urlObject;
15
+ }
16
+ catch (error) {
17
+ return null;
18
+ }
19
+ }
20
+ return null;
21
+ }
22
+ };
23
+ const isPathRelativeUrl = (url) => {
24
+ if (typeof url !== 'string')
25
+ return false;
26
+ return url.startsWith('/');
27
+ };
28
+ export const transformUrl = (url, allowedPrefixes, defaultOrigin) => {
29
+ if (!url)
30
+ return null;
31
+ const parsedUrl = parseUrl(url, defaultOrigin);
32
+ if (!parsedUrl)
33
+ return null;
34
+ // If the input is path relative, we output a path relative URL as well,
35
+ // however, we always run the same checks on an absolute URL and we
36
+ // always rescronstruct the output from the parsed URL to ensure that
37
+ // the output is always a valid URL.
38
+ const inputWasRelative = isPathRelativeUrl(url);
39
+ const urlString = parseUrl(url);
40
+ if (urlString &&
41
+ allowedPrefixes.some((prefix) => {
42
+ const parsedPrefix = parseUrl(prefix);
43
+ if (!parsedPrefix) {
44
+ return false;
45
+ }
46
+ if (parsedPrefix.origin !== urlString.origin) {
47
+ return false;
48
+ }
49
+ return urlString.href.startsWith(parsedPrefix.href);
50
+ })) {
51
+ if (inputWasRelative) {
52
+ return urlString.pathname + urlString.search + urlString.hash;
53
+ }
54
+ return urlString.href;
55
+ }
56
+ // Check for wildcard - allow all URLs
57
+ if (allowedPrefixes.includes('*')) {
58
+ // Wildcard only allows http and https URLs
59
+ if (parsedUrl.protocol !== 'https:' && parsedUrl.protocol !== 'http:') {
60
+ return null;
61
+ }
62
+ const inputWasRelative = isPathRelativeUrl(url);
63
+ if (parsedUrl) {
64
+ if (inputWasRelative) {
65
+ return parsedUrl.pathname + parsedUrl.search + parsedUrl.hash;
66
+ }
67
+ return parsedUrl.href;
68
+ }
69
+ }
70
+ return null;
71
+ };