@gi-tcg/gts-transpiler 0.3.1 → 0.3.2

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