-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxtgen.mjs
601 lines (601 loc) · 17.8 KB
/
xtgen.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
#!/usr/bin/env node
import * as fs from 'fs';
import AdmZip from 'adm-zip';
import * as path from 'path';
import * as process from 'process';
import fetch from 'node-fetch';
import { parse } from 'yaml';
import yargs from 'yargs';
const DEBUG = false;
// Definitions file starts with this string
const HEADER = `/** @noSelfInFile */
/// <reference types="@typescript-to-lua/language-extensions" />
/// <reference types="@ts-defold/types" />\n`;
// Invalid names in TypeScript
const INVALID_NAMES = [
'any',
'boolean',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'implements',
'import',
'in',
'instanceof',
'interface',
'let',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'static',
'super',
'switch',
'throw',
'true',
'try',
'typeof',
'undefined',
'var',
'void',
'while',
'with',
'yield',
];
// All valid types are listed here
const KNOWN_TYPES = {
TBL: '{}',
TABLE: '{}',
NUM: 'number',
NUMBER: 'number',
NUMMBER: 'number', // intentional typo
INT: 'number',
INTEGER: 'number',
FLOAT: 'number',
STR: 'string',
STRING: 'string',
BOOL: 'boolean',
BOOLEAN: 'boolean',
FN: '(...args: any[]) => any',
FUNC: '(...args: any[]) => any',
FUNCTION: '(...args: any[]) => any',
HASH: 'hash',
URL: 'url',
NODE: 'node',
BUFFER: 'buffer',
BUFFERSTREAM: 'bufferstream',
VECTOR3: 'vmath.vector3',
VECTOR4: 'vmath.vector4',
MATRIX: 'vmath.matrix4',
MATRIX4: 'vmath.matrix4',
QUAT: 'vmath.quaternion',
QUATERNION: 'vmath.quaternion',
QUATERTION: 'vmath.quaternion', // intentional typo
LUAUSERDATA: 'LuaUserdata',
// TO-DO: Parse strings that have pipes instead of relying on a naive lookup
'STRING|HASH|URL': 'string | hash | url',
'STRING|URL|HASH': 'string | hash | url',
'HASH|STRING|URL': 'string | hash | url',
'HASH|URL|STRING': 'string | hash | url',
'URL|STRING|HASH': 'string | hash | url',
'URL|HASH|STRING': 'string | hash | url',
'STRING | HASH | URL': 'string | hash | url',
'STRING | URL | HASH': 'string | hash | url',
'HASH | STRING | URL': 'string | hash | url',
'HASH | URL | STRING': 'string | hash | url',
'URL | STRING | HASH': 'string | hash | url',
'URL | HASH | STRING': 'string | hash | url',
'STRING|HASH': 'string | hash',
'HASH|STRING': 'string | hash',
'STRING | HASH': 'string | hash',
'HASH | STRING': 'string | hash',
'VECTOR3|VECTOR4': 'vmath.vector3 | vmath.vector4',
'VECTOR4|VECTOR3': 'vmath.vector3 | vmath.vector4',
'VECTOR3 | VECTOR4': 'vmath.vector3 | vmath.vector4',
'VECTOR4 | VECTOR3': 'vmath.vector3 | vmath.vector4',
};
// We'll make default return types slightly stricter than default param types
const DEFAULT_PARAM_TYPE = 'any';
const DEFAULT_RETURN_TYPE = 'unknown';
// Theoretically, it's impossible not to have a name, but just in case
const DEFAULT_NAME_IF_BLANK = 'missingName';
async function main() {
console.time('Done in');
// Command line args
const argv = await yargs(process.argv.slice(2))
.option('p', {
alias: 'project',
describe: 'Path to your project file',
type: 'string',
default: './app/game.project',
})
.option('o', {
alias: 'outDir',
describe: 'The output directory',
type: 'string',
default: './@types',
})
.parse();
const project = argv.p;
const outDir = argv.o;
// Find project file
const absPath = path.join(process.cwd(), project);
// Read project file
let iniData = '';
try {
iniData = await fs.promises.readFile(absPath, 'utf8');
} catch (e) {
console.error(e, absPath);
return;
}
// Locate dependencies
const deps = iniData
.split('\n')
.filter((l) => l.startsWith('dependencies'))
.map((dep) => {
return dep.split('=')[1].trim();
});
if (deps.length === 0) {
console.error('Could not find dependencies in project file.', absPath);
return;
}
// Iterate over each dependency
await Promise.all(
deps.map(async (dep) => {
const details = {
name: '', // We'll guess the name later
isLua: true,
};
// Fetch dependency zip file
const req = await fetch(dep);
if (!req.ok) {
console.error(`Failed to fetch dependency ${dep}`);
return;
}
// Get a node-specific buffer from the request
const zipBuffer = Buffer.from(await req.arrayBuffer());
// Unzip file into memory
const zip = new AdmZip(zipBuffer);
if (!zip.test()) {
console.error(`Zip archive damaged for ${dep}`);
return;
}
// Locate all files inside the zip
const files = zip.getEntries();
// If there's a C++ file, it's probably not a Lua module
files.some((entry) => {
if (entry.name.endsWith('.cpp')) {
details.isLua = false;
return true;
}
return false;
});
let depFilename = '';
try {
const depUrl = dep.split('/');
if (depUrl.length > 0) {
depFilename = depUrl[depUrl.length - 1];
const lastPeriodIndex = depFilename.lastIndexOf('.');
if (lastPeriodIndex !== -1) {
depFilename = depFilename.substring(0, lastPeriodIndex);
}
}
// Remove special characters
depFilename = depFilename.replace(/[^a-zA-Z0-9_.]/g, '');
// Shorten if the name is much too long
if (depFilename.length > 64) {
depFilename = depFilename.substring(0, 64);
}
} catch {
// Silence error
depFilename = '';
}
// Attempt to locate a `script_api` file to parse
const apis = {};
try {
files
.filter((entry) => entry.name.endsWith('.script_api'))
// Use a YAML parser to construction a JS object
.forEach((entry) => {
// Guess the name based on the script_api's filename
apis[
entry.name.split('.')[0] +
`${depFilename ? '_' + depFilename : ''}`
] = parse(entry.getData().toString('utf8'));
});
} catch (e) {
console.error(e, dep);
return;
}
for (const key in apis) {
if (Object.prototype.hasOwnProperty.call(apis, key)) {
// Set name according to key
details.name = key;
// Start processing api
const api = apis[key];
// If we have no API to parse, exit early
if (!api || api.length === 0) {
return;
}
// Make output directory
try {
await fs.promises.mkdir(path.join(process.cwd(), outDir));
} catch {
// Silence this error
}
// Debug: Export JSON of parsed YAML
if (DEBUG) {
try {
await fs.promises.writeFile(
path.join(process.cwd(), outDir, details.name + '.json'),
JSON.stringify(api),
);
} catch (e) {
console.error(e, dep);
return;
}
}
// Turn our parsed object into definitions
const result = generateTypeScriptDefinitions(api, details, true);
if (result) {
// Guess the URL by including only the first 6 strings split by slash
const depUrl = dep.split('/').slice(0, 5).join('/');
// Append header
const final = `${HEADER}/**\n * @see {@link ${depUrl}|Source}\n * @noResolution\n */\n${result}`;
// Save the definitions to file
try {
await fs.promises.writeFile(
path.join(process.cwd(), outDir, details.name + '.d.ts'),
final,
);
} catch (e) {
console.error(e, dep);
return;
}
}
}
}
}),
);
console.timeEnd('Done in');
console.log(`Exported definitions to ${path.join(process.cwd(), outDir)}`);
}
// Utility Functions
// Check if a string is all uppercase with optional underscores
function isAllUppercase(str) {
return /^[A-Z0-9_]+$/.test(str);
}
// Check type of API entry
function isApiTable(entry) {
return (
(typeof entry.type === 'string' && entry.type.toUpperCase() === 'TABLE') ||
'members' in entry
);
}
// Check type of API entry
function isApiFunc(entry) {
return (
(typeof entry.type === 'string' &&
entry.type.toUpperCase() === 'FUNCTION') ||
'parameters' in entry
);
}
function isNameInvalid(name, isParam) {
name = String(name);
if (isParam) {
return INVALID_NAMES.includes(name);
} else {
return ['this'].concat(INVALID_NAMES).includes(name);
}
}
// Sanitizes name
function getName(name, isParam) {
let modifiedName = String(name);
if (isParam) {
// Special case: arguments
modifiedName = modifiedName.replace(/^\.\.\.$/, 'args');
// Special case: Lua's `self` variable
modifiedName = modifiedName.replace(/^self$/, 'this');
}
// Sanitize type name: allow only alpha-numeric, underscore, dollar sign
modifiedName = modifiedName.replace(/[^a-zA-Z0-9_$]/g, '_');
// If the first character is a number, add a dollar sign to start
if (/^\d/.test(modifiedName)) {
modifiedName = '$' + modifiedName;
}
// If we're modifying a function name, not a parameter, give a warning
if (!isParam && modifiedName !== name) {
console.warn(
`Modifying invalid ${typeof name} "${name}" to "${modifiedName}"`,
);
}
// Check against the reserved keywords in TypeScript
if (isNameInvalid(modifiedName, isParam)) {
modifiedName = modifiedName + '_';
}
return modifiedName;
}
// Transforms API type to TS type
function getType(type, context) {
let defaultType = DEFAULT_PARAM_TYPE;
if (context === 'return') {
defaultType = DEFAULT_RETURN_TYPE;
}
if (typeof type === 'string') {
return KNOWN_TYPES[type.toUpperCase()] ?? defaultType;
} else if (Array.isArray(type)) {
const typeSet = new Set();
type.forEach((rawType) => {
if (typeof rawType === 'string') {
typeSet.add(KNOWN_TYPES[rawType.toUpperCase()] ?? defaultType);
}
});
const typeArray = Array.from(typeSet);
return typeArray.length ? typeArray.join(' | ') : defaultType;
}
return defaultType;
}
function sanitizeForComment(str) {
return str.replace(/\*\//g, '*\\/');
}
/**
* @param name the original, unsanitized name
* @param root
*/
function getDeclarationKeyword(name, root) {
if (root) {
return 'declare';
} else if (isNameInvalid(name, false)) {
return '';
} else {
return 'export';
}
}
// Transforms and sanitizes descriptions
function getComments(entry) {
// Make sure the description doesn't break out of the comment
const desc = entry.desc || entry.description;
let newDesc = desc ?? '';
// If params exist, let's create `@param`s in JSDoc format
if (entry.parameters && Array.isArray(entry.parameters)) {
newDesc = getParamComments(entry.parameters, newDesc);
}
// Comments for `@returns`
const returnObj = entry.return || entry.returns;
if (returnObj) {
newDesc = getReturnComments(returnObj, newDesc);
}
// Comments for `@example`
if (entry.examples && Array.isArray(entry.examples)) {
newDesc = getExampleComments(entry.examples, newDesc);
}
return newDesc ? `/**\n * ${sanitizeForComment(newDesc)}\n */\n` : '';
}
function getReturnComments(returnObj, newDesc) {
let returnType = '';
let comments = '';
if (Array.isArray(returnObj)) {
if (returnObj.length > 1) {
returnType = `LuaMultiReturn<[${returnObj.map((ret) => ret.type).join(', ')}]>`;
} else {
returnType = Array.isArray(returnObj[0].type)
? returnObj[0].type.join(' | ')
: returnObj[0].type ?? '';
}
// Add comments if they exist
if (returnObj.some((ret) => ret.desc || ret.description)) {
comments = `${returnObj.map((ret) => ret.desc || ret.description).join(' | ')}`;
}
} else if (returnObj.type) {
// Instead of getting a TS type here, use the raw Lua type
returnType = Array.isArray(returnObj.type)
? returnObj.type.join(' | ')
: returnObj.type;
comments = getType(returnObj.type, 'return');
}
// If we've figured out a comment, but not a returnType
if (comments.length && !returnType.length) {
returnType = DEFAULT_RETURN_TYPE;
}
newDesc += `\n * @returns {${returnType}} ${comments}`;
return newDesc;
}
function getParamComments(parameters, newDesc) {
parameters.forEach((param) => {
const name = param.name ? getName(param.name, true) : '';
if (name) {
newDesc += `\n * @param`;
if (param.type) {
// Instead of getting a TS type here, use the raw Lua type
let rawType = '';
if (Array.isArray(param.type)) {
// If multiple types, join them into a string
rawType = param.type.join('|');
} else {
rawType = param.type;
}
// Sanitize type name, allow alpha-numeric, underscore and pipe
rawType = rawType.replace(/[^a-zA-Z|0-9_$]/g, '_');
newDesc += ` {${rawType}}`;
}
newDesc += ` ${name}`;
const desc = param.desc || param.description;
if (desc) {
newDesc += ` ${desc}`;
}
if (param.fields && Array.isArray(param.fields)) {
newDesc = getParamFields(param.fields, newDesc);
}
}
});
return newDesc;
}
function getParamFields(fields, newDesc) {
fields.forEach((field) => {
newDesc += ` ${JSON.stringify(field)}`;
});
return newDesc;
}
function getExampleComments(examples, newDesc) {
examples.forEach((example) => {
const desc = example.desc || example.description;
if (desc) {
newDesc += `\n * @example ${desc}`;
}
});
return newDesc;
}
/**
* @param name must be the original, unsanitized name
* @param isParam
*/
function getExportOverride(name, isParam) {
if (isNameInvalid(name, isParam)) {
return `export {${getName(name, isParam)} as ${name}}`;
} else {
return '';
}
}
// Main Functions
// Function to generate TypeScript definitions for ScriptApiTable
function generateTableDefinition(entry, details, root) {
const declaration = getDeclarationKeyword(entry.name ?? '', root);
const override = entry.name ? getExportOverride(entry.name, false) : '';
const name = entry.name ? getName(entry.name, false) : DEFAULT_NAME_IF_BLANK;
let tableDeclaration = `${declaration ? declaration + ' ' : ''}namespace ${name} {\n`;
if (root) {
tableDeclaration = details.isLua
? `${declaration} module '${name}.${name}' {\n`
: `${declaration} namespace ${name} {\n`;
}
if (entry.members && Array.isArray(entry.members)) {
return `${tableDeclaration}${generateTypeScriptDefinitions(entry.members, details, false)}}${override ? override + ';\n' : ''}`;
} else {
return `${tableDeclaration}}${override ? override + ';\n' : ''}`;
}
}
// Function to generate TypeScript definitions for ScriptApiFunction
function generateFunctionDefinition(entry, isParam, root) {
const parameters = entry.parameters
? entry.parameters.map(getParameterDefinition).join(', ')
: '';
const returnType = getReturnType(entry.return || entry.returns);
if (isParam) {
return `(${parameters}) => ${returnType}`;
} else {
const comment = getComments(entry);
const declaration = getDeclarationKeyword(entry.name ?? '', root);
const override = entry.name ? getExportOverride(entry.name, isParam) : '';
const name = entry.name
? getName(entry.name, false)
: DEFAULT_NAME_IF_BLANK;
return `${comment}${declaration ? declaration + ' ' : ''}function ${name}(${parameters}): ${returnType};\n${override ? override + ';\n' : ''}`;
}
}
function getParameterDefinition(param) {
const name = param.name ? getName(param.name, true) : DEFAULT_NAME_IF_BLANK;
const optional = param.optional ? '?' : '';
let type = getType(param.type, 'param');
if (type === KNOWN_TYPES['FUNCTION']) {
// Get a more specific function signature
type = generateFunctionDefinition(param, true, false);
} else if (
type === KNOWN_TYPES['TABLE'] &&
param.fields &&
Array.isArray(param.fields)
) {
// Try to get the exact parameters of a table
type = `{ ${param.fields.map(getParameterDefinition).join('; ')} }`;
}
return `${name}${optional}: ${type}`;
}
function getReturnType(returnObj) {
if (!returnObj) {
return 'void';
}
if (Array.isArray(returnObj)) {
if (returnObj.length > 1) {
return `LuaMultiReturn<[${returnObj.map((ret) => getType(ret.type, 'return')).join(', ')}]>`;
} else {
return `${getType(returnObj[0].type, 'return')}`;
}
} else if (returnObj.type) {
return getType(returnObj.type, 'return');
} else {
return 'void'; // Fallback in case we can't parse it at all
}
}
// Function to generate TypeScript definitions for ScriptApiEntry
function generateEntryDefinition(entry, root) {
const declaration = getDeclarationKeyword(entry.name ?? '', root);
const override = entry.name ? getExportOverride(entry.name, false) : '';
const name = entry.name ? getName(entry.name, false) : DEFAULT_NAME_IF_BLANK;
const varType = isAllUppercase(name) ? 'const' : 'let';
const type = getType(entry.type, 'return');
const comment = getComments(entry);
return `${comment}${declaration ? declaration + ' ' : ''}${varType} ${name}: ${type};\n${override ? override + ';\n' : ''}`;
}
// Main function to generate TypeScript definitions for ScriptApi
function generateTypeScriptDefinitions(api, details, root) {
let definitions = '';
const namespaces = {};
api.forEach((entry) => {
// Handle nested properties
if (typeof entry.name === 'string' && entry.name.includes('.')) {
const namePieces = entry.name.split('.');
const entryNamespace = namePieces[0];
const entryName = namePieces[1];
// Create namespace if not already exists
namespaces[entryNamespace] = namespaces[entryNamespace] || [];
// Update entry name and add to the namespace
entry.name = entryName;
namespaces[entryNamespace].push(entry);
} else if (isApiTable(entry)) {
definitions += generateTableDefinition(entry, details, root);
} else if (isApiFunc(entry)) {
definitions += generateFunctionDefinition(entry, false, root);
} else {
definitions += generateEntryDefinition(entry, root);
}
});
// Loop through namespaces
for (const namespace in namespaces) {
if (Object.prototype.hasOwnProperty.call(namespaces, namespace)) {
const namespaceEntries = namespaces[namespace];
definitions += `${root ? 'declare' : 'export'} namespace ${namespace} {\n`;
// Loop through entries within the namespace
namespaceEntries.forEach((entry) => {
if (isApiTable(entry)) {
definitions += generateTableDefinition(entry, details, false);
} else if (isApiFunc(entry)) {
definitions += generateFunctionDefinition(entry, false, false);
} else {
definitions += generateEntryDefinition(entry, false);
}
});
definitions += '}\n';
}
}
return definitions;
}
// Run the main function
void main();