crankscript 0.10.5 → 0.10.7

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/package.json CHANGED
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "name": "crankscript",
3
- "version": "0.10.5",
3
+ "version": "0.10.7",
4
4
  "scripts": {
5
5
  "dev": "tsx src/index.ts",
6
- "post-build": "tsc-alias --project tsconfig.json",
7
- "prepare-assets": "npx tsc -p assets/tsconfig.json"
6
+ "post-build": "tsc-alias --project tsconfig.json"
8
7
  },
9
8
  "bin": {
10
9
  "crankscript": "./src/index.js"
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
2
3
  import open from 'open';
3
4
  import { useMemo } from 'react';
4
5
  import { isWindows } from '../../../utils/platform.js';
@@ -23,12 +24,13 @@ export const useCompileTasks = (pdcPath)=>{
23
24
  runningDescription: 'Compiling lua code...',
24
25
  finishedDescription: ()=>'Lua code compiled',
25
26
  runner: async ()=>{
27
+ const currentDirectory = process.cwd();
26
28
  await open('', {
27
29
  app: {
28
30
  name: pdcPath,
29
31
  arguments: [
30
- 'Source',
31
- 'Game.pdx'
32
+ join(currentDirectory, 'Source'),
33
+ join(currentDirectory, 'Game.pdx')
32
34
  ]
33
35
  }
34
36
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/cli/src/commands/CompileCommand/hooks/useCompileTasks.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport open from 'open';\nimport { useMemo } from 'react';\nimport { CheckListItem } from '@/cli/types.js';\nimport { isWindows } from '@/cli/utils/platform.js';\n\nexport const useCompileTasks = (pdcPath: string) => {\n return useMemo(\n () => [\n {\n waitingDescription: 'Waiting to check for pdc binary...',\n errorDescription: 'Could not find pdc binary',\n runningDescription: 'Checking for pdc binary...',\n finishedDescription: (result) =>\n `Found pdc binary at \"${result}\"`,\n runner: async () => {\n if (!existsSync(pdcPath)) {\n throw new Error('Could not find pdc binary');\n }\n\n return pdcPath;\n },\n ready: true,\n } satisfies CheckListItem<string>,\n {\n waitingDescription: 'Waiting for pdc binary path...',\n errorDescription: 'Could not compile lua code',\n runningDescription: 'Compiling lua code...',\n finishedDescription: () => 'Lua code compiled',\n runner: async () => {\n await open('', {\n app: {\n name: pdcPath,\n arguments: ['Source', 'Game.pdx'],\n },\n });\n\n if (isWindows) {\n // Wait for pdc.exe to compile\n // See https://github.com/sindresorhus/open/issues/298\n await new Promise((resolve) =>\n setTimeout(resolve, 1000)\n );\n }\n },\n ready: true,\n },\n ],\n []\n ) as CheckListItem<unknown>[];\n};\n"],"names":["existsSync","open","useMemo","isWindows","useCompileTasks","pdcPath","waitingDescription","errorDescription","runningDescription","finishedDescription","result","runner","Error","ready","app","name","arguments","Promise","resolve","setTimeout"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,UAAU,QAAQ,UAAU;AACrC,OAAOC,UAAU,OAAO;AACxB,SAASC,OAAO,QAAQ,QAAQ;AAEhC,SAASC,SAAS,QAAQ,0BAA0B;AAEpD,OAAO,MAAMC,kBAAkB,CAACC;IAC5B,OAAOH,QACH,IAAM;YACF;gBACII,oBAAoB;gBACpBC,kBAAkB;gBAClBC,oBAAoB;gBACpBC,qBAAqB,CAACC,SAClB,CAAC,qBAAqB,EAAEA,OAAO,CAAC,CAAC;gBACrCC,QAAQ;oBACJ,IAAI,CAACX,WAAWK,UAAU;wBACtB,MAAM,IAAIO,MAAM;oBACpB;oBAEA,OAAOP;gBACX;gBACAQ,OAAO;YACX;YACA;gBACIP,oBAAoB;gBACpBC,kBAAkB;gBAClBC,oBAAoB;gBACpBC,qBAAqB,IAAM;gBAC3BE,QAAQ;oBACJ,MAAMV,KAAK,IAAI;wBACXa,KAAK;4BACDC,MAAMV;4BACNW,WAAW;gCAAC;gCAAU;6BAAW;wBACrC;oBACJ;oBAEA,IAAIb,WAAW;wBACX,8BAA8B;wBAC9B,sDAAsD;wBACtD,MAAM,IAAIc,QAAQ,CAACC,UACfC,WAAWD,SAAS;oBAE5B;gBACJ;gBACAL,OAAO;YACX;SACH,EACD,EAAE;AAEV,EAAE"}
1
+ {"version":3,"sources":["../../../../../../../libs/cli/src/commands/CompileCommand/hooks/useCompileTasks.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport open from 'open';\nimport { useMemo } from 'react';\nimport { CheckListItem } from '@/cli/types.js';\nimport { isWindows } from '@/cli/utils/platform.js';\n\nexport const useCompileTasks = (pdcPath: string) => {\n return useMemo(\n () => [\n {\n waitingDescription: 'Waiting to check for pdc binary...',\n errorDescription: 'Could not find pdc binary',\n runningDescription: 'Checking for pdc binary...',\n finishedDescription: (result) =>\n `Found pdc binary at \"${result}\"`,\n runner: async () => {\n if (!existsSync(pdcPath)) {\n throw new Error('Could not find pdc binary');\n }\n\n return pdcPath;\n },\n ready: true,\n } satisfies CheckListItem<string>,\n {\n waitingDescription: 'Waiting for pdc binary path...',\n errorDescription: 'Could not compile lua code',\n runningDescription: 'Compiling lua code...',\n finishedDescription: () => 'Lua code compiled',\n runner: async () => {\n const currentDirectory = process.cwd();\n\n await open('', {\n app: {\n name: pdcPath,\n arguments: [\n join(currentDirectory, 'Source'),\n join(currentDirectory, 'Game.pdx'),\n ],\n },\n });\n\n if (isWindows) {\n // Wait for pdc.exe to compile\n // See https://github.com/sindresorhus/open/issues/298\n await new Promise((resolve) =>\n setTimeout(resolve, 1000)\n );\n }\n },\n ready: true,\n },\n ],\n []\n ) as CheckListItem<unknown>[];\n};\n"],"names":["existsSync","join","open","useMemo","isWindows","useCompileTasks","pdcPath","waitingDescription","errorDescription","runningDescription","finishedDescription","result","runner","Error","ready","currentDirectory","process","cwd","app","name","arguments","Promise","resolve","setTimeout"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,UAAU,QAAQ,UAAU;AACrC,SAASC,IAAI,QAAQ,YAAY;AACjC,OAAOC,UAAU,OAAO;AACxB,SAASC,OAAO,QAAQ,QAAQ;AAEhC,SAASC,SAAS,QAAQ,0BAA0B;AAEpD,OAAO,MAAMC,kBAAkB,CAACC;IAC5B,OAAOH,QACH,IAAM;YACF;gBACII,oBAAoB;gBACpBC,kBAAkB;gBAClBC,oBAAoB;gBACpBC,qBAAqB,CAACC,SAClB,CAAC,qBAAqB,EAAEA,OAAO,CAAC,CAAC;gBACrCC,QAAQ;oBACJ,IAAI,CAACZ,WAAWM,UAAU;wBACtB,MAAM,IAAIO,MAAM;oBACpB;oBAEA,OAAOP;gBACX;gBACAQ,OAAO;YACX;YACA;gBACIP,oBAAoB;gBACpBC,kBAAkB;gBAClBC,oBAAoB;gBACpBC,qBAAqB,IAAM;gBAC3BE,QAAQ;oBACJ,MAAMG,mBAAmBC,QAAQC,GAAG;oBAEpC,MAAMf,KAAK,IAAI;wBACXgB,KAAK;4BACDC,MAAMb;4BACNc,WAAW;gCACPnB,KAAKc,kBAAkB;gCACvBd,KAAKc,kBAAkB;6BAC1B;wBACL;oBACJ;oBAEA,IAAIX,WAAW;wBACX,8BAA8B;wBAC9B,sDAAsD;wBACtD,MAAM,IAAIiB,QAAQ,CAACC,UACfC,WAAWD,SAAS;oBAE5B;gBACJ;gBACAR,OAAO;YACX;SACH,EACD,EAAE;AAEV,EAAE"}
@@ -0,0 +1,23 @@
1
+ const getString = ()=>{
2
+ return 'some-string';
3
+ };
4
+ let A = class A {
5
+ constructor(firstArgument, otherArgument){
6
+ print(firstArgument);
7
+ print(otherArgument);
8
+ }
9
+ };
10
+ let B = class B extends A {
11
+ constructor(firstArgument, secondArgument, thirdArgument){
12
+ print(firstArgument);
13
+ print(secondArgument);
14
+ print(thirdArgument);
15
+ var _getString;
16
+ super(firstArgument, (_getString = getString()) != null ? _getString : 'hello');
17
+ }
18
+ };
19
+ playdate.update = ()=>{
20
+ printTable(new B(0, 1, 2));
21
+ };
22
+
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../../../libs/cli/src/commands/TranspileCommand/fn/_tests/test-super/src/index.ts"],"sourcesContent":["const getString = () => {\n return 'some-string';\n};\n\nclass A {\n constructor(firstArgument: number, otherArgument: string) {\n print(firstArgument);\n print(otherArgument);\n }\n}\n\nclass B extends A {\n constructor(\n firstArgument: number,\n secondArgument: number,\n thirdArgument: number\n ) {\n print(firstArgument);\n print(secondArgument);\n print(thirdArgument);\n\n super(firstArgument, getString() ?? 'hello');\n }\n}\n\nplaydate.update = () => {\n printTable(new B(0, 1, 2));\n};\n"],"names":["getString","A","constructor","firstArgument","otherArgument","print","B","secondArgument","thirdArgument","playdate","update","printTable"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,MAAMA,YAAY;IACd,OAAO;AACX;AAEA,IAAA,AAAMC,IAAN,MAAMA;IACFC,YAAYC,aAAqB,EAAEC,aAAqB,CAAE;QACtDC,MAAMF;QACNE,MAAMD;IACV;AACJ;AAEA,IAAA,AAAME,IAAN,MAAMA,UAAUL;IACZC,YACIC,aAAqB,EACrBI,cAAsB,EACtBC,aAAqB,CACvB;QACEH,MAAMF;QACNE,MAAME;QACNF,MAAMG;YAEeR;QAArB,KAAK,CAACG,eAAeH,CAAAA,aAAAA,uBAAAA,aAAe;IACxC;AACJ;AAEAS,SAASC,MAAM,GAAG;IACdC,WAAW,IAAIL,EAAE,GAAG,GAAG;AAC3B"}
@@ -1 +1,2 @@
1
- export declare const transpile: (path: string) => void;
1
+ import * as tstl from 'typescript-to-lua';
2
+ export declare const transpile: (path: string) => tstl.EmitResult;
@@ -3,14 +3,14 @@ import * as tstl from 'typescript-to-lua';
3
3
  import { LuaTarget } from 'typescript-to-lua';
4
4
  import { RootFolder } from '../../../constants.js';
5
5
  export const transpile = (path)=>{
6
- tstl.transpileProject(join(path, 'tsconfig.json'), {
6
+ return tstl.transpileProject(join(path, 'tsconfig.json'), {
7
7
  luaTarget: LuaTarget.Lua54,
8
8
  outDir: join(path, 'Source'),
9
9
  luaBundle: 'main.lua',
10
10
  luaBundleEntry: join(path, 'src', 'index.ts'),
11
11
  luaPlugins: [
12
12
  {
13
- name: join(RootFolder, 'assets', 'plugin.js')
13
+ name: join(RootFolder, 'assets', 'index.js')
14
14
  }
15
15
  ]
16
16
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/cli/src/commands/TranspileCommand/fn/transpile.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as tstl from 'typescript-to-lua';\nimport { LuaTarget } from 'typescript-to-lua';\nimport { RootFolder } from '@/cli/constants.js';\n\nexport const transpile = (path: string) => {\n tstl.transpileProject(join(path, 'tsconfig.json'), {\n luaTarget: LuaTarget.Lua54,\n outDir: join(path, 'Source'),\n luaBundle: 'main.lua',\n luaBundleEntry: join(path, 'src', 'index.ts'),\n luaPlugins: [\n {\n name: join(RootFolder, 'assets', 'plugin.js'),\n },\n ],\n });\n};\n"],"names":["join","tstl","LuaTarget","RootFolder","transpile","path","transpileProject","luaTarget","Lua54","outDir","luaBundle","luaBundleEntry","luaPlugins","name"],"rangeMappings":";;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,IAAI,QAAQ,YAAY;AACjC,YAAYC,UAAU,oBAAoB;AAC1C,SAASC,SAAS,QAAQ,oBAAoB;AAC9C,SAASC,UAAU,QAAQ,qBAAqB;AAEhD,OAAO,MAAMC,YAAY,CAACC;IACtBJ,KAAKK,gBAAgB,CAACN,KAAKK,MAAM,kBAAkB;QAC/CE,WAAWL,UAAUM,KAAK;QAC1BC,QAAQT,KAAKK,MAAM;QACnBK,WAAW;QACXC,gBAAgBX,KAAKK,MAAM,OAAO;QAClCO,YAAY;YACR;gBACIC,MAAMb,KAAKG,YAAY,UAAU;YACrC;SACH;IACL;AACJ,EAAE"}
1
+ {"version":3,"sources":["../../../../../../../libs/cli/src/commands/TranspileCommand/fn/transpile.ts"],"sourcesContent":["import { join } from 'node:path';\nimport * as tstl from 'typescript-to-lua';\nimport { LuaTarget } from 'typescript-to-lua';\nimport { RootFolder } from '@/cli/constants.js';\n\nexport const transpile = (path: string) => {\n return tstl.transpileProject(join(path, 'tsconfig.json'), {\n luaTarget: LuaTarget.Lua54,\n outDir: join(path, 'Source'),\n luaBundle: 'main.lua',\n luaBundleEntry: join(path, 'src', 'index.ts'),\n luaPlugins: [\n {\n name: join(RootFolder, 'assets', 'index.js'),\n },\n ],\n });\n};\n"],"names":["join","tstl","LuaTarget","RootFolder","transpile","path","transpileProject","luaTarget","Lua54","outDir","luaBundle","luaBundleEntry","luaPlugins","name"],"rangeMappings":";;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,IAAI,QAAQ,YAAY;AACjC,YAAYC,UAAU,oBAAoB;AAC1C,SAASC,SAAS,QAAQ,oBAAoB;AAC9C,SAASC,UAAU,QAAQ,qBAAqB;AAEhD,OAAO,MAAMC,YAAY,CAACC;IACtB,OAAOJ,KAAKK,gBAAgB,CAACN,KAAKK,MAAM,kBAAkB;QACtDE,WAAWL,UAAUM,KAAK;QAC1BC,QAAQT,KAAKK,MAAM;QACnBK,WAAW;QACXC,gBAAgBX,KAAKK,MAAM,OAAO;QAClCO,YAAY;YACR;gBACIC,MAAMb,KAAKG,YAAY,UAAU;YACrC;SACH;IACL;AACJ,EAAE"}
package/assets/plugin.js DELETED
@@ -1,260 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var _a;
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.transformSuperExpression = exports.transformClassDeclaration = void 0;
28
- exports.transformPropertyName = transformPropertyName;
29
- var ts = __importStar(require("typescript"));
30
- var tstl = __importStar(require("typescript-to-lua"));
31
- var lua = __importStar(require("typescript-to-lua/dist/LuaAST"));
32
- var scope_1 = require("typescript-to-lua/dist/transformation/utils/scope");
33
- var call_1 = require("typescript-to-lua/dist/transformation/visitors/call");
34
- var fields_1 = require("typescript-to-lua/dist/transformation/visitors/class/members/fields");
35
- var utils_1 = require("typescript-to-lua/dist/transformation/visitors/class/utils");
36
- var function_1 = require("typescript-to-lua/dist/transformation/visitors/function");
37
- var importMap = {
38
- graphics: new Set(['graphics']),
39
- sprites: new Set(['sprite']),
40
- crank: new Set(['getCrankTicks']),
41
- object: new Set(['printTable']),
42
- 'utilities/where': new Set(['where']),
43
- easing: new Set(['easingFunctions']),
44
- nineSlice: new Set(['nineSlice']),
45
- qrcode: new Set(['generateQRCode']),
46
- animation: new Set(['animation']),
47
- animator: new Set(['animator']),
48
- keyboard: new Set(['keyboard']),
49
- math: new Set(['math']),
50
- string: new Set(['string']),
51
- timer: new Set(['timer']),
52
- frameTimer: new Set(['frameTimer']),
53
- ui: new Set(['ui']),
54
- };
55
- var imports = new Set();
56
- function createClassCall(context, className, extendsNode) {
57
- // class('X')
58
- var classCall = tstl.createCallExpression(tstl.createIdentifier('class'), [tstl.createStringLiteral(className.text)]);
59
- var classCreationExpression;
60
- if (extendsNode) {
61
- // class('X').extends(Blah)
62
- classCreationExpression = tstl.createCallExpression(tstl.createTableIndexExpression(classCall, tstl.createStringLiteral('extends')), [context.transformExpression(extendsNode.expression)]);
63
- }
64
- else {
65
- classCreationExpression = tstl.createCallExpression(tstl.createTableIndexExpression(classCall, tstl.createStringLiteral('extends')), [tstl.createIdentifier('Object')]);
66
- }
67
- return tstl.createExpressionStatement(classCreationExpression);
68
- }
69
- function transformPropertyName(context, node) {
70
- if (ts.isComputedPropertyName(node)) {
71
- return context.transformExpression(node.expression);
72
- }
73
- else if (ts.isIdentifier(node)) {
74
- return tstl.createStringLiteral(node.text);
75
- }
76
- else if (ts.isPrivateIdentifier(node)) {
77
- throw new Error('PrivateIdentifier is not supported');
78
- }
79
- else {
80
- return context.transformExpression(node);
81
- }
82
- }
83
- function transformConstructor(context, className, instanceFields, constructor) {
84
- var methodName = 'init';
85
- context.pushScope(scope_1.ScopeType.Function);
86
- var bodyStatements = [];
87
- var params;
88
- if (constructor) {
89
- params = (0, function_1.transformParameters)(context, constructor === null || constructor === void 0 ? void 0 : constructor.parameters, tstl.createIdentifier('self'))[0];
90
- }
91
- else {
92
- params = [tstl.createIdentifier('self')];
93
- }
94
- bodyStatements.push(tstl.createExpressionStatement(tstl.createCallExpression(tstl.createTableIndexExpression(tstl.createTableIndexExpression(className, tstl.createStringLiteral('super')), tstl.createStringLiteral('init')), params)));
95
- var classInstanceFields = (0, fields_1.transformClassInstanceFields)(context, instanceFields);
96
- // initializers have to come before any body of the constructor
97
- bodyStatements.push.apply(bodyStatements, classInstanceFields);
98
- if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
99
- var body = (0, function_1.transformFunctionBodyContent)(context, constructor.body);
100
- // if the first expression in the body is a super call, ignore it, because we have
101
- // constructed our own super call.
102
- // if it's not, make sure to include the entire body.
103
- var firstStatement = constructor.body.statements[0];
104
- if (firstStatement &&
105
- ts.isExpressionStatement(firstStatement) &&
106
- ts.isCallExpression(firstStatement.expression) &&
107
- firstStatement.expression.expression.kind ===
108
- ts.SyntaxKind.SuperKeyword) {
109
- bodyStatements.push.apply(bodyStatements, body.slice(1));
110
- }
111
- else {
112
- bodyStatements.push.apply(bodyStatements, body);
113
- }
114
- }
115
- context.popScope();
116
- return tstl.createAssignmentStatement(tstl.createTableIndexExpression(className, tstl.createStringLiteral(methodName)), tstl.createFunctionExpression(tstl.createBlock(bodyStatements), params));
117
- }
118
- function transformMethodDeclaration(context, node, className) {
119
- var functionExpression = (0, function_1.transformFunctionToExpression)(context, node)[0];
120
- return tstl.createAssignmentStatement(tstl.createTableIndexExpression(className, transformPropertyName(context, node.name)), functionExpression);
121
- }
122
- var transformClassDeclaration = function (declaration, context) {
123
- imports.add('object');
124
- var className;
125
- if (declaration.name) {
126
- className = tstl.createIdentifier(declaration.name.text);
127
- }
128
- else {
129
- className = tstl.createIdentifier(context.createTempName('class'), declaration);
130
- }
131
- var extension = (0, utils_1.getExtendedNode)(declaration);
132
- if (context.classSuperInfos) {
133
- context.classSuperInfos.push({
134
- className: className,
135
- extendedTypeNode: extension,
136
- });
137
- }
138
- else {
139
- context.classSuperInfos = [{ className: className, extendedTypeNode: extension }];
140
- }
141
- // Get all properties with value
142
- var properties = declaration.members
143
- .filter(ts.isPropertyDeclaration)
144
- .filter(function (member) { return member.initializer; });
145
- // Divide properties into static and non-static
146
- var instanceFields = properties.filter(function (prop) { return !(0, utils_1.isStaticNode)(prop); });
147
- var statements = [];
148
- // class('X')
149
- statements.push(createClassCall(context, className, extension));
150
- // function X:init()
151
- // X.super.init(self)
152
- // end
153
- var constructor = declaration.members.find(function (n) {
154
- return ts.isConstructorDeclaration(n) && n.body !== undefined;
155
- });
156
- var transformedConstructor = transformConstructor(context, className, instanceFields, constructor);
157
- if (transformedConstructor) {
158
- statements.push(transformedConstructor);
159
- }
160
- var methods = declaration.members
161
- .filter(ts.isMethodDeclaration)
162
- .map(function (method) { return transformMethodDeclaration(context, method, className); })
163
- .filter(function (method) { return method !== undefined; });
164
- statements.push.apply(statements, methods);
165
- // export the class if needed
166
- // todo: check if there is a cleaner way to do this
167
- if ('localSymbol' in declaration &&
168
- typeof declaration.localSymbol === 'object' &&
169
- 'exportSymbol' in declaration.localSymbol &&
170
- typeof declaration.localSymbol.exportSymbol === 'object' &&
171
- 'escapedName' in declaration.localSymbol.exportSymbol &&
172
- typeof declaration.localSymbol.exportSymbol.escapedName === 'string') {
173
- var escapedName = declaration.localSymbol.exportSymbol.escapedName;
174
- statements.push(tstl.createAssignmentStatement(tstl.createTableIndexExpression(tstl.createIdentifier('____exports'), tstl.createStringLiteral(escapedName)), className));
175
- }
176
- return statements;
177
- };
178
- exports.transformClassDeclaration = transformClassDeclaration;
179
- var transformNewExpression = function (node, context) {
180
- var _a;
181
- var signature = context.checker.getResolvedSignature(node);
182
- var _b = (0, call_1.transformCallAndArguments)(context, node.expression, (_a = node.arguments) !== null && _a !== void 0 ? _a : [ts.factory.createTrue()], signature), name = _b[0], params = _b[1];
183
- return tstl.createCallExpression(name, params);
184
- };
185
- var transformSuperExpression = function (expression, context) {
186
- var superInfos = context.classSuperInfos;
187
- var superInfo = undefined;
188
- if (superInfos) {
189
- superInfo = superInfos[superInfos.length - 1];
190
- }
191
- if (!superInfo)
192
- return lua.createAnonymousIdentifier(expression);
193
- var className = superInfo.className;
194
- // Using `super` without extended type node is a TypeScript error
195
- // const extendsExpression = extendedTypeNode?.expression;
196
- // let baseClassName: lua.AssignmentLeftHandSideExpression | undefined;
197
- // if (extendsExpression && ts.isIdentifier(extendsExpression)) {
198
- // const symbol = context.checker.getSymbolAtLocation(extendsExpression);
199
- // if (symbol && !isSymbolExported(context, symbol)) {
200
- // // Use "baseClassName" if base is a simple identifier
201
- // baseClassName = transformIdentifier(context, extendsExpression);
202
- // }
203
- // }
204
- // if (!baseClassName) {
205
- // // Use "className.____super" if the base is not a simple identifier
206
- // baseClassName = lua.createTableIndexExpression(
207
- // className,
208
- // lua.createStringLiteral('____super'),
209
- // expression
210
- // );
211
- // }
212
- return lua.createTableIndexExpression(className, lua.createStringLiteral('super'));
213
- };
214
- exports.transformSuperExpression = transformSuperExpression;
215
- var processName = function (name) {
216
- for (var _i = 0, _a = Object.entries(importMap); _i < _a.length; _i++) {
217
- var _b = _a[_i], key = _b[0], value = _b[1];
218
- if (value instanceof Set && value.has(name)) {
219
- imports.add(key);
220
- }
221
- }
222
- };
223
- var plugin = {
224
- beforeEmit: function (_, __, ___, result) {
225
- var importsString = Array.from(imports)
226
- .map(function (importString) { return "import \"CoreLibs/".concat(importString, "\""); })
227
- .join('\n');
228
- if (importsString.trim() === '') {
229
- return;
230
- }
231
- result[0].code = "-- These imports were added automatically\n\n".concat(importsString, "\n\n-- End of automatic imports\n\n").concat(result[0].code);
232
- },
233
- visitors: (_a = {},
234
- _a[ts.SyntaxKind.ClassDeclaration] = exports.transformClassDeclaration,
235
- _a[ts.SyntaxKind.SuperKeyword] = exports.transformSuperExpression,
236
- _a[ts.SyntaxKind.NewExpression] = transformNewExpression,
237
- _a[ts.SyntaxKind.PropertyAccessExpression] = function (node, context) {
238
- if (ts.isIdentifier(node.expression)) {
239
- processName(node.name.text);
240
- }
241
- return context.superTransformExpression(node);
242
- },
243
- _a[ts.SyntaxKind.CallExpression] = function (node, context) {
244
- if (ts.isIdentifier(node.expression)) {
245
- processName(node.expression.escapedText.toString());
246
- }
247
- if (ts.isIdentifier(node.expression) &&
248
- node.expression.escapedText === 'require') {
249
- var normalNode = context.superTransformExpression(node);
250
- normalNode.expression.text = 'import';
251
- normalNode.expression.originalName = 'import';
252
- return normalNode;
253
- }
254
- else {
255
- return context.superTransformExpression(node);
256
- }
257
- },
258
- _a),
259
- };
260
- exports.default = plugin;
package/assets/plugin.ts DELETED
@@ -1,372 +0,0 @@
1
- import * as ts from 'typescript';
2
- import * as tstl from 'typescript-to-lua';
3
- import { FunctionVisitor, TransformationContext } from 'typescript-to-lua';
4
- import * as lua from 'typescript-to-lua/dist/LuaAST';
5
- import { ScopeType } from 'typescript-to-lua/dist/transformation/utils/scope';
6
- import { transformCallAndArguments } from 'typescript-to-lua/dist/transformation/visitors/call';
7
- import { transformClassInstanceFields } from 'typescript-to-lua/dist/transformation/visitors/class/members/fields';
8
- import {
9
- getExtendedNode,
10
- isStaticNode,
11
- } from 'typescript-to-lua/dist/transformation/visitors/class/utils';
12
- import {
13
- transformFunctionBodyContent,
14
- transformFunctionToExpression,
15
- transformParameters,
16
- } from 'typescript-to-lua/dist/transformation/visitors/function';
17
-
18
- const importMap = {
19
- graphics: new Set(['graphics']),
20
- sprites: new Set(['sprite']),
21
- crank: new Set(['getCrankTicks']),
22
- object: new Set(['printTable']),
23
- 'utilities/where': new Set(['where']),
24
- easing: new Set(['easingFunctions']),
25
- nineSlice: new Set(['nineSlice']),
26
- qrcode: new Set(['generateQRCode']),
27
- animation: new Set(['animation']),
28
- animator: new Set(['animator']),
29
- keyboard: new Set(['keyboard']),
30
- math: new Set(['math']),
31
- string: new Set(['string']),
32
- timer: new Set(['timer']),
33
- frameTimer: new Set(['frameTimer']),
34
- ui: new Set(['ui']),
35
- };
36
-
37
- const imports = new Set<string>();
38
-
39
- function createClassCall(
40
- context: tstl.TransformationContext,
41
- className: tstl.Identifier,
42
- extendsNode?: ts.ExpressionWithTypeArguments
43
- ): tstl.Statement {
44
- // class('X')
45
- const classCall = tstl.createCallExpression(
46
- tstl.createIdentifier('class'),
47
- [tstl.createStringLiteral(className.text)]
48
- );
49
- let classCreationExpression: tstl.Expression;
50
- if (extendsNode) {
51
- // class('X').extends(Blah)
52
- classCreationExpression = tstl.createCallExpression(
53
- tstl.createTableIndexExpression(
54
- classCall,
55
- tstl.createStringLiteral('extends')
56
- ),
57
- [context.transformExpression(extendsNode.expression)]
58
- );
59
- } else {
60
- classCreationExpression = tstl.createCallExpression(
61
- tstl.createTableIndexExpression(
62
- classCall,
63
- tstl.createStringLiteral('extends')
64
- ),
65
- [tstl.createIdentifier('Object')]
66
- );
67
- }
68
- return tstl.createExpressionStatement(classCreationExpression);
69
- }
70
-
71
- export function transformPropertyName(
72
- context: TransformationContext,
73
- node: ts.PropertyName
74
- ): tstl.Expression {
75
- if (ts.isComputedPropertyName(node)) {
76
- return context.transformExpression(node.expression);
77
- } else if (ts.isIdentifier(node)) {
78
- return tstl.createStringLiteral(node.text);
79
- } else if (ts.isPrivateIdentifier(node)) {
80
- throw new Error('PrivateIdentifier is not supported');
81
- } else {
82
- return context.transformExpression(node);
83
- }
84
- }
85
-
86
- function transformConstructor(
87
- context: TransformationContext,
88
- className: tstl.Identifier,
89
- instanceFields: ts.PropertyDeclaration[],
90
- constructor?: ts.ConstructorDeclaration
91
- ): tstl.Statement | undefined {
92
- const methodName = 'init';
93
- context.pushScope(ScopeType.Function);
94
- const bodyStatements: tstl.Statement[] = [];
95
- let params: tstl.Identifier[];
96
- if (constructor) {
97
- [params] = transformParameters(
98
- context,
99
- constructor?.parameters,
100
- tstl.createIdentifier('self')
101
- );
102
- } else {
103
- params = [tstl.createIdentifier('self')];
104
- }
105
- bodyStatements.push(
106
- tstl.createExpressionStatement(
107
- tstl.createCallExpression(
108
- tstl.createTableIndexExpression(
109
- tstl.createTableIndexExpression(
110
- className,
111
- tstl.createStringLiteral('super')
112
- ),
113
- tstl.createStringLiteral('init')
114
- ),
115
- params
116
- )
117
- )
118
- );
119
- const classInstanceFields = transformClassInstanceFields(
120
- context,
121
- instanceFields
122
- );
123
- // initializers have to come before any body of the constructor
124
- bodyStatements.push(...classInstanceFields);
125
- if (constructor?.body) {
126
- const body = transformFunctionBodyContent(context, constructor.body);
127
- // if the first expression in the body is a super call, ignore it, because we have
128
- // constructed our own super call.
129
- // if it's not, make sure to include the entire body.
130
- const firstStatement = constructor.body.statements[0];
131
- if (
132
- firstStatement &&
133
- ts.isExpressionStatement(firstStatement) &&
134
- ts.isCallExpression(firstStatement.expression) &&
135
- firstStatement.expression.expression.kind ===
136
- ts.SyntaxKind.SuperKeyword
137
- ) {
138
- bodyStatements.push(...body.slice(1));
139
- } else {
140
- bodyStatements.push(...body);
141
- }
142
- }
143
- context.popScope();
144
- return tstl.createAssignmentStatement(
145
- tstl.createTableIndexExpression(
146
- className,
147
- tstl.createStringLiteral(methodName)
148
- ),
149
- tstl.createFunctionExpression(tstl.createBlock(bodyStatements), params)
150
- );
151
- }
152
-
153
- function transformMethodDeclaration(
154
- context: TransformationContext,
155
- node: ts.MethodDeclaration,
156
- className: tstl.Identifier
157
- ): tstl.Statement | undefined {
158
- const [functionExpression] = transformFunctionToExpression(context, node);
159
- return tstl.createAssignmentStatement(
160
- tstl.createTableIndexExpression(
161
- className,
162
- transformPropertyName(context, node.name)
163
- ),
164
- functionExpression
165
- );
166
- }
167
- interface ClassSuperInfo {
168
- className: lua.Identifier;
169
- extendedTypeNode?: ts.ExpressionWithTypeArguments;
170
- }
171
-
172
- export const transformClassDeclaration: FunctionVisitor<
173
- ts.ClassLikeDeclaration
174
- > = (
175
- declaration,
176
- context: TransformationContext & { classSuperInfos?: [ClassSuperInfo] }
177
- ) => {
178
- imports.add('object');
179
-
180
- let className: tstl.Identifier;
181
- if (declaration.name) {
182
- className = tstl.createIdentifier(declaration.name.text);
183
- } else {
184
- className = tstl.createIdentifier(
185
- context.createTempName('class'),
186
- declaration
187
- );
188
- }
189
-
190
- const extension = getExtendedNode(declaration);
191
- if (context.classSuperInfos) {
192
- context.classSuperInfos.push({
193
- className,
194
- extendedTypeNode: extension,
195
- });
196
- } else {
197
- context.classSuperInfos = [{ className, extendedTypeNode: extension }];
198
- }
199
-
200
- // Get all properties with value
201
- const properties = declaration.members
202
- .filter(ts.isPropertyDeclaration)
203
- .filter((member) => member.initializer);
204
-
205
- // Divide properties into static and non-static
206
- const instanceFields = properties.filter((prop) => !isStaticNode(prop));
207
-
208
- const statements: tstl.Statement[] = [];
209
-
210
- // class('X')
211
- statements.push(createClassCall(context, className, extension));
212
-
213
- // function X:init()
214
- // X.super.init(self)
215
- // end
216
- const constructor = declaration.members.find(
217
- (n): n is ts.ConstructorDeclaration =>
218
- ts.isConstructorDeclaration(n) && n.body !== undefined
219
- );
220
- const transformedConstructor = transformConstructor(
221
- context,
222
- className,
223
- instanceFields,
224
- constructor
225
- );
226
- if (transformedConstructor) {
227
- statements.push(transformedConstructor);
228
- }
229
-
230
- const methods = declaration.members
231
- .filter(ts.isMethodDeclaration)
232
- .map((method) => transformMethodDeclaration(context, method, className))
233
- .filter((method): method is tstl.Statement => method !== undefined);
234
- statements.push(...methods);
235
-
236
- // export the class if needed
237
- // todo: check if there is a cleaner way to do this
238
- if (
239
- 'localSymbol' in declaration &&
240
- typeof declaration.localSymbol === 'object' &&
241
- 'exportSymbol' in declaration.localSymbol &&
242
- typeof declaration.localSymbol.exportSymbol === 'object' &&
243
- 'escapedName' in declaration.localSymbol.exportSymbol &&
244
- typeof declaration.localSymbol.exportSymbol.escapedName === 'string'
245
- ) {
246
- const escapedName = declaration.localSymbol.exportSymbol.escapedName;
247
-
248
- statements.push(
249
- tstl.createAssignmentStatement(
250
- tstl.createTableIndexExpression(
251
- tstl.createIdentifier('____exports'),
252
- tstl.createStringLiteral(escapedName)
253
- ),
254
- className
255
- )
256
- );
257
- }
258
-
259
- return statements;
260
- };
261
-
262
- const transformNewExpression: FunctionVisitor<ts.NewExpression> = (
263
- node,
264
- context
265
- ) => {
266
- const signature = context.checker.getResolvedSignature(node);
267
- const [name, params] = transformCallAndArguments(
268
- context,
269
- node.expression,
270
- node.arguments ?? [ts.factory.createTrue()],
271
- signature
272
- );
273
- return tstl.createCallExpression(name, params);
274
- };
275
-
276
- export const transformSuperExpression: FunctionVisitor<ts.SuperExpression> = (
277
- expression,
278
- context: TransformationContext & { classSuperInfos?: ClassSuperInfo[] }
279
- ) => {
280
- const superInfos = context.classSuperInfos;
281
- let superInfo: ClassSuperInfo | undefined = undefined;
282
- if (superInfos) {
283
- superInfo = superInfos[superInfos.length - 1];
284
- }
285
- if (!superInfo) return lua.createAnonymousIdentifier(expression);
286
- const { className } = superInfo;
287
-
288
- // Using `super` without extended type node is a TypeScript error
289
- // const extendsExpression = extendedTypeNode?.expression;
290
- // let baseClassName: lua.AssignmentLeftHandSideExpression | undefined;
291
-
292
- // if (extendsExpression && ts.isIdentifier(extendsExpression)) {
293
- // const symbol = context.checker.getSymbolAtLocation(extendsExpression);
294
- // if (symbol && !isSymbolExported(context, symbol)) {
295
- // // Use "baseClassName" if base is a simple identifier
296
- // baseClassName = transformIdentifier(context, extendsExpression);
297
- // }
298
- // }
299
-
300
- // if (!baseClassName) {
301
- // // Use "className.____super" if the base is not a simple identifier
302
- // baseClassName = lua.createTableIndexExpression(
303
- // className,
304
- // lua.createStringLiteral('____super'),
305
- // expression
306
- // );
307
- // }
308
-
309
- return lua.createTableIndexExpression(
310
- className,
311
- lua.createStringLiteral('super')
312
- );
313
- };
314
-
315
- const processName = (name: string) => {
316
- for (const [key, value] of Object.entries(importMap)) {
317
- if (value instanceof Set && value.has(name)) {
318
- imports.add(key);
319
- }
320
- }
321
- };
322
-
323
- const plugin = {
324
- beforeEmit: (_, __, ___, result) => {
325
- const importsString = Array.from(imports)
326
- .map((importString) => `import "CoreLibs/${importString}"`)
327
- .join('\n');
328
-
329
- if (importsString.trim() === '') {
330
- return;
331
- }
332
-
333
- result[0].code = `-- These imports were added automatically\n\n${importsString}\n\n-- End of automatic imports\n\n${result[0].code}`;
334
- },
335
- visitors: {
336
- [ts.SyntaxKind.ClassDeclaration]: transformClassDeclaration,
337
- [ts.SyntaxKind.SuperKeyword]: transformSuperExpression,
338
- [ts.SyntaxKind.NewExpression]: transformNewExpression,
339
- [ts.SyntaxKind.PropertyAccessExpression]: (node, context) => {
340
- if (ts.isIdentifier(node.expression)) {
341
- processName(node.name.text);
342
- }
343
-
344
- return context.superTransformExpression(node);
345
- },
346
- [ts.SyntaxKind.CallExpression]: (node, context) => {
347
- if (ts.isIdentifier(node.expression)) {
348
- processName(node.expression.escapedText.toString());
349
- }
350
-
351
- if (
352
- ts.isIdentifier(node.expression) &&
353
- node.expression.escapedText === 'require'
354
- ) {
355
- const normalNode = context.superTransformExpression(
356
- node
357
- ) as unknown as {
358
- expression: { text: string; originalName: string };
359
- };
360
-
361
- normalNode.expression.text = 'import';
362
- normalNode.expression.originalName = 'import';
363
-
364
- return normalNode as unknown as lua.Expression;
365
- } else {
366
- return context.superTransformExpression(node);
367
- }
368
- },
369
- },
370
- } satisfies tstl.Plugin;
371
-
372
- export default plugin;
@@ -1,10 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES5",
4
- "module": "Node16",
5
- "moduleResolution": "Node16"
6
- },
7
- "files": [
8
- "plugin.ts"
9
- ]
10
- }