ripple 0.2.82 → 0.2.84

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.
@@ -7,963 +7,1052 @@ import { regex_newline_characters } from '../../../utils/patterns.js';
7
7
  const parser = acorn.Parser.extend(tsPlugin({ allowSatisfies: true }), RipplePlugin());
8
8
 
9
9
  function convert_from_jsx(node) {
10
- if (node.type === 'JSXIdentifier') {
11
- node.type = 'Identifier';
12
- } else if (node.type === 'JSXMemberExpression') {
13
- node.type = 'MemberExpression';
14
- node.object = convert_from_jsx(node.object);
15
- node.property = convert_from_jsx(node.property);
16
- }
17
- return node;
10
+ if (node.type === 'JSXIdentifier') {
11
+ node.type = 'Identifier';
12
+ } else if (node.type === 'JSXMemberExpression') {
13
+ node.type = 'MemberExpression';
14
+ node.object = convert_from_jsx(node.object);
15
+ node.property = convert_from_jsx(node.property);
16
+ }
17
+ return node;
18
18
  }
19
19
 
20
20
  function RipplePlugin(config) {
21
- return (Parser) => {
22
- const original = acorn.Parser.prototype;
23
- const tt = Parser.tokTypes || acorn.tokTypes;
24
- const tc = Parser.tokContexts || acorn.tokContexts;
25
-
26
- class RippleParser extends Parser {
27
- #path = [];
28
-
29
- // Helper method to get the element name from a JSX identifier or member expression
30
- getElementName(node) {
31
- if (!node) return null;
32
- if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
33
- return node.name;
34
- } else if (node.type === 'MemberExpression' || node.type === 'JSXMemberExpression') {
35
- // For components like <Foo.Bar>, return "Foo.Bar"
36
- return this.getElementName(node.object) + '.' + this.getElementName(node.property);
37
- }
38
- return null;
39
- }
40
-
41
- getTokenFromCode(code) {
42
- if (code === 60) {
43
- // < character
44
- if (this.#path.findLast((n) => n.type === 'Component')) {
45
- // Check if everything before this position on the current line is whitespace
46
- let lineStart = this.pos - 1;
47
- while (
48
- lineStart >= 0 &&
49
- this.input.charCodeAt(lineStart) !== 10 &&
50
- this.input.charCodeAt(lineStart) !== 13
51
- ) {
52
- lineStart--;
53
- }
54
- lineStart++; // Move past the newline character
55
-
56
- // Check if all characters from line start to current position are whitespace
57
- let allWhitespace = true;
58
- for (let i = lineStart; i < this.pos; i++) {
59
- const ch = this.input.charCodeAt(i);
60
- if (ch !== 32 && ch !== 9) {
61
- allWhitespace = false;
62
- break;
63
- }
64
- }
65
-
66
- // Check if the character after < is not whitespace
67
- if (allWhitespace && this.pos + 1 < this.input.length) {
68
- const nextChar = this.input.charCodeAt(this.pos + 1);
69
- if (nextChar !== 32 && nextChar !== 9 && nextChar !== 10 && nextChar !== 13) {
70
- const tokTypes = this.acornTypeScript.tokTypes;
71
- ++this.pos;
72
- return this.finishToken(tokTypes.jsxTagStart);
73
- }
74
- }
75
- }
76
- }
77
-
78
- if (code === 64) {
79
- // @ character
80
- // Look ahead to see if this is followed by a valid identifier character
81
- if (this.pos + 1 < this.input.length) {
82
- const nextChar = this.input.charCodeAt(this.pos + 1);
83
- // Check if the next character can start an identifier
84
- if (
85
- (nextChar >= 65 && nextChar <= 90) || // A-Z
86
- (nextChar >= 97 && nextChar <= 122) || // a-z
87
- nextChar === 95 ||
88
- nextChar === 36
89
- ) {
90
- // _ or $
91
-
92
- // Check if we're in an expression context
93
- // In JSX expressions, inside parentheses, assignments, etc.
94
- // we want to treat @ as an identifier prefix rather than decorator
95
- const currentType = this.type;
96
- const inExpression =
97
- this.exprAllowed ||
98
- currentType === tt.braceL || // Inside { }
99
- currentType === tt.parenL || // Inside ( )
100
- currentType === tt.eq || // After =
101
- currentType === tt.comma || // After ,
102
- currentType === tt.colon || // After :
103
- currentType === tt.question || // After ?
104
- currentType === tt.logicalOR || // After ||
105
- currentType === tt.logicalAND || // After &&
106
- currentType === tt.dot || // After . (for member expressions like obj.@prop)
107
- currentType === tt.questionDot; // After ?. (for optional chaining like obj?.@prop)
108
-
109
- if (inExpression) {
110
- return this.readAtIdentifier();
111
- }
112
- }
113
- }
114
- }
115
- return super.getTokenFromCode(code);
116
- }
117
-
118
- // Read an @ prefixed identifier
119
- readAtIdentifier() {
120
- const start = this.pos;
121
- this.pos++; // skip '@'
122
-
123
- // Read the identifier part manually
124
- let word = '';
125
- while (this.pos < this.input.length) {
126
- const ch = this.input.charCodeAt(this.pos);
127
- if (
128
- (ch >= 65 && ch <= 90) || // A-Z
129
- (ch >= 97 && ch <= 122) || // a-z
130
- (ch >= 48 && ch <= 57) || // 0-9
131
- ch === 95 ||
132
- ch === 36
133
- ) {
134
- // _ or $
135
- word += this.input[this.pos++];
136
- } else {
137
- break;
138
- }
139
- }
140
-
141
- if (word === '') {
142
- this.raise(start, 'Invalid @ identifier');
143
- }
144
-
145
- // Return the full identifier including @
146
- return this.finishToken(tt.name, '@' + word);
147
- }
148
-
149
- // Override parseIdent to mark @ identifiers as tracked
150
- parseIdent(liberal) {
151
- const node = super.parseIdent(liberal);
152
- if (node.name && node.name.startsWith('@')) {
153
- node.name = node.name.slice(1); // Remove the '@' for internal use
154
- node.tracked = true;
155
- node.start++;
156
- const prev_pos = this.pos;
157
- this.pos = node.start;
158
- node.loc.start = this.curPosition();
159
- this.pos = prev_pos;
160
- }
161
- return node;
162
- }
163
-
164
- parseExportDefaultDeclaration() {
165
- // Check if this is "export default component"
166
- if (this.value === 'component') {
167
- const node = this.startNode();
168
- node.type = 'Component';
169
- node.css = null;
170
- node.default = true;
171
- this.next();
172
- this.enterScope(0);
173
-
174
- node.id = this.type.label === 'name' ? this.parseIdent() : null;
175
-
176
- this.parseFunctionParams(node);
177
- this.eat(tt.braceL);
178
- node.body = [];
179
- this.#path.push(node);
180
-
181
- this.parseTemplateBody(node.body);
182
- this.#path.pop();
183
- this.exitScope();
184
-
185
- this.next();
186
- this.finishNode(node, 'Component');
187
- this.awaitPos = 0;
188
-
189
- return node;
190
- }
191
-
192
- return super.parseExportDefaultDeclaration();
193
- }
194
-
195
- parseForStatement(node) {
196
- this.next()
197
- let awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1
198
- this.labels.push({kind: "loop"})
199
- this.enterScope(0)
200
- this.expect(tt.parenL)
201
-
202
- if (this.type === tt.semi) {
203
- if (awaitAt > -1) this.unexpected(awaitAt)
204
- return this.parseFor(node, null)
205
- }
206
-
207
- let isLet = this.isLet()
208
- if (this.type === tt._var || this.type === tt._const || isLet) {
209
- let init = this.startNode(), kind = isLet ? "let" : this.value
210
- this.next()
211
- this.parseVar(init, true, kind)
212
- this.finishNode(init, "VariableDeclaration")
213
- return this.parseForAfterInitWithIndex(node, init, awaitAt)
214
- }
215
-
216
- // Handle other cases like using declarations if they exist
217
- let startsWithLet = this.isContextual("let"), isForOf = false
218
- let usingKind = (this.isUsing && this.isUsing(true)) ? "using" : (this.isAwaitUsing && this.isAwaitUsing(true)) ? "await using" : null
219
- if (usingKind) {
220
- let init = this.startNode()
221
- this.next()
222
- if (usingKind === "await using") {
223
- if (!this.canAwait) {
224
- this.raise(this.start, "Await using cannot appear outside of async function")
225
- }
226
- this.next()
227
- }
228
- this.parseVar(init, true, usingKind)
229
- this.finishNode(init, "VariableDeclaration")
230
- return this.parseForAfterInitWithIndex(node, init, awaitAt)
231
- }
232
-
233
- let containsEsc = this.containsEsc
234
- let refDestructuringErrors = {}
235
- let initPos = this.start
236
- let init = awaitAt > -1
237
- ? this.parseExprSubscripts(refDestructuringErrors, "await")
238
- : this.parseExpression(true, refDestructuringErrors)
239
-
240
- if (this.type === tt._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
241
- if (awaitAt > -1) { // implies `ecmaVersion >= 9`
242
- if (this.type === tt._in) this.unexpected(awaitAt)
243
- node.await = true
244
- } else if (isForOf && this.options.ecmaVersion >= 8) {
245
- if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") this.unexpected()
246
- else if (this.options.ecmaVersion >= 9) node.await = false
247
- }
248
- if (startsWithLet && isForOf) this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.")
249
- this.toAssignable(init, false, refDestructuringErrors)
250
- this.checkLValPattern(init)
251
- return this.parseForInWithIndex(node, init)
252
- } else {
253
- this.checkExpressionErrors(refDestructuringErrors, true)
254
- }
255
-
256
- if (awaitAt > -1) this.unexpected(awaitAt)
257
- return this.parseFor(node, init)
258
- }
259
-
260
- parseForAfterInitWithIndex(node, init, awaitAt) {
261
- if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1) {
262
- if (this.options.ecmaVersion >= 9) {
263
- if (this.type === tt._in) {
264
- if (awaitAt > -1) this.unexpected(awaitAt)
265
- } else node.await = awaitAt > -1
266
- }
267
- return this.parseForInWithIndex(node, init)
268
- }
269
- if (awaitAt > -1) this.unexpected(awaitAt)
270
- return this.parseFor(node, init)
271
- }
272
-
273
- parseForInWithIndex(node, init) {
274
- const isForIn = this.type === tt._in
275
- this.next()
276
-
277
- if (
278
- init.type === "VariableDeclaration" &&
279
- init.declarations[0].init != null &&
280
- (
281
- !isForIn ||
282
- this.options.ecmaVersion < 8 ||
283
- this.strict ||
284
- init.kind !== "var" ||
285
- init.declarations[0].id.type !== "Identifier"
286
- )
287
- ) {
288
- this.raise(
289
- init.start,
290
- `${isForIn ? "for-in" : "for-of"} loop variable declaration may not have an initializer`
291
- )
292
- }
293
-
294
- node.left = init
295
- node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign()
296
-
297
- // Check for our extended syntax: "; index varName"
298
- if (!isForIn && this.type === tt.semi) {
299
- this.next() // consume ';'
300
-
301
- if (this.isContextual('index')) {
302
- this.next() // consume 'index'
303
-
304
- if (this.type === tt.name) {
305
- node.index = this.parseIdent()
306
- } else {
307
- this.raise(this.start, 'Expected identifier after "index" keyword')
308
- }
309
- } else {
310
- this.raise(this.start, 'Expected "index" keyword after semicolon in for-of loop')
311
- }
312
- } else if (!isForIn) {
313
- // Set index to null for standard for-of loops
314
- node.index = null
315
- }
316
-
317
- this.expect(tt.parenR)
318
- node.body = this.parseStatement("for")
319
- this.exitScope()
320
- this.labels.pop()
321
- return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
322
- }
323
-
324
- shouldParseExportStatement() {
325
- if (super.shouldParseExportStatement()) {
326
- return true;
327
- }
328
- if (this.value === 'component') {
329
- return true;
330
- }
331
- return this.type.keyword === 'var';
332
- }
333
-
334
- jsx_parseExpressionContainer() {
335
- let node = this.startNode();
336
- this.next();
337
-
338
- node.expression =
339
- this.type === tt.braceR ? this.jsx_parseEmptyExpression() : this.parseExpression();
340
- this.expect(tt.braceR);
341
- return this.finishNode(node, 'JSXExpressionContainer');
342
- }
343
-
344
- jsx_parseTupleContainer() {
345
- var t = this.startNode();
346
- return (
347
- this.next(),
348
- (t.expression =
349
- this.type === tt.bracketR ? this.jsx_parseEmptyExpression() : this.parseExpression()),
350
- this.expect(tt.bracketR),
351
- this.finishNode(t, 'JSXExpressionContainer')
352
- );
353
- }
354
-
355
- jsx_parseAttribute() {
356
- let node = this.startNode();
357
-
358
- if (this.eat(tt.braceL)) {
359
- if (this.value === 'ref') {
360
- this.next();
361
- if (this.type === tt.braceR) {
362
- this.raise(
363
- this.start,
364
- '"ref" is a Ripple keyword and must be used in the form {ref fn}',
365
- );
366
- }
367
- node.argument = this.parseMaybeAssign();
368
- this.expect(tt.braceR);
369
- return this.finishNode(node, 'RefAttribute');
370
- } else if (this.type === tt.ellipsis) {
371
- this.expect(tt.ellipsis);
372
- node.argument = this.parseMaybeAssign();
373
- this.expect(tt.braceR);
374
- return this.finishNode(node, 'SpreadAttribute');
375
- } else if (this.lookahead().type === tt.ellipsis) {
376
- this.expect(tt.ellipsis);
377
- node.argument = this.parseMaybeAssign();
378
- this.expect(tt.braceR);
379
- return this.finishNode(node, 'SpreadAttribute');
380
- } else {
381
- const id = this.parseIdentNode();
382
- id.tracked = false;
383
- if (id.name.startsWith('@')) {
384
- id.tracked = true;
385
- id.name = id.name.slice(1);
386
- }
387
- this.finishNode(id, 'Identifier');
388
- node.name = id;
389
- node.value = id;
390
- this.next();
391
- this.expect(tt.braceR);
392
- return this.finishNode(node, 'Attribute');
393
- }
394
- }
395
- node.name = this.jsx_parseNamespacedName();
396
- node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
397
- return this.finishNode(node, 'JSXAttribute');
398
- }
399
-
400
- jsx_parseNamespacedName() {
401
- const base = this.jsx_parseIdentifier();
402
- if (!this.eat(tt.colon)) return base;
403
- const node = this.startNodeAt(base.start, base.loc.start);
404
- node.namespace = base;
405
- node.name = this.jsx_parseIdentifier();
406
- return this.finishNode(node, 'JSXNamespacedName');
407
- }
408
-
409
- jsx_parseIdentifier() {
410
- const node = this.startNode();
411
-
412
- if (this.type.label === '@') {
413
- this.next(); // consume @
414
-
415
- if (this.type === tt.name || this.type.label === 'jsxName') {
416
- node.name = this.value;
417
- node.tracked = true;
418
- this.next();
419
- } else {
420
- // Unexpected token after @
421
- this.unexpected();
422
- }
423
- } else if (
424
- (this.type === tt.name || this.type.label === 'jsxName') &&
425
- this.value &&
426
- this.value.startsWith('@')
427
- ) {
428
- node.name = this.value.substring(1);
429
- node.tracked = true;
430
- this.next();
431
- } else if (this.type === tt.name || this.type.keyword || this.type.label === 'jsxName') {
432
- node.name = this.value;
433
- node.tracked = false; // Explicitly mark as not tracked
434
- this.next();
435
- } else {
436
- return super.jsx_parseIdentifier();
437
- }
438
-
439
- return this.finishNode(node, 'JSXIdentifier');
440
- }
441
-
442
- // Override jsx_parseElementName to support @ syntax in member expressions
443
- jsx_parseElementName() {
444
- let node = this.jsx_parseIdentifier();
445
- if (this.eat(tt.dot)) {
446
- let memberExpr = this.startNodeAt(node.start, node.loc && node.loc.start);
447
- memberExpr.object = node;
448
- memberExpr.property = this.jsx_parseIdentifier();
449
- memberExpr.computed = false;
450
- while (this.eat(tt.dot)) {
451
- let newMemberExpr = this.startNodeAt(
452
- memberExpr.start,
453
- memberExpr.loc && memberExpr.loc.start,
454
- );
455
- newMemberExpr.object = memberExpr;
456
- newMemberExpr.property = this.jsx_parseIdentifier();
457
- newMemberExpr.computed = false;
458
- memberExpr = this.finishNode(newMemberExpr, 'JSXMemberExpression');
459
- }
460
- return this.finishNode(memberExpr, 'JSXMemberExpression');
461
- }
462
- return node;
463
- }
464
-
465
- jsx_parseAttributeValue() {
466
- const tok = this.acornTypeScript.tokTypes;
467
-
468
- switch (this.type) {
469
- case tt.braceL:
470
- var t = this.jsx_parseExpressionContainer();
471
- return (
472
- 'JSXEmptyExpression' === t.expression.type &&
473
- this.raise(t.start, 'attributes must only be assigned a non-empty expression'),
474
- t
475
- );
476
- case tok.jsxTagStart:
477
- case tt.string:
478
- return this.parseExprAtom();
479
- default:
480
- this.raise(this.start, 'value should be either an expression or a quoted text');
481
- }
482
- }
483
-
484
- parseTryStatement(node) {
485
- this.next();
486
- node.block = this.parseBlock();
487
- node.handler = null;
488
-
489
- if (this.value === 'pending') {
490
- this.next();
491
- node.pending = this.parseBlock();
492
- } else {
493
- node.pending = null;
494
- }
495
-
496
- if (this.type === tt._catch) {
497
- var clause = this.startNode();
498
- this.next();
499
- if (this.eat(tt.parenL)) {
500
- clause.param = this.parseCatchClauseParam();
501
- } else {
502
- if (this.options.ecmaVersion < 10) {
503
- this.unexpected();
504
- }
505
- clause.param = null;
506
- this.enterScope(0);
507
- }
508
- clause.body = this.parseBlock(false);
509
- this.exitScope();
510
- node.handler = this.finishNode(clause, 'CatchClause');
511
- }
512
- node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
513
-
514
- if (!node.handler && !node.finalizer && !node.pending) {
515
- this.raise(node.start, 'Missing catch or finally clause');
516
- }
517
- return this.finishNode(node, 'TryStatement');
518
- }
519
-
520
- jsx_readToken() {
521
- let out = '',
522
- chunkStart = this.pos;
523
- const tok = this.acornTypeScript.tokTypes;
524
-
525
- for (;;) {
526
- if (this.pos >= this.input.length) this.raise(this.start, 'Unterminated JSX contents');
527
- let ch = this.input.charCodeAt(this.pos);
528
-
529
- switch (ch) {
530
- case 60: // '<'
531
- case 123: // '{'
532
- if (ch === 60 && this.exprAllowed) {
533
- ++this.pos;
534
- return this.finishToken(tok.jsxTagStart);
535
- }
536
- if (ch === 123 && this.exprAllowed) {
537
- return this.getTokenFromCode(ch);
538
- }
539
- throw new Error('TODO: Invalid syntax');
540
-
541
- case 47: // '/'
542
- // Check if this is a comment (// or /*)
543
- if (this.input.charCodeAt(this.pos + 1) === 47) {
544
- // '//'
545
- // Line comment - handle it properly
546
- const commentStart = this.pos;
547
- const startLoc = this.curPosition();
548
- this.pos += 2;
549
-
550
- let commentText = '';
551
- while (this.pos < this.input.length) {
552
- const nextCh = this.input.charCodeAt(this.pos);
553
- if (acorn.isNewLine(nextCh)) break;
554
- commentText += this.input[this.pos];
555
- this.pos++;
556
- }
557
-
558
- const commentEnd = this.pos;
559
- const endLoc = this.curPosition();
560
-
561
- // Call onComment if it exists
562
- if (this.options.onComment) {
563
- this.options.onComment(
564
- false,
565
- commentText,
566
- commentStart,
567
- commentEnd,
568
- startLoc,
569
- endLoc,
570
- );
571
- }
572
-
573
- // Continue processing from current position
574
- break;
575
- } else if (this.input.charCodeAt(this.pos + 1) === 42) {
576
- // '/*'
577
- // Block comment - handle it properly
578
- const commentStart = this.pos;
579
- const startLoc = this.curPosition();
580
- this.pos += 2;
581
-
582
- let commentText = '';
583
- while (this.pos < this.input.length - 1) {
584
- if (
585
- this.input.charCodeAt(this.pos) === 42 &&
586
- this.input.charCodeAt(this.pos + 1) === 47
587
- ) {
588
- this.pos += 2;
589
- break;
590
- }
591
- commentText += this.input[this.pos];
592
- this.pos++;
593
- }
594
-
595
- const commentEnd = this.pos;
596
- const endLoc = this.curPosition();
597
-
598
- // Call onComment if it exists
599
- if (this.options.onComment) {
600
- this.options.onComment(
601
- true,
602
- commentText,
603
- commentStart,
604
- commentEnd,
605
- startLoc,
606
- endLoc,
607
- );
608
- }
609
-
610
- // Continue processing from current position
611
- break;
612
- }
613
- // If not a comment, fall through to default case
614
- this.context.push(tc.b_stat);
615
- this.exprAllowed = true;
616
- return original.readToken.call(this, ch);
617
-
618
- case 38: // '&'
619
- out += this.input.slice(chunkStart, this.pos);
620
- out += this.jsx_readEntity();
621
- chunkStart = this.pos;
622
- break;
623
-
624
- case 62: // '>'
625
- case 125: {
626
- // '}'
627
- if (
628
- ch === 125 &&
629
- (this.#path.length === 0 ||
630
- this.#path.at(-1)?.type === 'Component' ||
631
- this.#path.at(-1)?.type === 'Element')
632
- ) {
633
- return original.readToken.call(this, ch);
634
- }
635
- this.raise(
636
- this.pos,
637
- 'Unexpected token `' +
638
- this.input[this.pos] +
639
- '`. Did you mean `' +
640
- (ch === 62 ? '&gt;' : '&rbrace;') +
641
- '` or ' +
642
- '`{"' +
643
- this.input[this.pos] +
644
- '"}' +
645
- '`?',
646
- );
647
- }
648
-
649
- default:
650
- if (acorn.isNewLine(ch)) {
651
- out += this.input.slice(chunkStart, this.pos);
652
- out += this.jsx_readNewLine(true);
653
- chunkStart = this.pos;
654
- } else if (ch === 32 || ch === 9) {
655
- ++this.pos;
656
- } else {
657
- this.context.push(tc.b_stat);
658
- this.exprAllowed = true;
659
- return original.readToken.call(this, ch);
660
- }
661
- }
662
- }
663
- }
664
-
665
- parseElement() {
666
- const tok = this.acornTypeScript.tokTypes;
667
- // Adjust the start so we capture the `<` as part of the element
668
- const prev_pos = this.pos;
669
- this.pos = this.start - 1;
670
- const position = this.curPosition();
671
- this.pos = prev_pos;
672
-
673
- const element = this.startNode();
674
- element.start = position.index;
675
- element.loc.start = position;
676
- element.type = 'Element';
677
- this.#path.push(element);
678
- element.children = [];
679
- const open = this.jsx_parseOpeningElementAt();
680
- for (const attr of open.attributes) {
681
- if (attr.type === 'JSXAttribute') {
682
- attr.type = 'Attribute';
683
- if (attr.name.type === 'JSXIdentifier') {
684
- attr.name.type = 'Identifier';
685
- }
686
- if (attr.value !== null) {
687
- if (attr.value.type === 'JSXExpressionContainer') {
688
- attr.value = attr.value.expression;
689
- }
690
- }
691
- }
692
- }
693
- if (open.name.type === 'JSXIdentifier') {
694
- open.name.type = 'Identifier';
695
- }
696
-
697
- element.id = convert_from_jsx(open.name);
698
- element.attributes = open.attributes;
699
- element.selfClosing = open.selfClosing;
700
- element.metadata = {};
701
-
702
- if (element.selfClosing) {
703
- this.#path.pop();
704
-
705
- if (this.type.label === '</>/<=/>=') {
706
- this.pos--;
707
- this.next();
708
- }
709
- } else {
710
- if (open.name.name === 'style') {
711
- // jsx_parseOpeningElementAt treats ID selectors (ie. #myid) or type selectors (ie. div) as identifier and read it
712
- // So backtrack to the end of the <style> tag to make sure everything is included
713
- const start = open.end;
714
- const input = this.input.slice(start);
715
- const end = input.indexOf('</style>');
716
- const content = input.slice(0, end);
717
-
718
- const component = this.#path.findLast((n) => n.type === 'Component');
719
- if (component.css !== null) {
720
- throw new Error('Components can only have one style tag');
721
- }
722
- component.css = parse_style(content);
723
-
724
- const newLines = content.match(regex_newline_characters)?.length;
725
- if (newLines) {
726
- this.curLine = open.loc.end.line + newLines;
727
- this.lineStart = start + content.lastIndexOf('\n') + 1;
728
- }
729
- this.pos = start + content.length + 1;
730
-
731
- this.type = tok.jsxTagStart;
732
- this.next();
733
- if (this.value === '/') {
734
- this.next();
735
- this.jsx_parseElementName();
736
- this.exprAllowed = true;
737
- this.#path.pop();
738
- this.next();
739
- }
740
- // This node is used for Prettier, we don't actually need
741
- // the node for Ripple's transform process
742
- element.children = [component.css];
743
- // Ensure we escape JSX <tag></tag> context
744
- const tokContexts = this.acornTypeScript.tokContexts;
745
- const curContext = this.curContext();
746
-
747
- if (curContext === tokContexts.tc_expr) {
748
- this.context.pop();
749
- }
750
-
751
- this.finishNode(element, 'Element');
752
- return element;
753
- } else {
754
- this.enterScope(0);
755
- this.parseTemplateBody(element.children);
756
- this.exitScope();
757
-
758
- // Check if this element was properly closed
759
- // If we reach here and this element is still in the path, it means it was never closed
760
- if (this.#path[this.#path.length - 1] === element) {
761
- const tagName = this.getElementName(element.id);
762
- this.raise(
763
- this.start,
764
- `Unclosed tag '<${tagName}>'. Expected '</${tagName}>' before end of component.`,
765
- );
766
- }
767
- }
768
- // Ensure we escape JSX <tag></tag> context
769
- const tokContexts = this.acornTypeScript.tokContexts;
770
- const curContext = this.curContext();
771
-
772
- if (curContext === tokContexts.tc_expr) {
773
- this.context.pop();
774
- }
775
- }
776
-
777
- this.finishNode(element, 'Element');
778
- return element;
779
- }
780
-
781
- parseTemplateBody(body) {
782
- var inside_func =
783
- this.context.some((n) => n.token === 'function') || this.scopeStack.length > 1;
784
-
785
- if (!inside_func) {
786
- if (this.type.label === 'return') {
787
- throw new Error('`return` statements are not allowed in components');
788
- }
789
- if (this.type.label === 'continue') {
790
- throw new Error('`continue` statements are not allowed in components');
791
- }
792
- if (this.type.label === 'break') {
793
- throw new Error('`break` statements are not allowed in components');
794
- }
795
- }
796
-
797
- if (this.type.label === '{') {
798
- const node = this.jsx_parseExpressionContainer();
799
- node.type = 'Text';
800
- body.push(node);
801
- } else if (this.type.label === '}') {
802
- return;
803
- } else if (this.type.label === 'jsxTagStart') {
804
- this.next();
805
- if (this.value === '/') {
806
- this.next();
807
- const closingTag = this.jsx_parseElementName();
808
- this.exprAllowed = true;
809
-
810
- // Validate that the closing tag matches the opening tag
811
- const currentElement = this.#path[this.#path.length - 1];
812
- if (!currentElement || currentElement.type !== 'Element') {
813
- this.raise(this.start, 'Unexpected closing tag');
814
- }
815
-
816
- const openingTagName = this.getElementName(currentElement.id);
817
- const closingTagName = this.getElementName(closingTag);
818
-
819
- if (openingTagName !== closingTagName) {
820
- this.raise(
821
- this.start,
822
- `Expected closing tag to match opening tag. Expected '</${openingTagName}>' but found '</${closingTagName}>'`,
823
- );
824
- }
825
-
826
- this.#path.pop();
827
- this.next();
828
- return;
829
- }
830
- const node = this.parseElement();
831
- if (node !== null) {
832
- body.push(node);
833
- }
834
- } else {
835
- const node = this.parseStatement(null);
836
- body.push(node);
837
- }
838
- this.parseTemplateBody(body);
839
- }
840
-
841
- parseStatement(context, topLevel, exports) {
842
- const tok = this.acornTypeScript.tokContexts;
843
-
844
- if (
845
- context !== 'for' &&
846
- context !== 'if' &&
847
- this.context.at(-1) === tc.b_stat &&
848
- this.type === tt.braceL &&
849
- this.context.some((c) => c === tok.tc_expr)
850
- ) {
851
- this.next();
852
- const node = this.jsx_parseExpressionContainer();
853
- node.type = 'Text';
854
- this.next();
855
- this.context.pop();
856
- this.context.pop();
857
- return node;
858
- }
859
-
860
- if (this.value === 'component') {
861
- const node = this.startNode();
862
- node.type = 'Component';
863
- node.css = null;
864
- this.next();
865
- this.enterScope(0);
866
- node.id = this.parseIdent();
867
- this.parseFunctionParams(node);
868
- this.eat(tt.braceL);
869
- node.body = [];
870
- this.#path.push(node);
871
-
872
- this.parseTemplateBody(node.body);
873
-
874
- this.#path.pop();
875
- this.exitScope();
876
-
877
- this.next();
878
- this.finishNode(node, 'Component');
879
- this.awaitPos = 0;
880
-
881
- return node;
882
- }
883
-
884
-
885
-
886
- if (this.type.label === '@') {
887
- // Try to parse as an expression statement first using tryParse
888
- // This allows us to handle Ripple @ syntax like @count++ without
889
- // interfering with legitimate decorator syntax
890
- this.skip_decorator = true;
891
- const expressionResult = this.tryParse(() => {
892
- const node = this.startNode();
893
- this.next();
894
- // Force expression context to ensure @ is tokenized correctly
895
- const old_expr_allowed = this.exprAllowed;
896
- this.exprAllowed = true;
897
- node.expression = this.parseExpression();
898
-
899
- if (node.expression.type === 'UpdateExpression') {
900
- let object = node.expression.argument;
901
- while (object.type === 'MemberExpression') {
902
- object = object.object;
903
- }
904
- if (object.type === 'Identifier') {
905
- object.tracked = true;
906
- }
907
- } else if (node.expression.type === 'AssignmentExpression') {
908
- let object = node.expression.left;
909
- while (object.type === 'MemberExpression') {
910
- object = object.object;
911
- }
912
- if (object.type === 'Identifier') {
913
- object.tracked = true;
914
- }
915
- } else if (node.expression.type === 'Identifier') {
916
- node.expression.tracked = true;
917
- } else {
918
- // TODO?
919
- }
920
-
921
- this.exprAllowed = old_expr_allowed;
922
- return this.finishNode(node, 'ExpressionStatement');
923
- });
924
- this.skip_decorator = false;
925
-
926
- // If parsing as expression statement succeeded, use that result
927
- if (expressionResult.node) {
928
- return expressionResult.node;
929
- }
930
- }
931
-
932
- return super.parseStatement(context, topLevel, exports);
933
- }
934
-
935
- parseBlock(createNewLexicalScope, node, exitStrict) {
936
- const parent = this.#path.at(-1);
937
-
938
- if (parent?.type === 'Component' || parent?.type === 'Element') {
939
- if (createNewLexicalScope === void 0) createNewLexicalScope = true;
940
- if (node === void 0) node = this.startNode();
941
-
942
- node.body = [];
943
- this.expect(tt.braceL);
944
- if (createNewLexicalScope) {
945
- this.enterScope(0);
946
- }
947
- this.parseTemplateBody(node.body);
948
-
949
- if (exitStrict) {
950
- this.strict = false;
951
- }
952
- this.exprAllowed = true;
953
-
954
- this.next();
955
- if (createNewLexicalScope) {
956
- this.exitScope();
957
- }
958
- return this.finishNode(node, 'BlockStatement');
959
- }
960
-
961
- return super.parseBlock(createNewLexicalScope, node, exitStrict);
962
- }
963
- }
964
-
965
- return RippleParser;
966
- };
21
+ return (Parser) => {
22
+ const original = acorn.Parser.prototype;
23
+ const tt = Parser.tokTypes || acorn.tokTypes;
24
+ const tc = Parser.tokContexts || acorn.tokContexts;
25
+
26
+ class RippleParser extends Parser {
27
+ #path = [];
28
+
29
+ // Helper method to get the element name from a JSX identifier or member expression
30
+ getElementName(node) {
31
+ if (!node) return null;
32
+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
33
+ return node.name;
34
+ } else if (node.type === 'MemberExpression' || node.type === 'JSXMemberExpression') {
35
+ // For components like <Foo.Bar>, return "Foo.Bar"
36
+ return this.getElementName(node.object) + '.' + this.getElementName(node.property);
37
+ }
38
+ return null;
39
+ }
40
+
41
+ getTokenFromCode(code) {
42
+ if (code === 60) {
43
+ // < character
44
+ if (this.#path.findLast((n) => n.type === 'Component')) {
45
+ // Check if everything before this position on the current line is whitespace
46
+ let lineStart = this.pos - 1;
47
+ while (
48
+ lineStart >= 0 &&
49
+ this.input.charCodeAt(lineStart) !== 10 &&
50
+ this.input.charCodeAt(lineStart) !== 13
51
+ ) {
52
+ lineStart--;
53
+ }
54
+ lineStart++; // Move past the newline character
55
+
56
+ // Check if all characters from line start to current position are whitespace
57
+ let allWhitespace = true;
58
+ for (let i = lineStart; i < this.pos; i++) {
59
+ const ch = this.input.charCodeAt(i);
60
+ if (ch !== 32 && ch !== 9) {
61
+ allWhitespace = false;
62
+ break;
63
+ }
64
+ }
65
+
66
+ // Check if the character after < is not whitespace
67
+ if (allWhitespace && this.pos + 1 < this.input.length) {
68
+ const nextChar = this.input.charCodeAt(this.pos + 1);
69
+ if (nextChar !== 32 && nextChar !== 9 && nextChar !== 10 && nextChar !== 13) {
70
+ const tokTypes = this.acornTypeScript.tokTypes;
71
+ ++this.pos;
72
+ return this.finishToken(tokTypes.jsxTagStart);
73
+ }
74
+ }
75
+ }
76
+ }
77
+
78
+ if (code === 35) {
79
+ // # character
80
+ // Look ahead to see if this is followed by [ for tuple syntax
81
+ if (this.pos + 1 < this.input.length) {
82
+ const nextChar = this.input.charCodeAt(this.pos + 1);
83
+ if (nextChar === 91) {
84
+ // [ character
85
+ // This is a tuple literal #[
86
+ // Consume both # and [
87
+ ++this.pos; // consume #
88
+ ++this.pos; // consume [
89
+ return this.finishToken(tt.bracketL, '#[');
90
+ }
91
+ }
92
+ }
93
+
94
+ if (code === 64) {
95
+ // @ character
96
+ // Look ahead to see if this is followed by a valid identifier character
97
+ if (this.pos + 1 < this.input.length) {
98
+ const nextChar = this.input.charCodeAt(this.pos + 1);
99
+ // Check if the next character can start an identifier
100
+ if (
101
+ (nextChar >= 65 && nextChar <= 90) || // A-Z
102
+ (nextChar >= 97 && nextChar <= 122) || // a-z
103
+ nextChar === 95 ||
104
+ nextChar === 36
105
+ ) {
106
+ // _ or $
107
+
108
+ // Check if we're in an expression context
109
+ // In JSX expressions, inside parentheses, assignments, etc.
110
+ // we want to treat @ as an identifier prefix rather than decorator
111
+ const currentType = this.type;
112
+ const inExpression =
113
+ this.exprAllowed ||
114
+ currentType === tt.braceL || // Inside { }
115
+ currentType === tt.parenL || // Inside ( )
116
+ currentType === tt.eq || // After =
117
+ currentType === tt.comma || // After ,
118
+ currentType === tt.colon || // After :
119
+ currentType === tt.question || // After ?
120
+ currentType === tt.logicalOR || // After ||
121
+ currentType === tt.logicalAND || // After &&
122
+ currentType === tt.dot || // After . (for member expressions like obj.@prop)
123
+ currentType === tt.questionDot; // After ?. (for optional chaining like obj?.@prop)
124
+
125
+ if (inExpression) {
126
+ return this.readAtIdentifier();
127
+ }
128
+ }
129
+ }
130
+ }
131
+ return super.getTokenFromCode(code);
132
+ }
133
+
134
+ // Read an @ prefixed identifier
135
+ readAtIdentifier() {
136
+ const start = this.pos;
137
+ this.pos++; // skip '@'
138
+
139
+ // Read the identifier part manually
140
+ let word = '';
141
+ while (this.pos < this.input.length) {
142
+ const ch = this.input.charCodeAt(this.pos);
143
+ if (
144
+ (ch >= 65 && ch <= 90) || // A-Z
145
+ (ch >= 97 && ch <= 122) || // a-z
146
+ (ch >= 48 && ch <= 57) || // 0-9
147
+ ch === 95 ||
148
+ ch === 36
149
+ ) {
150
+ // _ or $
151
+ word += this.input[this.pos++];
152
+ } else {
153
+ break;
154
+ }
155
+ }
156
+
157
+ if (word === '') {
158
+ this.raise(start, 'Invalid @ identifier');
159
+ }
160
+
161
+ // Return the full identifier including @
162
+ return this.finishToken(tt.name, '@' + word);
163
+ }
164
+
165
+ // Override parseIdent to mark @ identifiers as tracked
166
+ parseIdent(liberal) {
167
+ const node = super.parseIdent(liberal);
168
+ if (node.name && node.name.startsWith('@')) {
169
+ node.name = node.name.slice(1); // Remove the '@' for internal use
170
+ node.tracked = true;
171
+ node.start++;
172
+ const prev_pos = this.pos;
173
+ this.pos = node.start;
174
+ node.loc.start = this.curPosition();
175
+ this.pos = prev_pos;
176
+ }
177
+ return node;
178
+ }
179
+
180
+ parseExprAtom(refDestructuringErrors, forNew, forInit) {
181
+ // Check if this is a tuple literal starting with #[
182
+ if (this.type === tt.bracketL && this.value === '#[') {
183
+ return this.parseTrackedArrayExpression();
184
+ }
185
+
186
+ return super.parseExprAtom(refDestructuringErrors, forNew, forInit);
187
+ }
188
+
189
+ parseTrackedArrayExpression() {
190
+ const node = this.startNode();
191
+ this.next(); // consume the '#['
192
+
193
+ node.elements = [];
194
+
195
+ // Parse array elements similar to regular array parsing
196
+ let first = true;
197
+ while (!this.eat(tt.bracketR)) {
198
+ if (!first) {
199
+ this.expect(tt.comma);
200
+ if (this.afterTrailingComma(tt.bracketR)) break;
201
+ } else {
202
+ first = false;
203
+ }
204
+
205
+ if (this.type === tt.comma) {
206
+ // Hole in array
207
+ node.elements.push(null);
208
+ } else if (this.type === tt.ellipsis) {
209
+ // Spread element
210
+ const element = this.parseSpread();
211
+ node.elements.push(element);
212
+ if (this.type === tt.comma && this.input.charCodeAt(this.pos) === 93) {
213
+ this.raise(this.pos, 'Trailing comma is not permitted after the rest element');
214
+ }
215
+ } else {
216
+ // Regular element
217
+ node.elements.push(this.parseMaybeAssign(false));
218
+ }
219
+ }
220
+
221
+ return this.finishNode(node, 'TrackedArrayExpression');
222
+ }
223
+
224
+ parseExportDefaultDeclaration() {
225
+ // Check if this is "export default component"
226
+ if (this.value === 'component') {
227
+ const node = this.startNode();
228
+ node.type = 'Component';
229
+ node.css = null;
230
+ node.default = true;
231
+ this.next();
232
+ this.enterScope(0);
233
+
234
+ node.id = this.type.label === 'name' ? this.parseIdent() : null;
235
+
236
+ this.parseFunctionParams(node);
237
+ this.eat(tt.braceL);
238
+ node.body = [];
239
+ this.#path.push(node);
240
+
241
+ this.parseTemplateBody(node.body);
242
+ this.#path.pop();
243
+ this.exitScope();
244
+
245
+ this.next();
246
+ this.finishNode(node, 'Component');
247
+ this.awaitPos = 0;
248
+
249
+ return node;
250
+ }
251
+
252
+ return super.parseExportDefaultDeclaration();
253
+ }
254
+
255
+ parseForStatement(node) {
256
+ this.next();
257
+ let awaitAt =
258
+ this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual('await')
259
+ ? this.lastTokStart
260
+ : -1;
261
+ this.labels.push({ kind: 'loop' });
262
+ this.enterScope(0);
263
+ this.expect(tt.parenL);
264
+
265
+ if (this.type === tt.semi) {
266
+ if (awaitAt > -1) this.unexpected(awaitAt);
267
+ return this.parseFor(node, null);
268
+ }
269
+
270
+ let isLet = this.isLet();
271
+ if (this.type === tt._var || this.type === tt._const || isLet) {
272
+ let init = this.startNode(),
273
+ kind = isLet ? 'let' : this.value;
274
+ this.next();
275
+ this.parseVar(init, true, kind);
276
+ this.finishNode(init, 'VariableDeclaration');
277
+ return this.parseForAfterInitWithIndex(node, init, awaitAt);
278
+ }
279
+
280
+ // Handle other cases like using declarations if they exist
281
+ let startsWithLet = this.isContextual('let'),
282
+ isForOf = false;
283
+ let usingKind =
284
+ this.isUsing && this.isUsing(true)
285
+ ? 'using'
286
+ : this.isAwaitUsing && this.isAwaitUsing(true)
287
+ ? 'await using'
288
+ : null;
289
+ if (usingKind) {
290
+ let init = this.startNode();
291
+ this.next();
292
+ if (usingKind === 'await using') {
293
+ if (!this.canAwait) {
294
+ this.raise(this.start, 'Await using cannot appear outside of async function');
295
+ }
296
+ this.next();
297
+ }
298
+ this.parseVar(init, true, usingKind);
299
+ this.finishNode(init, 'VariableDeclaration');
300
+ return this.parseForAfterInitWithIndex(node, init, awaitAt);
301
+ }
302
+
303
+ let containsEsc = this.containsEsc;
304
+ let refDestructuringErrors = {};
305
+ let initPos = this.start;
306
+ let init =
307
+ awaitAt > -1
308
+ ? this.parseExprSubscripts(refDestructuringErrors, 'await')
309
+ : this.parseExpression(true, refDestructuringErrors);
310
+
311
+ if (
312
+ this.type === tt._in ||
313
+ (isForOf = this.options.ecmaVersion >= 6 && this.isContextual('of'))
314
+ ) {
315
+ if (awaitAt > -1) {
316
+ // implies `ecmaVersion >= 9`
317
+ if (this.type === tt._in) this.unexpected(awaitAt);
318
+ node.await = true;
319
+ } else if (isForOf && this.options.ecmaVersion >= 8) {
320
+ if (
321
+ init.start === initPos &&
322
+ !containsEsc &&
323
+ init.type === 'Identifier' &&
324
+ init.name === 'async'
325
+ )
326
+ this.unexpected();
327
+ else if (this.options.ecmaVersion >= 9) node.await = false;
328
+ }
329
+ if (startsWithLet && isForOf)
330
+ this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.");
331
+ this.toAssignable(init, false, refDestructuringErrors);
332
+ this.checkLValPattern(init);
333
+ return this.parseForInWithIndex(node, init);
334
+ } else {
335
+ this.checkExpressionErrors(refDestructuringErrors, true);
336
+ }
337
+
338
+ if (awaitAt > -1) this.unexpected(awaitAt);
339
+ return this.parseFor(node, init);
340
+ }
341
+
342
+ parseForAfterInitWithIndex(node, init, awaitAt) {
343
+ if (
344
+ (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual('of'))) &&
345
+ init.declarations.length === 1
346
+ ) {
347
+ if (this.options.ecmaVersion >= 9) {
348
+ if (this.type === tt._in) {
349
+ if (awaitAt > -1) this.unexpected(awaitAt);
350
+ } else node.await = awaitAt > -1;
351
+ }
352
+ return this.parseForInWithIndex(node, init);
353
+ }
354
+ if (awaitAt > -1) this.unexpected(awaitAt);
355
+ return this.parseFor(node, init);
356
+ }
357
+
358
+ parseForInWithIndex(node, init) {
359
+ const isForIn = this.type === tt._in;
360
+ this.next();
361
+
362
+ if (
363
+ init.type === 'VariableDeclaration' &&
364
+ init.declarations[0].init != null &&
365
+ (!isForIn ||
366
+ this.options.ecmaVersion < 8 ||
367
+ this.strict ||
368
+ init.kind !== 'var' ||
369
+ init.declarations[0].id.type !== 'Identifier')
370
+ ) {
371
+ this.raise(
372
+ init.start,
373
+ `${isForIn ? 'for-in' : 'for-of'} loop variable declaration may not have an initializer`,
374
+ );
375
+ }
376
+
377
+ node.left = init;
378
+ node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
379
+
380
+ // Check for our extended syntax: "; index varName"
381
+ if (!isForIn && this.type === tt.semi) {
382
+ this.next(); // consume ';'
383
+
384
+ if (this.isContextual('index')) {
385
+ this.next(); // consume 'index'
386
+
387
+ if (this.type === tt.name) {
388
+ node.index = this.parseIdent();
389
+ } else {
390
+ this.raise(this.start, 'Expected identifier after "index" keyword');
391
+ }
392
+ } else {
393
+ this.raise(this.start, 'Expected "index" keyword after semicolon in for-of loop');
394
+ }
395
+ } else if (!isForIn) {
396
+ // Set index to null for standard for-of loops
397
+ node.index = null;
398
+ }
399
+
400
+ this.expect(tt.parenR);
401
+ node.body = this.parseStatement('for');
402
+ this.exitScope();
403
+ this.labels.pop();
404
+ return this.finishNode(node, isForIn ? 'ForInStatement' : 'ForOfStatement');
405
+ }
406
+
407
+ shouldParseExportStatement() {
408
+ if (super.shouldParseExportStatement()) {
409
+ return true;
410
+ }
411
+ if (this.value === 'component') {
412
+ return true;
413
+ }
414
+ return this.type.keyword === 'var';
415
+ }
416
+
417
+ jsx_parseExpressionContainer() {
418
+ let node = this.startNode();
419
+ this.next();
420
+
421
+ node.expression =
422
+ this.type === tt.braceR ? this.jsx_parseEmptyExpression() : this.parseExpression();
423
+ this.expect(tt.braceR);
424
+ return this.finishNode(node, 'JSXExpressionContainer');
425
+ }
426
+
427
+ jsx_parseTupleContainer() {
428
+ var t = this.startNode();
429
+ return (
430
+ this.next(),
431
+ (t.expression =
432
+ this.type === tt.bracketR ? this.jsx_parseEmptyExpression() : this.parseExpression()),
433
+ this.expect(tt.bracketR),
434
+ this.finishNode(t, 'JSXExpressionContainer')
435
+ );
436
+ }
437
+
438
+ jsx_parseAttribute() {
439
+ let node = this.startNode();
440
+
441
+ if (this.eat(tt.braceL)) {
442
+ if (this.value === 'ref') {
443
+ this.next();
444
+ if (this.type === tt.braceR) {
445
+ this.raise(
446
+ this.start,
447
+ '"ref" is a Ripple keyword and must be used in the form {ref fn}',
448
+ );
449
+ }
450
+ node.argument = this.parseMaybeAssign();
451
+ this.expect(tt.braceR);
452
+ return this.finishNode(node, 'RefAttribute');
453
+ } else if (this.type === tt.ellipsis) {
454
+ this.expect(tt.ellipsis);
455
+ node.argument = this.parseMaybeAssign();
456
+ this.expect(tt.braceR);
457
+ return this.finishNode(node, 'SpreadAttribute');
458
+ } else if (this.lookahead().type === tt.ellipsis) {
459
+ this.expect(tt.ellipsis);
460
+ node.argument = this.parseMaybeAssign();
461
+ this.expect(tt.braceR);
462
+ return this.finishNode(node, 'SpreadAttribute');
463
+ } else {
464
+ const id = this.parseIdentNode();
465
+ id.tracked = false;
466
+ if (id.name.startsWith('@')) {
467
+ id.tracked = true;
468
+ id.name = id.name.slice(1);
469
+ }
470
+ this.finishNode(id, 'Identifier');
471
+ node.name = id;
472
+ node.value = id;
473
+ this.next();
474
+ this.expect(tt.braceR);
475
+ return this.finishNode(node, 'Attribute');
476
+ }
477
+ }
478
+ node.name = this.jsx_parseNamespacedName();
479
+ node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
480
+ return this.finishNode(node, 'JSXAttribute');
481
+ }
482
+
483
+ jsx_parseNamespacedName() {
484
+ const base = this.jsx_parseIdentifier();
485
+ if (!this.eat(tt.colon)) return base;
486
+ const node = this.startNodeAt(base.start, base.loc.start);
487
+ node.namespace = base;
488
+ node.name = this.jsx_parseIdentifier();
489
+ return this.finishNode(node, 'JSXNamespacedName');
490
+ }
491
+
492
+ jsx_parseIdentifier() {
493
+ const node = this.startNode();
494
+
495
+ if (this.type.label === '@') {
496
+ this.next(); // consume @
497
+
498
+ if (this.type === tt.name || this.type.label === 'jsxName') {
499
+ node.name = this.value;
500
+ node.tracked = true;
501
+ this.next();
502
+ } else {
503
+ // Unexpected token after @
504
+ this.unexpected();
505
+ }
506
+ } else if (
507
+ (this.type === tt.name || this.type.label === 'jsxName') &&
508
+ this.value &&
509
+ this.value.startsWith('@')
510
+ ) {
511
+ node.name = this.value.substring(1);
512
+ node.tracked = true;
513
+ this.next();
514
+ } else if (this.type === tt.name || this.type.keyword || this.type.label === 'jsxName') {
515
+ node.name = this.value;
516
+ node.tracked = false; // Explicitly mark as not tracked
517
+ this.next();
518
+ } else {
519
+ return super.jsx_parseIdentifier();
520
+ }
521
+
522
+ return this.finishNode(node, 'JSXIdentifier');
523
+ }
524
+
525
+ // Override jsx_parseElementName to support @ syntax in member expressions
526
+ jsx_parseElementName() {
527
+ let node = this.jsx_parseIdentifier();
528
+ if (this.eat(tt.dot)) {
529
+ let memberExpr = this.startNodeAt(node.start, node.loc && node.loc.start);
530
+ memberExpr.object = node;
531
+ memberExpr.property = this.jsx_parseIdentifier();
532
+ memberExpr.computed = false;
533
+ while (this.eat(tt.dot)) {
534
+ let newMemberExpr = this.startNodeAt(
535
+ memberExpr.start,
536
+ memberExpr.loc && memberExpr.loc.start,
537
+ );
538
+ newMemberExpr.object = memberExpr;
539
+ newMemberExpr.property = this.jsx_parseIdentifier();
540
+ newMemberExpr.computed = false;
541
+ memberExpr = this.finishNode(newMemberExpr, 'JSXMemberExpression');
542
+ }
543
+ return this.finishNode(memberExpr, 'JSXMemberExpression');
544
+ }
545
+ return node;
546
+ }
547
+
548
+ jsx_parseAttributeValue() {
549
+ const tok = this.acornTypeScript.tokTypes;
550
+
551
+ switch (this.type) {
552
+ case tt.braceL:
553
+ var t = this.jsx_parseExpressionContainer();
554
+ return (
555
+ 'JSXEmptyExpression' === t.expression.type &&
556
+ this.raise(t.start, 'attributes must only be assigned a non-empty expression'),
557
+ t
558
+ );
559
+ case tok.jsxTagStart:
560
+ case tt.string:
561
+ return this.parseExprAtom();
562
+ default:
563
+ this.raise(this.start, 'value should be either an expression or a quoted text');
564
+ }
565
+ }
566
+
567
+ parseTryStatement(node) {
568
+ this.next();
569
+ node.block = this.parseBlock();
570
+ node.handler = null;
571
+
572
+ if (this.value === 'pending') {
573
+ this.next();
574
+ node.pending = this.parseBlock();
575
+ } else {
576
+ node.pending = null;
577
+ }
578
+
579
+ if (this.type === tt._catch) {
580
+ var clause = this.startNode();
581
+ this.next();
582
+ if (this.eat(tt.parenL)) {
583
+ clause.param = this.parseCatchClauseParam();
584
+ } else {
585
+ if (this.options.ecmaVersion < 10) {
586
+ this.unexpected();
587
+ }
588
+ clause.param = null;
589
+ this.enterScope(0);
590
+ }
591
+ clause.body = this.parseBlock(false);
592
+ this.exitScope();
593
+ node.handler = this.finishNode(clause, 'CatchClause');
594
+ }
595
+ node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
596
+
597
+ if (!node.handler && !node.finalizer && !node.pending) {
598
+ this.raise(node.start, 'Missing catch or finally clause');
599
+ }
600
+ return this.finishNode(node, 'TryStatement');
601
+ }
602
+
603
+ jsx_readToken() {
604
+ let out = '',
605
+ chunkStart = this.pos;
606
+ const tok = this.acornTypeScript.tokTypes;
607
+
608
+ for (;;) {
609
+ if (this.pos >= this.input.length) this.raise(this.start, 'Unterminated JSX contents');
610
+ let ch = this.input.charCodeAt(this.pos);
611
+
612
+ switch (ch) {
613
+ case 60: // '<'
614
+ case 123: // '{'
615
+ if (ch === 60 && this.exprAllowed) {
616
+ ++this.pos;
617
+ return this.finishToken(tok.jsxTagStart);
618
+ }
619
+ if (ch === 123 && this.exprAllowed) {
620
+ return this.getTokenFromCode(ch);
621
+ }
622
+ throw new Error('TODO: Invalid syntax');
623
+
624
+ case 47: // '/'
625
+ // Check if this is a comment (// or /*)
626
+ if (this.input.charCodeAt(this.pos + 1) === 47) {
627
+ // '//'
628
+ // Line comment - handle it properly
629
+ const commentStart = this.pos;
630
+ const startLoc = this.curPosition();
631
+ this.pos += 2;
632
+
633
+ let commentText = '';
634
+ while (this.pos < this.input.length) {
635
+ const nextCh = this.input.charCodeAt(this.pos);
636
+ if (acorn.isNewLine(nextCh)) break;
637
+ commentText += this.input[this.pos];
638
+ this.pos++;
639
+ }
640
+
641
+ const commentEnd = this.pos;
642
+ const endLoc = this.curPosition();
643
+
644
+ // Call onComment if it exists
645
+ if (this.options.onComment) {
646
+ this.options.onComment(
647
+ false,
648
+ commentText,
649
+ commentStart,
650
+ commentEnd,
651
+ startLoc,
652
+ endLoc,
653
+ );
654
+ }
655
+
656
+ // Continue processing from current position
657
+ break;
658
+ } else if (this.input.charCodeAt(this.pos + 1) === 42) {
659
+ // '/*'
660
+ // Block comment - handle it properly
661
+ const commentStart = this.pos;
662
+ const startLoc = this.curPosition();
663
+ this.pos += 2;
664
+
665
+ let commentText = '';
666
+ while (this.pos < this.input.length - 1) {
667
+ if (
668
+ this.input.charCodeAt(this.pos) === 42 &&
669
+ this.input.charCodeAt(this.pos + 1) === 47
670
+ ) {
671
+ this.pos += 2;
672
+ break;
673
+ }
674
+ commentText += this.input[this.pos];
675
+ this.pos++;
676
+ }
677
+
678
+ const commentEnd = this.pos;
679
+ const endLoc = this.curPosition();
680
+
681
+ // Call onComment if it exists
682
+ if (this.options.onComment) {
683
+ this.options.onComment(
684
+ true,
685
+ commentText,
686
+ commentStart,
687
+ commentEnd,
688
+ startLoc,
689
+ endLoc,
690
+ );
691
+ }
692
+
693
+ // Continue processing from current position
694
+ break;
695
+ }
696
+ // If not a comment, fall through to default case
697
+ this.context.push(tc.b_stat);
698
+ this.exprAllowed = true;
699
+ return original.readToken.call(this, ch);
700
+
701
+ case 38: // '&'
702
+ out += this.input.slice(chunkStart, this.pos);
703
+ out += this.jsx_readEntity();
704
+ chunkStart = this.pos;
705
+ break;
706
+
707
+ case 62: // '>'
708
+ case 125: {
709
+ // '}'
710
+ if (
711
+ ch === 125 &&
712
+ (this.#path.length === 0 ||
713
+ this.#path.at(-1)?.type === 'Component' ||
714
+ this.#path.at(-1)?.type === 'Element')
715
+ ) {
716
+ return original.readToken.call(this, ch);
717
+ }
718
+ this.raise(
719
+ this.pos,
720
+ 'Unexpected token `' +
721
+ this.input[this.pos] +
722
+ '`. Did you mean `' +
723
+ (ch === 62 ? '&gt;' : '&rbrace;') +
724
+ '` or ' +
725
+ '`{"' +
726
+ this.input[this.pos] +
727
+ '"}' +
728
+ '`?',
729
+ );
730
+ }
731
+
732
+ default:
733
+ if (acorn.isNewLine(ch)) {
734
+ out += this.input.slice(chunkStart, this.pos);
735
+ out += this.jsx_readNewLine(true);
736
+ chunkStart = this.pos;
737
+ } else if (ch === 32 || ch === 9) {
738
+ ++this.pos;
739
+ } else {
740
+ this.context.push(tc.b_stat);
741
+ this.exprAllowed = true;
742
+ return original.readToken.call(this, ch);
743
+ }
744
+ }
745
+ }
746
+ }
747
+
748
+ parseElement() {
749
+ const inside_head = this.#path.findLast(
750
+ (n) => n.type === 'Element' && n.id.type === 'Identifier' && n.id.name === 'head',
751
+ );
752
+ const tok = this.acornTypeScript.tokTypes;
753
+ // Adjust the start so we capture the `<` as part of the element
754
+ const prev_pos = this.pos;
755
+ this.pos = this.start - 1;
756
+ const position = this.curPosition();
757
+ this.pos = prev_pos;
758
+
759
+ const element = this.startNode();
760
+ element.start = position.index;
761
+ element.loc.start = position;
762
+ element.type = 'Element';
763
+ this.#path.push(element);
764
+ element.children = [];
765
+ const open = this.jsx_parseOpeningElementAt();
766
+ for (const attr of open.attributes) {
767
+ if (attr.type === 'JSXAttribute') {
768
+ attr.type = 'Attribute';
769
+ if (attr.name.type === 'JSXIdentifier') {
770
+ attr.name.type = 'Identifier';
771
+ }
772
+ if (attr.value !== null) {
773
+ if (attr.value.type === 'JSXExpressionContainer') {
774
+ attr.value = attr.value.expression;
775
+ }
776
+ }
777
+ }
778
+ }
779
+ if (open.name.type === 'JSXIdentifier') {
780
+ open.name.type = 'Identifier';
781
+ }
782
+
783
+ element.id = convert_from_jsx(open.name);
784
+ element.attributes = open.attributes;
785
+ element.selfClosing = open.selfClosing;
786
+ element.metadata = {};
787
+
788
+ if (element.selfClosing) {
789
+ this.#path.pop();
790
+
791
+ if (this.type.label === '</>/<=/>=') {
792
+ this.pos--;
793
+ this.next();
794
+ }
795
+ } else {
796
+ if (open.name.name === 'style') {
797
+ // jsx_parseOpeningElementAt treats ID selectors (ie. #myid) or type selectors (ie. div) as identifier and read it
798
+ // So backtrack to the end of the <style> tag to make sure everything is included
799
+ const start = open.end;
800
+ const input = this.input.slice(start);
801
+ const end = input.indexOf('</style>');
802
+ const content = input.slice(0, end);
803
+
804
+ const component = this.#path.findLast((n) => n.type === 'Component');
805
+ if (!inside_head) {
806
+ if (component.css !== null) {
807
+ throw new Error('Components can only have one style tag');
808
+ }
809
+ component.css = parse_style(content);
810
+ }
811
+
812
+ const newLines = content.match(regex_newline_characters)?.length;
813
+ if (newLines) {
814
+ this.curLine = open.loc.end.line + newLines;
815
+ this.lineStart = start + content.lastIndexOf('\n') + 1;
816
+ }
817
+ this.pos = start + content.length + 1;
818
+
819
+ this.type = tok.jsxTagStart;
820
+ this.next();
821
+ if (this.value === '/') {
822
+ this.next();
823
+ this.jsx_parseElementName();
824
+ this.exprAllowed = true;
825
+ this.#path.pop();
826
+ this.next();
827
+ }
828
+ // This node is used for Prettier, we don't actually need
829
+ // the node for Ripple's transform process
830
+ if (!inside_head) {
831
+ element.children = [component.css];
832
+ }
833
+ // Ensure we escape JSX <tag></tag> context
834
+ const tokContexts = this.acornTypeScript.tokContexts;
835
+ const curContext = this.curContext();
836
+
837
+ if (curContext === tokContexts.tc_expr) {
838
+ this.context.pop();
839
+ }
840
+
841
+ element.css = content;
842
+ this.finishNode(element, 'Element');
843
+ return element;
844
+ } else {
845
+ this.enterScope(0);
846
+ this.parseTemplateBody(element.children);
847
+ this.exitScope();
848
+
849
+ // Check if this element was properly closed
850
+ // If we reach here and this element is still in the path, it means it was never closed
851
+ if (this.#path[this.#path.length - 1] === element) {
852
+ const tagName = this.getElementName(element.id);
853
+ this.raise(
854
+ this.start,
855
+ `Unclosed tag '<${tagName}>'. Expected '</${tagName}>' before end of component.`,
856
+ );
857
+ }
858
+ }
859
+ // Ensure we escape JSX <tag></tag> context
860
+ const tokContexts = this.acornTypeScript.tokContexts;
861
+ const curContext = this.curContext();
862
+
863
+ if (curContext === tokContexts.tc_expr) {
864
+ this.context.pop();
865
+ }
866
+ }
867
+
868
+ this.finishNode(element, 'Element');
869
+ return element;
870
+ }
871
+
872
+ parseTemplateBody(body) {
873
+ var inside_func =
874
+ this.context.some((n) => n.token === 'function') || this.scopeStack.length > 1;
875
+
876
+ if (!inside_func) {
877
+ if (this.type.label === 'return') {
878
+ throw new Error('`return` statements are not allowed in components');
879
+ }
880
+ if (this.type.label === 'continue') {
881
+ throw new Error('`continue` statements are not allowed in components');
882
+ }
883
+ if (this.type.label === 'break') {
884
+ throw new Error('`break` statements are not allowed in components');
885
+ }
886
+ }
887
+
888
+ if (this.type.label === '{') {
889
+ const node = this.jsx_parseExpressionContainer();
890
+ node.type = 'Text';
891
+ body.push(node);
892
+ } else if (this.type.label === '}') {
893
+ return;
894
+ } else if (this.type.label === 'jsxTagStart') {
895
+ this.next();
896
+ if (this.value === '/') {
897
+ this.next();
898
+ const closingTag = this.jsx_parseElementName();
899
+ this.exprAllowed = true;
900
+
901
+ // Validate that the closing tag matches the opening tag
902
+ const currentElement = this.#path[this.#path.length - 1];
903
+ if (!currentElement || currentElement.type !== 'Element') {
904
+ this.raise(this.start, 'Unexpected closing tag');
905
+ }
906
+
907
+ const openingTagName = this.getElementName(currentElement.id);
908
+ const closingTagName = this.getElementName(closingTag);
909
+
910
+ if (openingTagName !== closingTagName) {
911
+ this.raise(
912
+ this.start,
913
+ `Expected closing tag to match opening tag. Expected '</${openingTagName}>' but found '</${closingTagName}>'`,
914
+ );
915
+ }
916
+
917
+ this.#path.pop();
918
+ this.next();
919
+ return;
920
+ }
921
+ const node = this.parseElement();
922
+ if (node !== null) {
923
+ body.push(node);
924
+ }
925
+ } else {
926
+ const node = this.parseStatement(null);
927
+ body.push(node);
928
+ }
929
+ this.parseTemplateBody(body);
930
+ }
931
+
932
+ parseStatement(context, topLevel, exports) {
933
+ const tok = this.acornTypeScript.tokContexts;
934
+
935
+ if (
936
+ context !== 'for' &&
937
+ context !== 'if' &&
938
+ this.context.at(-1) === tc.b_stat &&
939
+ this.type === tt.braceL &&
940
+ this.context.some((c) => c === tok.tc_expr)
941
+ ) {
942
+ this.next();
943
+ const node = this.jsx_parseExpressionContainer();
944
+ node.type = 'Text';
945
+ this.next();
946
+ this.context.pop();
947
+ this.context.pop();
948
+ return node;
949
+ }
950
+
951
+ if (this.value === 'component') {
952
+ const node = this.startNode();
953
+ node.type = 'Component';
954
+ node.css = null;
955
+ this.next();
956
+ this.enterScope(0);
957
+ node.id = this.parseIdent();
958
+ this.parseFunctionParams(node);
959
+ this.eat(tt.braceL);
960
+ node.body = [];
961
+ this.#path.push(node);
962
+
963
+ this.parseTemplateBody(node.body);
964
+
965
+ this.#path.pop();
966
+ this.exitScope();
967
+
968
+ this.next();
969
+ this.finishNode(node, 'Component');
970
+ this.awaitPos = 0;
971
+
972
+ return node;
973
+ }
974
+
975
+ if (this.type.label === '@') {
976
+ // Try to parse as an expression statement first using tryParse
977
+ // This allows us to handle Ripple @ syntax like @count++ without
978
+ // interfering with legitimate decorator syntax
979
+ this.skip_decorator = true;
980
+ const expressionResult = this.tryParse(() => {
981
+ const node = this.startNode();
982
+ this.next();
983
+ // Force expression context to ensure @ is tokenized correctly
984
+ const old_expr_allowed = this.exprAllowed;
985
+ this.exprAllowed = true;
986
+ node.expression = this.parseExpression();
987
+
988
+ if (node.expression.type === 'UpdateExpression') {
989
+ let object = node.expression.argument;
990
+ while (object.type === 'MemberExpression') {
991
+ object = object.object;
992
+ }
993
+ if (object.type === 'Identifier') {
994
+ object.tracked = true;
995
+ }
996
+ } else if (node.expression.type === 'AssignmentExpression') {
997
+ let object = node.expression.left;
998
+ while (object.type === 'MemberExpression') {
999
+ object = object.object;
1000
+ }
1001
+ if (object.type === 'Identifier') {
1002
+ object.tracked = true;
1003
+ }
1004
+ } else if (node.expression.type === 'Identifier') {
1005
+ node.expression.tracked = true;
1006
+ } else {
1007
+ // TODO?
1008
+ }
1009
+
1010
+ this.exprAllowed = old_expr_allowed;
1011
+ return this.finishNode(node, 'ExpressionStatement');
1012
+ });
1013
+ this.skip_decorator = false;
1014
+
1015
+ // If parsing as expression statement succeeded, use that result
1016
+ if (expressionResult.node) {
1017
+ return expressionResult.node;
1018
+ }
1019
+ }
1020
+
1021
+ return super.parseStatement(context, topLevel, exports);
1022
+ }
1023
+
1024
+ parseBlock(createNewLexicalScope, node, exitStrict) {
1025
+ const parent = this.#path.at(-1);
1026
+
1027
+ if (parent?.type === 'Component' || parent?.type === 'Element') {
1028
+ if (createNewLexicalScope === void 0) createNewLexicalScope = true;
1029
+ if (node === void 0) node = this.startNode();
1030
+
1031
+ node.body = [];
1032
+ this.expect(tt.braceL);
1033
+ if (createNewLexicalScope) {
1034
+ this.enterScope(0);
1035
+ }
1036
+ this.parseTemplateBody(node.body);
1037
+
1038
+ if (exitStrict) {
1039
+ this.strict = false;
1040
+ }
1041
+ this.exprAllowed = true;
1042
+
1043
+ this.next();
1044
+ if (createNewLexicalScope) {
1045
+ this.exitScope();
1046
+ }
1047
+ return this.finishNode(node, 'BlockStatement');
1048
+ }
1049
+
1050
+ return super.parseBlock(createNewLexicalScope, node, exitStrict);
1051
+ }
1052
+ }
1053
+
1054
+ return RippleParser;
1055
+ };
967
1056
  }
968
1057
 
969
1058
  /**
@@ -975,115 +1064,115 @@ function RipplePlugin(config) {
975
1064
  * @param {number} index
976
1065
  */
977
1066
  function get_comment_handlers(source, comments, index = 0) {
978
- return {
979
- onComment: (block, value, start, end, start_loc, end_loc) => {
980
- if (block && /\n/.test(value)) {
981
- let a = start;
982
- while (a > 0 && source[a - 1] !== '\n') a -= 1;
983
-
984
- let b = a;
985
- while (/[ \t]/.test(source[b])) b += 1;
986
-
987
- const indentation = source.slice(a, b);
988
- value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
989
- }
990
-
991
- comments.push({
992
- type: block ? 'Block' : 'Line',
993
- value,
994
- start,
995
- end,
996
- loc: {
997
- start: /** @type {import('acorn').Position} */ (start_loc),
998
- end: /** @type {import('acorn').Position} */ (end_loc),
999
- },
1000
- });
1001
- },
1002
- add_comments: (ast) => {
1003
- if (comments.length === 0) return;
1004
-
1005
- comments = comments
1006
- .filter((comment) => comment.start >= index)
1007
- .map(({ type, value, start, end }) => ({ type, value, start, end }));
1008
-
1009
- walk(ast, null, {
1010
- _(node, { next, path }) {
1011
- let comment;
1012
-
1013
- while (comments[0] && comments[0].start < node.start) {
1014
- comment = /** @type {CommentWithLocation} */ (comments.shift());
1015
- (node.leadingComments ||= []).push(comment);
1016
- }
1017
-
1018
- next();
1019
-
1020
- if (comments[0]) {
1021
- if (node.type === 'BlockStatement' && node.body.length === 0) {
1022
- if (comments[0].start < node.end && comments[0].end < node.end) {
1023
- comment = /** @type {CommentWithLocation} */ (comments.shift());
1024
- (node.innerComments ||= []).push(comment);
1025
- return;
1026
- }
1027
- }
1028
- const parent = /** @type {any} */ (path.at(-1));
1029
-
1030
- if (parent === undefined || node.end !== parent.end) {
1031
- const slice = source.slice(node.end, comments[0].start);
1032
- const is_last_in_body =
1033
- ((parent?.type === 'BlockStatement' || parent?.type === 'Program') &&
1034
- parent.body.indexOf(node) === parent.body.length - 1) ||
1035
- (parent?.type === 'ArrayExpression' &&
1036
- parent.elements.indexOf(node) === parent.elements.length - 1) ||
1037
- (parent?.type === 'ObjectExpression' &&
1038
- parent.properties.indexOf(node) === parent.properties.length - 1);
1039
-
1040
- if (is_last_in_body) {
1041
- // Special case: There can be multiple trailing comments after the last node in a block,
1042
- // and they can be separated by newlines
1043
- let end = node.end;
1044
-
1045
- while (comments.length) {
1046
- const comment = comments[0];
1047
- if (parent && comment.start >= parent.end) break;
1048
-
1049
- (node.trailingComments ||= []).push(comment);
1050
- comments.shift();
1051
- end = comment.end;
1052
- }
1053
- } else if (node.end <= comments[0].start && /^[,) \t]*$/.test(slice)) {
1054
- node.trailingComments = [/** @type {CommentWithLocation} */ (comments.shift())];
1055
- }
1056
- }
1057
- }
1058
- },
1059
- });
1060
-
1061
- // Special case: Trailing comments after the root node (which can only happen for expression tags or for Program nodes).
1062
- // Adding them ensures that we can later detect the end of the expression tag correctly.
1063
- if (comments.length > 0 && (comments[0].start >= ast.end || ast.type === 'Program')) {
1064
- (ast.trailingComments ||= []).push(...comments.splice(0));
1065
- }
1066
- },
1067
- };
1067
+ return {
1068
+ onComment: (block, value, start, end, start_loc, end_loc) => {
1069
+ if (block && /\n/.test(value)) {
1070
+ let a = start;
1071
+ while (a > 0 && source[a - 1] !== '\n') a -= 1;
1072
+
1073
+ let b = a;
1074
+ while (/[ \t]/.test(source[b])) b += 1;
1075
+
1076
+ const indentation = source.slice(a, b);
1077
+ value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
1078
+ }
1079
+
1080
+ comments.push({
1081
+ type: block ? 'Block' : 'Line',
1082
+ value,
1083
+ start,
1084
+ end,
1085
+ loc: {
1086
+ start: /** @type {import('acorn').Position} */ (start_loc),
1087
+ end: /** @type {import('acorn').Position} */ (end_loc),
1088
+ },
1089
+ });
1090
+ },
1091
+ add_comments: (ast) => {
1092
+ if (comments.length === 0) return;
1093
+
1094
+ comments = comments
1095
+ .filter((comment) => comment.start >= index)
1096
+ .map(({ type, value, start, end }) => ({ type, value, start, end }));
1097
+
1098
+ walk(ast, null, {
1099
+ _(node, { next, path }) {
1100
+ let comment;
1101
+
1102
+ while (comments[0] && comments[0].start < node.start) {
1103
+ comment = /** @type {CommentWithLocation} */ (comments.shift());
1104
+ (node.leadingComments ||= []).push(comment);
1105
+ }
1106
+
1107
+ next();
1108
+
1109
+ if (comments[0]) {
1110
+ if (node.type === 'BlockStatement' && node.body.length === 0) {
1111
+ if (comments[0].start < node.end && comments[0].end < node.end) {
1112
+ comment = /** @type {CommentWithLocation} */ (comments.shift());
1113
+ (node.innerComments ||= []).push(comment);
1114
+ return;
1115
+ }
1116
+ }
1117
+ const parent = /** @type {any} */ (path.at(-1));
1118
+
1119
+ if (parent === undefined || node.end !== parent.end) {
1120
+ const slice = source.slice(node.end, comments[0].start);
1121
+ const is_last_in_body =
1122
+ ((parent?.type === 'BlockStatement' || parent?.type === 'Program') &&
1123
+ parent.body.indexOf(node) === parent.body.length - 1) ||
1124
+ (parent?.type === 'ArrayExpression' &&
1125
+ parent.elements.indexOf(node) === parent.elements.length - 1) ||
1126
+ (parent?.type === 'ObjectExpression' &&
1127
+ parent.properties.indexOf(node) === parent.properties.length - 1);
1128
+
1129
+ if (is_last_in_body) {
1130
+ // Special case: There can be multiple trailing comments after the last node in a block,
1131
+ // and they can be separated by newlines
1132
+ let end = node.end;
1133
+
1134
+ while (comments.length) {
1135
+ const comment = comments[0];
1136
+ if (parent && comment.start >= parent.end) break;
1137
+
1138
+ (node.trailingComments ||= []).push(comment);
1139
+ comments.shift();
1140
+ end = comment.end;
1141
+ }
1142
+ } else if (node.end <= comments[0].start && /^[,) \t]*$/.test(slice)) {
1143
+ node.trailingComments = [/** @type {CommentWithLocation} */ (comments.shift())];
1144
+ }
1145
+ }
1146
+ }
1147
+ },
1148
+ });
1149
+
1150
+ // Special case: Trailing comments after the root node (which can only happen for expression tags or for Program nodes).
1151
+ // Adding them ensures that we can later detect the end of the expression tag correctly.
1152
+ if (comments.length > 0 && (comments[0].start >= ast.end || ast.type === 'Program')) {
1153
+ (ast.trailingComments ||= []).push(...comments.splice(0));
1154
+ }
1155
+ },
1156
+ };
1068
1157
  }
1069
1158
 
1070
1159
  export function parse(source) {
1071
- const comments = [];
1072
- const { onComment, add_comments } = get_comment_handlers(source, comments);
1073
- let ast;
1074
-
1075
- try {
1076
- ast = parser.parse(source, {
1077
- sourceType: 'module',
1078
- ecmaVersion: 13,
1079
- locations: true,
1080
- onComment,
1081
- });
1082
- } catch (e) {
1083
- throw e;
1084
- }
1085
-
1086
- add_comments(ast);
1087
-
1088
- return ast;
1160
+ const comments = [];
1161
+ const { onComment, add_comments } = get_comment_handlers(source, comments);
1162
+ let ast;
1163
+
1164
+ try {
1165
+ ast = parser.parse(source, {
1166
+ sourceType: 'module',
1167
+ ecmaVersion: 13,
1168
+ locations: true,
1169
+ onComment,
1170
+ });
1171
+ } catch (e) {
1172
+ throw e;
1173
+ }
1174
+
1175
+ add_comments(ast);
1176
+
1177
+ return ast;
1089
1178
  }