-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlove.utils.js
More file actions
255 lines (217 loc) · 6.87 KB
/
love.utils.js
File metadata and controls
255 lines (217 loc) · 6.87 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
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
const fs = require("fs-extra");
const mustache = require("mustache");
const klawSync = require("klaw-sync");
const path = require("path");
const { sep, resolve } = path;
const { v4: uuidv4 } = require("uuid");
const https = require("https");
const http = require("http");
const os = require("os");
const AUDIO_SUFFIXES = [".ogg", ".wav", ".mp3", ".flac", ".xm"];
function isUrl(str) {
return /^https?:\/\//i.test(str);
}
function isDataUrl(str) {
return /^data:/i.test(str);
}
function decodeDataUrl(dataUrl) {
const matches = dataUrl.match(/^data:([^;,]+)?(;base64)?,(.*)$/);
if (!matches) {
throw new Error("Invalid data URL format");
}
const isBase64 = !!matches[2];
const data = matches[3];
const tempPath = path.join(os.tmpdir(), `love-${uuidv4()}.love`);
if (isBase64) {
fs.writeFileSync(tempPath, Buffer.from(data, "base64"));
} else {
fs.writeFileSync(tempPath, decodeURIComponent(data));
}
return tempPath;
}
async function downloadFile(url) {
return new Promise((resolve, reject) => {
const protocol = url.startsWith("https") ? https : http;
const tempPath = path.join(os.tmpdir(), `love-${uuidv4()}.love`);
const file = fs.createWriteStream(tempPath);
protocol
.get(url, (response) => {
if (response.statusCode === 301 || response.statusCode === 302) {
file.close();
fs.unlinkSync(tempPath);
downloadFile(response.headers.location).then(resolve).catch(reject);
return;
}
if (response.statusCode !== 200) {
file.close();
fs.unlinkSync(tempPath);
reject(new Error(`Failed to download: ${response.statusCode}`));
return;
}
response.pipe(file);
file.on("finish", () => {
file.close();
resolve(tempPath);
});
})
.on("error", (err) => {
file.close();
fs.unlink(tempPath, () => {});
reject(err);
});
});
}
function isDirectory(path) {
return fs.statSync(path).isDirectory();
}
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getFiles(input) {
const inputPath = resolve(input);
if (isDirectory(inputPath)) {
return klawSync(inputPath, { nodir: true });
}
return [{ path: inputPath, stats: fs.statSync(inputPath) }];
}
function buildGameData(inputPath) {
const files = getFiles(inputPath);
const isDir = isDirectory(resolve(inputPath));
const dirs = isDir ? klawSync(resolve(inputPath), { nofile: true }) : [];
const createFilePaths = dirs.map((f) => {
const relPath = f.path.replace(
new RegExp(`^.*${escapeRegex(inputPath)}`),
""
);
const splits = relPath.split(sep);
const length = splits.length - 1;
const directoryPath = splits.slice(0, length).join("/") || "/";
return `Module['FS_createPath']('${directoryPath}', '${splits[length]}', true, true);`;
});
const fileMetadata = [];
const fileBuffers = [];
let currentByte = 0;
for (const file of files) {
const relativePath = isDir
? file.path.replace(new RegExp(`^.*${escapeRegex(inputPath)}`), "")
: "/game.love";
const buffer = fs.readFileSync(file.path);
fileMetadata.push({
filename: relativePath,
crunched: 0,
start: currentByte,
end: currentByte + buffer.length,
audio: AUDIO_SUFFIXES.some((suffix) => file.path.endsWith(suffix)),
});
currentByte += buffer.length;
fileBuffers.push(buffer);
}
return {
totalBuffer: Buffer.concat(fileBuffers),
fileMetadata,
createFilePaths,
arguments: isDir ? JSON.stringify(["./"]) : JSON.stringify(["./game.love"]),
};
}
async function compileLoveProjects(projects, options = {}) {
const { output, memory = 67108864, compatibility = false } = options;
if (!output) {
throw new Error("Output directory is required");
}
if (!Array.isArray(projects) || projects.length === 0) {
throw new Error("Projects must be a non-empty array");
}
const outputDir = resolve(output);
const srcDir = resolve(__dirname, "node_modules/love.js/src");
const folderName = compatibility ? "compat" : "release";
fs.mkdirsSync(outputDir);
const results = [];
const tempFiles = [];
try {
for (const project of projects) {
const {
input,
title = "Love Game",
subfolder,
} = typeof project === "string"
? { input: project, title: "Love Game", subfolder: null }
: project;
let inputPath;
if (isDataUrl(input)) {
inputPath = decodeDataUrl(input);
tempFiles.push(inputPath);
} else if (isUrl(input)) {
inputPath = await downloadFile(input);
tempFiles.push(inputPath);
} else {
inputPath = resolve(input);
if (!fs.existsSync(inputPath)) {
throw new Error(`Input path does not exist: ${inputPath}`);
}
}
const gameData = buildGameData(inputPath);
if (memory < gameData.totalBuffer.length) {
throw new Error(
`Memory must be >= ${gameData.totalBuffer.length} bytes for ${input}`
);
}
const jsArgs = {
create_file_paths: gameData.createFilePaths.join("\n "),
metadata: JSON.stringify({
package_uuid: uuidv4(),
remote_package_size: gameData.totalBuffer.length,
files: gameData.fileMetadata,
}),
};
const templateArgs = {
memory,
title,
arguments: gameData.arguments,
};
const gameTemplate = fs.readFileSync(`${srcDir}/game.js`, "utf8");
const renderedGameTemplate = mustache.render(gameTemplate, jsArgs);
const htmlTemplate = fs.readFileSync(
`${srcDir}/${folderName}/index.html`,
"utf8"
);
const renderedHtml = mustache.render(htmlTemplate, templateArgs);
const projectOutput = subfolder
? resolve(outputDir, subfolder)
: outputDir;
fs.mkdirsSync(projectOutput);
fs.writeFileSync(`${projectOutput}/index.html`, renderedHtml);
fs.writeFileSync(`${projectOutput}/game.js`, renderedGameTemplate);
fs.writeFileSync(`${projectOutput}/game.data`, gameData.totalBuffer);
fs.copySync(
`${srcDir}/${folderName}/love.js`,
`${projectOutput}/love.js`
);
fs.copySync(
`${srcDir}/${folderName}/love.wasm`,
`${projectOutput}/love.wasm`
);
fs.copySync(`${srcDir}/${folderName}/theme`, `${projectOutput}/theme`);
if (!compatibility) {
fs.copySync(
`${srcDir}/${folderName}/love.worker.js`,
`${projectOutput}/love.worker.js`
);
}
results.push({
input,
output: projectOutput,
title,
size: gameData.totalBuffer.length,
});
}
return results;
} finally {
for (const tempFile of tempFiles) {
fs.unlink(tempFile, () => {});
}
}
}
module.exports = {
compileLoveProjects,
buildGameData,
};