forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types-undollar.mjs
81 lines (67 loc) · 2.25 KB
/
types-undollar.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
import fs from 'fs';
let content = fs.readFileSync('build/playcanvas.d.ts', 'utf8');
/**
* This will contain all matches found via `regexType`, as long the class names are equal.
*
* Example keys: `['AssetRegistry', 'GraphicsDevice', 'ResourceHandler', ...]`
*
* @type {Set<string>}
*/
const seenTypes = new Set();
const debug = false;
/**
* This regular expression matches code like:
*
* ```js
* type AssetRegistry$2 = AssetRegistry$c;
* type GraphicsDevice$3 = GraphicsDevice$l;
* type ResourceHandler$3 = ResourceHandler$h;
* ```
*/
const regexType = /type ([a-zA-Z0-9]+)(\$[a-zA-Z0-9]*)? = ([a-zA-Z0-9]+)(\$[a-zA-Z0-9]*)?;/g;
// STEP 1: Delete all lines of the form: type <TYPE-ALIAS> = <TYPE-ALIAS>;
content = content.replace(regexType, (all, first, firstDollar, second, secondDollar) => {
if (first == second) {
seenTypes.add(first);
if (debug) {
console.log('==', { first, second });
return '// ' + all;
}
return '';
}
if (debug) {
console.log('!=', { first, second });
}
return all;
});
// STEP 2: Replace all aliased type names with the original type name.
const longestTypesFirst = [...seenTypes].sort((a, b) => b.length - a.length);
for (const seenType of longestTypesFirst) {
const regex = new RegExp(`${seenType}\\$[a-zA-Z0-9]+`, 'g');
content = content.replace(regex, (all) => {
if (debug) {
return '/*removed dollar*/ ' + seenType;
}
return seenType;
});
}
// STEP 3: Replace 'SomeType as SomeType' with 'SomeType'. This fixes the final export in the types
// that export the alias type names as public API type names.
for (const seenType of longestTypesFirst) {
const regex = new RegExp(`${seenType} as ${seenType}`, 'g');
content = content.replace(regex, (all) => {
if (debug) {
return '/*removed as*/ ' + seenType;
}
return seenType;
});
}
if (debug) {
longestTypesFirst.forEach((seenType, i) => {
console.log(`longestTypesFirst[${i.toString().padStart(3)}] = ${seenType}`);
});
}
// Export all callbacks
const regexCallback = /type [a-zA-Z]+Callback/g;
content = content.replace(regexCallback, 'export $&');
fs.writeFileSync('build/playcanvas.d.ts', content);