@gi-tcg/gts-transpiler 0.3.1 → 0.3.3

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