-
Notifications
You must be signed in to change notification settings - Fork 2
/
build.js
346 lines (305 loc) · 10.8 KB
/
build.js
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
const Handlebars = require("handlebars");
const core = require('@actions/core');
const { exit, env } = require("process");
const i18next = require("i18next");
const parse5 = require("parse5");
const chalk = require("chalk");
const glob = require("glob");
const path = require("path");
const fs = require("fs");
const showdown = require("showdown");
const converter = new showdown.Converter();
const file_releases = 'tmp/releases.json';
const file_contributors = 'tmp/contributors.json';
let currentResource;
class Release {
name = '';
displayName = '';
downloads = [];
isGui = false;
}
// Configuration
const config = {
localesDir: "./locales",
templatesDir: "./public",
componentsDir: "./components",
outputDir: "./dist",
excludePatterns: ["**/*.html", "**/*.hbs"],
defaultLanguage: "en",
safeTags: ["b", "i", "br", "code"],
safeAttributes: [],
};
// Logger function
const log = (message, type = "info") => {
if (process.env.GITHUB_ACTIONS !== undefined) {
switch (type) {
case 'error':
core.error(message);
break;
case 'warning':
core.warning(message);
break;
case 'debug':
core.debug(message);
break;
case 'info':
default:
core.info(message);
break;
}
} else {
const prefix =
{
info: chalk.blue("INFO"),
warning: chalk.yellow("WARN"),
error: chalk.red("ERROR"),
}[type] || chalk.gray("LOG");
console.log(`[${prefix}] ${message}`);
}
};
function trimEndNewline(str) {
if (str.endsWith('\n')) {
return str.slice(0, -1);
}
return str;
}
function copyMissing(from, to, toName, keySoFar = '') {
for (const key in from) {
if (!(key in to)) {
log(`Key ${keySoFar}${key} is missing from ${toName}`, 'warning')
to[key] = from[key];
continue;
}
if (typeof from[key] === 'object') {
to[key] = copyMissing(from[key], to[key], toName, `${keySoFar}${key}.`);
}
}
return to;
}
function doesTmpFileNeedUpdate(filePath) {
if (!fs.existsSync(filePath))
return true;
const stats = fs.statSync(filePath);
const now = new Date();
const fileTime = new Date(stats.mtime);
const differenceInMinutes = (now.getTime() - fileTime.getTime()) / (1000 * 60);
return differenceInMinutes > 30;
}
async function updateGitHubData() {
let options = { headers: {} };
if (process.env.GITHUB_TOKEN !== undefined) {
options.headers.Authorization = `Bearer: ${process.env.GITHUB_TOKEN}`;
} else if (process.env.GITHUB_ACTIONS !== undefined) {
core.warning('Not authenticated! This will most likely result in a 403 from GitHub API calls. Generate a Personal Access Token and add it as a secret to this workflow under the "GITHUB_TOKEN" environment variable.')
} else {
core.info('GitHub API calls will be made without authentication. You may experience 403 errors.')
}
fs.mkdirSync('tmp', { recursive: true });
if (doesTmpFileNeedUpdate(file_releases)) {
log('Updating releases...');
let releases = [];
let page = 1;
while (true) {
const response = await fetch(`https://api.github.com/repos/vrc-get/vrc-get/releases?per_page=100&page=${page}`, options);
if (!response.ok) {
throw new Error(`GitHub API returned status ${response.status}: ${await response.text()}`);
}
const json = await response.json();
releases = releases.concat(json);
if (json.length != 100) break;
page = page + 1;
}
let items = [];
releases = releases.sort((a, b) => b.id - a.id);
releases.forEach(r => {
r.isGui = r.tag_name.startsWith('gui-');
r.displayName = r.tag_name.substring(r.isGui ? 5 : 1);
items.push(r);
});
fs.writeFileSync(file_releases, JSON.stringify(items));
}
if (doesTmpFileNeedUpdate(file_contributors)) {
log('Updating contributors...');
const response = await fetch(`https://api.github.com/repos/vrc-get/vrc-get/contributors`, options);
let contributors = await response.json();
contributors = contributors.sort((a, b) => b.contributions - a.contributions);
fs.writeFileSync(file_contributors, JSON.stringify(contributors));
}
}
// Build function
async function build() {
await updateGitHubData();
try {
log("Starting build...");
// Load locales (using async/await for i18next.init)
const locales = fs
.readdirSync(config.localesDir)
.filter((file) => file.endsWith(".json"))
.map((file) => file.replace(".json", ""))
.sort();
const resources = {};
let defaultLocale = require("./" + path.join(config.localesDir, `${config.defaultLanguage}.json`));
locales.forEach((locale) => {
const localePath = "./" + path.join(config.localesDir, `${locale}.json`);
let json = require(localePath);
if (locale !== config.defaultLanguage) {
json = copyMissing(defaultLocale, json, localePath);
}
resources[locale] = {
translation: json,
};
});
log(locales);
await i18next.init({
lng: config.defaultLanguage,
resources,
});
// Register the not helper
Handlebars.registerHelper('not', function (value) {
return !value;
});
// Register the safe-html helper
Handlebars.registerHelper("safe", function (key) {
const translatedString = i18next.t(key);
// Recursive sanitization function
function sanitize(node) {
if (node.type === "tag") {
if (!config.safeTags.includes(node.name.toLowerCase())) {
return "";
}
// Sanitize attributes
node.attribs = Object.keys(node.attribs).reduce((acc, attr) => {
if (config.safeAttributes.includes(attr.toLowerCase())) {
acc[attr] = node.attribs[attr];
}
return acc;
}, {});
}
if (node.children) {
node.children = node.children.map(sanitize).filter(Boolean);
}
return node;
}
// Parse, sanitize, and serialize
const doc = parse5.parseFragment(translatedString);
const sanitized = parse5.serialize(sanitize(doc));
return new Handlebars.SafeString(sanitized);
});
Handlebars.registerHelper("renderMarkdown", function(key) {
let markdown = i18next.t(key);
if (markdown === undefined || markdown === '') {
markdown = `*${currentResource.releases.noChangelogMessage}*`;
} else {
markdown = trimEndNewline(markdown);
}
const html = converter.makeHtml(markdown);
return new Handlebars.SafeString(html);
})
// Register the contains helper
Handlebars.registerHelper("contains", function (arrayStr, value, options) {
const array = (arrayStr ?? "").split(",").map((s) => s.trim());
if (array && array.indexOf(value) !== -1) {
return true;
} else {
return false;
}
});
// Register components
const componentFiles = fs
.readdirSync(config.componentsDir)
.filter((file) => file.endsWith(".hbs"))
.map((file) => file.replace(".hbs", ""));
componentFiles.forEach((componentFile) => {
const raw = fs.readFileSync(
path.join(config.componentsDir, componentFile + ".hbs"),
"utf-8",
);
Handlebars.registerPartial(componentFile, raw);
});
// Remove previous instance of the output directory
if (fs.existsSync(config.outputDir))
fs.rmSync(config.outputDir, { recursive: true, force: true });
// Find & copy non-HTML files (excluding patterns)
const nonHtmlFiles = glob
.sync(`${config.templatesDir}/**/*`, { nodir: true })
.filter(
(file) =>
!config.excludePatterns.some((pattern) => {
const regex = new RegExp(pattern.replace(/\*\*/g, ".*"));
return regex.test(file);
}),
);
nonHtmlFiles.forEach((file) => {
const relativePath = path.relative(config.templatesDir, file);
const outputPath = path.join(config.outputDir, relativePath);
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.copyFileSync(file, outputPath);
log(`Copied: ${relativePath}`);
});
// Update the locales
let localesList = {};
for (const locale of locales) {
const resources = i18next.getResourceBundle(locale, "translation");
localesList[resources.locale.code] = resources.locale;
}
const outputPath = path.join(config.outputDir, "resources", "locales");
fs.mkdirSync(outputPath, { recursive: true });
for (const locale of locales) {
const resources = i18next.getResourceBundle(locale, "translation");
resources.data = {
locales: localesList
};
const raw = JSON.stringify(resources, null, "\t");
fs.writeFileSync(path.join(outputPath, locale + ".json"), raw);
}
// Find HTML templates & generate localized pages
const templateFiles = glob
.sync(`${config.templatesDir}/**/*.{html,hbs}`)
.filter((filePath) => !path.basename(filePath).startsWith("_"));
const contributors = JSON.parse(fs.readFileSync(file_contributors));
const releases = JSON.parse(fs.readFileSync(file_releases));
for (const templateFile of templateFiles) {
const template = Handlebars.compile(
fs.readFileSync(templateFile, "utf8"),
);
for (const locale of locales) {
const resources = i18next.getResourceBundle(locale, "translation");
currentResource = resources;
resources.data.releases = releases;
resources.data.contributors = contributors;
resources.data.latestAlcomVersion = JSON.parse(
fs.readFileSync(
'./' + path.join(config.templatesDir, 'api', 'gui', 'tauri-updater.json')
)
).version;
const relativePath = path.relative(config.templatesDir, templateFile);
let url = path.dirname(relativePath);
if (url === '.') url = '';
else url = url + '/';
resources.data.relativeURL = url;
const htmlContent = template(resources);
let outputPath = path.join(config.outputDir, locale, relativePath);
if (outputPath.endsWith(".hbs")) {
outputPath = outputPath.replace(/\.hbs$/, ".html");
}
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, htmlContent);
if (locale === config.defaultLanguage) {
outputPath = path.join(config.outputDir, relativePath);
if (outputPath.endsWith(".hbs")) {
outputPath = outputPath.replace(/\.hbs$/, ".html");
}
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, htmlContent);
}
log(`Built: ${outputPath} (locale: ${locale})`);
}
}
log("Build complete!");
} catch (error) {
log(`Build failed: ${error.message}`, "error");
log(error.stack, "error");
exit(1);
}
}
build();