@gi-tcg/gts-transpiler 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2085 @@
1
+ // src/parse/index.ts
2
+ import { Parser } from "acorn";
3
+ import { tsPlugin } from "@sveltejs/acorn-typescript";
4
+
5
+ // src/parse/gts_plugin.ts
6
+ import { tokTypes as tokTypes2 } from "acorn";
7
+
8
+ // src/keywords.ts
9
+ var specialIdentifiers = [
10
+ "break",
11
+ "case",
12
+ "catch",
13
+ "class",
14
+ "const",
15
+ "continue",
16
+ "debugger",
17
+ "default",
18
+ "delete",
19
+ "do",
20
+ "else",
21
+ "export",
22
+ "extends",
23
+ "false",
24
+ "finally",
25
+ "for",
26
+ "function",
27
+ "if",
28
+ "import",
29
+ "in",
30
+ "instanceof",
31
+ "new",
32
+ "null",
33
+ "return",
34
+ "super",
35
+ "switch",
36
+ "this",
37
+ "throw",
38
+ "true",
39
+ "try",
40
+ "typeof",
41
+ "var",
42
+ "void",
43
+ "while",
44
+ "with",
45
+ "let",
46
+ "static",
47
+ "yield",
48
+ "await",
49
+ "enum",
50
+ "implements",
51
+ "interface",
52
+ "package",
53
+ "private",
54
+ "protected",
55
+ "public",
56
+ "as",
57
+ "async",
58
+ "from",
59
+ "get",
60
+ "of",
61
+ "set",
62
+ "type",
63
+ "define",
64
+ "query"
65
+ ];
66
+
67
+ // src/parse/loose_plugin.ts
68
+ import { tokTypes } from "acorn";
69
+ var DUMMY_PLACEHOLDER = "✖";
70
+ function loosePlugin() {
71
+ return function loosePluginTransformer(parser) {
72
+ return class LooseParser extends parser {
73
+ _patchedParseIdent = (liberal) => {
74
+ if (this.type !== tokTypes.name) {
75
+ return this.createDummyIdentifier();
76
+ } else {
77
+ return super.parseIdent(liberal);
78
+ }
79
+ };
80
+ _proxiedThis = new Proxy(this, {
81
+ get: (target, prop) => {
82
+ if (prop === "parseIdent") {
83
+ return this._patchedParseIdent;
84
+ }
85
+ const value = Reflect.get(target, prop);
86
+ if (typeof value === "function") {
87
+ return value.bind(target);
88
+ }
89
+ return value;
90
+ }
91
+ });
92
+ createDummyIdentifier() {
93
+ const dummy = this.startNode();
94
+ dummy.name = DUMMY_PLACEHOLDER;
95
+ dummy.isDummy = true;
96
+ return this.finishNode(dummy, "Identifier");
97
+ }
98
+ parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
99
+ return super.parseSubscript.call(this._proxiedThis, base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
100
+ }
101
+ };
102
+ };
103
+ }
104
+
105
+ // src/parse/gts_plugin.ts
106
+ function gtsPlugin(options = {}) {
107
+ return function gtsPluginTransformer(Parser) {
108
+ const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
109
+ const lineBreak = /\r\n?|\n|\u2028|\u2029/;
110
+ const acornScope = {
111
+ SCOPE_TOP: 1,
112
+ SCOPE_FUNCTION: 2,
113
+ SCOPE_ASYNC: 4,
114
+ SCOPE_GENERATOR: 8,
115
+ SCOPE_ARROW: 16
116
+ };
117
+ return class GtsParser extends Parser {
118
+ gtsOptions = options;
119
+ isShortcutContext = false;
120
+ parseStatement(context, topLevel, exports) {
121
+ if (topLevel && this.gts_isDefineStatement()) {
122
+ const node = this.startNode();
123
+ this.next();
124
+ node.body = this.gts_parseNamedAttributeDefinition();
125
+ return this.finishNode(node, "GTSDefineStatement");
126
+ }
127
+ return super.parseStatement(context, topLevel, exports);
128
+ }
129
+ gts_isDefineStatement() {
130
+ if (!this.isContextual("define")) {
131
+ return false;
132
+ }
133
+ skipWhiteSpace.lastIndex = this.pos;
134
+ const skip = skipWhiteSpace.exec(this.input);
135
+ const next = this.pos + skip[0].length;
136
+ return !lineBreak.test(this.input.slice(this.pos, next));
137
+ }
138
+ gts_parseNamedAttributeDefinition() {
139
+ const node = this.startNode();
140
+ let name;
141
+ if (this.type.label === "string") {
142
+ name = this.parseExprAtom();
143
+ } else if (this.type.label === "name") {
144
+ name = this.parseIdent();
145
+ } else {
146
+ this.raise(this.start, "Expected attribute name");
147
+ }
148
+ node.name = name;
149
+ node.body = this.gts_parseAttributeBody();
150
+ if (this.eatContextual("as")) {
151
+ if (this.eatContextual("public")) {
152
+ node.bindingAccessModifier = "public";
153
+ } else if (this.eatContextual("protected")) {
154
+ node.bindingAccessModifier = "protected";
155
+ } else if (this.eatContextual("private")) {
156
+ node.bindingAccessModifier = "private";
157
+ }
158
+ node.bindingName = this.parseIdent();
159
+ }
160
+ this.semicolon();
161
+ return this.finishNode(node, "GTSNamedAttributeDefinition");
162
+ }
163
+ gts_parseAttributeBody() {
164
+ const node = this.startNode();
165
+ node.positionalAttributes = this.gts_parsePositionalAttributeList();
166
+ if (this.type === tokTypes2.braceL) {
167
+ node.namedAttributes = this.gts_parseNamedAttributeBlock();
168
+ }
169
+ return this.finishNode(node, "GTSAttributeBody");
170
+ }
171
+ gts_parsePositionalAttributeList() {
172
+ const node = this.startNode();
173
+ node.attributes = [];
174
+ let first = true;
175
+ while (true) {
176
+ if (this.type === tokTypes2.braceL) {
177
+ break;
178
+ }
179
+ if (this.type === tokTypes2.semi || this.canInsertSemicolon()) {
180
+ break;
181
+ }
182
+ if (this.isContextual("as")) {
183
+ break;
184
+ }
185
+ if (!first) {
186
+ this.expect(tokTypes2.comma);
187
+ } else {
188
+ first = false;
189
+ }
190
+ node.attributes.push(this.gts_parseAttributeExpression());
191
+ }
192
+ return this.finishNode(node, "GTSPositionalAttributeList");
193
+ }
194
+ gts_parseNamedAttributeBlock() {
195
+ const node = this.startNode();
196
+ node.attributes = [];
197
+ this.expect(tokTypes2.braceL);
198
+ while (this.type !== tokTypes2.braceR && this.type !== tokTypes2.eof) {
199
+ if (specialIdentifiers.includes(this.value) || this.type === tokTypes2.colon) {
200
+ node.directAction = this.gts_parseDirectFunction();
201
+ break;
202
+ }
203
+ node.attributes.push(this.gts_parseNamedAttributeDefinition());
204
+ }
205
+ this.expect(tokTypes2.braceR);
206
+ return this.finishNode(node, "GTSNamedAttributeBlock");
207
+ }
208
+ gts_parseDirectFunction() {
209
+ const node = this.startNode();
210
+ node.body = [];
211
+ this.enterScope(acornScope.SCOPE_FUNCTION | acornScope.SCOPE_ARROW);
212
+ const oldShortcutContext = this.isShortcutContext;
213
+ this.isShortcutContext = true;
214
+ while (this.type !== tokTypes2.braceR && this.type !== tokTypes2.eof) {
215
+ const startPos = this.pos;
216
+ const stmt = this.parseStatement(null);
217
+ if (stmt.type === "GTSDefineStatement") {
218
+ this.raise(startPos, "DefineStatement is not allowed in direct function.");
219
+ }
220
+ node.body.push(stmt);
221
+ }
222
+ this.exitScope();
223
+ this.isShortcutContext = oldShortcutContext;
224
+ return this.finishNode(node, "GTSDirectFunction");
225
+ }
226
+ gts_parseAttributeExpression() {
227
+ if (this.type === tokTypes2.braceL) {
228
+ this.raise(this.start, "Expected attribute expression, got '{'.");
229
+ }
230
+ if (this.type === tokTypes2.colon) {
231
+ this.next();
232
+ return this.gts_parseShortcutFunction();
233
+ }
234
+ if (this.gtsOptions.allowEmptyPositionalAttribute && (this.type === tokTypes2.comma || this.type === tokTypes2.braceR || this.type === tokTypes2.semi || this.canInsertSemicolon() || this.isContextual("as"))) {
235
+ const dummy = this.startNode();
236
+ dummy.name = DUMMY_PLACEHOLDER;
237
+ dummy.isDummy = true;
238
+ return this.finishNode(dummy, "Identifier");
239
+ }
240
+ return this.parseExprAtom();
241
+ }
242
+ gts_parseShortcutFunction() {
243
+ const node = this.startNode();
244
+ this.enterScope(acornScope.SCOPE_FUNCTION | acornScope.SCOPE_ARROW);
245
+ const oldShortcutContext = this.isShortcutContext;
246
+ this.isShortcutContext = true;
247
+ if (this.type === tokTypes2.parenL) {
248
+ this.next();
249
+ node.expression = true;
250
+ node.body = this.parseExpression();
251
+ this.expect(tokTypes2.parenR);
252
+ } else if (this.type === tokTypes2.braceL) {
253
+ node.expression = false;
254
+ node.body = this.parseBlock();
255
+ }
256
+ this.exitScope();
257
+ this.isShortcutContext = oldShortcutContext;
258
+ return this.finishNode(node, "GTSShortcutFunctionExpression");
259
+ }
260
+ parseExprAtom(refDestructuringErrors, forInit, forNew) {
261
+ if (this.type === tokTypes2.colon) {
262
+ if (!this.isShortcutContext) {
263
+ this.raise(this.start, "ShortcutArgumentExpression ':' must be inside ShortcutFunction or DirectShortcutFunction.");
264
+ }
265
+ const node = this.startNode();
266
+ this.next();
267
+ if (this.gtsOptions.allowEmptyShortcutMember && this.type !== tokTypes2.name) {
268
+ const dummy = this.startNode();
269
+ dummy.name = DUMMY_PLACEHOLDER;
270
+ dummy.isDummy = true;
271
+ node.property = this.finishNode(dummy, "Identifier");
272
+ } else {
273
+ node.property = this.parseIdent();
274
+ }
275
+ return this.finishNode(node, "GTSShortcutArgumentExpression");
276
+ }
277
+ return super.parseExprAtom(refDestructuringErrors, forInit, forNew);
278
+ }
279
+ parseMaybeUnary(refDestructuringErrors, sawUnary, incDec, forInit) {
280
+ if (this.isContextual("query")) {
281
+ const expr = this.gts_parseQueryExpression();
282
+ if (!incDec && this.eat(tokTypes2.starstar)) {
283
+ this.unexpected(this.lastTokStart);
284
+ }
285
+ return expr;
286
+ }
287
+ return super.parseMaybeUnary(refDestructuringErrors, sawUnary, incDec, forInit);
288
+ }
289
+ gts_parseQueryExpression(forInit) {
290
+ const node = this.startNode();
291
+ this.next();
292
+ if (this.eat(tokTypes2.star)) {
293
+ node.star = true;
294
+ }
295
+ node.argument = this.parseMaybeUnary(null, true, false, forInit);
296
+ return this.finishNode(node, "GTSQueryExpression");
297
+ }
298
+ };
299
+ };
300
+ }
301
+
302
+ // src/parse/comment.js
303
+ import { walk } from "zimmerframe";
304
+ function getCommentHandlers(source, comments, index = 0) {
305
+ function getNextNonWhitespaceCharacter(text, startIndex) {
306
+ for (let i = startIndex;i < text.length; i++) {
307
+ const char = text[i];
308
+ if (char !== " " && char !== "\t" && char !== `
309
+ ` && char !== "\r") {
310
+ return char;
311
+ }
312
+ }
313
+ return null;
314
+ }
315
+ return {
316
+ onComment: (block, value, start, end, start_loc, end_loc, metadata) => {
317
+ if (block && /\n/.test(value)) {
318
+ let a = start;
319
+ while (a > 0 && source[a - 1] !== `
320
+ `)
321
+ a -= 1;
322
+ let b = a;
323
+ while (/[ \t]/.test(source[b]))
324
+ b += 1;
325
+ const indentation = source.slice(a, b);
326
+ value = value.replace(new RegExp(`^${indentation}`, "gm"), "");
327
+ }
328
+ comments.push({
329
+ type: block ? "Block" : "Line",
330
+ value,
331
+ start,
332
+ end,
333
+ loc: {
334
+ start: start_loc,
335
+ end: end_loc
336
+ },
337
+ context: metadata ?? null
338
+ });
339
+ },
340
+ addComments: (ast) => {
341
+ if (comments.length === 0)
342
+ return;
343
+ comments = comments.filter((comment) => comment.start >= index).map(({ type, value, start, end, loc, context }) => ({
344
+ type,
345
+ value,
346
+ start,
347
+ end,
348
+ loc,
349
+ context
350
+ }));
351
+ walk(ast, null, {
352
+ _(node, { next, path }) {
353
+ const metadata = node?.metadata;
354
+ if (metadata && metadata.commentContainerId !== undefined) {
355
+ while (comments[0] && comments[0].context && comments[0].context.containerId === metadata.commentContainerId && comments[0].context.beforeMeaningfulChild) {
356
+ const elementComment = comments.shift();
357
+ (metadata.elementLeadingComments ||= []).push(elementComment);
358
+ }
359
+ }
360
+ while (comments[0] && comments[0].start < node.start) {
361
+ const comment = comments.shift();
362
+ if (node.type === "BlockStatement") {
363
+ const parent = path.at(-1);
364
+ if (parent && (parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ArrowFunctionExpression") && parent.body === node) {
365
+ (parent.comments ||= []).push(comment);
366
+ continue;
367
+ }
368
+ }
369
+ const ancestorElements = path.filter((ancestor) => ancestor && ancestor.type === "Element" && ancestor.loc).sort((a, b) => a.loc.start.line - b.loc.start.line);
370
+ const targetAncestor = ancestorElements.find((ancestor) => comment.loc.start.line < ancestor.loc.start.line);
371
+ if (targetAncestor) {
372
+ targetAncestor.metadata ??= { path: [] };
373
+ (targetAncestor.metadata.elementLeadingComments ||= []).push(comment);
374
+ continue;
375
+ }
376
+ (node.leadingComments ||= []).push(comment);
377
+ }
378
+ next();
379
+ if (comments[0]) {
380
+ if (node.type === "BlockStatement" && node.body.length === 0) {
381
+ while (comments[0] && comments[0].start < node.end && comments[0].end < node.end) {
382
+ const comment = comments.shift();
383
+ (node.innerComments ||= []).push(comment);
384
+ }
385
+ if (node.innerComments && node.innerComments.length > 0) {
386
+ return;
387
+ }
388
+ }
389
+ if (node.type === "JSXEmptyExpression") {
390
+ while (comments[0] && comments[0].start >= node.start && comments[0].end <= node.end) {
391
+ const comment = comments.shift();
392
+ (node.innerComments ||= []).push(comment);
393
+ }
394
+ if (node.innerComments && node.innerComments.length > 0) {
395
+ return;
396
+ }
397
+ }
398
+ if (node.type === "Element" && (!node.children || node.children.length === 0)) {
399
+ while (comments[0] && comments[0].start < node.end && comments[0].end < node.end) {
400
+ const comment = comments.shift();
401
+ (node.innerComments ||= []).push(comment);
402
+ }
403
+ if (node.innerComments && node.innerComments.length > 0) {
404
+ return;
405
+ }
406
+ }
407
+ const parent = path.at(-1);
408
+ if (parent === undefined || node.end !== parent.end) {
409
+ const slice = source.slice(node.end, comments[0].start);
410
+ let is_last_in_array = false;
411
+ let node_array = null;
412
+ let isParam = false;
413
+ let isArgument = false;
414
+ let isSwitchCaseSibling = false;
415
+ if (parent.type === "BlockStatement" || parent.type === "Program" || parent.type === "Component" || parent.type === "ClassBody") {
416
+ node_array = parent.body;
417
+ } else if (parent.type === "SwitchStatement") {
418
+ node_array = parent.cases;
419
+ isSwitchCaseSibling = true;
420
+ } else if (parent.type === "SwitchCase") {
421
+ node_array = parent.consequent;
422
+ } else if (parent.type === "ArrayExpression" || parent.type === "TrackedArrayExpression") {
423
+ node_array = parent.elements;
424
+ } else if (parent.type === "ObjectExpression" || parent.type === "TrackedObjectExpression") {
425
+ node_array = parent.properties;
426
+ } else if (parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression" || parent.type === "ArrowFunctionExpression") {
427
+ node_array = parent.params;
428
+ isParam = true;
429
+ } else if (parent.type === "CallExpression" || parent.type === "NewExpression") {
430
+ node_array = parent.arguments;
431
+ isArgument = true;
432
+ }
433
+ if (node_array && Array.isArray(node_array)) {
434
+ is_last_in_array = node_array.indexOf(node) === node_array.length - 1;
435
+ }
436
+ if (is_last_in_array) {
437
+ if (isParam || isArgument) {
438
+ while (comments.length) {
439
+ const potentialComment = comments[0];
440
+ if (parent && potentialComment.start >= parent.end) {
441
+ break;
442
+ }
443
+ const nextChar = getNextNonWhitespaceCharacter(source, potentialComment.end);
444
+ if (nextChar === ")") {
445
+ (node.trailingComments ||= []).push(comments.shift());
446
+ continue;
447
+ }
448
+ break;
449
+ }
450
+ } else {
451
+ let end = node.end;
452
+ while (comments.length) {
453
+ const comment = comments[0];
454
+ if (parent && comment.start >= parent.end)
455
+ break;
456
+ (node.trailingComments ||= []).push(comment);
457
+ comments.shift();
458
+ end = comment.end;
459
+ }
460
+ }
461
+ } else if (node.end <= comments[0].start) {
462
+ const onlySimpleWhitespace = /^[,) \t]*$/.test(slice);
463
+ const onlyWhitespace = /^\s*$/.test(slice);
464
+ const hasBlankLine = /\n\s*\n/.test(slice);
465
+ const nodeEndLine = node.loc?.end?.line ?? null;
466
+ const commentStartLine = comments[0].loc?.start?.line ?? null;
467
+ const isImmediateNextLine = nodeEndLine !== null && commentStartLine !== null && commentStartLine === nodeEndLine + 1;
468
+ if (isSwitchCaseSibling && !is_last_in_array) {
469
+ if (nodeEndLine !== null && commentStartLine !== null && nodeEndLine === commentStartLine) {
470
+ node.trailingComments = [
471
+ comments.shift()
472
+ ];
473
+ }
474
+ return;
475
+ }
476
+ if (onlySimpleWhitespace || onlyWhitespace && !hasBlankLine && isImmediateNextLine) {
477
+ if (comments[0].type === "Block" && !is_last_in_array && node_array) {
478
+ const currentIndex = node_array.indexOf(node);
479
+ const nextSibling = node_array[currentIndex + 1];
480
+ if (nextSibling && nextSibling.loc) {
481
+ const commentEndLine = comments[0].loc?.end?.line;
482
+ const nextSiblingStartLine = nextSibling.loc?.start?.line;
483
+ if (commentEndLine === nextSiblingStartLine) {
484
+ return;
485
+ }
486
+ }
487
+ }
488
+ if (isParam) {
489
+ const nodeEndLine2 = source.slice(0, node.end).split(`
490
+ `).length;
491
+ const commentStartLine2 = source.slice(0, comments[0].start).split(`
492
+ `).length;
493
+ if (nodeEndLine2 === commentStartLine2) {
494
+ node.trailingComments = [
495
+ comments.shift()
496
+ ];
497
+ }
498
+ } else {
499
+ node.trailingComments = [
500
+ comments.shift()
501
+ ];
502
+ }
503
+ } else if (hasBlankLine && onlyWhitespace && node_array) {
504
+ const isStatementContext = parent.type === "BlockStatement" || parent.type === "Program";
505
+ if (!isStatementContext) {
506
+ return;
507
+ }
508
+ const currentIndex = node_array.indexOf(node);
509
+ const nextSibling = node_array[currentIndex + 1];
510
+ if (nextSibling && nextSibling.loc) {
511
+ let lastCommentIndex = 0;
512
+ let lastCommentEnd = comments[0].end;
513
+ while (comments[lastCommentIndex + 1]) {
514
+ const currentComment = comments[lastCommentIndex];
515
+ const nextComment = comments[lastCommentIndex + 1];
516
+ const sliceBetween = source.slice(currentComment.end, nextComment.start);
517
+ if (/\n\s*\n/.test(sliceBetween)) {
518
+ break;
519
+ }
520
+ lastCommentIndex++;
521
+ lastCommentEnd = nextComment.end;
522
+ }
523
+ const sliceAfterComments = source.slice(lastCommentEnd, nextSibling.start);
524
+ const hasBlankLineAfter = /\n\s*\n/.test(sliceAfterComments);
525
+ if (hasBlankLineAfter) {
526
+ const nextIsElement = nextSibling.type === "Element";
527
+ const commentsInsideElement = nextIsElement && nextSibling.loc && comments.some((c) => {
528
+ if (!c.loc)
529
+ return false;
530
+ return c.loc.start.line >= nextSibling.loc.start.line && c.loc.end.line <= nextSibling.loc.end.line;
531
+ });
532
+ if (!commentsInsideElement) {
533
+ for (let i = 0;i <= lastCommentIndex; i++) {
534
+ (node.trailingComments ||= []).push(comments.shift());
535
+ }
536
+ }
537
+ }
538
+ }
539
+ }
540
+ }
541
+ }
542
+ }
543
+ }
544
+ });
545
+ }
546
+ };
547
+ }
548
+
549
+ // src/error.ts
550
+ class GtsTranspilerError extends Error {
551
+ position;
552
+ constructor(message, position) {
553
+ super(message);
554
+ this.position = position;
555
+ this.name = "GtsTranspilerError";
556
+ }
557
+ }
558
+
559
+ // src/parse/index.ts
560
+ var TsParser = Parser.extend(tsPlugin());
561
+ function parse(input, options) {
562
+ try {
563
+ const GtsParser = TsParser.extend(gtsPlugin(options));
564
+ return GtsParser.parse(input, {
565
+ ecmaVersion: "latest",
566
+ sourceType: "module",
567
+ locations: true
568
+ });
569
+ } catch (e) {
570
+ if (e instanceof SyntaxError && "loc" in e) {
571
+ const loc = e.loc;
572
+ throw new GtsTranspilerError(e.message, {
573
+ start: loc,
574
+ end: { line: loc.line, column: loc.column + 1 }
575
+ });
576
+ } else {
577
+ throw new GtsTranspilerError(e?.message, null);
578
+ }
579
+ }
580
+ }
581
+ function parseLoose(input, options) {
582
+ try {
583
+ const GtsParser = TsParser.extend(loosePlugin(), gtsPlugin({
584
+ ...options,
585
+ allowEmptyShortcutMember: true,
586
+ allowEmptyPositionalAttribute: true
587
+ }));
588
+ const { onComment, addComments } = getCommentHandlers(input, []);
589
+ const ast = GtsParser.parse(input, {
590
+ ecmaVersion: "latest",
591
+ sourceType: "module",
592
+ locations: true,
593
+ onComment
594
+ });
595
+ addComments(ast);
596
+ return ast;
597
+ } catch (e) {
598
+ if (e instanceof SyntaxError && "loc" in e) {
599
+ const loc = e.loc;
600
+ throw new GtsTranspilerError(e.message, {
601
+ start: loc,
602
+ end: { line: loc.line, column: loc.column + 1 }
603
+ });
604
+ } else {
605
+ throw new GtsTranspilerError(e?.message, null);
606
+ }
607
+ }
608
+ }
609
+
610
+ // src/transform/erase_ts.ts
611
+ import { walk as walk2 } from "zimmerframe";
612
+ var empty = {
613
+ type: "EmptyStatement"
614
+ };
615
+ function removeThisParameter(node, context) {
616
+ if (node.params[0]?.type === "Identifier" && node.params[0].name === "this") {
617
+ node.params.shift();
618
+ }
619
+ return context.next();
620
+ }
621
+ var throwInvalidFeature = (node, feature) => {
622
+ throw new GtsTranspilerError(`TypeScript feature not supported: ${feature}`, node.loc ?? null);
623
+ };
624
+ var eraseTsVisitor = {
625
+ _(node, context) {
626
+ const n = context.next() ?? node;
627
+ delete n.typeAnnotation;
628
+ delete n.typeParameters;
629
+ delete n.typeArguments;
630
+ delete n.returnType;
631
+ delete n.accessibility;
632
+ delete n.readonly;
633
+ delete n.definite;
634
+ delete n.override;
635
+ },
636
+ Decorator(node) {
637
+ throwInvalidFeature(node, "decorators (related TSC proposal is not stage 4 yet)");
638
+ },
639
+ ImportDeclaration(node) {
640
+ if (node.importKind === "type")
641
+ return empty;
642
+ if (node.specifiers?.length > 0) {
643
+ const specifiers = node.specifiers.filter((s) => s.importKind !== "type");
644
+ if (specifiers.length === 0)
645
+ return empty;
646
+ return { ...node, specifiers };
647
+ }
648
+ return node;
649
+ },
650
+ ExportNamedDeclaration(node, context) {
651
+ if (node.exportKind === "type")
652
+ return empty;
653
+ if (node.declaration) {
654
+ const result = context.next();
655
+ if (result?.declaration?.type === "EmptyStatement") {
656
+ return empty;
657
+ }
658
+ return result;
659
+ }
660
+ if (node.specifiers) {
661
+ const specifiers = node.specifiers.filter((s) => s.exportKind !== "type");
662
+ if (specifiers.length === 0)
663
+ return empty;
664
+ return { ...node, specifiers };
665
+ }
666
+ return node;
667
+ },
668
+ ExportDefaultDeclaration(node) {
669
+ if (node.exportKind === "type")
670
+ return empty;
671
+ return node;
672
+ },
673
+ ExportAllDeclaration(node) {
674
+ if (node.exportKind === "type")
675
+ return empty;
676
+ return node;
677
+ },
678
+ PropertyDefinition(node, { next }) {
679
+ if (node.accessor) {
680
+ throwInvalidFeature(node, "accessor fields (related TSC proposal is not stage 4 yet)");
681
+ }
682
+ return next();
683
+ },
684
+ TSAsExpression(node, context) {
685
+ return context.visit(node.expression);
686
+ },
687
+ TSSatisfiesExpression(node, context) {
688
+ return context.visit(node.expression);
689
+ },
690
+ TSNonNullExpression(node, context) {
691
+ return context.visit(node.expression);
692
+ },
693
+ TSInterfaceDeclaration() {
694
+ return empty;
695
+ },
696
+ TSTypeAliasDeclaration() {
697
+ return empty;
698
+ },
699
+ TSTypeAssertion(node, context) {
700
+ return context.visit(node.expression);
701
+ },
702
+ TSEnumDeclaration(node) {
703
+ throwInvalidFeature(node, "enums");
704
+ },
705
+ TSParameterProperty(node, context) {
706
+ if ((node.readonly || node.accessibility) && context.path.at(-2)?.kind === "constructor") {
707
+ throwInvalidFeature(node, "accessibility modifiers on constructor parameters");
708
+ }
709
+ return context.visit(node.parameter);
710
+ },
711
+ TSInstantiationExpression(node, context) {
712
+ return context.visit(node.expression);
713
+ },
714
+ FunctionExpression: removeThisParameter,
715
+ FunctionDeclaration: removeThisParameter,
716
+ TSDeclareFunction() {
717
+ return empty;
718
+ },
719
+ ClassBody(node, context) {
720
+ const body = [];
721
+ for (const _child of node.body) {
722
+ const child = context.visit(_child);
723
+ if (child.type !== "PropertyDefinition" || !child.declare) {
724
+ body.push(child);
725
+ }
726
+ }
727
+ return {
728
+ ...node,
729
+ body
730
+ };
731
+ },
732
+ ClassDeclaration(node, context) {
733
+ if (node.declare) {
734
+ return empty;
735
+ }
736
+ delete node.abstract;
737
+ delete node.implements;
738
+ delete node.superTypeArguments;
739
+ return context.next();
740
+ },
741
+ ClassExpression(node, context) {
742
+ delete node.implements;
743
+ delete node.superTypeArguments;
744
+ return context.next();
745
+ },
746
+ MethodDefinition(node, context) {
747
+ if (node.abstract) {
748
+ return empty;
749
+ }
750
+ return context.next();
751
+ },
752
+ VariableDeclaration(node, context) {
753
+ if (node.declare) {
754
+ return empty;
755
+ }
756
+ return context.next();
757
+ },
758
+ TSModuleDeclaration(node, context) {
759
+ if (!node.body)
760
+ return empty;
761
+ const cleaned = node.body.body.map((entry) => context.visit(entry));
762
+ if (cleaned.some((entry) => entry !== empty)) {
763
+ throwInvalidFeature(node, "namespaces with non-type nodes");
764
+ }
765
+ return empty;
766
+ }
767
+ };
768
+ var eraseTs = (ast) => {
769
+ return walk2(ast, null, eraseTsVisitor);
770
+ };
771
+
772
+ // src/transform/index.ts
773
+ import { print as print2 } from "esrap";
774
+ import jsPrinter from "esrap/languages/ts";
775
+
776
+ // src/transform/gts.ts
777
+ import { walk as walk3 } from "zimmerframe";
778
+
779
+ // src/transform/constants.ts
780
+ var DEFAULT_SHORTCUT_FUNCTION_PRELUDES = [
781
+ "cryo",
782
+ "hydro",
783
+ "pyro",
784
+ "electro",
785
+ "anemo",
786
+ "geo",
787
+ "dendro",
788
+ "omni"
789
+ ];
790
+ var DEFAULT_QUERY_BINDINGS = ["my", "opp"];
791
+
792
+ // src/transform/gts.ts
793
+ var commonGtsVisitor = {
794
+ GTSDirectFunction(node, { visit, state }) {
795
+ return {
796
+ type: "ArrowFunctionExpression",
797
+ params: [],
798
+ body: {
799
+ type: "ObjectExpression",
800
+ properties: [
801
+ {
802
+ type: "Property",
803
+ key: { type: "Identifier", name: "name" },
804
+ computed: false,
805
+ kind: "init",
806
+ method: false,
807
+ shorthand: false,
808
+ value: state.ActionId,
809
+ loc: node.loc
810
+ },
811
+ {
812
+ type: "Property",
813
+ key: { type: "Identifier", name: "positionals" },
814
+ computed: false,
815
+ kind: "init",
816
+ method: false,
817
+ shorthand: false,
818
+ value: {
819
+ type: "ArrayExpression",
820
+ elements: [
821
+ {
822
+ type: "ArrowFunctionExpression",
823
+ params: state.shortcutFunctionParameters,
824
+ body: {
825
+ type: "BlockStatement",
826
+ body: node.body.map((stmt) => visit(stmt))
827
+ },
828
+ expression: false
829
+ }
830
+ ]
831
+ }
832
+ },
833
+ {
834
+ type: "Property",
835
+ key: { type: "Identifier", name: "named" },
836
+ computed: false,
837
+ kind: "init",
838
+ method: false,
839
+ shorthand: false,
840
+ value: {
841
+ type: "Literal",
842
+ value: null
843
+ }
844
+ }
845
+ ]
846
+ },
847
+ expression: true,
848
+ loc: node.loc
849
+ };
850
+ },
851
+ GTSShortcutFunctionExpression(node, { visit, state }) {
852
+ return {
853
+ type: "ArrowFunctionExpression",
854
+ params: state.shortcutFunctionParameters,
855
+ body: visit(node.body),
856
+ expression: node.expression,
857
+ loc: node.loc
858
+ };
859
+ },
860
+ GTSShortcutArgumentExpression(node, { state, visit }) {
861
+ return {
862
+ type: "MemberExpression",
863
+ object: state.fnArgId,
864
+ computed: false,
865
+ optional: false,
866
+ property: visit(node.property),
867
+ loc: node.loc
868
+ };
869
+ },
870
+ GTSQueryExpression(node, { state, visit }) {
871
+ state.hasQueryExpressions = true;
872
+ return {
873
+ ...node,
874
+ type: "CallExpression",
875
+ optional: false,
876
+ callee: state.queryFnId,
877
+ arguments: [
878
+ {
879
+ type: "ArrowFunctionExpression",
880
+ body: visit(node.argument),
881
+ params: state.queryParameters,
882
+ expression: true,
883
+ loc: node.argument.loc
884
+ },
885
+ {
886
+ type: "ObjectExpression",
887
+ properties: [
888
+ {
889
+ type: "Property",
890
+ key: { type: "Identifier", name: "star" },
891
+ computed: false,
892
+ kind: "init",
893
+ method: false,
894
+ shorthand: false,
895
+ value: {
896
+ type: "Literal",
897
+ value: !!node.star
898
+ }
899
+ }
900
+ ]
901
+ }
902
+ ]
903
+ };
904
+ }
905
+ };
906
+ var gtsVisitor = {
907
+ Program(node, { state, next }) {
908
+ node = next() ?? node;
909
+ const body = [...node.body];
910
+ if (state.externalizedBindings.length > 0) {
911
+ body.unshift({
912
+ type: "ImportDeclaration",
913
+ specifiers: [
914
+ {
915
+ type: "ImportDefaultSpecifier",
916
+ local: state.binderFnId
917
+ }
918
+ ],
919
+ source: {
920
+ type: "Literal",
921
+ value: `${state.providerImportSource}/binder`
922
+ },
923
+ attributes: []
924
+ }, ...state.externalizedBindings.flatMap((binding) => {
925
+ const internalDecl = {
926
+ type: "VariableDeclaration",
927
+ kind: "const",
928
+ declarations: [
929
+ {
930
+ type: "VariableDeclarator",
931
+ id: binding.internalId,
932
+ init: binding.value
933
+ }
934
+ ]
935
+ };
936
+ const externalDecl = {
937
+ type: "VariableDeclaration",
938
+ kind: "const",
939
+ declarations: [
940
+ {
941
+ type: "VariableDeclarator",
942
+ id: binding.bindingName,
943
+ init: {
944
+ type: "CallExpression",
945
+ optional: false,
946
+ callee: state.binderFnId,
947
+ arguments: [
948
+ binding.internalId,
949
+ {
950
+ type: "ObjectExpression",
951
+ properties: [
952
+ {
953
+ type: "Property",
954
+ key: { type: "Identifier", name: "path" },
955
+ computed: false,
956
+ kind: "init",
957
+ method: false,
958
+ shorthand: false,
959
+ value: {
960
+ type: "ArrayExpression",
961
+ elements: binding.path.map((segment) => ({
962
+ type: "Literal",
963
+ value: segment
964
+ }))
965
+ }
966
+ }
967
+ ]
968
+ }
969
+ ]
970
+ }
971
+ }
972
+ ]
973
+ };
974
+ return binding.export ? [
975
+ internalDecl,
976
+ {
977
+ type: "ExportNamedDeclaration",
978
+ declaration: externalDecl,
979
+ specifiers: [],
980
+ attributes: []
981
+ }
982
+ ] : [internalDecl, externalDecl];
983
+ }));
984
+ }
985
+ if (state.hasQueryExpressions) {
986
+ body.unshift({
987
+ type: "ImportDeclaration",
988
+ specifiers: [
989
+ {
990
+ type: "ImportDefaultSpecifier",
991
+ local: state.queryFnId
992
+ }
993
+ ],
994
+ source: {
995
+ type: "Literal",
996
+ value: `${state.providerImportSource}/query`
997
+ },
998
+ attributes: []
999
+ });
1000
+ }
1001
+ body.unshift({
1002
+ type: "ImportDeclaration",
1003
+ specifiers: [
1004
+ {
1005
+ type: "ImportSpecifier",
1006
+ imported: { type: "Identifier", name: "createDefine" },
1007
+ local: state.createDefineFnId
1008
+ },
1009
+ {
1010
+ type: "ImportSpecifier",
1011
+ imported: { type: "Identifier", name: "Action" },
1012
+ local: state.ActionId
1013
+ },
1014
+ {
1015
+ type: "ImportSpecifier",
1016
+ imported: { type: "Identifier", name: "Prelude" },
1017
+ local: state.preludeSymbolId
1018
+ }
1019
+ ],
1020
+ source: { type: "Literal", value: state.runtimeImportSource },
1021
+ attributes: []
1022
+ });
1023
+ return {
1024
+ ...node,
1025
+ body
1026
+ };
1027
+ },
1028
+ GTSDefineStatement(node, { state, visit }) {
1029
+ const body = visit(node.body);
1030
+ const wrapper = {
1031
+ type: "ObjectExpression",
1032
+ properties: [
1033
+ {
1034
+ type: "Property",
1035
+ key: { type: "Identifier", name: "attributes" },
1036
+ computed: false,
1037
+ kind: "init",
1038
+ method: false,
1039
+ shorthand: false,
1040
+ value: {
1041
+ type: "ArrayExpression",
1042
+ elements: [body]
1043
+ }
1044
+ }
1045
+ ]
1046
+ };
1047
+ return {
1048
+ type: "ExpressionStatement",
1049
+ expression: {
1050
+ type: "CallExpression",
1051
+ optional: false,
1052
+ callee: {
1053
+ ...state.createDefineFnId,
1054
+ loc: node.loc
1055
+ },
1056
+ arguments: [state.rootVmId, wrapper]
1057
+ },
1058
+ loc: node.loc
1059
+ };
1060
+ },
1061
+ GTSNamedAttributeDefinition(node, { visit, state }) {
1062
+ state.attributeNames.push(node.name);
1063
+ const namedBody = visit(node.body);
1064
+ state.attributeNames.pop();
1065
+ const properties = [...namedBody.properties];
1066
+ const nameValue = node.name.type === "Literal" ? node.name : {
1067
+ ...node.name,
1068
+ type: "Literal",
1069
+ value: node.name.name
1070
+ };
1071
+ properties.unshift({
1072
+ type: "Property",
1073
+ key: {
1074
+ type: "Identifier",
1075
+ name: "name"
1076
+ },
1077
+ computed: false,
1078
+ kind: "init",
1079
+ method: false,
1080
+ shorthand: false,
1081
+ value: nameValue,
1082
+ loc: node.loc
1083
+ });
1084
+ const body = { ...namedBody, properties };
1085
+ const arrow = {
1086
+ type: "ArrowFunctionExpression",
1087
+ params: [],
1088
+ expression: true,
1089
+ body,
1090
+ loc: node.loc
1091
+ };
1092
+ if (node.bindingName) {
1093
+ if (node.bindingAccessModifier === "protected") {
1094
+ throw new GtsTranspilerError("Protected bindings are not supported in this context.", node.loc ?? null);
1095
+ }
1096
+ const export_ = node.bindingAccessModifier !== "private";
1097
+ const internalId = {
1098
+ type: "Identifier",
1099
+ name: `__gts_internal_binding_${state.externalizedBindings.length}`
1100
+ };
1101
+ state.externalizedBindings.push({
1102
+ bindingName: node.bindingName,
1103
+ export: export_,
1104
+ internalId,
1105
+ value: arrow,
1106
+ path: [...state.attributeNames, node.name].map((n) => {
1107
+ if (n.type === "Literal") {
1108
+ return String(n.value);
1109
+ } else {
1110
+ return n.name;
1111
+ }
1112
+ })
1113
+ });
1114
+ return internalId;
1115
+ } else {
1116
+ return arrow;
1117
+ }
1118
+ },
1119
+ GTSAttributeBody(node, { visit }) {
1120
+ const positionals = visit(node.positionalAttributes);
1121
+ const named = node.namedAttributes ? visit(node.namedAttributes) : { type: "Literal", value: null };
1122
+ const partialBody = {
1123
+ type: "ObjectExpression",
1124
+ properties: [
1125
+ {
1126
+ type: "Property",
1127
+ key: { type: "Identifier", name: "positionals" },
1128
+ computed: false,
1129
+ kind: "init",
1130
+ method: false,
1131
+ shorthand: false,
1132
+ value: positionals,
1133
+ loc: positionals.loc
1134
+ },
1135
+ {
1136
+ type: "Property",
1137
+ key: { type: "Identifier", name: "named" },
1138
+ computed: false,
1139
+ kind: "init",
1140
+ method: false,
1141
+ shorthand: false,
1142
+ value: named,
1143
+ loc: named.loc
1144
+ }
1145
+ ],
1146
+ loc: node.loc
1147
+ };
1148
+ return partialBody;
1149
+ },
1150
+ GTSPositionalAttributeList(node, { visit }) {
1151
+ return {
1152
+ type: "ArrayExpression",
1153
+ elements: node.attributes.map((attr) => {
1154
+ if (attr.type === "Identifier" && /^[a-z_]/.test(attr.name)) {
1155
+ return {
1156
+ ...attr,
1157
+ type: "Literal",
1158
+ value: attr.name
1159
+ };
1160
+ } else {
1161
+ return visit(attr);
1162
+ }
1163
+ }),
1164
+ loc: node.loc
1165
+ };
1166
+ },
1167
+ GTSNamedAttributeBlock(node, { visit }) {
1168
+ const attributes = node.attributes.map((node2) => visit(node2));
1169
+ if (node.directAction) {
1170
+ attributes.push(visit(node.directAction));
1171
+ }
1172
+ return {
1173
+ type: "ObjectExpression",
1174
+ properties: [
1175
+ {
1176
+ type: "Property",
1177
+ key: { type: "Identifier", name: "attributes" },
1178
+ computed: false,
1179
+ kind: "init",
1180
+ method: false,
1181
+ shorthand: false,
1182
+ value: {
1183
+ type: "ArrayExpression",
1184
+ elements: attributes
1185
+ }
1186
+ }
1187
+ ],
1188
+ loc: node.loc
1189
+ };
1190
+ },
1191
+ ...commonGtsVisitor
1192
+ };
1193
+ var initialTranspileState = (option = {}) => {
1194
+ const shortcutFunctionPreludes = option.shortcutFunctionPreludes ?? DEFAULT_SHORTCUT_FUNCTION_PRELUDES;
1195
+ const queryBindings = option.queryBindings ?? DEFAULT_QUERY_BINDINGS;
1196
+ const fnArgId = { type: "Identifier", name: "__gts_fnArg" };
1197
+ const preludeSymbolId = {
1198
+ type: "Identifier",
1199
+ name: "__gts_Prelude"
1200
+ };
1201
+ const shortcutFunctionParameters = [
1202
+ fnArgId,
1203
+ {
1204
+ type: "AssignmentPattern",
1205
+ left: {
1206
+ type: "ObjectPattern",
1207
+ properties: shortcutFunctionPreludes.map((name) => ({
1208
+ type: "Property",
1209
+ computed: false,
1210
+ key: { type: "Identifier", name },
1211
+ value: { type: "Identifier", name },
1212
+ kind: "init",
1213
+ method: false,
1214
+ shorthand: true
1215
+ }))
1216
+ },
1217
+ right: {
1218
+ type: "MemberExpression",
1219
+ object: fnArgId,
1220
+ property: preludeSymbolId,
1221
+ computed: true,
1222
+ optional: false
1223
+ }
1224
+ }
1225
+ ];
1226
+ const queryParameters = [
1227
+ {
1228
+ type: "ObjectPattern",
1229
+ properties: queryBindings.map((name) => ({
1230
+ type: "Property",
1231
+ computed: false,
1232
+ key: { type: "Identifier", name },
1233
+ value: { type: "Identifier", name },
1234
+ kind: "init",
1235
+ method: false,
1236
+ shorthand: true
1237
+ }))
1238
+ }
1239
+ ];
1240
+ return {
1241
+ createDefineFnId: { type: "Identifier", name: "__gts_createDefine" },
1242
+ ActionId: { type: "Identifier", name: "__gts_Action" },
1243
+ preludeSymbolId,
1244
+ fnArgId,
1245
+ shortcutFunctionParameters,
1246
+ rootVmId: { type: "Identifier", name: "__gts_rootVm" },
1247
+ binderFnId: { type: "Identifier", name: "__gts_Binder" },
1248
+ queryFnId: { type: "Identifier", name: "__gts_query" },
1249
+ queryParameters,
1250
+ runtimeImportSource: option.runtimeImportSource ?? "@gi-tcg/gts-runtime",
1251
+ providerImportSource: option.providerImportSource ?? "@gi-tcg/core/gts",
1252
+ queryArg: {
1253
+ type: "ObjectPattern",
1254
+ properties: (option.queryBindings ?? []).map((name) => ({
1255
+ type: "Property",
1256
+ key: { type: "Identifier", name },
1257
+ computed: false,
1258
+ kind: "init",
1259
+ method: false,
1260
+ shorthand: true,
1261
+ value: { type: "Identifier", name }
1262
+ }))
1263
+ },
1264
+ attributeNames: [],
1265
+ externalizedBindings: [],
1266
+ hasQueryExpressions: false
1267
+ };
1268
+ };
1269
+ var gtsToTs = (ast, option = {}) => {
1270
+ const state = initialTranspileState(option);
1271
+ return walk3(ast, state, gtsVisitor);
1272
+ };
1273
+
1274
+ // src/transform/volar/index.ts
1275
+ import { walk as walk5 } from "zimmerframe";
1276
+ import { print } from "esrap";
1277
+ import tsPrinter from "esrap/languages/ts";
1278
+
1279
+ // src/transform/volar/replacements.ts
1280
+ var createReplacementHolder = (state, value) => {
1281
+ const rawValue = JSON.stringify(value);
1282
+ return {
1283
+ type: "ExpressionStatement",
1284
+ expression: {
1285
+ type: "TaggedTemplateExpression",
1286
+ tag: state.replacementTag,
1287
+ quasi: {
1288
+ type: "TemplateLiteral",
1289
+ expressions: [],
1290
+ quasis: [
1291
+ {
1292
+ type: "TemplateElement",
1293
+ value: { raw: rawValue },
1294
+ tail: true
1295
+ }
1296
+ ]
1297
+ }
1298
+ }
1299
+ };
1300
+ };
1301
+ function applyReplacements(state, code) {
1302
+ const replacementRegex = new RegExp("\\b" + state.replacementTag.name + "`(.*?)`", "gm");
1303
+ const {
1304
+ symbolsId: { NamedDefinition, Meta }
1305
+ } = state;
1306
+ return code.replace(replacementRegex, (_, rawPayload) => {
1307
+ const payload = JSON.parse(rawPayload);
1308
+ if (payload.type === "enterVMFromRoot") {
1309
+ return `type ${payload.defType} = (typeof ${payload.vm})[${NamedDefinition.name}]; type ${payload.metaType} = ${payload.defType}[${Meta.name}];`;
1310
+ } else if (payload.type === "enterVMFromAttr") {
1311
+ return `type ${payload.defType} = ${payload.returnType} extends { namedDefinition: infer Def } ? Def : { [${Meta.name}]: unknown }; type ${payload.metaType} = ${payload.defType}[${Meta.name}];`;
1312
+ } else if (payload.type === "exitVM") {
1313
+ const lhs = `${payload.finalMetaType}_lhs`;
1314
+ const requiredAttrsNs = `${payload.finalMetaType}_rans`;
1315
+ const collectedAttrsExpr = `${payload.collectedAttrs.join(" | ")}`;
1316
+ const needleString = `null! as ${requiredAttrsNs}.RequiredAttributes`;
1317
+ if (payload.errorLoc) {
1318
+ state.additionalMappings.set(payload.errorLoc, needleString);
1319
+ }
1320
+ return `type ${payload.finalMetaType} = ${payload.metaType}; const ${lhs}: { [${Meta.name}]: ${payload.metaType} } & Omit<${payload.defType}, ${Meta.name}> = 0 as any; type ${lhs} = typeof ${lhs}; namespace ${requiredAttrsNs} { export type CollectedAttributes = ${collectedAttrsExpr}; export type RequiredAttributes = { [K in keyof ${payload.defType}]: ${lhs}[K] extends { required(this: ${lhs}): true } ? K : never }[keyof ${payload.defType}]; }; ((_: ${requiredAttrsNs}.CollectedAttributes) => 0)(${needleString});`;
1321
+ } else if (payload.type === "enterAttr") {
1322
+ return `const ${payload.lhs}: { [${Meta.name}]: ${payload.metaType} } & Omit<${payload.defType}, ${Meta.name}> = 0 as any;`;
1323
+ } else if (payload.type === "createBindingTyping") {
1324
+ const typingIdLhs = `${payload.typingId}_lhs`;
1325
+ return `type ${typingIdLhs} = { [${Meta.name}]: ${payload.finalMetaType}; as: ${payload.defType}[${payload.attrName}] extends { as: infer As } ? As : unknown }; let ${typingIdLhs}!: ${typingIdLhs}; let ${payload.typingId} = ${typingIdLhs}.as(); type ${payload.typingId} = typeof ${payload.typingId};`;
1326
+ } else if (payload.type === "exitAttr") {
1327
+ return `type ${payload.returnType} = typeof ${payload.returnType}; type ${payload.newMetaType} = ${payload.returnType} extends { rewriteMeta: infer NewMeta extends {} } ? NewMeta : ${payload.oldMetaType}`;
1328
+ } else {
1329
+ return "";
1330
+ }
1331
+ });
1332
+ }
1333
+
1334
+ // src/transform/volar/walker.ts
1335
+ var EMPTY = { type: "EmptyStatement" };
1336
+ var ANY = {
1337
+ type: "TSAnyKeyword"
1338
+ };
1339
+ var ANY_INIT = {
1340
+ type: "TSAsExpression",
1341
+ expression: { type: "Literal", value: 0 },
1342
+ typeAnnotation: ANY
1343
+ };
1344
+ var emitPreface = (state) => {
1345
+ if (state.prefaceInserted) {
1346
+ return;
1347
+ }
1348
+ const symbolsLhs = {
1349
+ type: "TSQualifiedName",
1350
+ left: { type: "Identifier", name: state.rootVmId.name },
1351
+ right: { type: "Identifier", name: "_symbols" }
1352
+ };
1353
+ for (const symbolName of [
1354
+ "Meta",
1355
+ "Action",
1356
+ "NamedDefinition",
1357
+ "Prelude"
1358
+ ]) {
1359
+ const init = {
1360
+ type: "TSTypeQuery",
1361
+ exprName: {
1362
+ type: "TSQualifiedName",
1363
+ left: symbolsLhs,
1364
+ right: { type: "Identifier", name: symbolName }
1365
+ }
1366
+ };
1367
+ const symbolId = symbolName === "Action" ? state.ActionId : symbolName === "Prelude" ? state.preludeSymbolId : state.symbolsId[symbolName];
1368
+ state.pendingStatements.push({
1369
+ type: "TSTypeAliasDeclaration",
1370
+ id: symbolId,
1371
+ typeAnnotation: init
1372
+ }, {
1373
+ type: "VariableDeclaration",
1374
+ kind: "const",
1375
+ declarations: [
1376
+ {
1377
+ type: "VariableDeclarator",
1378
+ id: {
1379
+ ...symbolId,
1380
+ typeAnnotation: {
1381
+ type: "TSTypeAnnotation",
1382
+ typeAnnotation: {
1383
+ type: "TSTypeReference",
1384
+ typeName: symbolId
1385
+ }
1386
+ }
1387
+ },
1388
+ init: ANY_INIT
1389
+ }
1390
+ ]
1391
+ });
1392
+ }
1393
+ state.prefaceInserted = true;
1394
+ };
1395
+ var enterVMFromRoot = (state) => {
1396
+ emitPreface(state);
1397
+ let defTypeId = {
1398
+ type: "Identifier",
1399
+ name: `__gts_rootVmDefType_${state.idCounter++}`
1400
+ };
1401
+ let metaTypeId = {
1402
+ type: "Identifier",
1403
+ name: `__gts_rootVmInitMetaType_${state.idCounter++}`
1404
+ };
1405
+ let finalMetaTypeId = {
1406
+ type: "Identifier",
1407
+ name: `__gts_rootVmFinalMetaType_${state.idCounter++}`
1408
+ };
1409
+ state.pendingStatements.push(createReplacementHolder(state, {
1410
+ type: "enterVMFromRoot",
1411
+ vm: state.rootVmId.name,
1412
+ defType: defTypeId.name,
1413
+ metaType: metaTypeId.name
1414
+ }));
1415
+ state.vmDefTypeIdStack.push(defTypeId);
1416
+ state.metaTypeIdStack.push(metaTypeId);
1417
+ state.finalMetaTypeIdStack.push(finalMetaTypeId);
1418
+ state.attrsOfCurrentVm.push([]);
1419
+ };
1420
+ var enterVMFromAttr = (state, returningId) => {
1421
+ const defTypeId = {
1422
+ type: "Identifier",
1423
+ name: `__gts_nestedVm_${state.idCounter++}`
1424
+ };
1425
+ const metaTypeId = {
1426
+ type: "Identifier",
1427
+ name: `__gts_nestedVmInitMetaType_${state.idCounter++}`
1428
+ };
1429
+ const finalMetaTypeId = {
1430
+ type: "Identifier",
1431
+ name: `__gts_nestedVmFinalMetaType_${state.idCounter++}`
1432
+ };
1433
+ state.pendingStatements.push(createReplacementHolder(state, {
1434
+ type: "enterVMFromAttr",
1435
+ returnType: returningId.name,
1436
+ defType: defTypeId.name,
1437
+ metaType: metaTypeId.name
1438
+ }));
1439
+ state.vmDefTypeIdStack.push(defTypeId);
1440
+ state.metaTypeIdStack.push(metaTypeId);
1441
+ state.finalMetaTypeIdStack.push(finalMetaTypeId);
1442
+ state.attrsOfCurrentVm.push([]);
1443
+ };
1444
+ var exitVM = (state, errorLoc) => {
1445
+ const currentDefTypeId = state.vmDefTypeIdStack.pop();
1446
+ const currentMetaId = state.metaTypeIdStack.pop();
1447
+ const finalMetaId = state.finalMetaTypeIdStack.pop();
1448
+ const collectedAttrNames = state.attrsOfCurrentVm.pop();
1449
+ state.pendingStatements.push(createReplacementHolder(state, {
1450
+ type: "exitVM",
1451
+ metaType: currentMetaId.name,
1452
+ defType: currentDefTypeId.name,
1453
+ finalMetaType: finalMetaId.name,
1454
+ collectedAttrs: collectedAttrNames,
1455
+ errorLoc
1456
+ }));
1457
+ };
1458
+ var enterAttr = (state, attrName) => {
1459
+ const defTypeId = state.vmDefTypeIdStack.at(-1);
1460
+ const metaTypeId = state.metaTypeIdStack.at(-1);
1461
+ if (!defTypeId || !metaTypeId) {
1462
+ return { lhsId: { type: "Identifier", name: "__invalid_attr_obj" } };
1463
+ }
1464
+ state.attrsOfCurrentVm.at(-1).push(attrName);
1465
+ const lhsId = {
1466
+ type: "Identifier",
1467
+ name: `__gts_attr_obj_${state.idCounter++}`
1468
+ };
1469
+ state.pendingStatements.push(createReplacementHolder(state, {
1470
+ type: "enterAttr",
1471
+ defType: defTypeId.name,
1472
+ metaType: metaTypeId.name,
1473
+ lhs: lhsId.name
1474
+ }));
1475
+ return { lhsId };
1476
+ };
1477
+ var genBindingTyping = (state, info) => {
1478
+ const finalMetaId = state.finalMetaTypeIdStack.at(-1);
1479
+ const defTypeId = state.vmDefTypeIdStack.at(-1);
1480
+ if (!finalMetaId || !defTypeId) {
1481
+ return;
1482
+ }
1483
+ state.pendingStatements.push(createReplacementHolder(state, {
1484
+ type: "createBindingTyping",
1485
+ finalMetaType: finalMetaId.name,
1486
+ defType: defTypeId.name,
1487
+ attrName: info.attrName,
1488
+ typingId: info.typingId.name
1489
+ }));
1490
+ };
1491
+ var exitAttr = (state, returningId) => {
1492
+ const currentDefId = state.vmDefTypeIdStack.at(-1);
1493
+ if (!currentDefId) {
1494
+ return;
1495
+ }
1496
+ const newMetaTypeId = {
1497
+ type: "Identifier",
1498
+ name: `__gts_newMeta__${state.idCounter++}`
1499
+ };
1500
+ const [oldMetaTypeId] = state.metaTypeIdStack.splice(-1, 1, newMetaTypeId);
1501
+ state.pendingStatements.push(createReplacementHolder(state, {
1502
+ type: "exitAttr",
1503
+ defType: currentDefId.name,
1504
+ oldMetaType: oldMetaTypeId.name,
1505
+ newMetaType: newMetaTypeId.name,
1506
+ returnType: returningId.name
1507
+ }));
1508
+ };
1509
+ var gtsToTypingsWalker = {
1510
+ Program(node, { state, visit }) {
1511
+ const body = [];
1512
+ for (const stmt of node.body) {
1513
+ if (stmt.type === "GTSDefineStatement") {
1514
+ state.defineLeadingComments = stmt.leadingComments;
1515
+ visit(stmt);
1516
+ body.push(...state.pendingStatements);
1517
+ state.pendingStatements = [];
1518
+ } else {
1519
+ body.push(visit(stmt));
1520
+ }
1521
+ }
1522
+ if (state.externalizedBindings.length > 0) {
1523
+ body.unshift({
1524
+ type: "ImportDeclaration",
1525
+ specifiers: [
1526
+ {
1527
+ type: "ImportDefaultSpecifier",
1528
+ local: state.binderFnId
1529
+ }
1530
+ ],
1531
+ source: {
1532
+ type: "Literal",
1533
+ value: `${state.providerImportSource}/binder`
1534
+ },
1535
+ attributes: []
1536
+ }, ...state.externalizedBindings.flatMap((binding) => {
1537
+ const internalDecl = {
1538
+ type: "VariableDeclaration",
1539
+ kind: "const",
1540
+ declarations: [
1541
+ {
1542
+ type: "VariableDeclarator",
1543
+ id: binding.internalId,
1544
+ init: binding.value
1545
+ }
1546
+ ]
1547
+ };
1548
+ const externalDecl = {
1549
+ type: "VariableDeclaration",
1550
+ kind: "const",
1551
+ declarations: [
1552
+ {
1553
+ type: "VariableDeclarator",
1554
+ id: binding.bindingName,
1555
+ init: {
1556
+ type: "CallExpression",
1557
+ optional: false,
1558
+ callee: state.binderFnId,
1559
+ arguments: [
1560
+ binding.internalId,
1561
+ {
1562
+ type: "ObjectExpression",
1563
+ properties: [
1564
+ {
1565
+ type: "Property",
1566
+ key: { type: "Identifier", name: "path" },
1567
+ computed: false,
1568
+ kind: "init",
1569
+ method: false,
1570
+ shorthand: false,
1571
+ value: {
1572
+ type: "ArrayExpression",
1573
+ elements: binding.path.map((segment) => ({
1574
+ type: "Literal",
1575
+ value: segment
1576
+ }))
1577
+ }
1578
+ }
1579
+ ]
1580
+ }
1581
+ ]
1582
+ }
1583
+ }
1584
+ ]
1585
+ };
1586
+ return binding.export ? [
1587
+ internalDecl,
1588
+ {
1589
+ type: "ExportNamedDeclaration",
1590
+ declaration: externalDecl,
1591
+ specifiers: [],
1592
+ attributes: [],
1593
+ leadingComments: binding.leadingComments
1594
+ }
1595
+ ] : [
1596
+ internalDecl,
1597
+ {
1598
+ ...externalDecl,
1599
+ leadingComments: binding.leadingComments
1600
+ }
1601
+ ];
1602
+ }));
1603
+ }
1604
+ if (state.prefaceInserted) {
1605
+ body.unshift({
1606
+ type: "ImportDeclaration",
1607
+ specifiers: [
1608
+ {
1609
+ type: "ImportDefaultSpecifier",
1610
+ local: state.rootVmId
1611
+ }
1612
+ ],
1613
+ source: {
1614
+ type: "Literal",
1615
+ value: `${state.providerImportSource}/rootVM`
1616
+ },
1617
+ attributes: []
1618
+ });
1619
+ }
1620
+ if (state.hasQueryExpressions) {
1621
+ body.unshift({
1622
+ type: "ImportDeclaration",
1623
+ specifiers: [
1624
+ {
1625
+ type: "ImportDefaultSpecifier",
1626
+ local: state.queryFnId
1627
+ }
1628
+ ],
1629
+ source: {
1630
+ type: "Literal",
1631
+ value: `${state.providerImportSource}/query`
1632
+ },
1633
+ attributes: []
1634
+ });
1635
+ }
1636
+ return {
1637
+ ...node,
1638
+ body
1639
+ };
1640
+ },
1641
+ GTSDefineStatement(node, { state, visit }) {
1642
+ enterVMFromRoot(state);
1643
+ visit(node.body);
1644
+ exitVM(state);
1645
+ return EMPTY;
1646
+ },
1647
+ GTSNamedAttributeDefinition(node, { visit, state }) {
1648
+ const { name, body, bindingName } = node;
1649
+ const attrName = JSON.stringify(name.type === "Literal" ? String(name.value) : name.name);
1650
+ const { lhsId } = enterAttr(state, attrName);
1651
+ const positionals = body.positionalAttributes.attributes.map((attr) => {
1652
+ if (attr.type === "Identifier" && /^[a-z_]/.test(attr.name)) {
1653
+ const token = state.leafTokens.find((t) => t.loc === attr.loc);
1654
+ if (token) {
1655
+ token.locationAdjustment = {
1656
+ startOffset: 1,
1657
+ generatedLength: attr.name.length + 2
1658
+ };
1659
+ }
1660
+ return {
1661
+ type: "Literal",
1662
+ value: attr.name,
1663
+ loc: attr.loc
1664
+ };
1665
+ } else {
1666
+ return visit(attr);
1667
+ }
1668
+ });
1669
+ const returnValue = {
1670
+ type: "Identifier",
1671
+ name: `__gts_attrRet_${state.idCounter++}`
1672
+ };
1673
+ state.pendingStatements.push({
1674
+ type: "VariableDeclaration",
1675
+ kind: "const",
1676
+ declarations: [
1677
+ {
1678
+ type: "VariableDeclarator",
1679
+ id: returnValue,
1680
+ init: {
1681
+ type: "CallExpression",
1682
+ optional: false,
1683
+ callee: {
1684
+ type: "MemberExpression",
1685
+ object: lhsId,
1686
+ property: name,
1687
+ computed: name.type === "Literal",
1688
+ optional: false
1689
+ },
1690
+ arguments: positionals
1691
+ }
1692
+ }
1693
+ ]
1694
+ });
1695
+ if (body.namedAttributes) {
1696
+ enterVMFromAttr(state, returnValue);
1697
+ visit(body.namedAttributes);
1698
+ exitVM(state, `${body.namedAttributes.loc?.start.line}:${body.namedAttributes.loc?.start.column}`);
1699
+ }
1700
+ if (bindingName) {
1701
+ const export_ = node.bindingAccessModifier !== "private";
1702
+ const internalId = {
1703
+ type: "Identifier",
1704
+ name: `__gts_internal_binding_${state.externalizedBindings.length}`
1705
+ };
1706
+ const typingId = {
1707
+ type: "Identifier",
1708
+ name: `gts_binding_type_${state.externalizedBindings.length}`
1709
+ };
1710
+ genBindingTyping(state, {
1711
+ attrName,
1712
+ typingId
1713
+ });
1714
+ state.externalizedBindings.push({
1715
+ bindingName: {
1716
+ ...bindingName,
1717
+ typeAnnotation: {
1718
+ type: "TSTypeAnnotation",
1719
+ typeAnnotation: {
1720
+ type: "TSTypeReference",
1721
+ typeName: typingId
1722
+ }
1723
+ }
1724
+ },
1725
+ export: export_,
1726
+ internalId,
1727
+ value: { type: "Literal", value: null },
1728
+ path: [...state.attributeNames, node.name].map((n) => {
1729
+ if (n.type === "Literal") {
1730
+ return String(n.value);
1731
+ } else {
1732
+ return n.name;
1733
+ }
1734
+ }),
1735
+ typingId,
1736
+ leadingComments: state.defineLeadingComments
1737
+ });
1738
+ }
1739
+ exitAttr(state, returnValue);
1740
+ return EMPTY;
1741
+ },
1742
+ GTSNamedAttributeBlock(node, { state, visit }) {
1743
+ for (const attr of node.attributes) {
1744
+ visit(attr);
1745
+ }
1746
+ if (node.directAction) {
1747
+ const { lhsId } = enterAttr(state, state.ActionId.name);
1748
+ const fn = {
1749
+ type: "ArrowFunctionExpression",
1750
+ params: state.shortcutFunctionParameters,
1751
+ body: {
1752
+ type: "BlockStatement",
1753
+ body: node.directAction.body.map((stmt) => visit(stmt))
1754
+ },
1755
+ expression: false
1756
+ };
1757
+ const returnValue = {
1758
+ type: "Identifier",
1759
+ name: `__gts_attrRet_${state.idCounter++}`
1760
+ };
1761
+ state.pendingStatements.push({
1762
+ type: "VariableDeclaration",
1763
+ kind: "const",
1764
+ declarations: [
1765
+ {
1766
+ type: "VariableDeclarator",
1767
+ id: returnValue,
1768
+ init: {
1769
+ type: "CallExpression",
1770
+ optional: false,
1771
+ callee: {
1772
+ type: "MemberExpression",
1773
+ object: lhsId,
1774
+ property: state.ActionId,
1775
+ computed: true,
1776
+ optional: false
1777
+ },
1778
+ arguments: [fn]
1779
+ }
1780
+ }
1781
+ ]
1782
+ });
1783
+ }
1784
+ return EMPTY;
1785
+ },
1786
+ ...commonGtsVisitor,
1787
+ GTSShortcutArgumentExpression(node, { state, visit }) {
1788
+ const lhs = { ...state.fnArgId };
1789
+ return {
1790
+ type: "MemberExpression",
1791
+ object: lhs,
1792
+ computed: false,
1793
+ optional: false,
1794
+ property: visit(node.property)
1795
+ };
1796
+ }
1797
+ };
1798
+
1799
+ // src/transform/volar/mappings.ts
1800
+ import { decode } from "@jridgewell/sourcemap-codec";
1801
+ var DEFAULT_VOLAR_MAPPING_DATA = {
1802
+ completion: true,
1803
+ format: true,
1804
+ navigation: true,
1805
+ semantic: true,
1806
+ structure: true,
1807
+ verification: true
1808
+ };
1809
+ function buildSrcToGenMap(source_map, line_offsets, generated_code) {
1810
+ const map = new Map;
1811
+ const decoded = decode(source_map.mappings);
1812
+ const line_col_to_byte_offset = (line, column) => {
1813
+ return line_offsets[line - 1] + column;
1814
+ };
1815
+ const adjusted_segments = [];
1816
+ for (let generated_line = 0;generated_line < decoded.length; generated_line++) {
1817
+ const line = decoded[generated_line];
1818
+ adjusted_segments[generated_line] = [];
1819
+ for (const segment of line) {
1820
+ if (segment.length >= 4) {
1821
+ let adjusted_line = generated_line + 1;
1822
+ let adjusted_column = segment[0];
1823
+ adjusted_segments[generated_line].push({
1824
+ line: adjusted_line,
1825
+ column: adjusted_column,
1826
+ sourceLine: segment[2],
1827
+ sourceColumn: segment[3]
1828
+ });
1829
+ }
1830
+ }
1831
+ }
1832
+ for (let line_idx = 0;line_idx < adjusted_segments.length; line_idx++) {
1833
+ const line_segments = adjusted_segments[line_idx];
1834
+ for (let seg_idx = 0;seg_idx < line_segments.length; seg_idx++) {
1835
+ const segment = line_segments[seg_idx];
1836
+ const line = segment.line;
1837
+ const column = segment.column;
1838
+ let end_line = line;
1839
+ let end_column = column;
1840
+ if (seg_idx + 1 < line_segments.length) {
1841
+ const next_segment = line_segments[seg_idx + 1];
1842
+ end_line = next_segment.line;
1843
+ end_column = next_segment.column;
1844
+ } else if (line_idx + 1 < adjusted_segments.length && adjusted_segments[line_idx + 1].length > 0) {
1845
+ const next_segment = adjusted_segments[line_idx + 1][0];
1846
+ end_line = next_segment.line;
1847
+ end_column = next_segment.column;
1848
+ }
1849
+ const start_offset = line_col_to_byte_offset(line, column);
1850
+ const end_offset = line_col_to_byte_offset(end_line, end_column);
1851
+ const code_snippet = generated_code.slice(start_offset, end_offset);
1852
+ segment.sourceLine += 1;
1853
+ const key = `${segment.sourceLine}:${segment.sourceColumn}`;
1854
+ const gen_pos = {
1855
+ line,
1856
+ column,
1857
+ end_line,
1858
+ end_column,
1859
+ code: code_snippet,
1860
+ metadata: {}
1861
+ };
1862
+ if (!map.has(key)) {
1863
+ map.set(key, []);
1864
+ }
1865
+ map.get(key).push(gen_pos);
1866
+ }
1867
+ }
1868
+ return map;
1869
+ }
1870
+ function getGeneratedPosition(src_line, src_column, srcToGenMap) {
1871
+ const key = `${src_line}:${src_column}`;
1872
+ const positions = srcToGenMap.get(key);
1873
+ if (!positions || positions.length === 0) {}
1874
+ return positions?.[0];
1875
+ }
1876
+ function createLineOffsets(content) {
1877
+ const lines = content.split(`
1878
+ `);
1879
+ const offsets = [];
1880
+ let currentOffset = 0;
1881
+ for (const line of lines) {
1882
+ offsets.push(currentOffset);
1883
+ currentOffset += line.length + 1;
1884
+ }
1885
+ return offsets;
1886
+ }
1887
+ function locToOffset(line, column, line_offsets) {
1888
+ if (line < 1 || line > line_offsets.length) {}
1889
+ return line_offsets[line - 1] + column;
1890
+ }
1891
+ function convertToVolarMappings(generated, source, sourceMap, tokens, additionalMappings) {
1892
+ const sourceLineOffsets = createLineOffsets(source);
1893
+ const generatedLineOffsets = createLineOffsets(generated);
1894
+ const srcToGenMap = buildSrcToGenMap(sourceMap, generatedLineOffsets, generated);
1895
+ const mappings = [];
1896
+ for (const token of tokens) {
1897
+ let sourceStart = locToOffset(token.loc.start.line, token.loc.start.column, sourceLineOffsets);
1898
+ const sourceEnd = locToOffset(token.loc.end.line, token.loc.end.column, sourceLineOffsets);
1899
+ let sourceLength = token.sourceLength ?? sourceEnd - sourceStart;
1900
+ const genLineCol = getGeneratedPosition(token.loc.start.line, token.loc.start.column, srcToGenMap);
1901
+ if (!genLineCol) {
1902
+ continue;
1903
+ }
1904
+ let genStart = locToOffset(genLineCol.line, genLineCol.column, generatedLineOffsets);
1905
+ if (token.locationAdjustment) {
1906
+ mappings.push({
1907
+ sourceOffsets: [sourceStart],
1908
+ generatedOffsets: [genStart],
1909
+ lengths: [0],
1910
+ generatedLengths: [token.locationAdjustment.generatedLength],
1911
+ data: {
1912
+ verification: true
1913
+ }
1914
+ });
1915
+ genStart += token.locationAdjustment.startOffset;
1916
+ }
1917
+ if (token.isDummy) {
1918
+ while (sourceStart > 0 && /\s/.test(source[sourceStart - 1])) {
1919
+ sourceStart--;
1920
+ sourceLength++;
1921
+ }
1922
+ }
1923
+ const generatedLength = token.generatedLength ?? sourceLength;
1924
+ mappings.push({
1925
+ sourceOffsets: [sourceStart],
1926
+ generatedOffsets: [genStart],
1927
+ lengths: [sourceLength],
1928
+ generatedLengths: [generatedLength],
1929
+ data: DEFAULT_VOLAR_MAPPING_DATA
1930
+ });
1931
+ }
1932
+ for (const [loc, codeSnippet] of additionalMappings) {
1933
+ const generatedStart = generated.indexOf(codeSnippet);
1934
+ if (generatedStart === -1) {
1935
+ continue;
1936
+ }
1937
+ const [lineStr, columnStr] = loc.split(":");
1938
+ const line = Number(lineStr);
1939
+ const column = Number(columnStr);
1940
+ const sourceStart = locToOffset(line, column, sourceLineOffsets);
1941
+ const sourceLength = 1;
1942
+ const generatedLength = codeSnippet.length;
1943
+ mappings.push({
1944
+ sourceOffsets: [sourceStart],
1945
+ generatedOffsets: [generatedStart],
1946
+ lengths: [sourceLength],
1947
+ generatedLengths: [generatedLength],
1948
+ data: {
1949
+ verification: true
1950
+ }
1951
+ });
1952
+ }
1953
+ mappings.sort((a, b) => a.sourceOffsets[0] - b.sourceOffsets[0]);
1954
+ return mappings;
1955
+ }
1956
+
1957
+ // src/transform/volar/collect_tokens.ts
1958
+ import { walk as walk4 } from "zimmerframe";
1959
+ function isLeafNode(node) {
1960
+ for (const key in node) {
1961
+ const val = node[key];
1962
+ if (key === "loc" || key === "start" || key === "end" || key === "range") {
1963
+ continue;
1964
+ }
1965
+ if (val && typeof val === "object" && typeof val.type === "string") {
1966
+ return false;
1967
+ }
1968
+ if (Array.isArray(val) && val.length > 0 && typeof val[0].type === "string") {
1969
+ return false;
1970
+ }
1971
+ }
1972
+ return true;
1973
+ }
1974
+ function collectLeafTokens(ast) {
1975
+ const tokens = [];
1976
+ walk4(ast, tokens, {
1977
+ _(node, { state, next }) {
1978
+ if (isLeafNode(node) && node.loc) {
1979
+ const token = {
1980
+ loc: node.loc
1981
+ };
1982
+ if (node.isDummy) {
1983
+ token.isDummy = true;
1984
+ token.sourceLength = 0;
1985
+ token.generatedLength = 1;
1986
+ }
1987
+ state.push(token);
1988
+ }
1989
+ next();
1990
+ }
1991
+ });
1992
+ return tokens;
1993
+ }
1994
+
1995
+ // src/transform/volar/index.ts
1996
+ function gtsToTypings(ast, option) {
1997
+ const state = {
1998
+ ...initialTranspileState(option),
1999
+ leafTokens: option.leafTokens,
2000
+ idCounter: 0,
2001
+ pendingStatements: [],
2002
+ prefaceInserted: false,
2003
+ rootVmId: { type: "Identifier", name: "__root_vm" },
2004
+ replacementTag: { type: "Identifier", name: "__gts_replacement_tag" },
2005
+ symbolsId: {
2006
+ Meta: { type: "Identifier", name: "__gts_symbols_meta" },
2007
+ NamedDefinition: { type: "Identifier", name: "__gts_symbols_namedDef" }
2008
+ },
2009
+ vmDefTypeIdStack: [],
2010
+ metaTypeIdStack: [],
2011
+ finalMetaTypeIdStack: [],
2012
+ attrsOfCurrentVm: [],
2013
+ additionalMappings: option.additionalMappings
2014
+ };
2015
+ const newAst = walk5(ast, state, gtsToTypingsWalker);
2016
+ const printer = tsPrinter({
2017
+ getLeadingComments: (node) => node.leadingComments,
2018
+ getTrailingComments: (node) => node.trailingComments
2019
+ });
2020
+ const prevIdentifier = printer.Identifier;
2021
+ printer.Identifier = function(node, context) {
2022
+ if (node.isDummy) {
2023
+ context.write("", node);
2024
+ } else {
2025
+ prevIdentifier(node, context);
2026
+ }
2027
+ };
2028
+ const { code, map } = print(newAst, printer, {
2029
+ indent: " "
2030
+ });
2031
+ return {
2032
+ code: applyReplacements(state, code),
2033
+ sourceMap: map
2034
+ };
2035
+ }
2036
+ function transformForVolar(ast, option, sourceInfo) {
2037
+ const tokens = collectLeafTokens(ast);
2038
+ const additionalMappings = new Map;
2039
+ const { code, sourceMap } = gtsToTypings(ast, {
2040
+ ...option,
2041
+ leafTokens: tokens,
2042
+ additionalMappings
2043
+ });
2044
+ const volarMappings = convertToVolarMappings(code, sourceInfo.content, sourceMap, tokens, additionalMappings);
2045
+ return {
2046
+ code,
2047
+ mappings: volarMappings
2048
+ };
2049
+ }
2050
+
2051
+ // src/transform/index.ts
2052
+ function transform(ast, option = {}, sourceInfo = {}) {
2053
+ const ts = gtsToTs(ast, option);
2054
+ const js = eraseTs(ts);
2055
+ const { code, map } = print2(js, jsPrinter(), {
2056
+ indent: " ",
2057
+ sourceMapContent: sourceInfo.content,
2058
+ sourceMapSource: sourceInfo.filename
2059
+ });
2060
+ return {
2061
+ code,
2062
+ sourceMap: map
2063
+ };
2064
+ }
2065
+
2066
+ // src/index.ts
2067
+ function transpile(source, filename, option) {
2068
+ const ast = parse(source);
2069
+ return transform(ast, option, {
2070
+ content: source,
2071
+ filename
2072
+ });
2073
+ }
2074
+ function transpileForVolar(source, filename, option) {
2075
+ const ast = parseLoose(source);
2076
+ return transformForVolar(ast, option, {
2077
+ content: source,
2078
+ filename
2079
+ });
2080
+ }
2081
+ export {
2082
+ transpileForVolar,
2083
+ transpile,
2084
+ GtsTranspilerError
2085
+ };