-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplyMapping.ts
90 lines (76 loc) · 2.34 KB
/
applyMapping.ts
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
// deno-lint-ignore-file no-explicit-any
type Mapping = { Key: string; Value: string };
interface MappingObject {
libMBIN_version: string;
Mapping: Mapping[];
}
const [file, mappingFileName] = Deno.args;
let mapping;
if (mappingFileName) {
const mappingFileData = Deno.readTextFileSync(mappingFileName);
mapping = JSON.parse(mappingFileData);
} else {
mapping = await fetchMapping();
}
const fileData = Deno.readTextFileSync(file);
let fileJson;
console.log("parsing file...");
try {
fileJson = JSON.parse(fileData);
} catch {
fileJson = JSON.parse(fileData.slice(0, -1));
}
const isMapped = Boolean(fileJson.Version);
const mappingFunction = isMapped ? reverseMapKeys : mapKeys;
console.log("mapping...");
const mappedSave = mappingFunction(fileJson, mapping);
Deno.writeTextFileSync(
file,
JSON.stringify(mappedSave, null, isMapped ? undefined : 2), // minify when compressing
);
console.log("done!");
function mapKeys(json: any, mapping: Mapping[]): any {
if (Array.isArray(json)) {
return json.map((item) => mapKeys(item, mapping));
} else if (typeof json === "object" && json !== null) {
const newJson: any = {};
for (const key in json) {
const mappedKey = mapping.find((m) => m.Key === key)?.Value;
if (mappedKey) {
newJson[mappedKey] = mapKeys(json[key], mapping);
} else {
newJson[key] = mapKeys(json[key], mapping);
}
}
return newJson;
} else {
return json;
}
}
function reverseMapKeys(json: any, mapping: Mapping[]): any {
if (Array.isArray(json)) {
return json.map((item) => reverseMapKeys(item, mapping));
} else if (typeof json === "object" && json !== null) {
const newJson: any = {};
for (const key in json) {
const originalKey = mapping.find((m) => m.Value === key)?.Key;
if (originalKey) {
newJson[originalKey] = reverseMapKeys(json[key], mapping);
} else {
newJson[key] = reverseMapKeys(json[key], mapping);
}
}
return newJson;
} else {
return json;
}
}
async function fetchMapping() {
const mappingUrl =
"https://github.com/monkeyman192/MBINCompiler/releases/latest/download/mapping.json";
console.log("downloading mapping...");
const fetchedFile = await fetch(mappingUrl);
const fetchedJson: MappingObject = await fetchedFile.json();
console.log("success!");
return fetchedJson.Mapping;
}