@staix/vault-mem-ui 0.0.0-stage → 0.0.0

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 (64) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +96 -2
  4. package/THIRD_PARTY_NOTICES.md +164 -0
  5. package/bin/vmem-ui.ts +26 -0
  6. package/dist/panel.css +666 -0
  7. package/dist/panel.js +355 -0
  8. package/package.json +53 -4
  9. package/src/client/App.tsx +167 -0
  10. package/src/client/a11y.ts +54 -0
  11. package/src/client/acon.ts +46 -0
  12. package/src/client/components.tsx +243 -0
  13. package/src/client/data.ts +66 -0
  14. package/src/client/fake.ts +48 -0
  15. package/src/client/graph-export.tsx +21 -0
  16. package/src/client/host.ts +80 -0
  17. package/src/client/markdown/parse.ts +620 -0
  18. package/src/client/markdown/render.tsx +270 -0
  19. package/src/client/panel.css +666 -0
  20. package/src/client/panel.tsx +66 -0
  21. package/src/client/prefs.ts +76 -0
  22. package/src/client/standalone.ts +44 -0
  23. package/src/client/store.ts +201 -0
  24. package/src/client/views/assertions.tsx +109 -0
  25. package/src/client/views/common.ts +15 -0
  26. package/src/client/views/history.tsx +205 -0
  27. package/src/client/views/lint.tsx +27 -0
  28. package/src/client/views/log.tsx +64 -0
  29. package/src/client/views/note.tsx +128 -0
  30. package/src/client/views/notes.tsx +34 -0
  31. package/src/client/views/overview.tsx +74 -0
  32. package/src/client/views/promote.tsx +112 -0
  33. package/src/client/views/proposals.tsx +55 -0
  34. package/src/client/views/settings.tsx +57 -0
  35. package/src/client/write.ts +144 -0
  36. package/src/graph/decisionChains.ts +122 -0
  37. package/src/graph/derive.ts +338 -0
  38. package/src/graph/export.ts +44 -0
  39. package/src/graph/insights.ts +254 -0
  40. package/src/graph/labels.ts +67 -0
  41. package/src/graph/layout/client.ts +139 -0
  42. package/src/graph/layout/engine.ts +107 -0
  43. package/src/graph/layout/fa2.d.ts +8 -0
  44. package/src/graph/layout/protocol.ts +70 -0
  45. package/src/graph/layout/worker.ts +132 -0
  46. package/src/graph/model.ts +230 -0
  47. package/src/graph/positions.ts +41 -0
  48. package/src/graph/search.ts +54 -0
  49. package/src/graph/style.ts +301 -0
  50. package/src/graph/target.ts +38 -0
  51. package/src/graph/types.ts +64 -0
  52. package/src/graph/view/GraphView.tsx +279 -0
  53. package/src/graph/view/SidePanels.tsx +141 -0
  54. package/src/graph/view/cache.ts +42 -0
  55. package/src/graph/view/canvas.ts +309 -0
  56. package/src/graph/view/graph-snapshot.ts +75 -0
  57. package/src/graph/view/lod.ts +30 -0
  58. package/src/graph/view/motion.ts +4 -0
  59. package/src/graph/view/state.ts +240 -0
  60. package/src/plugin/assets.ts +33 -0
  61. package/src/plugin/graph.ts +71 -0
  62. package/src/plugin/index.ts +23 -0
  63. package/src/server/cli.ts +99 -0
  64. package/src/server/host.ts +287 -0
@@ -0,0 +1,620 @@
1
+ /**
2
+ * Markdown to a typed tree: blocks first, then the inline spans inside them.
3
+ *
4
+ * Nothing here produces an HTML string, and an HTML tag in the source is not a construct this parser knows, so it can
5
+ * only ever reach the tree as text. The subset is the one a note uses: headings, paragraphs, fenced code, quotes,
6
+ * lists (with task state), tables with alignment, rules, and inline code, strong, em, links, images and wiki-links.
7
+ */
8
+
9
+ export type Align = "left" | "center" | "right" | null;
10
+
11
+ export type Inline =
12
+ | { kind: "text"; text: string }
13
+ | { kind: "code"; text: string }
14
+ | { kind: "strong"; children: Inline[] }
15
+ | { kind: "em"; children: Inline[] }
16
+ | { kind: "link"; href: string; children: Inline[] }
17
+ | { kind: "image"; alt: string; src: string }
18
+ | { kind: "wiki"; target: string; heading: string; block: string; label: string; embed: boolean }
19
+ | { kind: "break" };
20
+
21
+ export interface ListItem {
22
+ children: Block[];
23
+ /** `true` for `- [x]`, `false` for `- [ ]`, `null` when the item is not a task. */
24
+ checked: boolean | null;
25
+ }
26
+
27
+ export type Block =
28
+ | { kind: "heading"; depth: number; children: Inline[] }
29
+ | { kind: "paragraph"; children: Inline[] }
30
+ | { kind: "code"; lang: string; text: string }
31
+ | { kind: "quote"; children: Block[] }
32
+ | { kind: "list"; ordered: boolean; start: number; items: ListItem[] }
33
+ | { kind: "table"; align: Align[]; head: Inline[][]; rows: Inline[][][] }
34
+ | { kind: "rule" };
35
+
36
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
37
+ const CLOSING_FENCE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
38
+ const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/;
39
+ const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
40
+ const RULE = /^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/;
41
+ const QUOTE = /^ {0,3}>[ ]?/;
42
+ const BULLET = /^( *)[-*+]([ \t]+)(.*)$/;
43
+ const ORDERED = /^( *)(\d{1,9})[.)]([ \t]+)(.*)$/;
44
+ const DELIMITER = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
45
+ const TASK = /^\[([ xX])\](?:[ \t]+|$)/;
46
+ const AUTOLINK = /^<([a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]+)>/;
47
+ const ESCAPABLE = /^[\\`*_{}[\]()#+\-.!|~<>]$/;
48
+ const WORD = /[\p{L}\p{N}]/u;
49
+
50
+ /** The schemes an external link may use. Anything else, including a relative target, stays text. */
51
+ const ALLOWED_SCHEMES = new Set(["http:", "https:", "mailto:"]);
52
+
53
+ /**
54
+ * How deep nesting is followed. Both passes recurse once per level, and a 6 KB note of `- ` or `>` repeats is well
55
+ * inside the provider's 16 KiB body limit, so an unbounded walk overflows the browser stack and the panel has no error
56
+ * boundary to catch it. Past the cap the source is kept as text instead of interpreted, so the bytes still reach the
57
+ * person and nothing recurses further.
58
+ */
59
+ export const MAX_BLOCK_DEPTH = 32;
60
+ export const MAX_INLINE_DEPTH = 32;
61
+
62
+ /** The href for a target only when it is an absolute http, https or mailto URL; `null` for everything else. */
63
+ export function safeHref(value: string): string | null {
64
+ const trimmed = value.trim();
65
+ if (!trimmed) return null;
66
+ try {
67
+ const url = new URL(trimmed);
68
+ return ALLOWED_SCHEMES.has(url.protocol) ? url.href : null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ export function parseMarkdown(text: string): Block[] {
75
+ return parseBlocks(text.replace(/\r\n?/g, "\n").split("\n"), 0);
76
+ }
77
+
78
+ function parseBlocks(lines: string[], depth: number): Block[] {
79
+ if (depth >= MAX_BLOCK_DEPTH) {
80
+ const text = lines.join("\n").trim();
81
+ return text ? [{ kind: "paragraph", children: [{ kind: "text", text }] }] : [];
82
+ }
83
+ const blocks: Block[] = [];
84
+ let at = 0;
85
+ while (at < lines.length) {
86
+ const line = lines[at]!;
87
+ if (!line.trim()) {
88
+ at += 1;
89
+ continue;
90
+ }
91
+
92
+ const fence = FENCE.exec(line);
93
+ // A backtick fence's info string cannot hold a backtick, and the same rule keeps ``` inline code a paragraph.
94
+ if (fence && !(fence[1]![0] === "`" && fence[2]!.includes("`"))) {
95
+ const marker = fence[1]!;
96
+ const lang = fence[2]!.trim().split(/[ \t]+/)[0] ?? "";
97
+ const body: string[] = [];
98
+ at += 1;
99
+ while (at < lines.length) {
100
+ const closing = CLOSING_FENCE.exec(lines[at]!);
101
+ if (closing && closing[1]![0] === marker[0] && closing[1]!.length >= marker.length) {
102
+ at += 1;
103
+ break;
104
+ }
105
+ body.push(lines[at]!);
106
+ at += 1;
107
+ }
108
+ blocks.push({ kind: "code", lang, text: body.join("\n") });
109
+ continue;
110
+ }
111
+
112
+ const atx = ATX.exec(line);
113
+ if (atx) {
114
+ const heading = (atx[2] ?? "").replace(/[ \t]+#+[ \t]*$/, "").trim();
115
+ blocks.push({ kind: "heading", depth: atx[1]!.length, children: parseInline(heading) });
116
+ at += 1;
117
+ continue;
118
+ }
119
+
120
+ if (RULE.test(line)) {
121
+ blocks.push({ kind: "rule" });
122
+ at += 1;
123
+ continue;
124
+ }
125
+
126
+ if (QUOTE.test(line)) {
127
+ const inner: string[] = [];
128
+ while (at < lines.length) {
129
+ const marker = QUOTE.exec(lines[at]!);
130
+ if (marker) {
131
+ inner.push(lines[at]!.slice(marker[0].length));
132
+ at += 1;
133
+ continue;
134
+ }
135
+ // A blank line keeps the quote open only when the next line is still quoted.
136
+ if (!lines[at]!.trim() && at + 1 < lines.length && QUOTE.test(lines[at + 1]!)) {
137
+ inner.push("");
138
+ at += 1;
139
+ continue;
140
+ }
141
+ break;
142
+ }
143
+ blocks.push({ kind: "quote", children: parseBlocks(inner, depth + 1) });
144
+ continue;
145
+ }
146
+
147
+ const head = listHead(line);
148
+ if (head) {
149
+ at = parseList(lines, at, head, blocks, depth);
150
+ continue;
151
+ }
152
+
153
+ if (line.includes("|") && at + 1 < lines.length && isTableHead(line, lines[at + 1]!)) {
154
+ const cells = splitRow(line);
155
+ const align = splitRow(lines[at + 1]!).map(cellAlign);
156
+ at += 2;
157
+ const rows: Inline[][][] = [];
158
+ while (at < lines.length && lines[at]!.trim() && lines[at]!.includes("|")) {
159
+ const row = splitRow(lines[at]!);
160
+ rows.push(row.slice(0, align.length).map((cell) => parseInline(cell)));
161
+ at += 1;
162
+ }
163
+ blocks.push({ kind: "table", align, head: align.map((_, index) => parseInline(cells[index] ?? "")), rows });
164
+ continue;
165
+ }
166
+
167
+ // A paragraph, or a setext heading when an underline follows its only line.
168
+ const para: string[] = [];
169
+ let setextDepth: number | null = null;
170
+ while (at < lines.length) {
171
+ const next = lines[at]!;
172
+ if (!next.trim()) break;
173
+ if (para.length) {
174
+ const underline = SETEXT.exec(next);
175
+ if (underline && para.length === 1) {
176
+ setextDepth = underline[1]![0] === "=" ? 1 : 2;
177
+ at += 1;
178
+ break;
179
+ }
180
+ if (startsBlock(next)) break;
181
+ }
182
+ para.push(next);
183
+ at += 1;
184
+ }
185
+ const children = parseInline(para.join("\n"));
186
+ blocks.push(setextDepth ? { kind: "heading", depth: setextDepth, children } : { kind: "paragraph", children });
187
+ }
188
+ return blocks;
189
+ }
190
+
191
+ interface Head {
192
+ ordered: boolean;
193
+ start: number;
194
+ /** The column the item's own content starts at, which is also what a continuation line has to reach. */
195
+ indent: number;
196
+ text: string;
197
+ }
198
+
199
+ function listHead(line: string): Head | null {
200
+ if (RULE.test(line)) return null;
201
+ const bullet = BULLET.exec(line);
202
+ if (bullet) return { ordered: false, start: 1, indent: bullet[1]!.length + 1 + bullet[2]!.length, text: bullet[3]! };
203
+ const ordered = ORDERED.exec(line);
204
+ if (ordered) {
205
+ const marker = ordered[2]!;
206
+ return { ordered: true, start: Number(marker), indent: ordered[1]!.length + marker.length + 1 + ordered[3]!.length, text: ordered[4]! };
207
+ }
208
+ return null;
209
+ }
210
+
211
+ function parseList(lines: string[], start: number, first: Head, blocks: Block[], depth: number): number {
212
+ const items: ListItem[] = [];
213
+ let at = start;
214
+ while (at < lines.length) {
215
+ const head = listHead(lines[at]!);
216
+ if (!head || head.ordered !== first.ordered) break;
217
+ const task = TASK.exec(head.text);
218
+ const checked = task ? task[1]!.toLowerCase() === "x" : null;
219
+ const content: string[] = [task ? head.text.slice(task[0].length) : head.text];
220
+ at += 1;
221
+ while (at < lines.length) {
222
+ const next = lines[at]!;
223
+ if (!next.trim()) {
224
+ // Blank lines stay in the item only while something indented enough follows them. The run is read once and
225
+ // kept whole: adding it a line at a time re-read the rest of the run for every blank line, so a note of blank
226
+ // lines cost the square of its length at every nesting level.
227
+ let look = at;
228
+ while (look < lines.length && !lines[look]!.trim()) look += 1;
229
+ if (look >= lines.length || leadingSpaces(lines[look]!) < head.indent) break;
230
+ while (at < look) {
231
+ content.push("");
232
+ at += 1;
233
+ }
234
+ continue;
235
+ }
236
+ if (leadingSpaces(next) < head.indent) break;
237
+ content.push(next.slice(head.indent));
238
+ at += 1;
239
+ }
240
+ items.push({ children: parseBlocks(content, depth + 1), checked });
241
+ }
242
+ blocks.push({ kind: "list", ordered: first.ordered, start: first.start, items });
243
+ return at;
244
+ }
245
+
246
+ function startsBlock(line: string): boolean {
247
+ return FENCE.test(line) || ATX.test(line) || RULE.test(line) || QUOTE.test(line) || listHead(line) !== null;
248
+ }
249
+
250
+ function leadingSpaces(line: string): number {
251
+ return /^ */.exec(line)![0].length;
252
+ }
253
+
254
+ function isTableHead(header: string, delimiter: string): boolean {
255
+ if (!DELIMITER.test(delimiter)) return false;
256
+ return splitRow(header).length === splitRow(delimiter).length;
257
+ }
258
+
259
+ function splitRow(line: string): string[] {
260
+ const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
261
+ const cells: string[] = [];
262
+ let cell = "";
263
+ for (let at = 0; at < trimmed.length; at += 1) {
264
+ const char = trimmed[at]!;
265
+ if (char === "\\" && trimmed[at + 1] === "|") {
266
+ // The escape stays in the cell: an inline pass turns `\|` into `|` where it is text, while a wiki-link target
267
+ // keeps the backslash exactly as vmem's own scan of the note reads it.
268
+ cell += "\\|";
269
+ at += 1;
270
+ continue;
271
+ }
272
+ if (char === "|") {
273
+ cells.push(cell.trim());
274
+ cell = "";
275
+ continue;
276
+ }
277
+ cell += char;
278
+ }
279
+ cells.push(cell.trim());
280
+ return cells;
281
+ }
282
+
283
+ function cellAlign(delimiter: string): Align {
284
+ const value = delimiter.trim();
285
+ if (value.startsWith(":") && value.endsWith(":")) return "center";
286
+ if (value.endsWith(":")) return "right";
287
+ if (value.startsWith(":")) return "left";
288
+ return null;
289
+ }
290
+
291
+ export function parseInline(text: string, depth = 0): Inline[] {
292
+ return inlinePass(text, depth, true);
293
+ }
294
+
295
+ /**
296
+ * The inline pass. `links` is off while a link's own label is read: an anchor cannot hold an anchor, so a link written
297
+ * inside a label stays the text it was, and skipping it there is also what keeps nested labels from being parsed once
298
+ * per level.
299
+ */
300
+ function inlinePass(text: string, depth: number, links: boolean): Inline[] {
301
+ if (depth >= MAX_INLINE_DEPTH) return text ? [{ kind: "text", text }] : [];
302
+ const out: Inline[] = [];
303
+ const delimiters = delimiterIndex(text);
304
+ // Every `[` is paired with its closing `]` in this one pass, so a candidate link start is a lookup rather than a scan
305
+ // to the end of the text: a note of many `[` and a single `]` re-read the same tail from each opening, which took 1.9 s
306
+ // at 48 KB under V8 with the old guard (that guard only helped when no `]` existed at all).
307
+ const pairs = text.includes("[") ? bracketPairs(text) : null;
308
+ const parens = pairs ? parenPairs(text) : null;
309
+ // Successful and rejected destinations may overlap; bound total substring decoding per inline pass.
310
+ const budget = { remaining: text.length * 4 };
311
+ const lastWiki = text.lastIndexOf("]]");
312
+ let buffer = "";
313
+ const flush = () => {
314
+ if (!buffer) return;
315
+ out.push({ kind: "text", text: buffer });
316
+ buffer = "";
317
+ };
318
+ let at = 0;
319
+ while (at < text.length) {
320
+ const char = text[at]!;
321
+ if (char === "\\" && text[at + 1] === "\n") {
322
+ flush();
323
+ out.push({ kind: "break" });
324
+ at += 2;
325
+ continue;
326
+ }
327
+ if (char === "\\" && text[at + 1] && ESCAPABLE.test(text[at + 1]!)) {
328
+ buffer += text[at + 1]!;
329
+ at += 2;
330
+ continue;
331
+ }
332
+ if (char === "\n") {
333
+ if (buffer.endsWith(" ")) {
334
+ let end = buffer.length;
335
+ while (end > 0 && buffer[end - 1] === " ") end -= 1;
336
+ buffer = buffer.slice(0, end);
337
+ flush();
338
+ out.push({ kind: "break" });
339
+ } else buffer += " ";
340
+ at += 1;
341
+ continue;
342
+ }
343
+ if (char === "`") {
344
+ const span = codeSpan(text, at);
345
+ if (span) {
346
+ flush();
347
+ out.push(span.node);
348
+ at = span.end;
349
+ continue;
350
+ }
351
+ }
352
+ if (char === "!" && text[at + 1] === "[") {
353
+ const span = (lastWiki >= at + 3 ? wikiSpan(text, at) : null) ??
354
+ (pairs && parens ? bracketLink(text, at, true, depth, pairs, parens, budget) : null);
355
+ if (span) {
356
+ flush();
357
+ out.push(span.node);
358
+ at = span.end;
359
+ continue;
360
+ }
361
+ }
362
+ if (char === "[" && links) {
363
+ const span = (lastWiki >= at + 2 && text[at + 1] === "[" ? wikiSpan(text, at) : null) ??
364
+ (pairs && parens ? bracketLink(text, at, false, depth, pairs, parens, budget) : null);
365
+ if (span) {
366
+ flush();
367
+ out.push(span.node);
368
+ at = span.end;
369
+ continue;
370
+ }
371
+ }
372
+ if (char === "<" && links) {
373
+ const span = autolink(text, at);
374
+ if (span) {
375
+ flush();
376
+ out.push(span.node);
377
+ at = span.end;
378
+ continue;
379
+ }
380
+ }
381
+ if (char === "*" || char === "_") {
382
+ const span = emphasis(text, at, delimiters, depth, links);
383
+ if (span) {
384
+ flush();
385
+ out.push(span.node);
386
+ at = span.end;
387
+ continue;
388
+ }
389
+ }
390
+ buffer += char;
391
+ at += 1;
392
+ }
393
+ flush();
394
+ return out;
395
+ }
396
+
397
+ interface Span {
398
+ node: Inline;
399
+ end: number;
400
+ }
401
+
402
+ function codeSpan(text: string, at: number): Span | null {
403
+ let size = 0;
404
+ while (text[at + size] === "`") size += 1;
405
+ let cursor = at + size;
406
+ while (cursor < text.length) {
407
+ if (text[cursor] !== "`") {
408
+ cursor += 1;
409
+ continue;
410
+ }
411
+ let run = 0;
412
+ while (text[cursor + run] === "`") run += 1;
413
+ if (run === size) return { node: { kind: "code", text: text.slice(at + size, cursor).replace(/\n/g, " ") }, end: cursor + run };
414
+ cursor += run;
415
+ }
416
+ return null;
417
+ }
418
+
419
+ /** `[[target]]`, `[[target|alias]]`, `[[target#heading]]` and the `![[…]]` embed, read the way vmem reads them. */
420
+ function wikiSpan(text: string, at: number): Span | null {
421
+ const embed = text[at] === "!";
422
+ const open = at + (embed ? 1 : 0);
423
+ if (text[open] !== "[" || text[open + 1] !== "[") return null;
424
+ const close = text.indexOf("]]", open + 2);
425
+ if (close < 0) return null;
426
+ const inner = text.slice(open + 2, close);
427
+ if (!inner.trim() || inner.includes("[") || inner.includes("\n")) return null;
428
+ const bar = inner.indexOf("|");
429
+ const address = (bar < 0 ? inner : inner.slice(0, bar)).trim();
430
+ const alias = bar < 0 ? "" : inner.slice(bar + 1).trim();
431
+ if (!address) return null;
432
+ const hash = address.indexOf("#");
433
+ const target = (hash < 0 ? address : address.slice(0, hash)).trim();
434
+ const anchor = hash < 0 ? "" : address.slice(hash + 1).trim();
435
+ // vmem splits the anchor into a heading and a `^block` reference, and resolves each link by both, so the tree keeps
436
+ // them apart: two links to one note with different anchors can resolve differently.
437
+ const block = anchor.startsWith("^") ? anchor.slice(1) : "";
438
+ const heading = anchor && !anchor.startsWith("^") ? anchor : "";
439
+ return { node: { kind: "wiki", target, heading, block, label: alias || address, embed }, end: close + 2 };
440
+ }
441
+
442
+ /**
443
+ * The `]` that closes each `[`, in one pass: `pairs[i]` is that index, or -1 when the bracket is never closed. The
444
+ * nesting rule is the one the label reader had: a `[` holds a `]` that arrived after it, so `[[a]](u)` labels `[a]`.
445
+ * An escaped character closes nothing.
446
+ */
447
+ function bracketPairs(text: string): Int32Array {
448
+ const pairs = new Int32Array(text.length).fill(-1);
449
+ const open: number[] = [];
450
+ for (let at = 0; at < text.length; at += 1) {
451
+ const char = text[at]!;
452
+ if (char === "\\") {
453
+ at += 1;
454
+ continue;
455
+ }
456
+ if (char === "[") open.push(at);
457
+ else if (char === "]" && open.length) pairs[open.pop()!] = at;
458
+ }
459
+ return pairs;
460
+ }
461
+
462
+ /** Match unescaped parentheses in one pass; destinations never cross a newline. */
463
+ function parenPairs(text: string): Int32Array {
464
+ const pairs = new Int32Array(text.length).fill(-1);
465
+ const stack: number[] = [];
466
+ for (let at = 0; at < text.length; at += 1) {
467
+ if (text[at] === "\\") { at += 1; continue; }
468
+ if (text[at] === "\n") { stack.length = 0; continue; }
469
+ if (text[at] === "(") stack.push(at);
470
+ else if (text[at] === ")" && stack.length) pairs[stack.pop()!] = at;
471
+ }
472
+ return pairs;
473
+ }
474
+
475
+ function bracketLink(text: string, at: number, image: boolean, depth: number, pairs: Int32Array, parens: Int32Array, budget: { remaining: number }): Span | null {
476
+ const bracket = at + (image ? 1 : 0);
477
+ const open = bracket + 1;
478
+ const close = pairs[bracket]!;
479
+ if (close < 0 || text[close + 1] !== "(") return null;
480
+ const end = parens[close + 1]!;
481
+ if (end < 0 || end - open > budget.remaining) return null;
482
+ budget.remaining -= end - open;
483
+ const label = text.slice(open, close);
484
+ const inside = destination(text, close + 1, end);
485
+ if (!inside) return null;
486
+ const target = linkTarget(inside.dest);
487
+ if (!target) return null;
488
+ // An image target is shown, not fetched, so it is kept as written; a link target has to pass the scheme check.
489
+ if (image) return { node: { kind: "image", alt: label.trim(), src: target }, end: end + 1 };
490
+ const href = safeHref(target);
491
+ if (!href) return null;
492
+ // An anchor cannot hold an anchor, so a link inside this label is left as the text it was written as. The label is
493
+ // read with links off for that reason, and also for cost: refusing this outer link instead (letting the inner one
494
+ // win, as CommonMark has it) meant the label was parsed and then re-parsed again from the next character at every
495
+ // nesting level, which doubles the work per level — 320 ms at depth 20 and minutes at depth 3000.
496
+ return { node: { kind: "link", href, children: inlinePass(label, depth + 1, false) }, end: end + 1 };
497
+ }
498
+
499
+ /** The destination of `(…)` starting at `open`, read the way a link target is, and the index of its closing paren. */
500
+ function destination(text: string, open: number, closing: number): { dest: string; end: number } | null {
501
+ let dest = "";
502
+ let parens = 1;
503
+ let end = open + 1;
504
+ for (; end <= closing; end += 1) {
505
+ const char = text[end]!;
506
+ if (char === "\\") {
507
+ dest += text[end + 1] ?? "";
508
+ end += 1;
509
+ continue;
510
+ }
511
+ if (char === "\n") return null;
512
+ if (char === "(") {
513
+ parens += 1;
514
+ dest += char;
515
+ continue;
516
+ }
517
+ if (char === ")") {
518
+ parens -= 1;
519
+ if (!parens) break;
520
+ dest += char;
521
+ continue;
522
+ }
523
+ dest += char;
524
+ }
525
+ return parens ? null : { dest, end };
526
+ }
527
+
528
+ /** The target of `[label](target "title")`, without the optional title. */
529
+ function linkTarget(dest: string): string {
530
+ const trimmed = dest.trim();
531
+ const angle = /^<([^>]*)>/.exec(trimmed);
532
+ if (angle) return (angle[1] ?? "").trim();
533
+ return trimmed.split(/\s+/)[0] ?? "";
534
+ }
535
+
536
+ function autolink(text: string, at: number): Span | null {
537
+ const match = AUTOLINK.exec(text.slice(at));
538
+ if (!match) return null;
539
+ const href = safeHref(match[1]!);
540
+ if (!href) return null;
541
+ return { node: { kind: "link", href, children: [{ kind: "text", text: match[1]! }] }, end: at + match[0].length };
542
+ }
543
+
544
+ interface Delimiters {
545
+ /** How many `char` characters start at `at`. */
546
+ runAt(at: number, char: string): number;
547
+ /** The first usable closing run at or after `from`, or -1 when the opener never closes. */
548
+ closeAt(from: number, char: string, width: number): number;
549
+ }
550
+
551
+ /**
552
+ * The `*` and `_` runs of one text, each read in a single pass. Without it every opener that never closes rescans the
553
+ * rest of the run, which is quadratic on a note that repeats `*a `; here the positions are computed once and each
554
+ * lookup is a binary search.
555
+ */
556
+ function delimiterIndex(text: string): Delimiters {
557
+ const runs = new Map<string, Int32Array>();
558
+ const starts = new Map<string, number[]>();
559
+ const runAt = (at: number, char: string): number => {
560
+ let table = runs.get(char);
561
+ if (!table) {
562
+ table = new Int32Array(text.length + 1);
563
+ for (let index = text.length - 1; index >= 0; index -= 1) {
564
+ table[index] = text[index] === char ? table[index + 1]! + 1 : 0;
565
+ }
566
+ runs.set(char, table);
567
+ }
568
+ return table[at] ?? 0;
569
+ };
570
+ const usable = (found: number, char: string, width: number): boolean => {
571
+ const run = runAt(found, char);
572
+ const before = text[found - 1];
573
+ const after = text[found + run];
574
+ return before !== undefined && !/\s/.test(before) && run === width && !(char === "_" && after !== undefined && WORD.test(after));
575
+ };
576
+ const closeAt = (from: number, char: string, width: number): number => {
577
+ // An opener can start inside a longer run (`***a***`), where the run remaining from here is the one that counts.
578
+ if (text[from] === char && usable(from, char, width)) return from;
579
+ const key = `${char}\u0000${width}`;
580
+ let list = starts.get(key);
581
+ if (!list) {
582
+ list = [];
583
+ for (let at = 0; at < text.length; ) {
584
+ if (text[at] !== char) {
585
+ at += 1;
586
+ continue;
587
+ }
588
+ const run = runAt(at, char);
589
+ if (usable(at, char, width)) list.push(at);
590
+ at += run;
591
+ }
592
+ starts.set(key, list);
593
+ }
594
+ let low = 0;
595
+ let high = list.length;
596
+ while (low < high) {
597
+ const middle = (low + high) >> 1;
598
+ if (list[middle]! < from) low = middle + 1;
599
+ else high = middle;
600
+ }
601
+ return low < list.length ? list[low]! : -1;
602
+ };
603
+ return { runAt, closeAt };
604
+ }
605
+
606
+ function emphasis(text: string, at: number, delimiters: Delimiters, depth: number, links: boolean): Span | null {
607
+ const char = text[at]!;
608
+ const run = delimiters.runAt(at, char);
609
+ const width = Math.min(run, 2);
610
+ const open = at + width;
611
+ const first = text[open];
612
+ if (!first || /\s/.test(first)) return null;
613
+ if (char === "_" && at > 0 && WORD.test(text[at - 1]!)) return null;
614
+ const close = delimiters.closeAt(open, char, width);
615
+ // A run that closes on itself (`****`, which can open and close at the same character) holds nothing, and an
616
+ // emphasis with no content would swallow its own delimiters and render nothing at all.
617
+ if (close < 0 || close === open) return null;
618
+ const children = inlinePass(text.slice(open, close), depth + 1, links);
619
+ return { node: width === 2 ? { kind: "strong", children } : { kind: "em", children }, end: close + width };
620
+ }