-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathbatToExe.ts
More file actions
84 lines (67 loc) · 2.64 KB
/
Copy pathbatToExe.ts
File metadata and controls
84 lines (67 loc) · 2.64 KB
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
import CommonFormats from "src/CommonFormats.ts";
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
import { BadMagicError, EOFError, InitializationError } from "src/errors.ts";
import headUrl from "./batToExe/exe65824head.bin?url";
import footUrl from "./batToExe/exe65824foot.bin?url";
class batToExeHandler implements FormatHandler {
public name = "batToExe";
public supportedFormats = [
CommonFormats.BATCH.supported("bat", true, false),
CommonFormats.EXE.supported("exe", false, true, true) // Lossless because it stores exact input side
];
public ready = false;
private header: Uint8Array|null = null;
private footer: Uint8Array|null = null;
async init() {
this.header = await fetch(headUrl).then(res => res.arrayBuffer()).then(buf => new Uint8Array(buf));
this.footer = await fetch(footUrl).then(res => res.arrayBuffer()).then(buf => new Uint8Array(buf));;
this.ready = true;
}
async doConvert(
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat,
): Promise<FileData[]> {
const header = this.header;
const footer = this.footer;
if (!this.ready || !header || !footer) throw new InitializationError("Handler not initialized.");
const CONTENT_SIZE = 65824;
const EXIT_BYTES = new Uint8Array([0x0d, 0x0a, 0x65, 0x78, 0x69, 0x74]); // \r\nexit
const PAD_BYTE = 0x20; // space
const outputFiles: FileData[] = [];
for (const file of inputFiles) {
if (inputFormat.internal !== "bat") {
throw new TypeError(`Unsupported input format: ${inputFormat.internal}`);
}
if (outputFormat.internal !== "exe") {
throw new TypeError(`Unsupported output format: ${outputFormat.internal}`);
}
if (file.bytes.length + EXIT_BYTES.length > CONTENT_SIZE) {
throw new RangeError(`Input too long. Max ${CONTENT_SIZE-EXIT_BYTES.length} bytes.`);
}
// Build padded content block
const content = new Uint8Array(CONTENT_SIZE);
content.fill(PAD_BYTE);
content.set(file.bytes, 0);
content.set(EXIT_BYTES, file.bytes.length);
// Assemble final EXE
const out = new Uint8Array(header.length + CONTENT_SIZE + footer.length);
let offset = 0;
out.set(header, offset);
offset += header.length;
out.set(content, offset);
offset += CONTENT_SIZE;
out.set(footer, offset);
const outputName =
file.name.split(".").slice(0, -1).join(".") +
"." +
outputFormat.extension;
outputFiles.push({
name: outputName,
bytes: out,
});
}
return outputFiles;
}
}
export default batToExeHandler;