@aljazmc/syntax 0.0.0-stage → 0.4.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.
package/bin/index.js ADDED
@@ -0,0 +1,4612 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // shared/syntax/src/markdown/scan.ts
5
+ var TAGNAME = "[A-Za-z][A-Za-z0-9-]*";
6
+ var ATTRIBUTE = `(?:\\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\\s*=\\s*(?:[^"'=<>\`\\x00-\\x20]+|'[^']*'|"[^"]*"))?)`;
7
+ var OPEN_TAG = `<${TAGNAME}${ATTRIBUTE}*\\s*/?>`;
8
+ var CLOSE_TAG = `</${TAGNAME}\\s*[>]`;
9
+ var Scan = class {
10
+ static {
11
+ __name(this, "Scan");
12
+ }
13
+ /** Normalizes a link label for matching, like `[Foo Bar]` and `[foo bar]`. */
14
+ static label(label) {
15
+ return label.slice(1, -1).trim().replace(/[ \t\r\n]+/g, " ").toLowerCase().toUpperCase();
16
+ }
17
+ /** A link destination, `<...>` or without spaces and with balanced parentheses. */
18
+ static destination(text, from) {
19
+ if (text[from] === "<") {
20
+ for (let index2 = from + 1; index2 < text.length; index2++) {
21
+ const char = text[index2];
22
+ if (char === "\\") index2++;
23
+ else if (char === "\n" || char === "<") return;
24
+ else if (char === ">")
25
+ return [index2 + 1, text.slice(from, index2 + 1)];
26
+ }
27
+ return;
28
+ }
29
+ let depth = 0;
30
+ let index = from;
31
+ while (index < text.length) {
32
+ const char = text[index];
33
+ if (char === "\\" && /[!-/:-@[-`{-~]/.test(text[index + 1] ?? "")) {
34
+ index += 2;
35
+ continue;
36
+ }
37
+ if (char === "(") depth++;
38
+ else if (char === ")") {
39
+ if (depth === 0) break;
40
+ depth--;
41
+ } else if (char <= " " || char === "\x7F") break;
42
+ index++;
43
+ }
44
+ if (depth !== 0) return;
45
+ return [index, text.slice(from, index)];
46
+ }
47
+ /** The position after a link title in quotes or parentheses. */
48
+ static title(text, from) {
49
+ const open = text[from];
50
+ const close = open === "(" ? ")" : open;
51
+ if (open !== '"' && open !== "'" && open !== "(") return;
52
+ for (let index = from + 1; index < text.length; index++) {
53
+ const char = text[index];
54
+ if (char === "\\") index++;
55
+ else if (char === close) return index + 1;
56
+ else if (open === "(" && char === "(") return;
57
+ else if (char === "\n" && text[index + 1] === "\n") return;
58
+ }
59
+ }
60
+ };
61
+
62
+ // shared/syntax/src/markdown/inlines.ts
63
+ var Item = class {
64
+ static {
65
+ __name(this, "Item");
66
+ }
67
+ kind;
68
+ start;
69
+ end;
70
+ parent = null;
71
+ first = null;
72
+ last = null;
73
+ prev = null;
74
+ next = null;
75
+ delimiter = "";
76
+ tail = "";
77
+ reference = null;
78
+ label = null;
79
+ destination = "";
80
+ title = null;
81
+ constructor(kind, start, end) {
82
+ this.kind = kind;
83
+ this.start = start;
84
+ this.end = end;
85
+ }
86
+ append(child) {
87
+ child.unlink();
88
+ child.parent = this;
89
+ if (this.last) {
90
+ this.last.next = child;
91
+ child.prev = this.last;
92
+ } else this.first = child;
93
+ this.last = child;
94
+ }
95
+ insertAfter(sibling) {
96
+ sibling.unlink();
97
+ sibling.next = this.next;
98
+ if (sibling.next) sibling.next.prev = sibling;
99
+ sibling.prev = this;
100
+ this.next = sibling;
101
+ sibling.parent = this.parent;
102
+ if (this.parent && !sibling.next) this.parent.last = sibling;
103
+ }
104
+ unlink() {
105
+ if (this.prev) this.prev.next = this.next;
106
+ else if (this.parent) this.parent.first = this.next;
107
+ if (this.next) this.next.prev = this.prev;
108
+ else if (this.parent) this.parent.last = this.prev;
109
+ this.parent = null;
110
+ this.next = null;
111
+ this.prev = null;
112
+ }
113
+ };
114
+ var ENTITY = /^&(?:#[xX][a-fA-F0-9]{1,6}|#[0-9]{1,7}|[A-Za-z][A-Za-z0-9]{1,31});/;
115
+ var AUTOLINK = /^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\p{Cc} ]*>/u;
116
+ var EMAIL = /^<[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*>/;
117
+ var HTML_TAG = new RegExp(
118
+ `^(?:${OPEN_TAG}|${CLOSE_TAG}|<!-->|<!--->|<!--[\\s\\S]*?-->|[<][?][\\s\\S]*?[?][>]|<![A-Za-z][^>]*>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>)`,
119
+ "i"
120
+ );
121
+ var PUNCTUATION = /[\p{P}\p{S}]/u;
122
+ var WHITESPACE = /[\s\p{Zs}]/u;
123
+ var Inlines = class _Inlines {
124
+ static {
125
+ __name(this, "Inlines");
126
+ }
127
+ #labels;
128
+ #gfm;
129
+ #text = "";
130
+ #position = 0;
131
+ #delimiters = null;
132
+ #brackets = null;
133
+ constructor(labels, gfm) {
134
+ this.#labels = labels;
135
+ this.#gfm = gfm;
136
+ }
137
+ parse(text) {
138
+ this.#text = text;
139
+ this.#position = 0;
140
+ this.#delimiters = null;
141
+ this.#brackets = null;
142
+ const root = new Item("text", 0, text.length);
143
+ while (this.#position < text.length) this.#inline(root);
144
+ this.#processEmphasis(null);
145
+ return _Inlines.#convert(root, text);
146
+ }
147
+ #inline(block) {
148
+ const text = this.#text;
149
+ const char = text[this.#position];
150
+ switch (char) {
151
+ case "\n":
152
+ this.#newline(block);
153
+ return;
154
+ case "\\":
155
+ this.#backslash(block);
156
+ return;
157
+ case "`":
158
+ this.#backticks(block);
159
+ return;
160
+ case "~":
161
+ if (!this.#gfm) break;
162
+ this.#delimiter(block, char);
163
+ return;
164
+ case "*":
165
+ case "_":
166
+ this.#delimiter(block, char);
167
+ return;
168
+ case "!":
169
+ if (text[this.#position + 1] !== "[") break;
170
+ this.#openBracket(block, true);
171
+ return;
172
+ case "[":
173
+ this.#openBracket(block, false);
174
+ return;
175
+ case "]":
176
+ this.#closeBracket(block);
177
+ return;
178
+ case "<": {
179
+ const rest = text.slice(this.#position);
180
+ const match = AUTOLINK.exec(rest) ?? EMAIL.exec(rest);
181
+ const tag = match ? null : HTML_TAG.exec(rest);
182
+ if (match || tag) {
183
+ this.#add(
184
+ block,
185
+ match ? "autolink" : "html",
186
+ (match ?? tag)[0].length
187
+ );
188
+ return;
189
+ }
190
+ break;
191
+ }
192
+ case "&": {
193
+ const entity = ENTITY.exec(text.slice(this.#position));
194
+ if (entity) {
195
+ this.#add(block, "text", entity[0].length);
196
+ return;
197
+ }
198
+ break;
199
+ }
200
+ }
201
+ const special = this.#gfm ? /[\n`[\]\\!<&*_~]/g : /[\n`[\]\\!<&*_]/g;
202
+ special.lastIndex = this.#position + 1;
203
+ const next = special.exec(text);
204
+ this.#add(
205
+ block,
206
+ "text",
207
+ (next ? next.index : text.length) - this.#position
208
+ );
209
+ }
210
+ #add(block, kind, length) {
211
+ const item = new Item(kind, this.#position, this.#position + length);
212
+ block.append(item);
213
+ this.#position += length;
214
+ return item;
215
+ }
216
+ #newline(block) {
217
+ const last = block.last;
218
+ let start = this.#position;
219
+ let hard = false;
220
+ if (last?.kind === "text" && this.#text[last.end - 1] === " ") {
221
+ let spaces = last.end;
222
+ while (spaces > last.start && this.#text[spaces - 1] === " ")
223
+ spaces--;
224
+ hard = last.end - spaces >= 2;
225
+ start = spaces;
226
+ last.end = spaces;
227
+ if (last.end === last.start) last.unlink();
228
+ }
229
+ const item = new Item(
230
+ hard ? "hardbreak" : "softbreak",
231
+ start,
232
+ this.#position + 1
233
+ );
234
+ block.append(item);
235
+ this.#position++;
236
+ while (this.#text[this.#position] === " ") this.#position++;
237
+ }
238
+ #backslash(block) {
239
+ const next = this.#text[this.#position + 1];
240
+ if (next === "\n") {
241
+ this.#add(block, "hardbreak", 2);
242
+ while (this.#text[this.#position] === " ") this.#position++;
243
+ } else if (next !== void 0 && /[!-/:-@[-`{-~]/.test(next))
244
+ this.#add(block, "text", 2);
245
+ else this.#add(block, "text", 1);
246
+ }
247
+ #backticks(block) {
248
+ const text = this.#text;
249
+ const run = /^`+/.exec(text.slice(this.#position))?.[0];
250
+ const pattern = /`+/g;
251
+ pattern.lastIndex = this.#position + run.length;
252
+ for (let match = pattern.exec(text); match; match = pattern.exec(text))
253
+ if (match[0].length === run.length) {
254
+ this.#add(
255
+ block,
256
+ "code",
257
+ match.index + run.length - this.#position
258
+ );
259
+ return;
260
+ }
261
+ this.#add(block, "text", run.length);
262
+ }
263
+ #delimiter(block, char) {
264
+ const text = this.#text;
265
+ const start = this.#position;
266
+ let end = start;
267
+ while (text[end] === char) end++;
268
+ const count = end - start;
269
+ const before = start === 0 ? "\n" : _Inlines.#charBefore(text, start);
270
+ const after = end >= text.length ? "\n" : _Inlines.#charAt(text, end);
271
+ const afterSpace = WHITESPACE.test(after);
272
+ const afterPunct = PUNCTUATION.test(after);
273
+ const beforeSpace = WHITESPACE.test(before);
274
+ const beforePunct = PUNCTUATION.test(before);
275
+ const left = !afterSpace && (!afterPunct || beforeSpace || beforePunct);
276
+ const right = !beforeSpace && (!beforePunct || afterSpace || afterPunct);
277
+ let canOpen;
278
+ let canClose;
279
+ if (char === "_") {
280
+ canOpen = left && (!right || beforePunct);
281
+ canClose = right && (!left || afterPunct);
282
+ } else {
283
+ canOpen = left;
284
+ canClose = right;
285
+ }
286
+ if (char === "~" && count > 2) {
287
+ canOpen = false;
288
+ canClose = false;
289
+ }
290
+ const item = this.#add(block, "text", count);
291
+ this.#delimiters = {
292
+ char,
293
+ count,
294
+ original: count,
295
+ item,
296
+ previous: this.#delimiters,
297
+ next: null,
298
+ canOpen,
299
+ canClose
300
+ };
301
+ if (this.#delimiters.previous)
302
+ this.#delimiters.previous.next = this.#delimiters;
303
+ }
304
+ static #charBefore(text, index) {
305
+ const code = text.codePointAt(index - 2);
306
+ if (code !== void 0 && code > 65535)
307
+ return String.fromCodePoint(code);
308
+ return text[index - 1];
309
+ }
310
+ static #charAt(text, index) {
311
+ return String.fromCodePoint(text.codePointAt(index));
312
+ }
313
+ #openBracket(block, image) {
314
+ const start = this.#position;
315
+ const item = this.#add(block, "text", image ? 2 : 1);
316
+ if (this.#brackets) this.#brackets.bracketAfter = true;
317
+ this.#brackets = {
318
+ item,
319
+ previous: this.#brackets,
320
+ previousDelimiter: this.#delimiters,
321
+ index: start + (image ? 2 : 1),
322
+ image,
323
+ active: true,
324
+ bracketAfter: false
325
+ };
326
+ }
327
+ #closeBracket(block) {
328
+ const text = this.#text;
329
+ const close = this.#position;
330
+ this.#position++;
331
+ const opener = this.#brackets;
332
+ if (!opener) {
333
+ block.append(new Item("text", close, close + 1));
334
+ return;
335
+ }
336
+ if (!opener.active) {
337
+ block.append(new Item("text", close, close + 1));
338
+ this.#brackets = opener.previous;
339
+ return;
340
+ }
341
+ let matched = false;
342
+ let reference = null;
343
+ let label = null;
344
+ let destination = "";
345
+ let title = null;
346
+ const save = this.#position;
347
+ if (text[this.#position] === "(") {
348
+ this.#position++;
349
+ this.#spaces();
350
+ const parsed = Scan.destination(text, this.#position);
351
+ if (parsed && (parsed[0] > this.#position || text[parsed[0]] === ")")) {
352
+ destination = parsed[1];
353
+ this.#position = parsed[0];
354
+ const beforeSpaces = this.#position;
355
+ this.#spaces();
356
+ if (this.#position > beforeSpaces) {
357
+ const end = Scan.title(text, this.#position);
358
+ if (end !== void 0) {
359
+ title = text.slice(this.#position, end);
360
+ this.#position = end;
361
+ this.#spaces();
362
+ }
363
+ }
364
+ if (text[this.#position] === ")") {
365
+ this.#position++;
366
+ matched = true;
367
+ }
368
+ }
369
+ if (!matched) {
370
+ this.#position = save;
371
+ destination = "";
372
+ title = null;
373
+ }
374
+ }
375
+ if (!matched) {
376
+ const before = this.#position;
377
+ const length = this.#label();
378
+ let key;
379
+ if (length > 2) key = text.slice(before, before + length);
380
+ else if (!opener.bracketAfter)
381
+ key = `[${text.slice(opener.index, close)}]`;
382
+ if (length === 0) this.#position = save;
383
+ if (key && this.#labels.has(Scan.label(key))) {
384
+ matched = true;
385
+ label = key;
386
+ reference = length > 2 ? "full" : length === 2 ? "collapsed" : "shortcut";
387
+ } else this.#position = save;
388
+ }
389
+ if (!matched) {
390
+ this.#brackets = opener.previous;
391
+ block.append(new Item("text", close, close + 1));
392
+ return;
393
+ }
394
+ const link = new Item(
395
+ opener.image ? "image" : "link",
396
+ opener.item.start,
397
+ this.#position
398
+ );
399
+ link.tail = text.slice(close + 1, this.#position);
400
+ link.reference = reference;
401
+ link.label = label;
402
+ link.destination = destination;
403
+ link.title = title;
404
+ let child = opener.item.next;
405
+ while (child) {
406
+ const next = child.next;
407
+ link.append(child);
408
+ child = next;
409
+ }
410
+ block.append(link);
411
+ this.#processEmphasis(opener.previousDelimiter);
412
+ this.#brackets = opener.previous;
413
+ opener.item.unlink();
414
+ if (!opener.image) {
415
+ for (let bracket = this.#brackets; bracket; bracket = bracket.previous)
416
+ if (!bracket.image) bracket.active = false;
417
+ }
418
+ }
419
+ /** The length of a link label at the position, 0 when there is none. */
420
+ #label() {
421
+ const text = this.#text;
422
+ if (text[this.#position] !== "[") return 0;
423
+ for (let index = this.#position + 1; index < text.length; index++) {
424
+ const char = text[index];
425
+ if (char === "\\") index++;
426
+ else if (char === "[") return 0;
427
+ else if (char === "]") {
428
+ if (index - this.#position > 1e3) return 0;
429
+ const length = index + 1 - this.#position;
430
+ if (length > 2 && !/[^ \t\n]/.test(text.slice(this.#position + 1, index)))
431
+ return 0;
432
+ this.#position = index + 1;
433
+ return length;
434
+ }
435
+ }
436
+ return 0;
437
+ }
438
+ #spaces() {
439
+ let newline = false;
440
+ while (this.#position < this.#text.length) {
441
+ const char = this.#text[this.#position];
442
+ if (char === "\n" && !newline) newline = true;
443
+ else if (char !== " " && char !== " ") break;
444
+ this.#position++;
445
+ }
446
+ }
447
+ #remove(delimiter) {
448
+ if (delimiter.previous) delimiter.previous.next = delimiter.next;
449
+ if (delimiter.next) delimiter.next.previous = delimiter.previous;
450
+ else this.#delimiters = delimiter.previous;
451
+ }
452
+ #processEmphasis(bottom) {
453
+ const openersBottom = /* @__PURE__ */ new Map();
454
+ let closer = this.#delimiters;
455
+ while (closer && closer.previous !== bottom) closer = closer.previous;
456
+ while (closer) {
457
+ if (!closer.canClose) {
458
+ closer = closer.next;
459
+ continue;
460
+ }
461
+ const key = closer.char === "~" ? `~${closer.count}` : `${closer.char}${closer.canOpen}${closer.original % 3}`;
462
+ const floor = openersBottom.has(key) ? openersBottom.get(key) : bottom;
463
+ let opener = closer.previous;
464
+ let found = false;
465
+ while (opener && opener !== bottom && opener !== floor) {
466
+ if (opener.char === closer.char && opener.canOpen) {
467
+ if (closer.char === "~") {
468
+ if (opener.count === closer.count) {
469
+ found = true;
470
+ break;
471
+ }
472
+ } else {
473
+ const odd = (closer.canOpen || opener.canClose) && closer.original % 3 !== 0 && (opener.original + closer.original) % 3 === 0;
474
+ if (!odd) {
475
+ found = true;
476
+ break;
477
+ }
478
+ }
479
+ }
480
+ opener = opener.previous;
481
+ }
482
+ const old = closer;
483
+ if (found && opener) {
484
+ const use = closer.char === "~" ? closer.count : closer.count >= 2 && opener.count >= 2 ? 2 : 1;
485
+ const openItem = opener.item;
486
+ const closeItem = closer.item;
487
+ opener.count -= use;
488
+ closer.count -= use;
489
+ openItem.end -= use;
490
+ closeItem.start += use;
491
+ const emph = new Item(
492
+ closer.char === "~" ? "del" : use === 1 ? "emph" : "strong",
493
+ openItem.end,
494
+ closeItem.start
495
+ );
496
+ emph.delimiter = closer.char.repeat(use);
497
+ let child = openItem.next;
498
+ while (child && child !== closeItem) {
499
+ const next = child.next;
500
+ emph.append(child);
501
+ child = next;
502
+ }
503
+ openItem.insertAfter(emph);
504
+ let between = closer.previous;
505
+ while (between && between !== opener) {
506
+ const previous = between.previous;
507
+ this.#remove(between);
508
+ between = previous;
509
+ }
510
+ if (opener.count === 0) {
511
+ openItem.unlink();
512
+ this.#remove(opener);
513
+ }
514
+ if (closer.count === 0) {
515
+ closeItem.unlink();
516
+ const next = closer.next;
517
+ this.#remove(closer);
518
+ closer = next;
519
+ }
520
+ } else {
521
+ closer = closer.next;
522
+ openersBottom.set(key, old.previous);
523
+ if (!old.canOpen) this.#remove(old);
524
+ }
525
+ }
526
+ while (this.#delimiters && this.#delimiters !== bottom)
527
+ this.#remove(this.#delimiters);
528
+ }
529
+ static #convert(parent, text) {
530
+ const inlines = [];
531
+ for (let item = parent.first; item; item = item.next) {
532
+ const { start, end } = item;
533
+ const raw = text.slice(start, end);
534
+ const previous = inlines.at(-1);
535
+ switch (item.kind) {
536
+ case "text":
537
+ if (start === end) break;
538
+ if (previous?.type === "Text" && previous.end === start) {
539
+ previous.end = end;
540
+ previous.raw = text.slice(previous.start, end);
541
+ } else inlines.push({ type: "Text", start, end, raw });
542
+ break;
543
+ case "softbreak":
544
+ case "hardbreak":
545
+ inlines.push({
546
+ type: "Break",
547
+ start,
548
+ end,
549
+ hard: item.kind === "hardbreak",
550
+ raw
551
+ });
552
+ break;
553
+ case "code":
554
+ inlines.push({ type: "Code", start, end, raw });
555
+ break;
556
+ case "autolink":
557
+ inlines.push({ type: "Autolink", start, end, raw });
558
+ break;
559
+ case "html":
560
+ inlines.push({ type: "Html", start, end, raw });
561
+ break;
562
+ case "emph":
563
+ case "strong":
564
+ case "del":
565
+ inlines.push({
566
+ type: item.kind === "emph" ? "Emphasis" : item.kind === "strong" ? "Strong" : "Strikethrough",
567
+ start,
568
+ end,
569
+ delimiter: item.delimiter,
570
+ children: _Inlines.#convert(item, text)
571
+ });
572
+ break;
573
+ case "link":
574
+ case "image":
575
+ inlines.push({
576
+ type: item.kind === "link" ? "Link" : "Image",
577
+ start,
578
+ end,
579
+ children: _Inlines.#convert(item, text),
580
+ tail: item.tail,
581
+ reference: item.reference,
582
+ label: item.label,
583
+ destination: item.destination,
584
+ title: item.title
585
+ });
586
+ break;
587
+ }
588
+ }
589
+ return inlines;
590
+ }
591
+ };
592
+
593
+ // shared/syntax/src/markdown/blocks.ts
594
+ var htmlOpen = [
595
+ /./,
596
+ /^<(?:script|pre|textarea|style)(?:\s|>|$)/i,
597
+ /^<!--/,
598
+ /^<[?]/,
599
+ /^<![A-Za-z]/,
600
+ /^<!\[CDATA\[/,
601
+ /^<[/]?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|[/]?[>]|$)/i,
602
+ new RegExp(`^(?:${OPEN_TAG}|${CLOSE_TAG})\\s*$`, "i")
603
+ ];
604
+ var htmlClose = [
605
+ /./,
606
+ /<\/(?:script|pre|textarea|style)>/i,
607
+ /-->/,
608
+ /\?>/,
609
+ />/,
610
+ /\]\]>/
611
+ ];
612
+ var thematicBreak = /^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$|^(?:-[ \t]*){3,}$/;
613
+ var delimiterRow = /^\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
614
+ var Blocks = class _Blocks {
615
+ static {
616
+ __name(this, "Blocks");
617
+ }
618
+ #source;
619
+ #gfm;
620
+ #lines = [];
621
+ #root;
622
+ #tip;
623
+ #oldTip;
624
+ #lastMatched;
625
+ #allClosed = true;
626
+ #lineNumber = 0;
627
+ #line = "";
628
+ #lineStart = 0;
629
+ #offset = 0;
630
+ #column = 0;
631
+ #nextNonspace = 0;
632
+ #nextNonspaceColumn = 0;
633
+ #indent = 0;
634
+ #indented = false;
635
+ #blank = false;
636
+ #partialTab = false;
637
+ /** Whether a block took the whole line when it started, like a fence or a delimiter row. */
638
+ #consumed = false;
639
+ /** Where the content of the line starts, after the prefixes of the containers. */
640
+ #contentStart = 0;
641
+ constructor(source, options = {}) {
642
+ this.#source = source;
643
+ this.#gfm = options.gfm ?? true;
644
+ this.#root = this.#create("Root", null, 0, 1);
645
+ this.#tip = this.#root;
646
+ this.#oldTip = this.#root;
647
+ this.#lastMatched = this.#root;
648
+ const pattern = /\r\n|\r|\n/g;
649
+ let start = 0;
650
+ for (const match of source.matchAll(pattern)) {
651
+ this.#lines.push({
652
+ text: source.slice(start, match.index),
653
+ start
654
+ });
655
+ start = match.index + match[0].length;
656
+ }
657
+ if (start < source.length)
658
+ this.#lines.push({ text: source.slice(start), start });
659
+ }
660
+ parse(frontmatter = false) {
661
+ const bom = this.#source.startsWith("\uFEFF");
662
+ let first = 0;
663
+ let matter = null;
664
+ if (bom && this.#lines[0])
665
+ this.#lines[0] = {
666
+ text: this.#lines[0].text.slice(1),
667
+ start: 1
668
+ };
669
+ if (frontmatter && /^---[ \t]*$/.test(this.#lines[0]?.text ?? "")) {
670
+ const close = this.#lines.findIndex(
671
+ (line, index) => index > 0 && /^---[ \t]*$/.test(line.text)
672
+ );
673
+ if (close > 0) {
674
+ const end = this.#lines[close];
675
+ matter = {
676
+ type: "Frontmatter",
677
+ start: this.#lines[0]?.start ?? 0,
678
+ end: end.start + end.text.length,
679
+ line: 1,
680
+ endLine: close + 1,
681
+ raw: this.#source.slice(
682
+ this.#lines[0]?.start ?? 0,
683
+ end.start + end.text.length
684
+ )
685
+ };
686
+ first = close + 1;
687
+ this.#lineNumber = first;
688
+ }
689
+ }
690
+ for (const { text, start } of this.#lines.slice(first)) {
691
+ this.#lineStart = start;
692
+ this.#incorporate(text);
693
+ }
694
+ while (this.#tip !== this.#root) this.#close(this.#tip);
695
+ this.#close(this.#root);
696
+ const definitions = /* @__PURE__ */ new Map();
697
+ const children = this.#blocks(this.#root, definitions);
698
+ const inlines = new Inlines(new Set(definitions.keys()), this.#gfm);
699
+ _Blocks.#inlines(children, inlines);
700
+ return {
701
+ type: "Root",
702
+ start: 0,
703
+ end: this.#source.length,
704
+ line: 1,
705
+ endLine: Math.max(this.#lines.length, 1),
706
+ bom,
707
+ frontmatter: matter,
708
+ children
709
+ };
710
+ }
711
+ #create(kind, parent, start, line) {
712
+ return {
713
+ kind,
714
+ parent,
715
+ children: [],
716
+ open: true,
717
+ start,
718
+ line,
719
+ endLine: line,
720
+ lines: [],
721
+ offsets: [],
722
+ markerOffset: 0,
723
+ padding: 0,
724
+ marker: "",
725
+ spaces: 0,
726
+ delimiter: "",
727
+ ordered: false,
728
+ number: null,
729
+ fence: "",
730
+ fenceOffset: 0,
731
+ info: "",
732
+ closed: false,
733
+ htmlKind: 0,
734
+ level: 0,
735
+ setext: false,
736
+ alignments: [],
737
+ definitions: [],
738
+ indents: [],
739
+ prefixes: [],
740
+ lazy: /* @__PURE__ */ new Set()
741
+ };
742
+ }
743
+ // line state, like commonmark.js
744
+ #findNextNonspace() {
745
+ const line = this.#line;
746
+ let index = this.#offset;
747
+ let column = this.#column;
748
+ let char = line[index];
749
+ while (char === " " || char === " ") {
750
+ column += char === " " ? 1 : 4 - column % 4;
751
+ char = line[++index];
752
+ }
753
+ this.#blank = index >= line.length;
754
+ this.#nextNonspace = index;
755
+ this.#nextNonspaceColumn = column;
756
+ this.#indent = column - this.#column;
757
+ this.#indented = this.#indent >= 4;
758
+ }
759
+ #advanceNextNonspace() {
760
+ this.#offset = this.#nextNonspace;
761
+ this.#column = this.#nextNonspaceColumn;
762
+ this.#partialTab = false;
763
+ }
764
+ #advance(count, columns = false) {
765
+ const line = this.#line;
766
+ let remaining = count;
767
+ let char = line[this.#offset];
768
+ while (remaining > 0 && char !== void 0) {
769
+ if (char === " ") {
770
+ const toTab = 4 - this.#column % 4;
771
+ if (columns) {
772
+ this.#partialTab = toTab > remaining;
773
+ const advance = Math.min(toTab, remaining);
774
+ this.#column += advance;
775
+ this.#offset += this.#partialTab ? 0 : 1;
776
+ remaining -= advance;
777
+ } else {
778
+ this.#partialTab = false;
779
+ this.#column += toTab;
780
+ this.#offset += 1;
781
+ remaining -= 1;
782
+ }
783
+ } else {
784
+ this.#partialTab = false;
785
+ this.#offset += 1;
786
+ this.#column += 1;
787
+ remaining -= 1;
788
+ }
789
+ char = line[this.#offset];
790
+ }
791
+ }
792
+ #rest() {
793
+ return this.#line.slice(this.#nextNonspace);
794
+ }
795
+ #addLine() {
796
+ this.#tip.prefixes.push(this.#line.slice(0, this.#offset));
797
+ let text = this.#line.slice(this.#offset);
798
+ if (this.#partialTab) {
799
+ this.#offset += 1;
800
+ const spaces = 4 - this.#column % 4;
801
+ text = " ".repeat(spaces) + this.#line.slice(this.#offset);
802
+ }
803
+ this.#tip.indents.push(
804
+ this.#line.slice(
805
+ this.#contentStart,
806
+ Math.max(this.#offset, this.#contentStart)
807
+ )
808
+ );
809
+ this.#tip.lines.push(text);
810
+ this.#tip.offsets.push(this.#lineStart + this.#offset);
811
+ this.#tip.endLine = this.#lineNumber;
812
+ }
813
+ #add(kind, offset) {
814
+ while (!_Blocks.#canContain(this.#tip.kind, kind))
815
+ this.#close(this.#tip);
816
+ const block = this.#create(
817
+ kind,
818
+ this.#tip,
819
+ this.#lineStart + offset,
820
+ this.#lineNumber
821
+ );
822
+ this.#tip.children.push(block);
823
+ this.#tip = block;
824
+ return block;
825
+ }
826
+ static #canContain(parent, child) {
827
+ if (parent === "List") return child === "ListItem";
828
+ return (parent === "Root" || parent === "BlockQuote" || parent === "ListItem") && child !== "ListItem";
829
+ }
830
+ #closeUnmatched() {
831
+ if (this.#allClosed) return;
832
+ while (this.#oldTip !== this.#lastMatched) {
833
+ const parent = this.#oldTip.parent;
834
+ this.#close(this.#oldTip);
835
+ this.#oldTip = parent;
836
+ }
837
+ this.#allClosed = true;
838
+ }
839
+ #close(block) {
840
+ const parent = block.parent;
841
+ block.open = false;
842
+ if (block.kind === "Paragraph") this.#takeDefinitions(block);
843
+ if (block.kind === "CodeBlock" && !block.fence) {
844
+ while (block.lines.length > 0 && /^[ \t]*$/.test(block.lines.at(-1) ?? "")) {
845
+ block.lines.pop();
846
+ block.offsets.pop();
847
+ block.prefixes.pop();
848
+ }
849
+ block.endLine = block.line + Math.max(block.lines.length - 1, 0);
850
+ }
851
+ if (block.children.length > 0)
852
+ block.endLine = Math.max(
853
+ block.endLine,
854
+ ...block.children.map((child) => child.endLine)
855
+ );
856
+ if (parent) this.#tip = parent;
857
+ }
858
+ /** Continues an open block on the current line: 0 matched, 1 not, 2 the line is consumed. */
859
+ #continue(block) {
860
+ const line = this.#line;
861
+ switch (block.kind) {
862
+ case "BlockQuote":
863
+ if (!this.#indented && line[this.#nextNonspace] === ">") {
864
+ this.#advanceNextNonspace();
865
+ this.#advance(1);
866
+ if (line[this.#offset] === " " || line[this.#offset] === " ")
867
+ this.#advance(1, true);
868
+ block.endLine = this.#lineNumber;
869
+ return 0;
870
+ }
871
+ return 1;
872
+ case "ListItem":
873
+ if (this.#blank) {
874
+ if (block.children.length === 0) return 1;
875
+ this.#advanceNextNonspace();
876
+ return 0;
877
+ }
878
+ if (this.#indent >= block.markerOffset + block.padding) {
879
+ this.#advance(block.markerOffset + block.padding, true);
880
+ return 0;
881
+ }
882
+ return 1;
883
+ case "CodeBlock": {
884
+ if (block.fence) {
885
+ const match = this.#indent <= 3 && line[this.#nextNonspace] === block.fence[0] ? /^(?:`{3,}|~{3,})(?=[ \t]*$)/.exec(this.#rest()) : null;
886
+ if (match && match[0].length >= block.fence.length) {
887
+ block.closed = true;
888
+ block.endLine = this.#lineNumber;
889
+ this.#close(block);
890
+ return 2;
891
+ }
892
+ let skip = block.fenceOffset;
893
+ while (skip > 0 && (line[this.#offset] === " " || line[this.#offset] === " ")) {
894
+ this.#advance(1, true);
895
+ skip--;
896
+ }
897
+ return 0;
898
+ }
899
+ if (this.#indent >= 4) {
900
+ this.#advance(4, true);
901
+ return 0;
902
+ }
903
+ if (this.#blank) {
904
+ this.#advanceNextNonspace();
905
+ return 0;
906
+ }
907
+ return 1;
908
+ }
909
+ case "HtmlBlock":
910
+ return this.#blank && (block.htmlKind === 6 || block.htmlKind === 7) ? 1 : 0;
911
+ case "Paragraph":
912
+ case "Table":
913
+ return this.#blank ? 1 : 0;
914
+ case "Heading":
915
+ case "ThematicBreak":
916
+ return 1;
917
+ default:
918
+ return 0;
919
+ }
920
+ }
921
+ #incorporate(text) {
922
+ let container = this.#root;
923
+ this.#oldTip = this.#tip;
924
+ this.#offset = 0;
925
+ this.#column = 0;
926
+ this.#blank = false;
927
+ this.#partialTab = false;
928
+ this.#consumed = false;
929
+ this.#lineNumber++;
930
+ this.#line = text.includes("\0") ? text.replaceAll("\0", "\uFFFD") : text;
931
+ for (; ; ) {
932
+ const last = container.children.at(-1);
933
+ if (!last?.open) break;
934
+ container = last;
935
+ this.#findNextNonspace();
936
+ const result = this.#continue(container);
937
+ if (result === 2) return;
938
+ if (result === 1) {
939
+ container = container.parent;
940
+ break;
941
+ }
942
+ }
943
+ this.#allClosed = container === this.#oldTip;
944
+ this.#lastMatched = container;
945
+ this.#contentStart = this.#offset;
946
+ let matchedLeaf = container.kind !== "Paragraph" && container.kind !== "Table" && (container.kind === "CodeBlock" || container.kind === "HtmlBlock");
947
+ while (!matchedLeaf) {
948
+ this.#findNextNonspace();
949
+ if (!this.#indented && !/^[#`~*+_=<>0-9-|:]/.test(this.#rest())) {
950
+ this.#advanceNextNonspace();
951
+ break;
952
+ }
953
+ const result = this.#start(container);
954
+ if (result === 0) {
955
+ this.#advanceNextNonspace();
956
+ break;
957
+ }
958
+ container = this.#tip;
959
+ if (result === 1) this.#contentStart = this.#offset;
960
+ if (result === 2) matchedLeaf = true;
961
+ }
962
+ if (!this.#allClosed && !this.#blank && this.#tip.kind === "Paragraph") {
963
+ this.#tip.lazy.add(this.#lineNumber);
964
+ this.#addLine();
965
+ for (let block = this.#tip; block; block = block.parent)
966
+ if (block.kind === "BlockQuote" || block.kind === "ListItem")
967
+ block.endLine = this.#lineNumber;
968
+ return;
969
+ }
970
+ this.#closeUnmatched();
971
+ const kind = container.kind;
972
+ if (this.#consumed) return;
973
+ if (kind === "CodeBlock" || kind === "HtmlBlock") {
974
+ this.#addLine();
975
+ if (kind === "HtmlBlock" && container.htmlKind >= 1 && container.htmlKind <= 5 && htmlClose[container.htmlKind]?.test(
976
+ this.#line.slice(this.#offset)
977
+ ))
978
+ this.#close(container);
979
+ } else if (kind === "Table") {
980
+ if (!this.#blank) this.#addLine();
981
+ } else if (kind === "Paragraph") {
982
+ if (!this.#blank) this.#addLine();
983
+ } else if (this.#offset < this.#line.length && !this.#blank) {
984
+ this.#add("Paragraph", this.#nextNonspace);
985
+ this.#advanceNextNonspace();
986
+ this.#addLine();
987
+ }
988
+ }
989
+ /** Tries to start a block: 0 none, 1 a container, 2 a leaf that takes the rest of the line. */
990
+ #start(container) {
991
+ const line = this.#line;
992
+ const rest = this.#rest();
993
+ const char = line[this.#nextNonspace];
994
+ if (!this.#indented && char === ">") {
995
+ this.#advanceNextNonspace();
996
+ this.#advance(1);
997
+ if (line[this.#offset] === " " || line[this.#offset] === " ")
998
+ this.#advance(1, true);
999
+ this.#closeUnmatched();
1000
+ this.#add("BlockQuote", this.#nextNonspace);
1001
+ return 1;
1002
+ }
1003
+ if (!this.#indented) {
1004
+ const atx = /^#{1,6}(?:[ \t]+|$)/.exec(rest);
1005
+ if (atx) {
1006
+ const start = this.#nextNonspace;
1007
+ this.#advanceNextNonspace();
1008
+ this.#advance(atx[0].length);
1009
+ this.#closeUnmatched();
1010
+ const heading = this.#add("Heading", start);
1011
+ heading.level = atx[0].trim().length;
1012
+ heading.lines.push(
1013
+ line.slice(this.#offset).replace(/^[ \t]*#+[ \t]*$/, "").replace(/[ \t]+#+[ \t]*$/, "")
1014
+ );
1015
+ heading.offsets.push(this.#lineStart + this.#offset);
1016
+ this.#advance(line.length - this.#offset);
1017
+ return 2;
1018
+ }
1019
+ const fence = /^`{3,}(?!.*`)|^~{3,}/.exec(rest);
1020
+ if (fence) {
1021
+ const start = this.#nextNonspace;
1022
+ this.#closeUnmatched();
1023
+ const code = this.#add("CodeBlock", start);
1024
+ code.fence = fence[0];
1025
+ code.fenceOffset = this.#indent;
1026
+ code.info = rest.slice(fence[0].length).trim();
1027
+ this.#advanceNextNonspace();
1028
+ this.#advance(line.length - this.#offset);
1029
+ this.#consumed = true;
1030
+ return 2;
1031
+ }
1032
+ if (char === "<") {
1033
+ for (let kind = 1; kind <= 7; kind++) {
1034
+ if (htmlOpen[kind]?.test(rest) && (kind < 7 || container.kind !== "Paragraph" && !(!this.#allClosed && !this.#blank && this.#tip.kind === "Paragraph"))) {
1035
+ this.#closeUnmatched();
1036
+ const html = this.#add("HtmlBlock", this.#offset);
1037
+ html.htmlKind = kind;
1038
+ return 2;
1039
+ }
1040
+ }
1041
+ }
1042
+ if (this.#gfm && container.kind === "Paragraph" && this.#allClosed && delimiterRow.test(rest) && rest.includes("-")) {
1043
+ const header = container.lines.at(-1) ?? "";
1044
+ const delimiters = _Blocks.cells(rest);
1045
+ if ((rest.includes("|") || /(?:^|[^\\])\|/.test(header)) && _Blocks.cells(header).length === delimiters.length) {
1046
+ this.#closeUnmatched();
1047
+ this.#table(container, delimiters);
1048
+ return 2;
1049
+ }
1050
+ }
1051
+ if (container.kind === "Paragraph" && /^(?:=+|-+)[ \t]*$/.test(rest)) {
1052
+ this.#closeUnmatched();
1053
+ this.#takeDefinitions(container);
1054
+ if (container.lines.length > 0) {
1055
+ container.info = rest.trim();
1056
+ container.kind = "Heading";
1057
+ container.setext = true;
1058
+ container.level = char === "=" ? 1 : 2;
1059
+ container.endLine = this.#lineNumber;
1060
+ this.#advance(line.length - this.#offset);
1061
+ return 2;
1062
+ }
1063
+ }
1064
+ if (thematicBreak.test(rest)) {
1065
+ const start = this.#nextNonspace;
1066
+ this.#closeUnmatched();
1067
+ const block = this.#add("ThematicBreak", start);
1068
+ block.lines.push(rest.trimEnd());
1069
+ this.#advance(line.length - this.#offset);
1070
+ return 2;
1071
+ }
1072
+ }
1073
+ if (!this.#indented || container.kind === "List") {
1074
+ const item = this.#listMarker(container);
1075
+ if (item) return 1;
1076
+ }
1077
+ if (this.#indented && this.#tip.kind !== "Paragraph" && !this.#blank) {
1078
+ this.#advance(4, true);
1079
+ this.#closeUnmatched();
1080
+ this.#add("CodeBlock", this.#offset);
1081
+ return 2;
1082
+ }
1083
+ return 0;
1084
+ }
1085
+ /** Turns the last line of a paragraph and the delimiter row into a table. */
1086
+ #table(paragraph, delimiters) {
1087
+ const headerLine = paragraph.lines.pop();
1088
+ const headerOffset = paragraph.offsets.pop();
1089
+ paragraph.indents.pop();
1090
+ paragraph.prefixes.pop();
1091
+ const parent = paragraph.parent;
1092
+ const table = this.#create(
1093
+ "Table",
1094
+ parent,
1095
+ headerOffset,
1096
+ paragraph.line + paragraph.lines.length
1097
+ );
1098
+ table.alignments = delimiters.map((cell) => {
1099
+ const left = cell.startsWith(":");
1100
+ const right = cell.endsWith(":");
1101
+ return left && right ? "center" : left ? "left" : right ? "right" : null;
1102
+ });
1103
+ table.lines.push(headerLine, this.#line.slice(this.#nextNonspace));
1104
+ table.offsets.push(headerOffset, this.#lineStart + this.#nextNonspace);
1105
+ table.endLine = this.#lineNumber;
1106
+ if (paragraph.lines.length === 0) {
1107
+ parent.children.splice(
1108
+ parent.children.indexOf(paragraph),
1109
+ 1,
1110
+ table
1111
+ );
1112
+ } else {
1113
+ paragraph.endLine = table.line - 1;
1114
+ paragraph.open = false;
1115
+ this.#takeDefinitions(paragraph);
1116
+ parent.children.push(table);
1117
+ }
1118
+ this.#tip = table;
1119
+ this.#advance(this.#line.length - this.#offset);
1120
+ this.#consumed = true;
1121
+ }
1122
+ #listMarker(container) {
1123
+ if (this.#indent >= 4) return false;
1124
+ const rest = this.#rest();
1125
+ const bullet = /^[*+-]/.exec(rest);
1126
+ const ordered = bullet ? null : /^(\d{1,9})([.)])/.exec(rest);
1127
+ const match = bullet ?? ordered;
1128
+ if (!match) return false;
1129
+ if (ordered && container.kind === "Paragraph" && Number(ordered[1]) !== 1)
1130
+ return false;
1131
+ const after = this.#line[this.#nextNonspace + match[0].length];
1132
+ if (after !== void 0 && after !== " " && after !== " ")
1133
+ return false;
1134
+ if (container.kind === "Paragraph" && !/[^ \t]/.test(
1135
+ this.#line.slice(this.#nextNonspace + match[0].length)
1136
+ ))
1137
+ return false;
1138
+ const markerOffset = this.#indent;
1139
+ const start = this.#nextNonspace;
1140
+ this.#advanceNextNonspace();
1141
+ this.#advance(match[0].length, true);
1142
+ const spacesColumn = this.#column;
1143
+ const spacesOffset = this.#offset;
1144
+ let next;
1145
+ do {
1146
+ this.#advance(1, true);
1147
+ next = this.#line[this.#offset];
1148
+ } while (this.#column - spacesColumn < 5 && (next === " " || next === " "));
1149
+ const blankItem = this.#line[this.#offset] === void 0;
1150
+ const spaces = this.#column - spacesColumn;
1151
+ const written = /^ */.exec(this.#line.slice(spacesOffset))?.[0].length ?? 0;
1152
+ let padding;
1153
+ if (spaces >= 5 || spaces < 1 || blankItem) {
1154
+ padding = match[0].length + 1;
1155
+ this.#column = spacesColumn;
1156
+ this.#offset = spacesOffset;
1157
+ this.#partialTab = false;
1158
+ const char = this.#line[this.#offset];
1159
+ if (char === " " || char === " ") this.#advance(1, true);
1160
+ } else padding = match[0].length + spaces;
1161
+ this.#closeUnmatched();
1162
+ const delimiter = bullet ? match[0] : ordered?.[2];
1163
+ if (this.#tip.kind !== "List" || this.#tip.ordered !== !!ordered || this.#tip.delimiter !== delimiter) {
1164
+ const list = this.#add("List", start);
1165
+ list.ordered = !!ordered;
1166
+ list.delimiter = delimiter;
1167
+ }
1168
+ const item = this.#add("ListItem", start);
1169
+ item.markerOffset = markerOffset;
1170
+ item.padding = padding;
1171
+ item.marker = match[0];
1172
+ item.number = ordered ? Number(ordered[1]) : null;
1173
+ item.spaces = blankItem ? 0 : spaces >= 5 || written < 1 ? 1 : Math.min(written, spaces);
1174
+ return true;
1175
+ }
1176
+ /** Splits a table row into its cells, on pipes that are not escaped. */
1177
+ static cells(row) {
1178
+ let text = row.trim();
1179
+ if (text.startsWith("|")) text = text.slice(1);
1180
+ if (text.endsWith("|") && !text.endsWith("\\|"))
1181
+ text = text.slice(0, -1);
1182
+ const cells = [];
1183
+ let cell = "";
1184
+ for (let index = 0; index < text.length; index++) {
1185
+ const char = text[index];
1186
+ if (char === "\\" && text[index + 1] === "|") {
1187
+ cell += "\\|";
1188
+ index++;
1189
+ } else if (char === "|") {
1190
+ cells.push(cell.trim());
1191
+ cell = "";
1192
+ } else cell += char;
1193
+ }
1194
+ cells.push(cell.trim());
1195
+ return cells;
1196
+ }
1197
+ /** Link reference definitions at the start of a paragraph become blocks of their own. */
1198
+ #takeDefinitions(paragraph) {
1199
+ if (paragraph.lines.length === 0) return;
1200
+ const text = paragraph.lines.map((line) => line.trimStart()).join("\n");
1201
+ let position = 0;
1202
+ for (; ; ) {
1203
+ if (text[position] !== "[") break;
1204
+ const definition = _Blocks.#definition(text, position);
1205
+ if (!definition) break;
1206
+ const [end, label, destination, title] = definition;
1207
+ const first = _Blocks.#countLines(text, 0, position);
1208
+ const last = _Blocks.#countLines(
1209
+ text,
1210
+ 0,
1211
+ Math.max(end - 1, position)
1212
+ );
1213
+ const line = paragraph.lines[first] ?? "";
1214
+ paragraph.definitions.push({
1215
+ type: "Definition",
1216
+ indent: `${paragraph.indents[first] ?? ""}${/^[ \t]*/.exec(line)?.[0] ?? ""}`,
1217
+ start: paragraph.offsets[first] ?? paragraph.start,
1218
+ end: (paragraph.offsets[last] ?? paragraph.start) + (paragraph.lines[last]?.length ?? 0),
1219
+ line: paragraph.line + first,
1220
+ endLine: paragraph.line + last,
1221
+ label,
1222
+ destination,
1223
+ title
1224
+ });
1225
+ position = end;
1226
+ }
1227
+ if (position === 0) return;
1228
+ const consumed = position >= text.length ? paragraph.lines.length : _Blocks.#countLines(text, 0, position);
1229
+ paragraph.indents.splice(0, consumed);
1230
+ paragraph.prefixes.splice(0, consumed);
1231
+ paragraph.lines.splice(0, consumed);
1232
+ paragraph.offsets.splice(0, consumed);
1233
+ paragraph.line += consumed;
1234
+ paragraph.start = paragraph.offsets[0] ?? paragraph.start;
1235
+ }
1236
+ static #countLines(text, from, to) {
1237
+ let count = 0;
1238
+ for (let index = from; index < to; index++)
1239
+ if (text[index] === "\n") count++;
1240
+ return count;
1241
+ }
1242
+ /** Parses a definition at a position, to the position after its line ending. */
1243
+ static #definition(text, from) {
1244
+ const label = _Blocks.#linkLabel(text, from);
1245
+ if (label === void 0 || text[label] !== ":") return;
1246
+ const raw = text.slice(from, label);
1247
+ if (!/[^ \t\r\n[\]]/.test(raw.slice(1, -1))) return;
1248
+ let position = _Blocks.#spaces(text, label + 1, true);
1249
+ const destination = Scan.destination(text, position);
1250
+ if (!destination) return;
1251
+ const [destinationEnd, destinationText] = destination;
1252
+ if (destinationText === "" && text[position] !== "<") return;
1253
+ position = destinationEnd;
1254
+ const beforeTitle = position;
1255
+ const afterSpaces = _Blocks.#spaces(text, position, true);
1256
+ let title = null;
1257
+ let titleEnd = -1;
1258
+ if (afterSpaces !== position) {
1259
+ const parsed = Scan.title(text, afterSpaces);
1260
+ if (parsed !== void 0) {
1261
+ titleEnd = parsed;
1262
+ title = text.slice(afterSpaces, parsed);
1263
+ }
1264
+ }
1265
+ const lineEnd = /* @__PURE__ */ __name((at) => {
1266
+ let index = at;
1267
+ while (text[index] === " " || text[index] === " ") index++;
1268
+ if (index >= text.length) return index;
1269
+ if (text[index] === "\n") return index + 1;
1270
+ }, "lineEnd");
1271
+ if (titleEnd >= 0) {
1272
+ const end2 = lineEnd(titleEnd);
1273
+ if (end2 !== void 0) return [end2, raw, destinationText, title];
1274
+ }
1275
+ const end = lineEnd(beforeTitle);
1276
+ if (end === void 0) return;
1277
+ return [end, raw, destinationText, null];
1278
+ }
1279
+ /** The position after a link label `[...]`, if one starts at a position. */
1280
+ static #linkLabel(text, from) {
1281
+ if (text[from] !== "[") return;
1282
+ for (let index = from + 1; index < text.length && index - from <= 1e3; index++) {
1283
+ const char = text[index];
1284
+ if (char === "\\") index++;
1285
+ else if (char === "[") return;
1286
+ else if (char === "]") return index + 1;
1287
+ }
1288
+ }
1289
+ static #spaces(text, from, newline) {
1290
+ let index = from;
1291
+ let newlines = 0;
1292
+ while (index < text.length) {
1293
+ const char = text[index];
1294
+ if (char === "\n" && newline && newlines === 0) newlines++;
1295
+ else if (char !== " " && char !== " ") break;
1296
+ index++;
1297
+ }
1298
+ return index;
1299
+ }
1300
+ // finishing
1301
+ #blocks(parent, definitions) {
1302
+ const blocks = [];
1303
+ for (const child of parent.children) {
1304
+ for (const definition of child.definitions) {
1305
+ blocks.push(definition);
1306
+ const key = Scan.label(definition.label);
1307
+ if (!definitions.has(key)) definitions.set(key, definition);
1308
+ }
1309
+ const block = this.#block(child, definitions);
1310
+ if (block) blocks.push(block);
1311
+ }
1312
+ return blocks;
1313
+ }
1314
+ #end(block) {
1315
+ const line = this.#lines[block.endLine - 1];
1316
+ return line ? line.start + line.text.length : this.#source.length;
1317
+ }
1318
+ #block(open, definitions) {
1319
+ const base = {
1320
+ start: open.start,
1321
+ end: Math.max(this.#end(open), open.start),
1322
+ line: open.line,
1323
+ endLine: open.endLine
1324
+ };
1325
+ switch (open.kind) {
1326
+ case "Paragraph": {
1327
+ if (open.lines.length === 0) return;
1328
+ const text = open.lines.map((line) => line.trimStart()).join("\n");
1329
+ return {
1330
+ type: "Paragraph",
1331
+ ...base,
1332
+ text: text.replace(/[ \t]+$/, ""),
1333
+ indents: open.lines.map(
1334
+ (line, index) => `${open.indents[index] ?? ""}${/^[ \t]*/.exec(line)?.[0] ?? ""}`
1335
+ ),
1336
+ prefixes: open.prefixes,
1337
+ lazy: open.lines.map(
1338
+ (_, index) => open.lazy.has(open.line + index)
1339
+ ),
1340
+ children: []
1341
+ };
1342
+ }
1343
+ case "Heading": {
1344
+ const text = open.setext ? open.lines.map((line) => line.trim()).join("\n") : (open.lines[0] ?? "").trimStart();
1345
+ return {
1346
+ type: "Heading",
1347
+ ...base,
1348
+ level: open.level,
1349
+ setext: open.setext,
1350
+ text,
1351
+ underline: open.setext ? open.info : "",
1352
+ children: []
1353
+ };
1354
+ }
1355
+ case "ThematicBreak":
1356
+ return {
1357
+ type: "ThematicBreak",
1358
+ ...base,
1359
+ raw: open.lines[0] ?? ""
1360
+ };
1361
+ case "CodeBlock":
1362
+ return {
1363
+ type: "CodeBlock",
1364
+ ...base,
1365
+ fence: open.fence,
1366
+ indent: open.fenceOffset,
1367
+ info: open.info,
1368
+ lines: open.lines,
1369
+ prefixes: open.prefixes,
1370
+ closed: open.closed
1371
+ };
1372
+ case "HtmlBlock":
1373
+ return {
1374
+ type: "HtmlBlock",
1375
+ ...base,
1376
+ kind: open.htmlKind,
1377
+ lines: open.lines
1378
+ };
1379
+ case "BlockQuote":
1380
+ return {
1381
+ type: "BlockQuote",
1382
+ ...base,
1383
+ children: this.#blocks(open, definitions)
1384
+ };
1385
+ case "List": {
1386
+ const items = open.children.map(
1387
+ (item) => this.#block(item, definitions)
1388
+ );
1389
+ return {
1390
+ type: "List",
1391
+ ...base,
1392
+ ordered: open.ordered,
1393
+ delimiter: open.delimiter,
1394
+ tight: _Blocks.#tight(items),
1395
+ children: items
1396
+ };
1397
+ }
1398
+ case "ListItem": {
1399
+ const children = this.#blocks(open, definitions);
1400
+ let checked = null;
1401
+ const first = children[0];
1402
+ const task = this.#gfm && first?.type === "Paragraph" ? /^\[([ xX])\](?=[ \t]|$)/.exec(first.text) : null;
1403
+ if (task && first?.type === "Paragraph" && first.line === open.line) {
1404
+ checked = task[1] !== " ";
1405
+ }
1406
+ return {
1407
+ type: "ListItem",
1408
+ ...base,
1409
+ marker: open.marker,
1410
+ number: open.number,
1411
+ indent: open.markerOffset,
1412
+ spaces: open.spaces,
1413
+ checked,
1414
+ children
1415
+ };
1416
+ }
1417
+ case "Table": {
1418
+ const rows = open.lines.map((line, index) => ({ line, index })).filter(({ index }) => index !== 1).map(({ line, index }) => {
1419
+ const start = open.offsets[index] ?? open.start;
1420
+ return {
1421
+ type: "TableRow",
1422
+ start,
1423
+ end: start + line.length,
1424
+ line: open.line + index,
1425
+ endLine: open.line + index,
1426
+ cells: _Blocks.cells(line).map((text) => ({
1427
+ type: "TableCell",
1428
+ start,
1429
+ end: start + line.length,
1430
+ text,
1431
+ children: []
1432
+ }))
1433
+ };
1434
+ });
1435
+ return {
1436
+ type: "Table",
1437
+ ...base,
1438
+ alignments: open.alignments,
1439
+ rows
1440
+ };
1441
+ }
1442
+ }
1443
+ }
1444
+ /** Lists are loose when blank lines separate items, or blocks of an item. */
1445
+ static #tight(items) {
1446
+ for (const [index, item] of items.entries()) {
1447
+ const next = items[index + 1];
1448
+ if (next && next.line > item.endLine + 1) return false;
1449
+ for (const [position, child] of item.children.entries()) {
1450
+ const sibling = item.children[position + 1];
1451
+ if (sibling && sibling.line > child.endLine + 1) return false;
1452
+ }
1453
+ }
1454
+ return true;
1455
+ }
1456
+ static #inlines(blocks, inlines) {
1457
+ for (const block of blocks) {
1458
+ switch (block.type) {
1459
+ case "Paragraph":
1460
+ case "Heading":
1461
+ block.children = inlines.parse(block.text);
1462
+ break;
1463
+ case "Table":
1464
+ for (const row of block.rows)
1465
+ for (const cell of row.cells)
1466
+ cell.children = inlines.parse(cell.text);
1467
+ break;
1468
+ case "BlockQuote":
1469
+ _Blocks.#inlines(block.children, inlines);
1470
+ break;
1471
+ case "List":
1472
+ for (const item of block.children)
1473
+ _Blocks.#inlines(item.children, inlines);
1474
+ break;
1475
+ }
1476
+ }
1477
+ }
1478
+ };
1479
+
1480
+ // shared/syntax/src/scanner.ts
1481
+ var ParseError = class extends SyntaxError {
1482
+ static {
1483
+ __name(this, "ParseError");
1484
+ }
1485
+ position;
1486
+ constructor(message, position) {
1487
+ super(message);
1488
+ this.position = position;
1489
+ }
1490
+ };
1491
+ var Scanner = class _Scanner {
1492
+ static {
1493
+ __name(this, "Scanner");
1494
+ }
1495
+ static #punctuators = [
1496
+ ">>>=",
1497
+ "...",
1498
+ "===",
1499
+ "!==",
1500
+ "**=",
1501
+ "&&=",
1502
+ "||=",
1503
+ "??=",
1504
+ "=>",
1505
+ "==",
1506
+ "!=",
1507
+ "<=",
1508
+ "&&",
1509
+ "||",
1510
+ "??",
1511
+ "?.",
1512
+ "++",
1513
+ "--",
1514
+ "+=",
1515
+ "-=",
1516
+ "*=",
1517
+ "/=",
1518
+ "%=",
1519
+ "&=",
1520
+ "|=",
1521
+ "^=",
1522
+ "**"
1523
+ ];
1524
+ static #greater = [">>>=", ">>>", ">>=", ">>", ">=", ">"];
1525
+ static #less = ["<<=", "<<", "<=", "<"];
1526
+ source;
1527
+ comments = [];
1528
+ #position = 0;
1529
+ constructor(source) {
1530
+ this.source = source;
1531
+ }
1532
+ get position() {
1533
+ return this.#position;
1534
+ }
1535
+ /** Moves back (or forward) and forgets comments scanned beyond. */
1536
+ reset(position) {
1537
+ this.#position = position;
1538
+ while ((this.comments.at(-1)?.start ?? -1) >= position)
1539
+ this.comments.pop();
1540
+ }
1541
+ next() {
1542
+ const newline = this.#trivia();
1543
+ const start = this.#position;
1544
+ const char = this.source[start];
1545
+ if (char === void 0) return this.#token("eof", start, newline);
1546
+ if (_Scanner.#identifierStart(char) || char === "\\")
1547
+ return this.#word("name", start, newline);
1548
+ if (char === "#") return this.#word("private", start, newline);
1549
+ if (/[0-9]/.test(char) || char === "." && /[0-9]/.test(this.source[start + 1] ?? ""))
1550
+ return this.#number(start, newline);
1551
+ if (char === '"' || char === "'") return this.#string(start, newline);
1552
+ if (char === "`") return this.template(start, newline);
1553
+ const punctuator = _Scanner.#punctuators.find(
1554
+ (value) => this.source.startsWith(value, start) && !(value === "?." && /[0-9]/.test(this.source[start + 2] ?? ""))
1555
+ ) ?? char;
1556
+ this.#position = start + punctuator.length;
1557
+ return this.#token("punct", start, newline);
1558
+ }
1559
+ /** Rescans a `/` or `/=` token as a regular expression literal. */
1560
+ regex(token) {
1561
+ let inClass = false;
1562
+ for (let index = token.start + 1; ; index++) {
1563
+ const char = this.source[index];
1564
+ if (char === void 0 || char === "\n" || char === "\r")
1565
+ return this.#invalid(token.start, "Unterminated regex");
1566
+ if (char === "\\") index++;
1567
+ else if (char === "[") inClass = true;
1568
+ else if (char === "]") inClass = false;
1569
+ else if (char === "/" && !inClass) {
1570
+ this.#position = index + 1;
1571
+ while (_Scanner.#identifierPart(this.source[this.#position] ?? ""))
1572
+ this.#position++;
1573
+ return this.#token("regex", token.start, token.newline);
1574
+ }
1575
+ }
1576
+ }
1577
+ /** Rescans `>` as the longest of `>>>=`, `>>>`, `>>=`, `>>`, `>=`. */
1578
+ greater(token) {
1579
+ return this.#operator(token, _Scanner.#greater);
1580
+ }
1581
+ /** Rescans `<` as the longest of `<<=`, `<<`, `<=`, since types nest `<<T>() => T>`. */
1582
+ less(token) {
1583
+ return this.#operator(token, _Scanner.#less);
1584
+ }
1585
+ #operator(token, candidates) {
1586
+ const value = candidates.find(
1587
+ (value2) => this.source.startsWith(value2, token.start)
1588
+ ) ?? token.value;
1589
+ this.reset(token.start + value.length);
1590
+ return { ...token, value, end: token.start + value.length };
1591
+ }
1592
+ /** Scans a template part, from a backtick or a closing `}`, up to `${` or a backtick. */
1593
+ template(start, newline = false) {
1594
+ for (let index = start + 1; index < this.source.length; index++) {
1595
+ const char = this.source[index];
1596
+ if (char === "\\") index++;
1597
+ else if (char === "`" || char === "$" && this.source[index + 1] === "{") {
1598
+ this.#position = index + (char === "`" ? 1 : 2);
1599
+ return this.#token("template", start, newline);
1600
+ }
1601
+ }
1602
+ return this.#invalid(start, "Unterminated template");
1603
+ }
1604
+ /** Scans JSX text up to `{` or `<`. */
1605
+ jsxText(start) {
1606
+ let index = start;
1607
+ while (index < this.source.length && !"{<".includes(this.source[index] ?? ""))
1608
+ index++;
1609
+ this.#position = index;
1610
+ return this.#token("jsxText", start, false);
1611
+ }
1612
+ /** Rescans a name token to include JSX's `-` characters. */
1613
+ jsxName(token) {
1614
+ let index = token.end;
1615
+ while (/[-\p{ID_Continue}$]/u.test(this.source[index] ?? "")) index++;
1616
+ this.reset(index);
1617
+ return {
1618
+ ...token,
1619
+ value: this.source.slice(token.start, index),
1620
+ end: index
1621
+ };
1622
+ }
1623
+ /** Rescans a quoted JSX attribute value, which has no escapes. */
1624
+ jsxString(token) {
1625
+ const quote = this.source[token.start] ?? "";
1626
+ const end = this.source.indexOf(quote, token.start + 1);
1627
+ if (end < 0) return this.#invalid(token.start, "Unterminated string");
1628
+ this.reset(end + 1);
1629
+ return {
1630
+ ...token,
1631
+ type: "string",
1632
+ value: this.source.slice(token.start, end + 1),
1633
+ end: end + 1
1634
+ };
1635
+ }
1636
+ #token(type, start, newline) {
1637
+ return {
1638
+ type,
1639
+ value: this.source.slice(start, this.#position),
1640
+ start,
1641
+ end: this.#position,
1642
+ newline
1643
+ };
1644
+ }
1645
+ #invalid(start, message) {
1646
+ this.#position = this.source.length;
1647
+ return {
1648
+ type: "invalid",
1649
+ value: message,
1650
+ start,
1651
+ end: start,
1652
+ newline: false
1653
+ };
1654
+ }
1655
+ /** Skips whitespace and comments, returns whether a line break was crossed. */
1656
+ #trivia() {
1657
+ let newline = false;
1658
+ if (this.#position === 0 && this.source.startsWith("#!")) {
1659
+ const end = this.#lineEnd(0);
1660
+ this.comments.push({
1661
+ type: "Line",
1662
+ value: this.source.slice(0, end),
1663
+ start: 0,
1664
+ end
1665
+ });
1666
+ this.#position = end;
1667
+ }
1668
+ while (this.#position < this.source.length) {
1669
+ const char = this.source[this.#position] ?? "";
1670
+ const next = this.source[this.#position + 1];
1671
+ if (char === "\n" || char === "\r" || char === "\u2028" || char === "\u2029") {
1672
+ newline = true;
1673
+ this.#position++;
1674
+ } else if (/\s/.test(char)) this.#position++;
1675
+ else if (char === "/" && next === "/") {
1676
+ const end = this.#lineEnd(this.#position);
1677
+ this.#comment("Line", end);
1678
+ } else if (char === "/" && next === "*") {
1679
+ const close = this.source.indexOf("*/", this.#position + 2);
1680
+ const end = close < 0 ? this.source.length : close + 2;
1681
+ if (/[\r\n\u2028\u2029]/.test(
1682
+ this.source.slice(this.#position, end)
1683
+ ))
1684
+ newline = true;
1685
+ this.#comment("Block", end);
1686
+ } else break;
1687
+ }
1688
+ return newline;
1689
+ }
1690
+ #comment(type, end) {
1691
+ const start = this.#position;
1692
+ this.comments.push({
1693
+ type,
1694
+ value: this.source.slice(start, end),
1695
+ start,
1696
+ end
1697
+ });
1698
+ this.#position = end;
1699
+ }
1700
+ #lineEnd(start) {
1701
+ const match = /[\r\n\u2028\u2029]/.exec(this.source.slice(start));
1702
+ return match ? start + match.index : this.source.length;
1703
+ }
1704
+ #word(type, start, newline) {
1705
+ let index = start + 1;
1706
+ while (index < this.source.length) {
1707
+ const char = this.source[index] ?? "";
1708
+ if (char === "\\")
1709
+ index += /^\\u\{/.test(this.source.slice(index, index + 3)) ? this.source.indexOf("}", index) - index + 1 : 6;
1710
+ else if (_Scanner.#identifierPart(char)) index += char.length;
1711
+ else {
1712
+ const code = this.source.codePointAt(index) ?? 0;
1713
+ const symbol = String.fromCodePoint(code);
1714
+ if (code > 65535 && _Scanner.#identifierPart(symbol))
1715
+ index += 2;
1716
+ else break;
1717
+ }
1718
+ }
1719
+ this.#position = index;
1720
+ return this.#token(type, start, newline);
1721
+ }
1722
+ #number(start, newline) {
1723
+ const pattern = /0[xX][\da-fA-F_]+n?|0[oO][0-7_]+n?|0[bB][01_]+n?|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?n?/y;
1724
+ pattern.lastIndex = start;
1725
+ pattern.exec(this.source);
1726
+ this.#position = pattern.lastIndex;
1727
+ return this.#token("number", start, newline);
1728
+ }
1729
+ #string(start, newline) {
1730
+ const quote = this.source[start];
1731
+ for (let index = start + 1; index < this.source.length; index++) {
1732
+ const char = this.source[index];
1733
+ if (char === "\\")
1734
+ index += this.source.startsWith("\r\n", index + 1) ? 2 : 1;
1735
+ else if (char === quote) {
1736
+ this.#position = index + 1;
1737
+ return this.#token("string", start, newline);
1738
+ } else if (char === "\n" || char === "\r") break;
1739
+ }
1740
+ return this.#invalid(start, "Unterminated string");
1741
+ }
1742
+ static #identifierStart(char) {
1743
+ return /[\p{ID_Start}$_]/u.test(char) || /[\ud800-\udbff]/.test(char);
1744
+ }
1745
+ static #identifierPart(char) {
1746
+ return /[\p{ID_Continue}$‌‍]/u.test(char);
1747
+ }
1748
+ };
1749
+
1750
+ // shared/syntax/src/parser/base.ts
1751
+ var BaseParser = class {
1752
+ static {
1753
+ __name(this, "BaseParser");
1754
+ }
1755
+ source;
1756
+ scanner;
1757
+ options;
1758
+ token;
1759
+ /** End of the last consumed token. */
1760
+ previous = 0;
1761
+ /** Whether `in` is a binary operator here (not in a for-in head). */
1762
+ allowIn = true;
1763
+ constructor(source, options) {
1764
+ this.source = source;
1765
+ this.options = options;
1766
+ this.scanner = new Scanner(source);
1767
+ this.token = this.scanner.next();
1768
+ }
1769
+ get comments() {
1770
+ return this.scanner.comments;
1771
+ }
1772
+ next() {
1773
+ const token = this.token;
1774
+ if (token.type === "invalid") this.raise(token.value, token.start);
1775
+ this.previous = token.end;
1776
+ this.token = this.scanner.next();
1777
+ return token;
1778
+ }
1779
+ /** Replaces the current token with a rescanned one. */
1780
+ replace(token) {
1781
+ this.token = token;
1782
+ }
1783
+ /** Continues scanning from a position, discarding the current token. */
1784
+ rescan(position) {
1785
+ this.scanner.reset(position);
1786
+ this.token = this.scanner.next();
1787
+ }
1788
+ is(value, token = this.token) {
1789
+ return token.value === value && (token.type === "punct" || token.type === "name");
1790
+ }
1791
+ isName(token = this.token) {
1792
+ return token.type === "name";
1793
+ }
1794
+ eat(value) {
1795
+ if (!this.is(value)) return false;
1796
+ this.next();
1797
+ return true;
1798
+ }
1799
+ expect(value) {
1800
+ if (!this.is(value)) this.unexpected(`Expected "${value}"`);
1801
+ return this.next();
1802
+ }
1803
+ /** Peeks the token after the current one. */
1804
+ peek() {
1805
+ const snapshot = this.snapshot();
1806
+ this.next();
1807
+ const token = this.token;
1808
+ this.restore(snapshot);
1809
+ return token;
1810
+ }
1811
+ snapshot() {
1812
+ return {
1813
+ position: this.scanner.position,
1814
+ token: this.token,
1815
+ previous: this.previous
1816
+ };
1817
+ }
1818
+ restore({ position, token, previous }) {
1819
+ this.scanner.reset(position);
1820
+ this.token = token;
1821
+ this.previous = previous;
1822
+ }
1823
+ /** Runs a speculative parse, undoing it when it fails. */
1824
+ attempt(parse2) {
1825
+ const snapshot = this.snapshot();
1826
+ try {
1827
+ return parse2();
1828
+ } catch (error) {
1829
+ if (!(error instanceof ParseError)) throw error;
1830
+ this.restore(snapshot);
1831
+ return void 0;
1832
+ }
1833
+ }
1834
+ finish(type, start, fields) {
1835
+ return { type, start, end: this.previous, ...fields };
1836
+ }
1837
+ /** Consumes a semicolon or accepts automatic semicolon insertion. */
1838
+ semicolon() {
1839
+ if (this.eat(";")) return;
1840
+ if (this.is("}") || this.token.type === "eof" || this.token.newline)
1841
+ return;
1842
+ this.unexpected('Expected ";"');
1843
+ }
1844
+ canInsertSemicolon() {
1845
+ return this.is(";") || this.is("}") || this.token.type === "eof" || this.token.newline;
1846
+ }
1847
+ unexpected(message = "Unexpected token") {
1848
+ const { type, value, start } = this.token;
1849
+ this.raise(
1850
+ `${message}, got ${type === "eof" ? "end of file" : `"${value}"`}`,
1851
+ start
1852
+ );
1853
+ }
1854
+ raise(message, position) {
1855
+ const before = this.source.slice(0, position);
1856
+ const line = before.split("\n").length;
1857
+ const column = position - before.lastIndexOf("\n");
1858
+ throw new ParseError(`${message} (${line}:${column})`, position);
1859
+ }
1860
+ };
1861
+
1862
+ // shared/syntax/src/parser/types.ts
1863
+ var TypeParser = class _TypeParser extends BaseParser {
1864
+ static {
1865
+ __name(this, "TypeParser");
1866
+ }
1867
+ static #keywords = /* @__PURE__ */ new Set([
1868
+ "any",
1869
+ "bigint",
1870
+ "boolean",
1871
+ "intrinsic",
1872
+ "never",
1873
+ "null",
1874
+ "number",
1875
+ "object",
1876
+ "string",
1877
+ "symbol",
1878
+ "undefined",
1879
+ "unknown",
1880
+ "void"
1881
+ ]);
1882
+ /** Whether a conditional type may start here (not in its extends clause). */
1883
+ #conditional = true;
1884
+ parseIdentifier() {
1885
+ if (!this.isName()) this.unexpected("Expected an identifier");
1886
+ const { start, value } = this.next();
1887
+ return this.finish("Identifier", start, { name: value });
1888
+ }
1889
+ parseString() {
1890
+ if (this.token.type !== "string") this.unexpected("Expected a string");
1891
+ const { start, value } = this.next();
1892
+ return this.finish("StringLiteral", start, { raw: value });
1893
+ }
1894
+ /** Parses a template, with parts parsed by the given parser. */
1895
+ parseTemplateParts(part) {
1896
+ const quasis = [];
1897
+ const parts = [];
1898
+ for (; ; ) {
1899
+ const token = this.token;
1900
+ if (token.type !== "template")
1901
+ this.unexpected("Expected a template");
1902
+ const tail = token.value.endsWith("`") && (token.value.length > 1 || quasis.length > 0);
1903
+ const raw = token.value.slice(1, tail ? -1 : -2);
1904
+ quasis.push({
1905
+ type: "TemplateElement",
1906
+ start: token.start,
1907
+ end: token.end,
1908
+ raw,
1909
+ tail
1910
+ });
1911
+ this.next();
1912
+ if (tail) return { quasis, parts };
1913
+ parts.push(part());
1914
+ if (!this.is("}")) this.unexpected('Expected "}" in template');
1915
+ this.replace(
1916
+ this.scanner.template(this.token.start, this.token.newline)
1917
+ );
1918
+ }
1919
+ }
1920
+ parseTypeAnnotation() {
1921
+ if (!this.eat(":")) return null;
1922
+ return this.parseType();
1923
+ }
1924
+ parseType() {
1925
+ const start = this.token.start;
1926
+ if (this.is("<")) return this.#functionType(start, false);
1927
+ if (this.is("new") || this.is("abstract") && this.is("new", this.peek()))
1928
+ return this.#functionType(start, true);
1929
+ if (this.is("(")) {
1930
+ const fn = this.attempt(() => this.#functionType(start, false));
1931
+ if (fn) return fn;
1932
+ }
1933
+ const check = this.#union();
1934
+ if (!this.#conditional || this.token.newline || !this.is("extends"))
1935
+ return check;
1936
+ this.next();
1937
+ this.#conditional = false;
1938
+ const extendsType = this.parseType();
1939
+ this.#conditional = true;
1940
+ this.expect("?");
1941
+ const trueType = this.parseType();
1942
+ this.expect(":");
1943
+ const falseType = this.parseType();
1944
+ return this.finish("TSConditionalType", start, {
1945
+ checkType: check,
1946
+ extendsType,
1947
+ trueType,
1948
+ falseType
1949
+ });
1950
+ }
1951
+ parseReturnType() {
1952
+ const start = this.token.start;
1953
+ const asserts = this.is("asserts") && (this.isName(this.peek()) || this.is("this", this.peek())) && !this.peek().newline;
1954
+ if (asserts) this.next();
1955
+ if ((this.isName() || this.is("this")) && (asserts || this.is("is", this.peek()))) {
1956
+ const parameter = this.is("this") ? this.#thisType() : this.parseIdentifier();
1957
+ let typeAnnotation = null;
1958
+ if (!this.token.newline && this.eat("is"))
1959
+ typeAnnotation = this.parseType();
1960
+ if (asserts || typeAnnotation)
1961
+ return this.finish("TSTypePredicate", start, {
1962
+ parameterName: parameter,
1963
+ typeAnnotation,
1964
+ asserts
1965
+ });
1966
+ return parameter;
1967
+ }
1968
+ return this.parseType();
1969
+ }
1970
+ parseTypeParameters() {
1971
+ if (!this.is("<")) return null;
1972
+ const start = this.next().start;
1973
+ const params = [];
1974
+ while (!this.is(">")) {
1975
+ const paramStart = this.token.start;
1976
+ const modifiers = { in: false, out: false, const: false };
1977
+ while (["in", "out", "const"].includes(this.token.value) && this.isName(this.peek())) {
1978
+ modifiers[this.token.value] = true;
1979
+ this.next();
1980
+ }
1981
+ const { value: name } = this.next();
1982
+ const constraint = this.eat("extends") ? this.parseType() : null;
1983
+ const fallback = this.eat("=") ? this.parseType() : null;
1984
+ params.push(
1985
+ this.finish("TSTypeParameter", paramStart, {
1986
+ name,
1987
+ constraint,
1988
+ default: fallback,
1989
+ ...modifiers
1990
+ })
1991
+ );
1992
+ if (!this.eat(",")) break;
1993
+ }
1994
+ this.expect(">");
1995
+ return this.finish("TSTypeParameterDeclaration", start, { params });
1996
+ }
1997
+ parseTypeArguments() {
1998
+ const start = this.expect("<").start;
1999
+ const params = [];
2000
+ while (!this.is(">")) {
2001
+ params.push(this.parseType());
2002
+ if (!this.eat(",")) break;
2003
+ }
2004
+ this.expect(">");
2005
+ return this.finish("TSTypeParameterInstantiation", start, { params });
2006
+ }
2007
+ parseEntityName() {
2008
+ const start = this.token.start;
2009
+ let name = this.parseIdentifier();
2010
+ while (this.is(".") && this.isName(this.peek())) {
2011
+ this.next();
2012
+ name = this.finish("TSQualifiedName", start, {
2013
+ left: name,
2014
+ right: this.parseIdentifier()
2015
+ });
2016
+ }
2017
+ return name;
2018
+ }
2019
+ /** Parses `{ ... }` members of an interface or a type literal. */
2020
+ parseTypeMembers() {
2021
+ this.expect("{");
2022
+ const members = [];
2023
+ while (!this.is("}")) {
2024
+ members.push(this.#member());
2025
+ if (!this.eat(";") && !this.eat(",") && !this.is("}") && !this.token.newline)
2026
+ this.unexpected();
2027
+ }
2028
+ this.expect("}");
2029
+ return members;
2030
+ }
2031
+ #functionType(start, construct) {
2032
+ const abstract = construct && this.eat("abstract");
2033
+ if (construct) this.expect("new");
2034
+ const typeParameters = this.parseTypeParameters();
2035
+ const params = this.parseParameters();
2036
+ this.expect("=>");
2037
+ const returnType = this.parseReturnType();
2038
+ return construct ? this.finish("TSConstructorType", start, {
2039
+ typeParameters,
2040
+ params,
2041
+ returnType,
2042
+ abstract
2043
+ }) : this.finish("TSFunctionType", start, {
2044
+ typeParameters,
2045
+ params,
2046
+ returnType
2047
+ });
2048
+ }
2049
+ #union() {
2050
+ return this.#list(
2051
+ "|",
2052
+ "TSUnionType",
2053
+ () => this.#list("&", "TSIntersectionType", () => this.#operator())
2054
+ );
2055
+ }
2056
+ #list(operator, type, parse2) {
2057
+ const start = this.token.start;
2058
+ const leading = this.eat(operator);
2059
+ const types = [parse2()];
2060
+ while (this.eat(operator)) types.push(parse2());
2061
+ if (types.length === 1 && !leading) return types[0];
2062
+ return this.finish(type, start, { types });
2063
+ }
2064
+ #operator() {
2065
+ const start = this.token.start;
2066
+ if (["keyof", "unique", "readonly"].includes(this.token.value) && this.isName() && !this.#ends(this.peek())) {
2067
+ const operator = this.next().value;
2068
+ return this.finish("TSTypeOperator", start, {
2069
+ operator,
2070
+ typeAnnotation: this.#operator()
2071
+ });
2072
+ }
2073
+ if (this.is("infer") && this.isName(this.peek())) {
2074
+ this.next();
2075
+ const name = this.next().value;
2076
+ const constraint = this.is("extends") ? this.attempt(() => {
2077
+ this.next();
2078
+ const conditional = this.#conditional;
2079
+ this.#conditional = false;
2080
+ const type2 = this.parseType();
2081
+ this.#conditional = conditional;
2082
+ if (conditional && this.is("?")) this.unexpected();
2083
+ return type2;
2084
+ }) ?? null : null;
2085
+ return this.finish("TSInferType", start, { name, constraint });
2086
+ }
2087
+ let type = this.#primary();
2088
+ while (!this.token.newline && this.is("[")) {
2089
+ this.next();
2090
+ if (this.eat("]"))
2091
+ type = this.finish("TSArrayType", start, { elementType: type });
2092
+ else {
2093
+ const indexType = this.parseType();
2094
+ this.expect("]");
2095
+ type = this.finish("TSIndexedAccessType", start, {
2096
+ objectType: type,
2097
+ indexType
2098
+ });
2099
+ }
2100
+ }
2101
+ return type;
2102
+ }
2103
+ /** Whether the token ends a type, so a preceding keyword is a plain name. */
2104
+ #ends(token) {
2105
+ return [")", "]", ",", ";", ">", "=", "|", "&", "}", "?", ":"].includes(
2106
+ token.value
2107
+ ) || token.type === "eof";
2108
+ }
2109
+ /** Parses a primary type; brackets inside allow conditional types again. */
2110
+ #primary() {
2111
+ const conditional = this.#conditional;
2112
+ this.#conditional = true;
2113
+ try {
2114
+ return this.#primaryType();
2115
+ } finally {
2116
+ this.#conditional = conditional;
2117
+ }
2118
+ }
2119
+ #primaryType() {
2120
+ const { start, type, value } = this.token;
2121
+ if (type === "string" || type === "number")
2122
+ return this.#literal(start, () => this.next());
2123
+ if (type === "template") {
2124
+ const { quasis, parts } = this.parseTemplateParts(
2125
+ () => this.parseType()
2126
+ );
2127
+ return this.finish("TSTemplateLiteralType", start, {
2128
+ quasis,
2129
+ types: parts
2130
+ });
2131
+ }
2132
+ if (this.is("-") && this.peek().type === "number")
2133
+ return this.#literal(start, () => this.next());
2134
+ switch (value) {
2135
+ case "(": {
2136
+ this.next();
2137
+ const inner = this.parseType();
2138
+ this.expect(")");
2139
+ inner.parenthesized = true;
2140
+ return inner;
2141
+ }
2142
+ case "[":
2143
+ return this.#tuple(start);
2144
+ case "{":
2145
+ return this.#mapped(start) ?? this.finish("TSTypeLiteral", start, {
2146
+ members: this.parseTypeMembers()
2147
+ });
2148
+ }
2149
+ if (!this.isName()) this.unexpected("Expected a type");
2150
+ if ((value === "true" || value === "false") && this.isName())
2151
+ return this.#literal(start, () => this.next());
2152
+ if (value === "this") return this.#thisType();
2153
+ if (value === "typeof") {
2154
+ this.next();
2155
+ const exprName = this.is("import") ? this.#importType(this.token.start) : this.parseEntityName();
2156
+ const typeArguments2 = !this.token.newline && this.is("<") ? this.parseTypeArguments() : null;
2157
+ return this.finish("TSTypeQuery", start, {
2158
+ exprName,
2159
+ typeArguments: typeArguments2
2160
+ });
2161
+ }
2162
+ if (value === "import") return this.#importType(start);
2163
+ if (_TypeParser.#keywords.has(value) && !this.is(".", this.peek())) {
2164
+ this.next();
2165
+ return this.finish("TSKeyword", start, { name: value });
2166
+ }
2167
+ const typeName = this.parseEntityName();
2168
+ const typeArguments = !this.token.newline && this.is("<") ? this.parseTypeArguments() : null;
2169
+ return this.finish("TSTypeReference", start, {
2170
+ typeName,
2171
+ typeArguments
2172
+ });
2173
+ }
2174
+ #literal(start, consume) {
2175
+ const negative = this.is("-");
2176
+ if (negative) this.next();
2177
+ const token = this.token;
2178
+ consume();
2179
+ let literal = token.type === "string" ? this.finish("StringLiteral", token.start, {
2180
+ raw: token.value
2181
+ }) : token.type === "number" ? this.finish("NumericLiteral", token.start, {
2182
+ raw: token.value
2183
+ }) : this.finish("BooleanLiteral", token.start, {
2184
+ value: token.value === "true"
2185
+ });
2186
+ if (negative)
2187
+ literal = this.finish("UnaryExpression", start, {
2188
+ operator: "-",
2189
+ argument: literal
2190
+ });
2191
+ return this.finish("TSLiteralType", start, { literal });
2192
+ }
2193
+ #thisType() {
2194
+ const { start } = this.expect("this");
2195
+ return this.finish("TSThisType", start, {});
2196
+ }
2197
+ #importType(start) {
2198
+ this.expect("import");
2199
+ this.expect("(");
2200
+ const argument = this.parseType();
2201
+ const options = this.eat(",") && !this.is(")") ? this.parseAssignment() : null;
2202
+ this.eat(",");
2203
+ this.expect(")");
2204
+ let qualifier = null;
2205
+ if (this.eat(".")) qualifier = this.parseEntityName();
2206
+ const typeArguments = this.is("<") ? this.parseTypeArguments() : null;
2207
+ return this.finish("TSImportType", start, {
2208
+ argument,
2209
+ options,
2210
+ qualifier,
2211
+ typeArguments
2212
+ });
2213
+ }
2214
+ #tuple(start) {
2215
+ this.expect("[");
2216
+ const elementTypes = [];
2217
+ while (!this.is("]")) {
2218
+ const elementStart = this.token.start;
2219
+ const rest = this.eat("...");
2220
+ let element;
2221
+ if (this.isName() && (this.is(":", this.peek()) || this.is("?", this.peek()) && this.#labelled())) {
2222
+ const label = this.parseIdentifier();
2223
+ const optional = this.eat("?");
2224
+ this.expect(":");
2225
+ element = this.finish("TSNamedTupleMember", elementStart, {
2226
+ label,
2227
+ elementType: this.parseType(),
2228
+ optional
2229
+ });
2230
+ } else {
2231
+ element = this.parseType();
2232
+ if (this.eat("?"))
2233
+ element = this.finish("TSOptionalType", elementStart, {
2234
+ typeAnnotation: element
2235
+ });
2236
+ }
2237
+ if (rest)
2238
+ element = this.finish("TSRestType", elementStart, {
2239
+ typeAnnotation: element
2240
+ });
2241
+ elementTypes.push(element);
2242
+ if (!this.eat(",")) break;
2243
+ }
2244
+ this.expect("]");
2245
+ return this.finish("TSTupleType", start, { elementTypes });
2246
+ }
2247
+ /** Whether `name ?` starts a labelled tuple member `name?: T`. */
2248
+ #labelled() {
2249
+ const snapshot = this.snapshot();
2250
+ this.next();
2251
+ this.next();
2252
+ const labelled = this.is(":");
2253
+ this.restore(snapshot);
2254
+ return labelled;
2255
+ }
2256
+ #mapped(start) {
2257
+ return this.attempt(() => {
2258
+ this.expect("{");
2259
+ let readonly = null;
2260
+ if (this.is("+") || this.is("-")) readonly = this.next().value;
2261
+ if (this.is("readonly")) {
2262
+ this.next();
2263
+ readonly = readonly ? readonly : "true";
2264
+ } else if (readonly) this.unexpected();
2265
+ this.expect("[");
2266
+ const { value: key } = this.next();
2267
+ this.expect("in");
2268
+ const constraint = this.parseType();
2269
+ const nameType = this.eat("as") ? this.parseType() : null;
2270
+ this.expect("]");
2271
+ let optional = null;
2272
+ if (this.is("+") || this.is("-")) {
2273
+ optional = this.next().value;
2274
+ this.expect("?");
2275
+ } else if (this.eat("?")) optional = "true";
2276
+ const typeAnnotation = this.parseTypeAnnotation();
2277
+ this.eat(";") || this.eat(",");
2278
+ this.expect("}");
2279
+ return this.finish("TSMappedType", start, {
2280
+ key,
2281
+ constraint,
2282
+ nameType,
2283
+ typeAnnotation,
2284
+ optional,
2285
+ readonly
2286
+ });
2287
+ });
2288
+ }
2289
+ #member() {
2290
+ const start = this.token.start;
2291
+ if (this.is("(") || this.is("<"))
2292
+ return this.#signature(start, "TSCallSignatureDeclaration");
2293
+ if (this.is("new") && (this.is("(", this.peek()) || this.is("<", this.peek()))) {
2294
+ this.next();
2295
+ return this.#signature(start, "TSConstructSignatureDeclaration");
2296
+ }
2297
+ const readonly = this.is("readonly") && this.#modifies();
2298
+ if (readonly) this.next();
2299
+ if (this.is("[")) {
2300
+ const index = this.attempt(
2301
+ () => this.#index(start, readonly, false)
2302
+ );
2303
+ if (index) return index;
2304
+ }
2305
+ let kind = "method";
2306
+ if ((this.is("get") || this.is("set")) && this.#modifies())
2307
+ kind = this.next().value;
2308
+ const { key, computed } = this.parsePropertyKey();
2309
+ const optional = this.eat("?");
2310
+ if (this.is("(") || this.is("<")) {
2311
+ const typeParameters = this.parseTypeParameters();
2312
+ const params = this.parseParameters();
2313
+ const returnType = this.eat(":") ? this.parseReturnType() : null;
2314
+ return this.finish("TSMethodSignature", start, {
2315
+ key,
2316
+ computed,
2317
+ optional,
2318
+ kind,
2319
+ typeParameters,
2320
+ params,
2321
+ returnType
2322
+ });
2323
+ }
2324
+ const typeAnnotation = this.parseTypeAnnotation();
2325
+ return this.finish("TSPropertySignature", start, {
2326
+ key,
2327
+ computed,
2328
+ optional,
2329
+ readonly,
2330
+ typeAnnotation
2331
+ });
2332
+ }
2333
+ /** Whether the current word modifies a following member name. */
2334
+ #modifies() {
2335
+ const next = this.peek();
2336
+ return !next.newline && !["(", ")", ":", "?", ";", ",", "}", "=", "<", "!"].includes(
2337
+ next.value
2338
+ );
2339
+ }
2340
+ #signature(start, type) {
2341
+ const typeParameters = this.parseTypeParameters();
2342
+ const params = this.parseParameters();
2343
+ const returnType = this.eat(":") ? this.parseReturnType() : null;
2344
+ return this.finish(type, start, { typeParameters, params, returnType });
2345
+ }
2346
+ /** Parses `[key: T]: U` after optional modifiers. */
2347
+ parseIndexSignature(start, readonly, isStatic) {
2348
+ return this.attempt(() => this.#index(start, readonly, isStatic));
2349
+ }
2350
+ #index(start, readonly, isStatic) {
2351
+ this.expect("[");
2352
+ const parameters = [];
2353
+ do {
2354
+ const paramStart = this.token.start;
2355
+ const { value: name } = this.next();
2356
+ this.expect(":");
2357
+ const typeAnnotation2 = this.parseType();
2358
+ parameters.push(
2359
+ this.finish("Identifier", paramStart, { name, typeAnnotation: typeAnnotation2 })
2360
+ );
2361
+ } while (this.eat(","));
2362
+ this.expect("]");
2363
+ const typeAnnotation = this.parseTypeAnnotation();
2364
+ return this.finish("TSIndexSignature", start, {
2365
+ parameters,
2366
+ typeAnnotation,
2367
+ readonly,
2368
+ static: isStatic
2369
+ });
2370
+ }
2371
+ };
2372
+
2373
+ // shared/syntax/src/parser/expressions.ts
2374
+ var ExpressionParser = class _ExpressionParser extends TypeParser {
2375
+ static {
2376
+ __name(this, "ExpressionParser");
2377
+ }
2378
+ static #precedence = {
2379
+ "??": 1,
2380
+ "||": 2,
2381
+ "&&": 3,
2382
+ "|": 4,
2383
+ "^": 5,
2384
+ "&": 6,
2385
+ "==": 7,
2386
+ "!=": 7,
2387
+ "===": 7,
2388
+ "!==": 7,
2389
+ "<": 8,
2390
+ ">": 8,
2391
+ "<=": 8,
2392
+ ">=": 8,
2393
+ instanceof: 8,
2394
+ in: 8,
2395
+ as: 8,
2396
+ satisfies: 8,
2397
+ "<<": 9,
2398
+ ">>": 9,
2399
+ ">>>": 9,
2400
+ "+": 10,
2401
+ "-": 10,
2402
+ "*": 11,
2403
+ "/": 11,
2404
+ "%": 11,
2405
+ "**": 12
2406
+ };
2407
+ static #assignments = /* @__PURE__ */ new Set([
2408
+ "=",
2409
+ "+=",
2410
+ "-=",
2411
+ "*=",
2412
+ "/=",
2413
+ "%=",
2414
+ "**=",
2415
+ "<<=",
2416
+ ">>=",
2417
+ ">>>=",
2418
+ "&=",
2419
+ "|=",
2420
+ "^=",
2421
+ "&&=",
2422
+ "||=",
2423
+ "??="
2424
+ ]);
2425
+ static #modifiers = /* @__PURE__ */ new Set([
2426
+ "abstract",
2427
+ "accessor",
2428
+ "async",
2429
+ "declare",
2430
+ "override",
2431
+ "private",
2432
+ "protected",
2433
+ "public",
2434
+ "readonly",
2435
+ "static"
2436
+ ]);
2437
+ /** Tokens after `f<T>` that make it an instantiation, not a comparison. */
2438
+ static #afterTypeArguments = /* @__PURE__ */ new Set([
2439
+ ")",
2440
+ "]",
2441
+ "}",
2442
+ ",",
2443
+ ";",
2444
+ ".",
2445
+ "?.",
2446
+ ":",
2447
+ "=",
2448
+ "==",
2449
+ "===",
2450
+ "!=",
2451
+ "!==",
2452
+ "&&",
2453
+ "||",
2454
+ "??",
2455
+ "?",
2456
+ "{",
2457
+ "extends",
2458
+ "implements",
2459
+ // like TypeScript, binary operators that cannot start an expression,
2460
+ // `<`, `>`, `+` and `-` would read as comparisons or unary operators
2461
+ "*",
2462
+ "/",
2463
+ "%",
2464
+ "**",
2465
+ "|",
2466
+ "^",
2467
+ "&",
2468
+ "<<",
2469
+ "<=",
2470
+ "as",
2471
+ "satisfies",
2472
+ "instanceof",
2473
+ "+=",
2474
+ "-=",
2475
+ "*=",
2476
+ "/=",
2477
+ "%=",
2478
+ "**=",
2479
+ "<<=",
2480
+ "&=",
2481
+ "|=",
2482
+ "^=",
2483
+ "&&=",
2484
+ "||=",
2485
+ "??="
2486
+ ]);
2487
+ parseExpression() {
2488
+ const start = this.token.start;
2489
+ const first = this.parseAssignment();
2490
+ if (!this.is(",")) return first;
2491
+ const expressions = [first];
2492
+ while (this.eat(",")) expressions.push(this.parseAssignment());
2493
+ return this.finish("SequenceExpression", start, { expressions });
2494
+ }
2495
+ parseAssignment() {
2496
+ const start = this.token.start;
2497
+ if (this.is("yield") && this.#yields()) return this.#yield(start);
2498
+ const arrow = this.#tryArrow(start);
2499
+ if (arrow) return arrow;
2500
+ const left = this.#conditional(start);
2501
+ if (this.token.type === "punct" && this.is(">"))
2502
+ this.replace(this.scanner.greater(this.token));
2503
+ if (this.token.type === "punct" && this.is("<"))
2504
+ this.replace(this.scanner.less(this.token));
2505
+ if (this.token.type !== "punct" || !_ExpressionParser.#assignments.has(this.token.value))
2506
+ return left;
2507
+ const operator = this.next().value;
2508
+ const right = this.parseAssignment();
2509
+ return this.finish("AssignmentExpression", start, {
2510
+ operator,
2511
+ left: operator === "=" ? this.toPattern(left) : left,
2512
+ right
2513
+ });
2514
+ }
2515
+ /** Converts an object or array literal used as an assignment target into a pattern. */
2516
+ toPattern(node) {
2517
+ switch (node.type) {
2518
+ case "ObjectExpression":
2519
+ return {
2520
+ ...node,
2521
+ type: "ObjectPattern",
2522
+ typeAnnotation: null,
2523
+ properties: node.properties.map((property) => {
2524
+ if (property.type === "SpreadElement")
2525
+ return {
2526
+ ...property,
2527
+ type: "RestElement",
2528
+ argument: this.toPattern(property.argument),
2529
+ typeAnnotation: null
2530
+ };
2531
+ if (property.type === "Property" && !property.shorthand)
2532
+ return {
2533
+ ...property,
2534
+ value: this.toPattern(property.value)
2535
+ };
2536
+ return property;
2537
+ })
2538
+ };
2539
+ case "ArrayExpression":
2540
+ return {
2541
+ ...node,
2542
+ type: "ArrayPattern",
2543
+ typeAnnotation: null,
2544
+ elements: node.elements.map((element) => {
2545
+ if (!element) return element;
2546
+ if (element.type === "SpreadElement")
2547
+ return {
2548
+ ...element,
2549
+ type: "RestElement",
2550
+ argument: this.toPattern(element.argument),
2551
+ typeAnnotation: null
2552
+ };
2553
+ return this.toPattern(element);
2554
+ })
2555
+ };
2556
+ case "AssignmentExpression":
2557
+ return node.operator === "=" ? {
2558
+ ...node,
2559
+ type: "AssignmentPattern",
2560
+ left: this.toPattern(node.left)
2561
+ } : node;
2562
+ default:
2563
+ return node;
2564
+ }
2565
+ }
2566
+ /** Parses with `in` allowed or not, restoring the previous setting. */
2567
+ withIn(allow, parse2) {
2568
+ const allowIn = this.allowIn;
2569
+ this.allowIn = allow;
2570
+ try {
2571
+ return parse2();
2572
+ } finally {
2573
+ this.allowIn = allowIn;
2574
+ }
2575
+ }
2576
+ #yields() {
2577
+ const next = this.peek();
2578
+ return !next.newline || next.value === "*";
2579
+ }
2580
+ #yield(start) {
2581
+ this.next();
2582
+ const delegate = this.eat("*");
2583
+ const argument = delegate || !this.token.newline && !this.#ends() ? this.parseAssignment() : null;
2584
+ return this.finish("YieldExpression", start, { argument, delegate });
2585
+ }
2586
+ /** Whether the current token cannot start an expression. */
2587
+ #ends() {
2588
+ return [")", "]", "}", ",", ";", ":", "=>"].includes(this.token.value) || this.token.type === "eof";
2589
+ }
2590
+ #tryArrow(start) {
2591
+ const next = this.isName() || this.is("(") || this.is("<") ? this.peek() : void 0;
2592
+ if (!next) return;
2593
+ if (this.is("async") && !next.newline && (this.isName(next) || this.is("(", next) || this.is("<", next))) {
2594
+ const arrow = this.attempt(() => {
2595
+ this.next();
2596
+ return this.#arrow(start, true);
2597
+ });
2598
+ if (arrow) return arrow;
2599
+ }
2600
+ if (this.isName() && this.is("=>", next) && !next.newline)
2601
+ return this.#arrow(start, false);
2602
+ if (this.is("(") || this.is("<") && this.options.typescript)
2603
+ return this.attempt(() => this.#arrow(start, false));
2604
+ }
2605
+ #arrow(start, async) {
2606
+ let typeParameters = null;
2607
+ let params;
2608
+ let returnType = null;
2609
+ if (this.isName() && !this.is("(")) params = [this.parseIdentifier()];
2610
+ else {
2611
+ typeParameters = this.parseTypeParameters();
2612
+ params = this.parseParameters();
2613
+ if (this.eat(":")) returnType = this.parseReturnType();
2614
+ }
2615
+ if (this.token.newline || !this.is("=>"))
2616
+ this.unexpected('Expected "=>"');
2617
+ this.next();
2618
+ const body = this.is("{") ? this.parseBlock() : this.parseAssignment();
2619
+ return this.finish("ArrowFunctionExpression", start, {
2620
+ id: null,
2621
+ params,
2622
+ body,
2623
+ async,
2624
+ generator: false,
2625
+ typeParameters,
2626
+ returnType
2627
+ });
2628
+ }
2629
+ #conditional(start) {
2630
+ const test = this.#binary(0);
2631
+ if (!this.is("?")) return test;
2632
+ this.next();
2633
+ const consequent = this.withIn(true, () => this.parseAssignment());
2634
+ this.expect(":");
2635
+ const alternate = this.parseAssignment();
2636
+ return this.finish("ConditionalExpression", start, {
2637
+ test,
2638
+ consequent,
2639
+ alternate
2640
+ });
2641
+ }
2642
+ #binary(minimum) {
2643
+ const start = this.token.start;
2644
+ let left = this.#unary();
2645
+ for (; ; ) {
2646
+ if (this.is(">")) this.replace(this.scanner.greater(this.token));
2647
+ else if (this.is("<") && this.token.type === "punct")
2648
+ this.replace(this.scanner.less(this.token));
2649
+ const { value, type } = this.token;
2650
+ const precedence = _ExpressionParser.#precedence[value];
2651
+ if (precedence === void 0 || type !== "punct" && type !== "name")
2652
+ break;
2653
+ if (type === "name" && !["in", "instanceof", "as", "satisfies"].includes(value))
2654
+ break;
2655
+ if (value === "in" && !this.allowIn) break;
2656
+ if ((value === "as" || value === "satisfies") && (this.token.newline || !this.options.typescript))
2657
+ break;
2658
+ if (value === "**" ? precedence < minimum : precedence <= minimum)
2659
+ break;
2660
+ this.next();
2661
+ if (value === "as" || value === "satisfies") {
2662
+ const typeAnnotation = this.is("const") ? this.#constType() : this.parseType();
2663
+ left = this.finish(
2664
+ value === "as" ? "TSAsExpression" : "TSSatisfiesExpression",
2665
+ start,
2666
+ { expression: left, typeAnnotation }
2667
+ );
2668
+ continue;
2669
+ }
2670
+ const right = this.#binary(precedence);
2671
+ const logical = value === "&&" || value === "||" || value === "??";
2672
+ left = this.finish(
2673
+ logical ? "LogicalExpression" : "BinaryExpression",
2674
+ start,
2675
+ { operator: value, left, right }
2676
+ );
2677
+ }
2678
+ return left;
2679
+ }
2680
+ #constType() {
2681
+ const start = this.token.start;
2682
+ const typeName = this.parseIdentifier();
2683
+ return this.finish("TSTypeReference", start, {
2684
+ typeName,
2685
+ typeArguments: null
2686
+ });
2687
+ }
2688
+ #unary() {
2689
+ const start = this.token.start;
2690
+ const { value, type } = this.token;
2691
+ if (type === "punct" && ["!", "~", "+", "-"].includes(value)) {
2692
+ this.next();
2693
+ return this.finish("UnaryExpression", start, {
2694
+ operator: value,
2695
+ argument: this.#unary()
2696
+ });
2697
+ }
2698
+ if (type === "name" && ["typeof", "void", "delete"].includes(value) && !this.#keywordEnds()) {
2699
+ this.next();
2700
+ return this.finish("UnaryExpression", start, {
2701
+ operator: value,
2702
+ argument: this.#unary()
2703
+ });
2704
+ }
2705
+ if (type === "punct" && (value === "++" || value === "--")) {
2706
+ this.next();
2707
+ return this.finish("UpdateExpression", start, {
2708
+ operator: value,
2709
+ prefix: true,
2710
+ argument: this.#unary()
2711
+ });
2712
+ }
2713
+ if (this.is("await") && !this.#keywordEnds()) {
2714
+ this.next();
2715
+ return this.finish("AwaitExpression", start, {
2716
+ argument: this.#unary()
2717
+ });
2718
+ }
2719
+ if (this.is("<") && this.options.typescript && !this.options.jsx) {
2720
+ this.next();
2721
+ const typeAnnotation = this.is("const") ? this.#constType() : this.parseType();
2722
+ this.expect(">");
2723
+ return this.finish("TSTypeAssertion", start, {
2724
+ typeAnnotation,
2725
+ expression: this.#unary()
2726
+ });
2727
+ }
2728
+ const argument = this.parseLeftHandSide();
2729
+ if (!this.token.newline && (this.is("++") || this.is("--"))) {
2730
+ const operator = this.next().value;
2731
+ return this.finish("UpdateExpression", start, {
2732
+ operator,
2733
+ prefix: false,
2734
+ argument
2735
+ });
2736
+ }
2737
+ return argument;
2738
+ }
2739
+ /** Whether a keyword like `await` is used as a plain name here. */
2740
+ #keywordEnds() {
2741
+ const next = this.peek();
2742
+ return [")", "]", "}", ",", ";", ":", "=", ".", "?.", "=>", "?"].includes(
2743
+ next.value
2744
+ ) || next.type === "eof" || next.type === "punct" && _ExpressionParser.#assignments.has(next.value);
2745
+ }
2746
+ parseLeftHandSide() {
2747
+ const start = this.token.start;
2748
+ const expression = this.is("new") ? this.#new() : this.#primary();
2749
+ return this.#subscripts(expression, start, false);
2750
+ }
2751
+ #subscripts(object, start, noCall) {
2752
+ let expression = object;
2753
+ for (; ; ) {
2754
+ if (this.eat(".")) {
2755
+ expression = this.finish("MemberExpression", start, {
2756
+ object: expression,
2757
+ property: this.#memberName(),
2758
+ computed: false,
2759
+ optional: false
2760
+ });
2761
+ } else if (this.is("?.")) {
2762
+ if (noCall) break;
2763
+ this.next();
2764
+ if (this.is("("))
2765
+ expression = this.#call(start, expression, null, true);
2766
+ else if (this.eat("[")) {
2767
+ const property = this.withIn(
2768
+ true,
2769
+ () => this.parseExpression()
2770
+ );
2771
+ this.expect("]");
2772
+ expression = this.finish("MemberExpression", start, {
2773
+ object: expression,
2774
+ property,
2775
+ computed: true,
2776
+ optional: true
2777
+ });
2778
+ } else if (this.is("<")) {
2779
+ const typeArguments = this.parseTypeArguments();
2780
+ expression = this.#call(
2781
+ start,
2782
+ expression,
2783
+ typeArguments,
2784
+ true
2785
+ );
2786
+ } else
2787
+ expression = this.finish("MemberExpression", start, {
2788
+ object: expression,
2789
+ property: this.#memberName(),
2790
+ computed: false,
2791
+ optional: true
2792
+ });
2793
+ } else if (this.is("[")) {
2794
+ this.next();
2795
+ const property = this.withIn(
2796
+ true,
2797
+ () => this.parseExpression()
2798
+ );
2799
+ this.expect("]");
2800
+ expression = this.finish("MemberExpression", start, {
2801
+ object: expression,
2802
+ property,
2803
+ computed: true,
2804
+ optional: false
2805
+ });
2806
+ } else if (!noCall && this.is("(")) {
2807
+ expression = this.#call(start, expression, null, false);
2808
+ } else if (this.token.type === "template") {
2809
+ const quasi = this.#template();
2810
+ expression = this.finish("TaggedTemplateExpression", start, {
2811
+ tag: expression,
2812
+ quasi,
2813
+ typeArguments: null
2814
+ });
2815
+ } else if (this.options.typescript && this.is("!") && !this.token.newline) {
2816
+ this.next();
2817
+ expression = this.finish("TSNonNullExpression", start, {
2818
+ expression
2819
+ });
2820
+ } else if (this.options.typescript && this.is("<") && !this.token.newline) {
2821
+ const result = this.attempt(
2822
+ () => this.#typeArgumentsSubscript(start, expression, noCall)
2823
+ );
2824
+ if (!result) break;
2825
+ expression = result;
2826
+ } else break;
2827
+ }
2828
+ return expression;
2829
+ }
2830
+ #typeArgumentsSubscript(start, expression, noCall) {
2831
+ const typeArguments = this.parseTypeArguments();
2832
+ if (!noCall && this.is("("))
2833
+ return this.#call(start, expression, typeArguments, false);
2834
+ if (this.token.type === "template") {
2835
+ const quasi = this.#template();
2836
+ return this.finish("TaggedTemplateExpression", start, {
2837
+ tag: expression,
2838
+ quasi,
2839
+ typeArguments
2840
+ });
2841
+ }
2842
+ if (this.token.type === "eof" || this.token.newline || _ExpressionParser.#afterTypeArguments.has(this.token.value) && this.token.type !== "string")
2843
+ return this.finish("TSInstantiationExpression", start, {
2844
+ expression,
2845
+ typeArguments
2846
+ });
2847
+ return this.unexpected();
2848
+ }
2849
+ #memberName() {
2850
+ if (this.token.type === "private") {
2851
+ const { start, value } = this.next();
2852
+ return this.finish("PrivateName", start, { name: value.slice(1) });
2853
+ }
2854
+ return this.parseIdentifier();
2855
+ }
2856
+ #call(start, callee, typeArguments, optional) {
2857
+ const args = this.parseArguments();
2858
+ return this.finish("CallExpression", start, {
2859
+ callee,
2860
+ arguments: args,
2861
+ optional,
2862
+ typeArguments
2863
+ });
2864
+ }
2865
+ parseArguments() {
2866
+ this.expect("(");
2867
+ const args = [];
2868
+ while (!this.is(")")) {
2869
+ const start = this.token.start;
2870
+ if (this.eat("..."))
2871
+ args.push(
2872
+ this.finish("SpreadElement", start, {
2873
+ argument: this.withIn(
2874
+ true,
2875
+ () => this.parseAssignment()
2876
+ )
2877
+ })
2878
+ );
2879
+ else args.push(this.withIn(true, () => this.parseAssignment()));
2880
+ if (!this.eat(",")) break;
2881
+ }
2882
+ this.expect(")");
2883
+ return args;
2884
+ }
2885
+ #new() {
2886
+ const start = this.expect("new").start;
2887
+ if (this.eat(".")) {
2888
+ const property = this.parseIdentifier().name;
2889
+ return this.finish("MetaProperty", start, {
2890
+ meta: "new",
2891
+ property
2892
+ });
2893
+ }
2894
+ const calleeStart = this.token.start;
2895
+ const inner = this.is("new") ? this.#new() : this.#primary();
2896
+ let callee = this.#subscripts(inner, calleeStart, true);
2897
+ let typeArguments = null;
2898
+ if (callee.type === "TSInstantiationExpression") {
2899
+ typeArguments = callee.typeArguments;
2900
+ callee = callee.expression;
2901
+ } else if (this.options.typescript && this.is("<")) {
2902
+ typeArguments = this.attempt(() => this.parseTypeArguments()) ?? null;
2903
+ }
2904
+ const parentheses = this.is("(");
2905
+ const args = parentheses ? this.parseArguments() : [];
2906
+ return this.finish("NewExpression", start, {
2907
+ callee,
2908
+ arguments: args,
2909
+ typeArguments,
2910
+ parentheses
2911
+ });
2912
+ }
2913
+ #primary() {
2914
+ const token = this.token;
2915
+ const { start, type, value } = token;
2916
+ switch (type) {
2917
+ case "number":
2918
+ this.next();
2919
+ return this.finish("NumericLiteral", start, { raw: value });
2920
+ case "string":
2921
+ this.next();
2922
+ return this.finish("StringLiteral", start, { raw: value });
2923
+ case "template":
2924
+ return this.#template();
2925
+ case "private":
2926
+ this.next();
2927
+ return this.finish("PrivateName", start, {
2928
+ name: value.slice(1)
2929
+ });
2930
+ case "punct":
2931
+ return this.#punctuation(start, value);
2932
+ case "name":
2933
+ return this.#word(start, value);
2934
+ default:
2935
+ return this.unexpected();
2936
+ }
2937
+ }
2938
+ #punctuation(start, value) {
2939
+ switch (value) {
2940
+ case "(": {
2941
+ this.next();
2942
+ const expression = this.withIn(
2943
+ true,
2944
+ () => this.parseExpression()
2945
+ );
2946
+ this.expect(")");
2947
+ expression.parenthesized = true;
2948
+ return expression;
2949
+ }
2950
+ case "[":
2951
+ return this.#array(start);
2952
+ case "{":
2953
+ return this.#object(start);
2954
+ case "/":
2955
+ case "/=": {
2956
+ const regex = this.scanner.regex(this.token);
2957
+ this.replace(regex);
2958
+ this.next();
2959
+ return this.finish("RegExpLiteral", start, {
2960
+ raw: regex.value
2961
+ });
2962
+ }
2963
+ case "<":
2964
+ if (!this.options.jsx) return this.unexpected();
2965
+ return this.#jsxExpression();
2966
+ case "@": {
2967
+ const decorators = this.parseDecorators();
2968
+ return this.parseClass(start, decorators, true, false, false);
2969
+ }
2970
+ default:
2971
+ return this.unexpected();
2972
+ }
2973
+ }
2974
+ #word(start, value) {
2975
+ switch (value) {
2976
+ case "function":
2977
+ return this.parseFunction(start, false, true);
2978
+ case "class":
2979
+ return this.parseClass(start, [], true, false, false);
2980
+ case "this":
2981
+ this.next();
2982
+ return this.finish("ThisExpression", start, {});
2983
+ case "super":
2984
+ this.next();
2985
+ return this.finish("Super", start, {});
2986
+ case "null":
2987
+ this.next();
2988
+ return this.finish("NullLiteral", start, {});
2989
+ case "true":
2990
+ case "false":
2991
+ this.next();
2992
+ return this.finish("BooleanLiteral", start, {
2993
+ value: value === "true"
2994
+ });
2995
+ case "async": {
2996
+ const next = this.peek();
2997
+ if (this.is("function", next) && !next.newline) {
2998
+ this.next();
2999
+ return this.parseFunction(start, true, true);
3000
+ }
3001
+ break;
3002
+ }
3003
+ case "import":
3004
+ return this.#import(start);
3005
+ }
3006
+ return this.parseIdentifier();
3007
+ }
3008
+ #import(start) {
3009
+ const next = this.peek();
3010
+ if (this.is(".", next)) {
3011
+ this.next();
3012
+ this.next();
3013
+ const property = this.parseIdentifier().name;
3014
+ if (this.is("(")) {
3015
+ this.next();
3016
+ return this.#importCall(start, property);
3017
+ }
3018
+ return this.finish("MetaProperty", start, {
3019
+ meta: "import",
3020
+ property
3021
+ });
3022
+ }
3023
+ this.next();
3024
+ this.expect("(");
3025
+ return this.#importCall(start, null);
3026
+ }
3027
+ #importCall(start, phase) {
3028
+ const source = this.withIn(true, () => this.parseAssignment());
3029
+ const options = this.eat(",") && !this.is(")") ? this.parseAssignment() : null;
3030
+ this.eat(",");
3031
+ this.expect(")");
3032
+ return this.finish("ImportExpression", start, {
3033
+ source,
3034
+ options,
3035
+ phase
3036
+ });
3037
+ }
3038
+ #template() {
3039
+ const start = this.token.start;
3040
+ const { quasis, parts } = this.parseTemplateParts(
3041
+ () => this.withIn(true, () => this.parseExpression())
3042
+ );
3043
+ return this.finish("TemplateLiteral", start, {
3044
+ quasis,
3045
+ expressions: parts
3046
+ });
3047
+ }
3048
+ #array(start) {
3049
+ this.expect("[");
3050
+ const elements = [];
3051
+ while (!this.is("]")) {
3052
+ if (this.is(",")) {
3053
+ this.next();
3054
+ elements.push(null);
3055
+ continue;
3056
+ }
3057
+ const elementStart = this.token.start;
3058
+ if (this.eat("..."))
3059
+ elements.push(
3060
+ this.finish("SpreadElement", elementStart, {
3061
+ argument: this.withIn(
3062
+ true,
3063
+ () => this.parseAssignment()
3064
+ )
3065
+ })
3066
+ );
3067
+ else elements.push(this.withIn(true, () => this.parseAssignment()));
3068
+ if (!this.eat(",")) break;
3069
+ }
3070
+ this.expect("]");
3071
+ return this.finish("ArrayExpression", start, { elements });
3072
+ }
3073
+ #object(start) {
3074
+ this.expect("{");
3075
+ const properties = [];
3076
+ while (!this.is("}")) {
3077
+ properties.push(this.withIn(true, () => this.#property()));
3078
+ if (!this.eat(",")) break;
3079
+ }
3080
+ this.expect("}");
3081
+ return this.finish("ObjectExpression", start, { properties });
3082
+ }
3083
+ #property() {
3084
+ const start = this.token.start;
3085
+ if (this.eat("..."))
3086
+ return this.finish("SpreadElement", start, {
3087
+ argument: this.parseAssignment()
3088
+ });
3089
+ let async = false;
3090
+ let generator = false;
3091
+ let kind = "init";
3092
+ if (this.is("async") && this.#modifies()) {
3093
+ this.next();
3094
+ async = true;
3095
+ }
3096
+ if (this.eat("*")) generator = true;
3097
+ if ((this.is("get") || this.is("set")) && this.#modifies())
3098
+ kind = this.next().value;
3099
+ const { key, computed } = this.parsePropertyKey();
3100
+ if (this.is("(") || this.is("<")) {
3101
+ const value2 = this.#method(this.token.start, async, generator);
3102
+ return this.finish("Property", start, {
3103
+ key,
3104
+ value: value2,
3105
+ kind,
3106
+ method: kind === "init",
3107
+ shorthand: false,
3108
+ computed
3109
+ });
3110
+ }
3111
+ if (this.eat(":"))
3112
+ return this.finish("Property", start, {
3113
+ key,
3114
+ value: this.parseAssignment(),
3115
+ kind,
3116
+ method: false,
3117
+ shorthand: false,
3118
+ computed
3119
+ });
3120
+ let value = key;
3121
+ if (this.is("=")) {
3122
+ this.next();
3123
+ value = this.finish("AssignmentPattern", start, {
3124
+ left: key,
3125
+ right: this.parseAssignment()
3126
+ });
3127
+ }
3128
+ return this.finish("Property", start, {
3129
+ key,
3130
+ value,
3131
+ kind,
3132
+ method: false,
3133
+ shorthand: true,
3134
+ computed
3135
+ });
3136
+ }
3137
+ /** Whether a modifier word (async, get, set, static...) applies to a following name. */
3138
+ #modifies() {
3139
+ const next = this.peek();
3140
+ return !next.newline && !["(", ")", ":", ",", "}", "=", ";", "?", "!", "<", "."].includes(
3141
+ next.value
3142
+ ) && next.type !== "eof";
3143
+ }
3144
+ parsePropertyKey() {
3145
+ const { start, type, value } = this.token;
3146
+ if (this.is("[")) {
3147
+ this.next();
3148
+ const key = this.withIn(true, () => this.parseAssignment());
3149
+ this.expect("]");
3150
+ return { key, computed: true };
3151
+ }
3152
+ this.next();
3153
+ switch (type) {
3154
+ case "string":
3155
+ return {
3156
+ key: this.finish("StringLiteral", start, { raw: value }),
3157
+ computed: false
3158
+ };
3159
+ case "number":
3160
+ return {
3161
+ key: this.finish("NumericLiteral", start, { raw: value }),
3162
+ computed: false
3163
+ };
3164
+ case "private":
3165
+ return {
3166
+ key: this.finish("PrivateName", start, {
3167
+ name: value.slice(1)
3168
+ }),
3169
+ computed: false
3170
+ };
3171
+ case "name":
3172
+ return {
3173
+ key: this.finish("Identifier", start, { name: value }),
3174
+ computed: false
3175
+ };
3176
+ default:
3177
+ return this.raise("Expected a property name", start);
3178
+ }
3179
+ }
3180
+ #method(start, async, generator) {
3181
+ const typeParameters = this.parseTypeParameters();
3182
+ const params = this.parseParameters();
3183
+ const returnType = this.eat(":") ? this.parseReturnType() : null;
3184
+ const body = this.is("{") ? this.parseBlock() : null;
3185
+ return this.finish("FunctionExpression", start, {
3186
+ id: null,
3187
+ params,
3188
+ body,
3189
+ async,
3190
+ generator,
3191
+ typeParameters,
3192
+ returnType
3193
+ });
3194
+ }
3195
+ parseFunction(start, async, expression) {
3196
+ this.expect("function");
3197
+ const generator = this.eat("*");
3198
+ const id = this.isName() && !this.is("(") ? this.parseIdentifier() : null;
3199
+ const typeParameters = this.parseTypeParameters();
3200
+ const params = this.parseParameters();
3201
+ const returnType = this.eat(":") ? this.parseReturnType() : null;
3202
+ const parts = {
3203
+ id,
3204
+ params,
3205
+ async,
3206
+ generator,
3207
+ typeParameters,
3208
+ returnType
3209
+ };
3210
+ if (expression) {
3211
+ const body = this.is("{") || !this.options.typescript ? this.parseBlock() : null;
3212
+ return this.finish("FunctionExpression", start, { ...parts, body });
3213
+ }
3214
+ if (!this.is("{")) {
3215
+ this.semicolon();
3216
+ return this.finish("TSDeclareFunction", start, {
3217
+ ...parts,
3218
+ body: null,
3219
+ declare: false
3220
+ });
3221
+ }
3222
+ return this.finish("FunctionDeclaration", start, {
3223
+ ...parts,
3224
+ body: this.parseBlock(),
3225
+ declare: false
3226
+ });
3227
+ }
3228
+ parseParameters() {
3229
+ this.expect("(");
3230
+ const params = [];
3231
+ while (!this.is(")")) {
3232
+ params.push(this.#parameter());
3233
+ if (!this.eat(",")) break;
3234
+ }
3235
+ this.expect(")");
3236
+ return params;
3237
+ }
3238
+ #parameter() {
3239
+ const start = this.token.start;
3240
+ const decorators = this.parseDecorators();
3241
+ const modifiers = {};
3242
+ while (["public", "private", "protected", "readonly", "override"].includes(
3243
+ this.token.value
3244
+ ) && this.#modifies()) {
3245
+ const { value } = this.next();
3246
+ if (value === "readonly") modifiers.readonly = true;
3247
+ else if (value === "override") modifiers.override = true;
3248
+ else
3249
+ modifiers.accessibility = value;
3250
+ }
3251
+ const parameter = this.parseBindingElement();
3252
+ if (Object.keys(modifiers).length === 0 && decorators.length === 0)
3253
+ return parameter;
3254
+ return this.finish("TSParameterProperty", start, {
3255
+ ...modifiers,
3256
+ decorators,
3257
+ parameter
3258
+ });
3259
+ }
3260
+ /** Parses a binding target with optional `?`, type annotation and default. */
3261
+ parseBindingElement() {
3262
+ const start = this.token.start;
3263
+ if (this.eat("...")) {
3264
+ const argument = this.parseBindingTarget();
3265
+ const optional = this.eat("?");
3266
+ const typeAnnotation = this.parseTypeAnnotation();
3267
+ return this.finish("RestElement", start, {
3268
+ argument,
3269
+ typeAnnotation,
3270
+ optional
3271
+ });
3272
+ }
3273
+ const target = this.parseBindingTarget();
3274
+ if (this.eat("?")) target.optional = true;
3275
+ if (this.is(":")) {
3276
+ const typeAnnotation = this.parseTypeAnnotation();
3277
+ target.typeAnnotation = typeAnnotation;
3278
+ target.end = this.previous;
3279
+ }
3280
+ if (!this.eat("=")) return target;
3281
+ return this.finish("AssignmentPattern", start, {
3282
+ left: target,
3283
+ right: this.withIn(true, () => this.parseAssignment())
3284
+ });
3285
+ }
3286
+ parseBindingTarget() {
3287
+ const start = this.token.start;
3288
+ if (this.eat("[")) {
3289
+ const elements = [];
3290
+ while (!this.is("]")) {
3291
+ if (this.eat(",")) {
3292
+ elements.push(null);
3293
+ continue;
3294
+ }
3295
+ elements.push(this.parseBindingElement());
3296
+ if (!this.eat(",")) break;
3297
+ }
3298
+ this.expect("]");
3299
+ return this.finish("ArrayPattern", start, {
3300
+ elements,
3301
+ typeAnnotation: null
3302
+ });
3303
+ }
3304
+ if (this.eat("{")) {
3305
+ const properties = [];
3306
+ while (!this.is("}")) {
3307
+ const propertyStart = this.token.start;
3308
+ if (this.eat("...")) {
3309
+ properties.push(
3310
+ this.finish("RestElement", propertyStart, {
3311
+ argument: this.parseBindingTarget(),
3312
+ typeAnnotation: null
3313
+ })
3314
+ );
3315
+ } else {
3316
+ const { key, computed } = this.parsePropertyKey();
3317
+ if (this.eat(":")) {
3318
+ const value = this.parseBindingElement();
3319
+ properties.push(
3320
+ this.finish("Property", propertyStart, {
3321
+ key,
3322
+ value,
3323
+ kind: "init",
3324
+ method: false,
3325
+ shorthand: false,
3326
+ computed
3327
+ })
3328
+ );
3329
+ } else {
3330
+ const value = this.eat("=") ? this.finish("AssignmentPattern", propertyStart, {
3331
+ left: key,
3332
+ right: this.withIn(
3333
+ true,
3334
+ () => this.parseAssignment()
3335
+ )
3336
+ }) : key;
3337
+ properties.push(
3338
+ this.finish("Property", propertyStart, {
3339
+ key,
3340
+ value,
3341
+ kind: "init",
3342
+ method: false,
3343
+ shorthand: true,
3344
+ computed
3345
+ })
3346
+ );
3347
+ }
3348
+ }
3349
+ if (!this.eat(",")) break;
3350
+ }
3351
+ this.expect("}");
3352
+ return this.finish("ObjectPattern", start, {
3353
+ properties,
3354
+ typeAnnotation: null
3355
+ });
3356
+ }
3357
+ if (this.is("this")) {
3358
+ this.next();
3359
+ return this.finish("Identifier", start, { name: "this" });
3360
+ }
3361
+ return this.parseIdentifier();
3362
+ }
3363
+ parseDecorators() {
3364
+ const decorators = [];
3365
+ while (this.is("@")) {
3366
+ const start = this.next().start;
3367
+ let expression;
3368
+ if (this.is("(")) {
3369
+ this.next();
3370
+ expression = this.parseExpression();
3371
+ this.expect(")");
3372
+ expression.parenthesized = true;
3373
+ } else {
3374
+ const nameStart = this.token.start;
3375
+ expression = this.parseIdentifier();
3376
+ while (this.eat("."))
3377
+ expression = this.finish("MemberExpression", nameStart, {
3378
+ object: expression,
3379
+ property: this.#memberName(),
3380
+ computed: false,
3381
+ optional: false
3382
+ });
3383
+ let typeArguments = null;
3384
+ if (this.options.typescript && this.is("<"))
3385
+ typeArguments = this.parseTypeArguments();
3386
+ if (this.is("("))
3387
+ expression = this.#call(
3388
+ nameStart,
3389
+ expression,
3390
+ typeArguments,
3391
+ false
3392
+ );
3393
+ }
3394
+ decorators.push(this.finish("Decorator", start, { expression }));
3395
+ }
3396
+ return decorators;
3397
+ }
3398
+ parseClass(start, decorators, expression, abstract, declare) {
3399
+ this.expect("class");
3400
+ const id = this.isName() && !["extends", "implements"].includes(this.token.value) ? this.parseIdentifier() : null;
3401
+ const typeParameters = this.parseTypeParameters();
3402
+ let superClass = null;
3403
+ let superTypeArguments = null;
3404
+ if (this.eat("extends")) {
3405
+ superClass = this.parseLeftHandSide();
3406
+ if (superClass.type === "TSInstantiationExpression") {
3407
+ superTypeArguments = superClass.typeArguments;
3408
+ superClass = superClass.expression;
3409
+ }
3410
+ }
3411
+ const implemented = [];
3412
+ if (this.eat("implements")) {
3413
+ do
3414
+ implemented.push(this.parseType());
3415
+ while (this.eat(","));
3416
+ }
3417
+ const body = this.#classBody();
3418
+ const parts = {
3419
+ id,
3420
+ superClass,
3421
+ superTypeArguments,
3422
+ implements: implemented,
3423
+ body,
3424
+ decorators,
3425
+ typeParameters,
3426
+ abstract,
3427
+ declare
3428
+ };
3429
+ return expression ? this.finish("ClassExpression", start, parts) : this.finish("ClassDeclaration", start, parts);
3430
+ }
3431
+ #classBody() {
3432
+ const start = this.expect("{").start;
3433
+ const body = [];
3434
+ while (!this.is("}")) {
3435
+ if (this.eat(";")) continue;
3436
+ body.push(this.#member());
3437
+ }
3438
+ this.expect("}");
3439
+ return this.finish("ClassBody", start, { body });
3440
+ }
3441
+ #member() {
3442
+ const start = this.token.start;
3443
+ const decorators = this.parseDecorators();
3444
+ const modifiers = {};
3445
+ while (_ExpressionParser.#modifiers.has(this.token.value) && this.isName() && (this.#modifies() || this.is("static") && this.is("{", this.peek()))) {
3446
+ if (this.is("static") && this.is("{", this.peek())) break;
3447
+ const { value: value2 } = this.next();
3448
+ if (["private", "protected", "public"].includes(value2))
3449
+ modifiers.accessibility = value2;
3450
+ else modifiers[value2] = true;
3451
+ }
3452
+ if (this.is("static") && this.is("{", this.peek())) {
3453
+ this.next();
3454
+ const block = this.parseBlock();
3455
+ return this.finish("StaticBlock", start, { body: block.body });
3456
+ }
3457
+ const flags = {
3458
+ static: modifiers.static === true,
3459
+ ...typeof modifiers.accessibility === "string" ? {
3460
+ accessibility: modifiers.accessibility
3461
+ } : {},
3462
+ abstract: modifiers.abstract === true,
3463
+ declare: modifiers.declare === true,
3464
+ override: modifiers.override === true,
3465
+ readonly: modifiers.readonly === true
3466
+ };
3467
+ if (this.is("[")) {
3468
+ const index = this.parseIndexSignature(
3469
+ start,
3470
+ flags.readonly,
3471
+ flags.static
3472
+ );
3473
+ if (index) {
3474
+ this.eat(";") || this.eat(",");
3475
+ return index;
3476
+ }
3477
+ }
3478
+ const generator = this.eat("*");
3479
+ let kind = "method";
3480
+ if ((this.is("get") || this.is("set")) && this.#modifies())
3481
+ kind = this.next().value;
3482
+ const { key, computed } = this.parsePropertyKey();
3483
+ if (!computed && key.type === "Identifier" && key.name === "constructor" && (this.is("(") || this.is("<")))
3484
+ kind = "constructor";
3485
+ if (!computed && key.type === "StringLiteral" && key.raw.slice(1, -1) === "constructor")
3486
+ kind = "constructor";
3487
+ const optional = this.eat("?");
3488
+ if (this.is("(") || this.is("<")) {
3489
+ const value2 = this.#method(
3490
+ this.token.start,
3491
+ modifiers.async === true,
3492
+ generator
3493
+ );
3494
+ if (!value2.body) this.semicolon();
3495
+ return this.finish("MethodDefinition", start, {
3496
+ ...flags,
3497
+ key,
3498
+ value: value2,
3499
+ kind,
3500
+ computed,
3501
+ optional,
3502
+ decorators
3503
+ });
3504
+ }
3505
+ const definite = this.eat("!");
3506
+ const typeAnnotation = this.parseTypeAnnotation();
3507
+ const value = this.eat("=") ? this.withIn(true, () => this.parseAssignment()) : null;
3508
+ this.semicolon();
3509
+ return this.finish("PropertyDefinition", start, {
3510
+ ...flags,
3511
+ key,
3512
+ value,
3513
+ computed,
3514
+ optional,
3515
+ definite,
3516
+ accessor: modifiers.accessor === true,
3517
+ typeAnnotation,
3518
+ decorators
3519
+ });
3520
+ }
3521
+ // JSX
3522
+ #jsxExpression() {
3523
+ const element = this.#jsxElement();
3524
+ this.rescan(element.end);
3525
+ this.previous = element.end;
3526
+ return element;
3527
+ }
3528
+ /** Parses an element from `<`; leaves the scanner right after its last `>`. */
3529
+ #jsxElement() {
3530
+ const start = this.expect("<").start;
3531
+ if (this.is(">")) return this.#jsxChildren(start, null, [], null);
3532
+ const name = this.#jsxName();
3533
+ const typeArguments = this.options.typescript && this.is("<") ? this.parseTypeArguments() : null;
3534
+ const attributes = [];
3535
+ while (!this.is("/") && !this.is(">")) {
3536
+ const attributeStart = this.token.start;
3537
+ if (this.is("{")) {
3538
+ this.next();
3539
+ this.expect("...");
3540
+ const argument = this.parseAssignment();
3541
+ this.expect("}");
3542
+ attributes.push(
3543
+ this.finish("JSXSpreadAttribute", attributeStart, {
3544
+ argument
3545
+ })
3546
+ );
3547
+ continue;
3548
+ }
3549
+ const attributeName = this.#jsxName();
3550
+ let value = null;
3551
+ if (this.eat("=")) value = this.#jsxValue();
3552
+ attributes.push(
3553
+ this.finish("JSXAttribute", attributeStart, {
3554
+ name: attributeName,
3555
+ value
3556
+ })
3557
+ );
3558
+ }
3559
+ if (this.is("/")) {
3560
+ this.next();
3561
+ if (!this.is(">")) this.unexpected();
3562
+ this.previous = this.token.end;
3563
+ return this.finish("JSXElement", start, {
3564
+ name,
3565
+ attributes,
3566
+ children: [],
3567
+ selfClosing: true,
3568
+ typeArguments
3569
+ });
3570
+ }
3571
+ return this.#jsxChildren(start, name, attributes, typeArguments);
3572
+ }
3573
+ #jsxName() {
3574
+ if (!this.isName()) this.unexpected("Expected a JSX name");
3575
+ this.replace(this.scanner.jsxName(this.token));
3576
+ let name = this.next().value;
3577
+ while ((this.is(".") || this.is(":")) && this.isName(this.peek())) {
3578
+ name += this.next().value;
3579
+ this.replace(this.scanner.jsxName(this.token));
3580
+ name += this.next().value;
3581
+ }
3582
+ return name;
3583
+ }
3584
+ #jsxValue() {
3585
+ const start = this.token.start;
3586
+ if (this.token.type === "string" || this.token.type === "invalid" && /["']/.test(this.source[start] ?? "")) {
3587
+ const token = this.scanner.jsxString(this.token);
3588
+ this.replace(token);
3589
+ this.next();
3590
+ return this.finish("StringLiteral", start, { raw: token.value });
3591
+ }
3592
+ if (this.is("<")) {
3593
+ const element = this.#jsxElement();
3594
+ this.rescan(element.end);
3595
+ return element;
3596
+ }
3597
+ this.expect("{");
3598
+ const expression = this.is("}") ? null : this.parseAssignment();
3599
+ this.expect("}");
3600
+ return this.finish("JSXExpressionContainer", start, { expression });
3601
+ }
3602
+ /** Parses children after the opening `>` up to and including the closing tag. */
3603
+ #jsxChildren(start, name, attributes, typeArguments) {
3604
+ if (!this.is(">")) this.unexpected();
3605
+ let position = this.token.end;
3606
+ const children = [];
3607
+ for (; ; ) {
3608
+ const char = this.source[position];
3609
+ if (char === void 0)
3610
+ this.raise("Unterminated JSX element", start);
3611
+ if (char !== "{" && char !== "<") {
3612
+ const text = this.scanner.jsxText(position);
3613
+ children.push({
3614
+ type: "JSXText",
3615
+ start: text.start,
3616
+ end: text.end,
3617
+ raw: text.value
3618
+ });
3619
+ position = text.end;
3620
+ continue;
3621
+ }
3622
+ this.rescan(position);
3623
+ if (char === "{") {
3624
+ const childStart = this.next().start;
3625
+ let child2;
3626
+ if (this.is("}"))
3627
+ child2 = this.finish("JSXExpressionContainer", childStart, {
3628
+ expression: null
3629
+ });
3630
+ else if (this.eat("...")) {
3631
+ const expression = this.parseExpression();
3632
+ child2 = this.finish("JSXSpreadChild", childStart, {
3633
+ expression
3634
+ });
3635
+ } else {
3636
+ const expression = this.parseExpression();
3637
+ child2 = this.finish("JSXExpressionContainer", childStart, {
3638
+ expression
3639
+ });
3640
+ }
3641
+ if (!this.is("}")) this.unexpected();
3642
+ child2.end = this.token.end;
3643
+ children.push(child2);
3644
+ position = this.token.end;
3645
+ continue;
3646
+ }
3647
+ if (this.is("/", this.peek())) {
3648
+ this.next();
3649
+ this.next();
3650
+ const closing = this.is(">") ? null : this.#jsxName();
3651
+ if (closing !== name)
3652
+ this.raise(
3653
+ `Expected closing tag for ${name ?? "fragment"}`,
3654
+ this.token.start
3655
+ );
3656
+ if (!this.is(">")) this.unexpected();
3657
+ this.previous = this.token.end;
3658
+ return this.finish("JSXElement", start, {
3659
+ name,
3660
+ attributes,
3661
+ children,
3662
+ selfClosing: false,
3663
+ typeArguments
3664
+ });
3665
+ }
3666
+ const child = this.#jsxElement();
3667
+ children.push(child);
3668
+ position = child.end;
3669
+ }
3670
+ }
3671
+ };
3672
+
3673
+ // shared/syntax/src/parser/statements.ts
3674
+ var Parser = class extends ExpressionParser {
3675
+ static {
3676
+ __name(this, "Parser");
3677
+ }
3678
+ parseProgram() {
3679
+ const { body, directives } = this.#list(
3680
+ true,
3681
+ () => this.token.type === "eof"
3682
+ );
3683
+ if (this.token.type !== "eof") this.unexpected();
3684
+ return {
3685
+ type: "Program",
3686
+ start: 0,
3687
+ end: this.source.length,
3688
+ body,
3689
+ directives
3690
+ };
3691
+ }
3692
+ /** Parses a whole document as one expression, for JSON. */
3693
+ parseDocument() {
3694
+ const expression = this.parseAssignment();
3695
+ if (this.token.type !== "eof") this.unexpected();
3696
+ return expression;
3697
+ }
3698
+ parseBlock() {
3699
+ const start = this.expect("{").start;
3700
+ const { body, directives } = this.#list(true, () => this.is("}"));
3701
+ this.expect("}");
3702
+ return this.finish("BlockStatement", start, { body, directives });
3703
+ }
3704
+ #list(directives, done) {
3705
+ const body = [];
3706
+ const prologue = [];
3707
+ let inPrologue = directives;
3708
+ while (!done() && this.token.type !== "eof") {
3709
+ if (inPrologue && this.token.type === "string") {
3710
+ const directive = this.attempt(() => {
3711
+ const value = this.parseString();
3712
+ if (!this.canInsertSemicolon()) this.unexpected();
3713
+ this.semicolon();
3714
+ return this.finish("Directive", value.start, { value });
3715
+ });
3716
+ if (directive) {
3717
+ prologue.push(directive);
3718
+ continue;
3719
+ }
3720
+ }
3721
+ inPrologue = false;
3722
+ body.push(this.#statement());
3723
+ }
3724
+ return { body, directives: prologue };
3725
+ }
3726
+ #statement() {
3727
+ const start = this.token.start;
3728
+ const { type, value } = this.token;
3729
+ if (type === "punct") {
3730
+ if (value === "{") return this.parseBlock();
3731
+ if (value === ";") {
3732
+ this.next();
3733
+ return this.finish("EmptyStatement", start, {});
3734
+ }
3735
+ if (value === "@") {
3736
+ const decorators = this.parseDecorators();
3737
+ if (this.is("export")) return this.#export(start, decorators);
3738
+ const abstract = this.eat("abstract");
3739
+ return this.parseClass(
3740
+ start,
3741
+ decorators,
3742
+ false,
3743
+ abstract,
3744
+ false
3745
+ );
3746
+ }
3747
+ }
3748
+ if (type === "name") {
3749
+ const statement = this.#keyword(start, value);
3750
+ if (statement) return statement;
3751
+ if (this.is(":", this.peek())) {
3752
+ const label = this.parseIdentifier();
3753
+ this.next();
3754
+ return this.finish("LabeledStatement", start, {
3755
+ label,
3756
+ body: this.#statement()
3757
+ });
3758
+ }
3759
+ }
3760
+ const expression = this.parseExpression();
3761
+ this.semicolon();
3762
+ return this.finish("ExpressionStatement", start, { expression });
3763
+ }
3764
+ #keyword(start, value) {
3765
+ const next = this.peek();
3766
+ const followedByName = this.isName(next) && !next.newline;
3767
+ switch (value) {
3768
+ case "var":
3769
+ case "const":
3770
+ if (value === "const" && this.is("enum", next))
3771
+ return this.#declaration(start, false);
3772
+ return this.#variables(start, false);
3773
+ case "let":
3774
+ if (this.isName(next) || this.is("[", next) || this.is("{", next))
3775
+ return this.#variables(start, false);
3776
+ return;
3777
+ case "using":
3778
+ if (followedByName) return this.#variables(start, false);
3779
+ return;
3780
+ case "await": {
3781
+ if (!this.is("using", next) || next.newline) return;
3782
+ const snapshot = this.snapshot();
3783
+ this.next();
3784
+ const after = this.peek();
3785
+ this.restore(snapshot);
3786
+ if (!this.isName(after) || after.newline) return;
3787
+ this.next();
3788
+ const declaration = this.#variables(start, false);
3789
+ declaration.kind = "await using";
3790
+ return declaration;
3791
+ }
3792
+ case "function":
3793
+ return this.parseFunction(start, false, false);
3794
+ case "async":
3795
+ if (this.is("function", next) && !next.newline) {
3796
+ this.next();
3797
+ return this.parseFunction(start, true, false);
3798
+ }
3799
+ return;
3800
+ case "class":
3801
+ return this.parseClass(start, [], false, false, false);
3802
+ case "if":
3803
+ return this.#if(start);
3804
+ case "for":
3805
+ return this.#for(start);
3806
+ case "while": {
3807
+ this.next();
3808
+ const test = this.#parenthesized();
3809
+ return this.finish("WhileStatement", start, {
3810
+ test,
3811
+ body: this.#statement()
3812
+ });
3813
+ }
3814
+ case "do": {
3815
+ this.next();
3816
+ const body = this.#statement();
3817
+ this.expect("while");
3818
+ const test = this.#parenthesized();
3819
+ this.eat(";");
3820
+ return this.finish("DoWhileStatement", start, { body, test });
3821
+ }
3822
+ case "return": {
3823
+ this.next();
3824
+ const argument = this.canInsertSemicolon() ? null : this.parseExpression();
3825
+ this.semicolon();
3826
+ return this.finish("ReturnStatement", start, { argument });
3827
+ }
3828
+ case "throw": {
3829
+ this.next();
3830
+ const argument = this.parseExpression();
3831
+ this.semicolon();
3832
+ return this.finish("ThrowStatement", start, { argument });
3833
+ }
3834
+ case "break":
3835
+ case "continue": {
3836
+ this.next();
3837
+ const label = !this.canInsertSemicolon() && this.isName() ? this.parseIdentifier() : null;
3838
+ this.semicolon();
3839
+ return this.finish(
3840
+ value === "break" ? "BreakStatement" : "ContinueStatement",
3841
+ start,
3842
+ { label }
3843
+ );
3844
+ }
3845
+ case "debugger":
3846
+ this.next();
3847
+ this.semicolon();
3848
+ return this.finish("DebuggerStatement", start, {});
3849
+ case "try":
3850
+ return this.#try(start);
3851
+ case "switch":
3852
+ return this.#switch(start);
3853
+ case "with": {
3854
+ this.next();
3855
+ const object = this.#parenthesized();
3856
+ return this.finish("WithStatement", start, {
3857
+ object,
3858
+ body: this.#statement()
3859
+ });
3860
+ }
3861
+ case "import":
3862
+ if (this.is("(", next) || this.is(".", next)) return;
3863
+ return this.#import(start);
3864
+ case "export":
3865
+ return this.#export(start, []);
3866
+ }
3867
+ if (this.options.typescript) return this.#declaration(start, false);
3868
+ return void 0;
3869
+ }
3870
+ /** TypeScript declarations, undefined when the word is used as a name. */
3871
+ #declaration(start, declare) {
3872
+ const next = this.peek();
3873
+ const sameLine = !next.newline;
3874
+ switch (this.token.value) {
3875
+ case "interface":
3876
+ if (!this.isName(next) || !sameLine) return;
3877
+ return this.#interface(start, declare);
3878
+ case "type":
3879
+ if (!this.isName(next) || !sameLine) return;
3880
+ return this.#typeAlias(start, declare);
3881
+ case "enum":
3882
+ if (!this.isName(next)) return;
3883
+ return this.#enum(start, false, declare);
3884
+ case "const":
3885
+ if (!this.is("enum", next))
3886
+ return this.#variables(start, declare);
3887
+ this.next();
3888
+ return this.#enum(start, true, declare);
3889
+ case "namespace":
3890
+ case "module":
3891
+ if (!sameLine || !(this.isName(next) || this.token.value === "module" && next.type === "string"))
3892
+ return;
3893
+ return this.#module(start, declare);
3894
+ case "global":
3895
+ if (!this.is("{", next)) return;
3896
+ return this.#module(start, declare);
3897
+ case "abstract":
3898
+ if (!this.is("class", next) || !sameLine) return;
3899
+ this.next();
3900
+ return this.parseClass(start, [], false, true, declare);
3901
+ case "declare": {
3902
+ if (!sameLine || !(this.isName(next) || this.is("@", next)))
3903
+ return;
3904
+ this.next();
3905
+ const declared = this.#declared(start);
3906
+ return declared;
3907
+ }
3908
+ }
3909
+ return void 0;
3910
+ }
3911
+ #declared(start) {
3912
+ switch (this.token.value) {
3913
+ case "var":
3914
+ case "let":
3915
+ case "using":
3916
+ return this.#variables(start, true);
3917
+ case "function": {
3918
+ const fn = this.parseFunction(start, false, false);
3919
+ return {
3920
+ ...fn,
3921
+ type: "TSDeclareFunction",
3922
+ declare: true,
3923
+ body: null
3924
+ };
3925
+ }
3926
+ case "async": {
3927
+ this.next();
3928
+ const fn = this.parseFunction(start, true, false);
3929
+ return {
3930
+ ...fn,
3931
+ type: "TSDeclareFunction",
3932
+ declare: true,
3933
+ body: null
3934
+ };
3935
+ }
3936
+ case "class":
3937
+ return this.parseClass(start, [], false, false, true);
3938
+ }
3939
+ const declaration = this.#declaration(start, true);
3940
+ if (!declaration) this.unexpected("Expected a declaration");
3941
+ return declaration;
3942
+ }
3943
+ #variables(start, declare) {
3944
+ const declaration = this.parseVariables(start, declare);
3945
+ this.semicolon();
3946
+ declaration.end = this.previous;
3947
+ return declaration;
3948
+ }
3949
+ parseVariables(start, declare) {
3950
+ const kind = this.next().value;
3951
+ const declarations = [];
3952
+ do {
3953
+ const declaratorStart = this.token.start;
3954
+ const id = this.parseBindingTarget();
3955
+ const definite = this.eat("!");
3956
+ if (this.is(":")) {
3957
+ id.typeAnnotation = this.parseTypeAnnotation();
3958
+ id.end = this.previous;
3959
+ }
3960
+ const init = this.eat("=") ? this.parseAssignment() : null;
3961
+ declarations.push(
3962
+ this.finish("VariableDeclarator", declaratorStart, {
3963
+ id,
3964
+ init,
3965
+ definite
3966
+ })
3967
+ );
3968
+ } while (this.eat(","));
3969
+ return this.finish("VariableDeclaration", start, {
3970
+ kind,
3971
+ declarations,
3972
+ declare
3973
+ });
3974
+ }
3975
+ #parenthesized() {
3976
+ this.expect("(");
3977
+ const expression = this.withIn(true, () => this.parseExpression());
3978
+ this.expect(")");
3979
+ return expression;
3980
+ }
3981
+ #if(start) {
3982
+ this.next();
3983
+ const test = this.#parenthesized();
3984
+ const consequent = this.#statement();
3985
+ const alternate = this.eat("else") ? this.#statement() : null;
3986
+ return this.finish("IfStatement", start, {
3987
+ test,
3988
+ consequent,
3989
+ alternate
3990
+ });
3991
+ }
3992
+ #for(start) {
3993
+ this.next();
3994
+ const awaits = this.eat("await");
3995
+ this.expect("(");
3996
+ let init = null;
3997
+ if (!this.is(";")) {
3998
+ const initStart = this.token.start;
3999
+ const declares = ["var", "const"].includes(this.token.value) || ["let", "using"].includes(this.token.value) && (this.isName(this.peek()) || this.is("[", this.peek()) || this.is("{", this.peek()));
4000
+ init = this.withIn(
4001
+ false,
4002
+ () => declares ? this.parseVariables(initStart, false) : this.parseExpression()
4003
+ );
4004
+ }
4005
+ if (init && (this.is("of") || this.is("in"))) {
4006
+ if (init.type !== "VariableDeclaration")
4007
+ init = this.toPattern(init);
4008
+ const of = this.next().value === "of";
4009
+ const right = this.withIn(
4010
+ true,
4011
+ () => of ? this.parseAssignment() : this.parseExpression()
4012
+ );
4013
+ this.expect(")");
4014
+ const body = this.#statement();
4015
+ return of ? this.finish("ForOfStatement", start, {
4016
+ left: init,
4017
+ right,
4018
+ body,
4019
+ await: awaits
4020
+ }) : this.finish("ForInStatement", start, {
4021
+ left: init,
4022
+ right,
4023
+ body
4024
+ });
4025
+ }
4026
+ this.expect(";");
4027
+ const test = this.is(";") ? null : this.withIn(true, () => this.parseExpression());
4028
+ this.expect(";");
4029
+ const update = this.is(")") ? null : this.withIn(true, () => this.parseExpression());
4030
+ this.expect(")");
4031
+ return this.finish("ForStatement", start, {
4032
+ init,
4033
+ test,
4034
+ update,
4035
+ body: this.#statement()
4036
+ });
4037
+ }
4038
+ #try(start) {
4039
+ this.next();
4040
+ const block = this.parseBlock();
4041
+ let handler = null;
4042
+ if (this.is("catch")) {
4043
+ const handlerStart = this.next().start;
4044
+ let param = null;
4045
+ if (this.eat("(")) {
4046
+ const target = this.parseBindingTarget();
4047
+ if (this.is(":")) {
4048
+ target.typeAnnotation = this.parseTypeAnnotation();
4049
+ target.end = this.previous;
4050
+ }
4051
+ param = target;
4052
+ this.expect(")");
4053
+ }
4054
+ handler = this.finish("CatchClause", handlerStart, {
4055
+ param,
4056
+ body: this.parseBlock()
4057
+ });
4058
+ }
4059
+ const finalizer = this.eat("finally") ? this.parseBlock() : null;
4060
+ return this.finish("TryStatement", start, {
4061
+ block,
4062
+ handler,
4063
+ finalizer
4064
+ });
4065
+ }
4066
+ #switch(start) {
4067
+ this.next();
4068
+ const discriminant = this.#parenthesized();
4069
+ this.expect("{");
4070
+ const cases = [];
4071
+ while (!this.is("}")) {
4072
+ const caseStart = this.token.start;
4073
+ let test = null;
4074
+ if (this.eat("case"))
4075
+ test = this.withIn(true, () => this.parseExpression());
4076
+ else this.expect("default");
4077
+ this.expect(":");
4078
+ const consequent = [];
4079
+ while (!this.is("case") && !this.is("default") && !this.is("}"))
4080
+ consequent.push(this.#statement());
4081
+ cases.push(
4082
+ this.finish("SwitchCase", caseStart, { test, consequent })
4083
+ );
4084
+ }
4085
+ this.expect("}");
4086
+ return this.finish("SwitchStatement", start, { discriminant, cases });
4087
+ }
4088
+ // Modules
4089
+ #import(start) {
4090
+ this.expect("import");
4091
+ let importKind = "value";
4092
+ const next = this.peek();
4093
+ if (this.is("type") && (this.is("{", next) || this.is("*", next) || this.isName(next) && !this.is("from", next) || this.is("from", next) && this.isName(this.#peekTwo())))
4094
+ importKind = this.next().value;
4095
+ let phase = null;
4096
+ if ((this.is("defer") || this.is("source")) && (this.isName(this.peek()) || this.is("*", this.peek())) && !this.is("from", this.peek()))
4097
+ phase = this.next().value;
4098
+ if (this.token.type === "string") {
4099
+ const source2 = this.parseString();
4100
+ const attributes2 = this.#attributes();
4101
+ this.semicolon();
4102
+ return this.finish("ImportDeclaration", start, {
4103
+ specifiers: [],
4104
+ source: source2,
4105
+ attributes: attributes2,
4106
+ importKind,
4107
+ phase
4108
+ });
4109
+ }
4110
+ const specifiers = [];
4111
+ if (this.isName() && !this.is("from")) {
4112
+ const local = this.parseIdentifier();
4113
+ if (this.is("="))
4114
+ return this.#importEquals(start, local, importKind, false);
4115
+ specifiers.push(
4116
+ this.finish("ImportDefaultSpecifier", local.start, { local })
4117
+ );
4118
+ this.eat(",");
4119
+ } else if (this.isName() && this.is("from") && this.is("=", this.peek())) {
4120
+ const local = this.parseIdentifier();
4121
+ return this.#importEquals(start, local, importKind, false);
4122
+ } else if (this.isName() && this.is("from") && this.isName(this.peek())) {
4123
+ const local = this.parseIdentifier();
4124
+ specifiers.push(
4125
+ this.finish("ImportDefaultSpecifier", local.start, { local })
4126
+ );
4127
+ }
4128
+ if (this.is("*")) {
4129
+ const namespaceStart = this.next().start;
4130
+ this.expect("as");
4131
+ const local = this.parseIdentifier();
4132
+ specifiers.push(
4133
+ this.finish("ImportNamespaceSpecifier", namespaceStart, {
4134
+ local
4135
+ })
4136
+ );
4137
+ } else if (this.is("{")) {
4138
+ this.next();
4139
+ while (!this.is("}")) {
4140
+ const specifierStart = this.token.start;
4141
+ let kind = "value";
4142
+ if (this.#typeModifier()) {
4143
+ this.next();
4144
+ kind = "type";
4145
+ }
4146
+ const imported = this.#moduleName();
4147
+ const local = this.eat("as") ? this.parseIdentifier() : imported;
4148
+ specifiers.push(
4149
+ this.finish("ImportSpecifier", specifierStart, {
4150
+ imported,
4151
+ local,
4152
+ importKind: kind
4153
+ })
4154
+ );
4155
+ if (!this.eat(",")) break;
4156
+ }
4157
+ this.expect("}");
4158
+ }
4159
+ this.expect("from");
4160
+ const source = this.parseString();
4161
+ const attributes = this.#attributes();
4162
+ this.semicolon();
4163
+ return this.finish("ImportDeclaration", start, {
4164
+ specifiers,
4165
+ source,
4166
+ attributes,
4167
+ importKind,
4168
+ phase
4169
+ });
4170
+ }
4171
+ /** A module export name: an identifier or a string. */
4172
+ #moduleName() {
4173
+ return this.token.type === "string" ? this.parseString() : this.parseIdentifier();
4174
+ }
4175
+ /** Whether `type` modifies the following specifier, as in `{ type A }`. */
4176
+ #typeModifier() {
4177
+ const next = this.peek();
4178
+ return this.is("type") && (this.isName(next) || next.type === "string") && !this.is("as", next);
4179
+ }
4180
+ #peekTwo() {
4181
+ const snapshot = this.snapshot();
4182
+ this.next();
4183
+ this.next();
4184
+ const token = this.token;
4185
+ this.restore(snapshot);
4186
+ return token;
4187
+ }
4188
+ #importEquals(start, id, importKind, isExport) {
4189
+ this.expect("=");
4190
+ let moduleReference;
4191
+ if (this.is("require") && this.is("(", this.peek())) {
4192
+ const referenceStart = this.next().start;
4193
+ this.expect("(");
4194
+ const expression = this.parseString();
4195
+ this.expect(")");
4196
+ moduleReference = this.finish(
4197
+ "TSExternalModuleReference",
4198
+ referenceStart,
4199
+ { expression }
4200
+ );
4201
+ } else moduleReference = this.parseEntityName();
4202
+ this.semicolon();
4203
+ return this.finish("TSImportEqualsDeclaration", start, {
4204
+ id,
4205
+ moduleReference,
4206
+ importKind: importKind === "type" ? "type" : "value",
4207
+ isExport
4208
+ });
4209
+ }
4210
+ #attributes() {
4211
+ if (this.token.newline || !(this.is("with") || this.is("assert")))
4212
+ return [];
4213
+ this.next();
4214
+ this.expect("{");
4215
+ const attributes = [];
4216
+ while (!this.is("}")) {
4217
+ const start = this.token.start;
4218
+ const key = this.#moduleName();
4219
+ this.expect(":");
4220
+ const value = this.parseString();
4221
+ attributes.push(
4222
+ this.finish("ImportAttribute", start, { key, value })
4223
+ );
4224
+ if (!this.eat(",")) break;
4225
+ }
4226
+ this.expect("}");
4227
+ return attributes;
4228
+ }
4229
+ #export(start, decorators) {
4230
+ this.expect("export");
4231
+ if (this.is("=")) {
4232
+ this.next();
4233
+ const expression = this.parseExpression();
4234
+ this.semicolon();
4235
+ return this.finish("TSExportAssignment", start, { expression });
4236
+ }
4237
+ if (this.is("as") && this.is("namespace", this.peek())) {
4238
+ this.next();
4239
+ this.next();
4240
+ const id = this.parseIdentifier();
4241
+ this.semicolon();
4242
+ return this.finish("TSNamespaceExportDeclaration", start, { id });
4243
+ }
4244
+ if (this.is("import") && this.isName(this.peek())) {
4245
+ this.next();
4246
+ let kind = "value";
4247
+ if (this.is("type") && this.isName(this.peek()) && !this.is("=", this.peek())) {
4248
+ this.next();
4249
+ kind = "type";
4250
+ }
4251
+ const id = this.parseIdentifier();
4252
+ return this.#importEquals(start, id, kind, true);
4253
+ }
4254
+ if (this.is("default")) {
4255
+ this.next();
4256
+ const declarationStart2 = this.token.start;
4257
+ let declaration2;
4258
+ if (this.is("function"))
4259
+ declaration2 = this.#defaultFunction(declarationStart2, false);
4260
+ else if (this.is("async") && this.is("function", this.peek()) && !this.peek().newline) {
4261
+ this.next();
4262
+ declaration2 = this.#defaultFunction(declarationStart2, true);
4263
+ } else if (this.is("class"))
4264
+ declaration2 = this.parseClass(
4265
+ declarationStart2,
4266
+ decorators,
4267
+ false,
4268
+ false,
4269
+ false
4270
+ );
4271
+ else if (this.is("@")) {
4272
+ const classDecorators = this.parseDecorators();
4273
+ declaration2 = this.parseClass(
4274
+ declarationStart2,
4275
+ classDecorators,
4276
+ false,
4277
+ false,
4278
+ false
4279
+ );
4280
+ } else if (this.is("abstract") && this.is("class", this.peek())) {
4281
+ this.next();
4282
+ declaration2 = this.parseClass(
4283
+ declarationStart2,
4284
+ decorators,
4285
+ false,
4286
+ true,
4287
+ false
4288
+ );
4289
+ } else if (this.is("interface") && this.isName(this.peek())) {
4290
+ declaration2 = this.#interface(declarationStart2, false);
4291
+ } else {
4292
+ declaration2 = this.parseAssignment();
4293
+ this.semicolon();
4294
+ }
4295
+ return this.finish("ExportDefaultDeclaration", start, {
4296
+ declaration: declaration2
4297
+ });
4298
+ }
4299
+ let exportKind = "value";
4300
+ if (this.is("type") && (this.is("{", this.peek()) || this.is("*", this.peek()))) {
4301
+ this.next();
4302
+ exportKind = "type";
4303
+ }
4304
+ if (this.is("*")) {
4305
+ this.next();
4306
+ const exported = this.eat("as") ? this.#moduleName() : null;
4307
+ this.expect("from");
4308
+ const source = this.parseString();
4309
+ const attributes = this.#attributes();
4310
+ this.semicolon();
4311
+ return this.finish("ExportAllDeclaration", start, {
4312
+ exported,
4313
+ source,
4314
+ attributes,
4315
+ exportKind
4316
+ });
4317
+ }
4318
+ if (this.is("{")) {
4319
+ this.next();
4320
+ const specifiers = [];
4321
+ while (!this.is("}")) {
4322
+ const specifierStart = this.token.start;
4323
+ let kind = "value";
4324
+ if (this.#typeModifier()) {
4325
+ this.next();
4326
+ kind = "type";
4327
+ }
4328
+ const local = this.#moduleName();
4329
+ const exported = this.eat("as") ? this.#moduleName() : local;
4330
+ specifiers.push(
4331
+ this.finish("ExportSpecifier", specifierStart, {
4332
+ local,
4333
+ exported,
4334
+ exportKind: kind
4335
+ })
4336
+ );
4337
+ if (!this.eat(",")) break;
4338
+ }
4339
+ this.expect("}");
4340
+ let source = null;
4341
+ let attributes = [];
4342
+ if (this.eat("from")) {
4343
+ source = this.parseString();
4344
+ attributes = this.#attributes();
4345
+ }
4346
+ this.semicolon();
4347
+ return this.finish("ExportNamedDeclaration", start, {
4348
+ declaration: null,
4349
+ specifiers,
4350
+ source,
4351
+ attributes,
4352
+ exportKind
4353
+ });
4354
+ }
4355
+ const declarationStart = this.token.start;
4356
+ let declaration;
4357
+ if (this.is("@")) {
4358
+ const classDecorators = this.parseDecorators();
4359
+ declaration = this.parseClass(
4360
+ declarationStart,
4361
+ classDecorators,
4362
+ false,
4363
+ this.eat("abstract"),
4364
+ false
4365
+ );
4366
+ } else if (this.is("class"))
4367
+ declaration = this.parseClass(
4368
+ declarationStart,
4369
+ decorators,
4370
+ false,
4371
+ false,
4372
+ false
4373
+ );
4374
+ else
4375
+ declaration = this.#keyword(declarationStart, this.token.value) ?? this.#declaration(declarationStart, false);
4376
+ if (!declaration) this.unexpected("Expected a declaration");
4377
+ if (declaration.type === "ClassDeclaration" && decorators.length > 0 && declaration.decorators.length === 0)
4378
+ declaration.decorators = decorators;
4379
+ return this.finish("ExportNamedDeclaration", start, {
4380
+ declaration,
4381
+ specifiers: [],
4382
+ source: null,
4383
+ attributes: [],
4384
+ exportKind: "value"
4385
+ });
4386
+ }
4387
+ #defaultFunction(start, async) {
4388
+ this.expect("function");
4389
+ const generator = this.eat("*");
4390
+ const id = this.isName() && !this.is("(") ? this.parseIdentifier() : null;
4391
+ const typeParameters = this.parseTypeParameters();
4392
+ const params = this.parseParameters();
4393
+ const returnType = this.eat(":") ? this.parseReturnType() : null;
4394
+ const parts = {
4395
+ id,
4396
+ params,
4397
+ async,
4398
+ generator,
4399
+ typeParameters,
4400
+ returnType
4401
+ };
4402
+ if (!this.is("{")) {
4403
+ this.semicolon();
4404
+ return this.finish("TSDeclareFunction", start, {
4405
+ ...parts,
4406
+ body: null,
4407
+ declare: false
4408
+ });
4409
+ }
4410
+ return this.finish("FunctionDeclaration", start, {
4411
+ ...parts,
4412
+ body: this.parseBlock(),
4413
+ declare: false
4414
+ });
4415
+ }
4416
+ // TypeScript declarations
4417
+ #interface(start, declare) {
4418
+ this.expect("interface");
4419
+ const id = this.parseIdentifier();
4420
+ const typeParameters = this.parseTypeParameters();
4421
+ const extended = [];
4422
+ if (this.eat("extends")) {
4423
+ do
4424
+ extended.push(this.parseType());
4425
+ while (this.eat(","));
4426
+ }
4427
+ const bodyStart = this.token.start;
4428
+ const members = this.parseTypeMembers();
4429
+ const body = this.finish("TSInterfaceBody", bodyStart, {
4430
+ body: members
4431
+ });
4432
+ return this.finish("TSInterfaceDeclaration", start, {
4433
+ id,
4434
+ typeParameters,
4435
+ extends: extended,
4436
+ body,
4437
+ declare
4438
+ });
4439
+ }
4440
+ #typeAlias(start, declare) {
4441
+ this.expect("type");
4442
+ const id = this.parseIdentifier();
4443
+ const typeParameters = this.parseTypeParameters();
4444
+ this.expect("=");
4445
+ const typeAnnotation = this.parseType();
4446
+ this.semicolon();
4447
+ return this.finish("TSTypeAliasDeclaration", start, {
4448
+ id,
4449
+ typeParameters,
4450
+ typeAnnotation,
4451
+ declare
4452
+ });
4453
+ }
4454
+ #enum(start, isConst, declare) {
4455
+ this.expect("enum");
4456
+ const id = this.parseIdentifier();
4457
+ this.expect("{");
4458
+ const members = [];
4459
+ while (!this.is("}")) {
4460
+ const memberStart = this.token.start;
4461
+ const { key } = this.parsePropertyKey();
4462
+ const initializer = this.eat("=") ? this.parseAssignment() : null;
4463
+ members.push(
4464
+ this.finish("TSEnumMember", memberStart, {
4465
+ id: key,
4466
+ initializer
4467
+ })
4468
+ );
4469
+ if (!this.eat(",")) break;
4470
+ }
4471
+ this.expect("}");
4472
+ return this.finish("TSEnumDeclaration", start, {
4473
+ id,
4474
+ members,
4475
+ const: isConst,
4476
+ declare
4477
+ });
4478
+ }
4479
+ #module(start, declare) {
4480
+ const keyword = this.next().value;
4481
+ const kind = keyword === "global" ? "global" : keyword === "module" ? "module" : "namespace";
4482
+ let id;
4483
+ if (kind === "global")
4484
+ id = this.finish("Identifier", start, { name: "global" });
4485
+ else if (this.token.type === "string") id = this.parseString();
4486
+ else id = this.parseEntityName();
4487
+ if (!this.is("{")) {
4488
+ this.semicolon();
4489
+ return this.finish("TSModuleDeclaration", start, {
4490
+ id,
4491
+ body: null,
4492
+ kind,
4493
+ declare
4494
+ });
4495
+ }
4496
+ const bodyStart = this.expect("{").start;
4497
+ const { body } = this.#list(false, () => this.is("}"));
4498
+ this.expect("}");
4499
+ const block = this.finish("TSModuleBlock", bodyStart, { body });
4500
+ return this.finish("TSModuleDeclaration", start, {
4501
+ id,
4502
+ body: block,
4503
+ kind,
4504
+ declare
4505
+ });
4506
+ }
4507
+ };
4508
+
4509
+ // shared/syntax/src/lines.ts
4510
+ var Lines = class {
4511
+ static {
4512
+ __name(this, "Lines");
4513
+ }
4514
+ #starts = [0];
4515
+ constructor(text) {
4516
+ for (const match of text.matchAll(/\r\n|\r|\n/g))
4517
+ this.#starts.push(match.index + match[0].length);
4518
+ }
4519
+ line(offset) {
4520
+ let low = 0;
4521
+ let high = this.#starts.length - 1;
4522
+ while (low < high) {
4523
+ const middle = Math.ceil((low + high) / 2);
4524
+ if (this.#starts[middle] <= offset) low = middle;
4525
+ else high = middle - 1;
4526
+ }
4527
+ return low + 1;
4528
+ }
4529
+ column(offset) {
4530
+ return offset - this.#starts[this.line(offset) - 1] + 1;
4531
+ }
4532
+ };
4533
+
4534
+ // shared/syntax/src/walker.ts
4535
+ var Walker = class _Walker {
4536
+ static {
4537
+ __name(this, "Walker");
4538
+ }
4539
+ static isNode(value) {
4540
+ return typeof value === "object" && value !== null && typeof value.type === "string" && typeof value.start === "number";
4541
+ }
4542
+ /** Child nodes by start, outer nodes before inner ones starting with them. */
4543
+ static children(node) {
4544
+ const children = [];
4545
+ for (const [key, value] of Object.entries(node)) {
4546
+ if (key === "comments") continue;
4547
+ if (node.type === "Property" && node.shorthand && key === "key")
4548
+ continue;
4549
+ if (Array.isArray(value)) {
4550
+ for (const item of value)
4551
+ if (_Walker.isNode(item)) children.push(item);
4552
+ } else if (_Walker.isNode(value)) children.push(value);
4553
+ }
4554
+ return children.sort((a, b) => a.start - b.start || b.end - a.end);
4555
+ }
4556
+ };
4557
+
4558
+ // shared/syntax/src/index.ts
4559
+ function language(file) {
4560
+ if (/\.jsonc?$/.test(file))
4561
+ return { json: true, typescript: false, jsx: false };
4562
+ if (!/\.[cm]?[jt]sx?$/.test(file)) return;
4563
+ return {
4564
+ json: false,
4565
+ typescript: /\.[cm]?tsx?$/.test(file),
4566
+ jsx: !/\.[cm]?ts$/.test(file)
4567
+ };
4568
+ }
4569
+ __name(language, "language");
4570
+ function isMarkdown(file) {
4571
+ return /\.(?:md|markdown)$/i.test(file);
4572
+ }
4573
+ __name(isMarkdown, "isMarkdown");
4574
+ function parseMarkdown(source, options = {}) {
4575
+ return new Blocks(source, options).parse(options.frontmatter);
4576
+ }
4577
+ __name(parseMarkdown, "parseMarkdown");
4578
+ function parse(source, options) {
4579
+ const parser = new Parser(source, options);
4580
+ const program = parser.parseProgram();
4581
+ return { program, comments: parser.comments };
4582
+ }
4583
+ __name(parse, "parse");
4584
+ function parseExpression(source) {
4585
+ const parser = new Parser(source, { typescript: false, jsx: false });
4586
+ const expression = parser.parseDocument();
4587
+ const statement = {
4588
+ type: "ExpressionStatement",
4589
+ start: expression.start,
4590
+ end: expression.end,
4591
+ expression
4592
+ };
4593
+ const program = {
4594
+ type: "Program",
4595
+ start: 0,
4596
+ end: source.length,
4597
+ body: [statement],
4598
+ directives: []
4599
+ };
4600
+ return { program, comments: parser.comments };
4601
+ }
4602
+ __name(parseExpression, "parseExpression");
4603
+ export {
4604
+ Lines,
4605
+ ParseError,
4606
+ Walker,
4607
+ isMarkdown,
4608
+ language,
4609
+ parse,
4610
+ parseExpression,
4611
+ parseMarkdown
4612
+ };