-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathbuild.js
More file actions
230 lines (218 loc) · 6.95 KB
/
Copy pathbuild.js
File metadata and controls
230 lines (218 loc) · 6.95 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
import * as path from "node:path";
import * as fs from "node:fs";
import * as esbuild from "esbuild";
import { minify as minifyHTML } from "html-minifier-next";
import browserslist from "browserslist";
import { transform, browserslistToTargets } from "lightningcss";
import minifyJSON from "jsonminify";
const srcDir = "src";
const distDir = "dist";
const versionParamName = "--version=";
const exportHoloPrintLibFlagName = "--export-holoprint-lib";
const buildVersion = process.argv.find(arg => arg.startsWith(versionParamName))?.slice(versionParamName.length) ?? "testing";
const exportHoloPrintLib = process.argv.includes(exportHoloPrintLibFlagName);
const cssTargets = browserslistToTargets(browserslist(">= 0.1%"));
const importMapPattern = /<script type="importmap">([^]+?)<\/script>/;
process.chdir(path.resolve(import.meta.dirname, "../"));
rmDir("temp");
fs.cpSync(srcDir, "temp", {
recursive: true
});
await processDir("temp");
rmDir(distDir);
fs.cpSync("temp", distDir, {
recursive: true,
filter: filename => !(path.extname(filename) == ".js" || (fs.statSync(filename).isDirectory() && fs.readdirSync(filename).every(file => path.extname(file) == ".js")))
});
let importMapJSON = fs.readFileSync(`${distDir}/index.html`, "utf-8").match(importMapPattern)[1];
let externalModules = Object.keys(JSON.parse(importMapJSON)["imports"]);
let { metafile } = esbuild.buildSync({
absWorkingDir: process.cwd(),
entryPoints: ["temp/index.js"],
bundle: true,
external: externalModules,
dropLabels: ["TS"],
minify: true,
format: "esm",
outdir: distDir,
entryNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
loader: {
".molang.js": "copy" // don't process these files at all, treat them as assets
},
sourcemap: true,
metafile: true
});
rmDir("temp");
console.log(esbuild.analyzeMetafileSync(metafile));
let scriptImportReplacements = [];
Object.entries(metafile["outputs"]).forEach(([output, { entryPoint }]) => {
if(entryPoint) {
scriptImportReplacements.push([entryPoint.replace("temp/", ""), output.replace(distDir + "/", "")]);
}
});
fs.readdirSync(distDir).forEach(filename => {
if(path.extname(filename) == ".html") {
let filepath = path.join(distDir, filename);
let html = fs.readFileSync(filepath, "utf-8");
scriptImportReplacements.forEach(([oldName, newName]) => {
let regExp = new RegExp(`\\b${oldName.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g");
html = html.replaceAll(regExp, newName);
});
if(importMapPattern.test(html)) {
html = html.replace(importMapPattern, (_, importMapJSON) => addImportReplacementsToImportMap(JSON.parse(importMapJSON)));
} else {
let importMapScript = addImportReplacementsToImportMap({});
if(html.includes("</head>")) {
html = html.replace("</head>", `${importMapScript}</head>`);
} else {
html += importMapScript;
}
}
fs.writeFileSync(filepath, html);
}
});
/**
* @param {string} dir
*/
async function processDir(dir) {
let directoryContents = fs.readdirSync(dir);
await Promise.all(directoryContents.map(async filename => {
let filepath = path.join(dir, filename);
let stats = fs.statSync(filepath);
if(stats.isDirectory()) {
await processDir(filepath);
} else {
let processingFunction = findProcessingFunction(filepath);
if(processingFunction) {
let fileContent = fs.readFileSync(filepath, "utf-8");
let { code, sourceMap } = await processingFunction(fileContent, filename);
fs.writeFileSync(filepath, code);
if(sourceMap) {
fs.writeFileSync(filepath + ".map", sourceMap);
}
}
}
}));
}
/**
* @param {string} filename
* @returns {((code: string, filename: string) => MaybePromise<{ code: string, sourceMap?: string }>) | undefined}
*/
function findProcessingFunction(filename) {
let fileExtension = path.extname(filename);
switch (fileExtension) {
case ".html": return processHTML;
case ".css": return processCSS;
case ".js": return processJS;
case ".json":
case ".material":
case ".webmanifest": return processJSON;
}
}
/**
* @param {string} code
* @param {string} filename
* @returns {Promise<{ code: string }>}
*/
async function processHTML(code, filename) {
code = code.replaceAll(/<script type="(importmap|application\/ld\+json)">([^]+?)<\/script>/g, (_, scriptType, json) => `<script type="${scriptType}">${processJSON(json).code}</script>`);
code = await minifyHTML(code, {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
sortAttributes: true,
sortClassName: true,
minifyCSS: css => processCSS(css, filename, true).code,
inlineCustomElements: ["vec-3-input", "slot", "span"]
});
return { code };
}
/**
* @param {string} code
* @param {string} filename
* @param {boolean} [disableSourceMap]
* @returns {{ code: string, sourceMap?: string }}
*/
function processCSS(code, filename, disableSourceMap = false) {
let { code: codeBytes, map: sourceMapBytes } = transform({
filename,
minify: true,
code: (new TextEncoder()).encode(code),
targets: cssTargets,
sourceMap: !disableSourceMap
});
code = (new TextDecoder()).decode(codeBytes);
if(sourceMapBytes) {
code += `\n/*# sourceMappingURL=${filename}.map */`;
let sourceMap = (new TextDecoder()).decode(sourceMapBytes);
return { code, sourceMap };
} else {
return { code };
}
}
/**
* @param {string} code
* @param {string} filename
* @returns {Promise<{ code: string }>}
*/
async function processJS(code, filename) {
code = code.replace("const IN_PRODUCTION = false;", "const IN_PRODUCTION = true;");
if(filename == "HoloPrint.js") {
code = code.replace(`const VERSION = "dev";`, `const VERSION = "${buildVersion}";`);
} else if(filename == "index.js") {
if(exportHoloPrintLib) {
code = `export * from "./HoloPrint.js";` + code;
}
}
code = await replaceAllAsync(code, /html`([^]+?)`/g, async (_, html) => "`" + (await processHTML(html, filename)).code + "`");
return { code };
}
/**
* @param {string} code
* @returns {{ code: string }}
*/
function processJSON(code) {
code = minifyJSON(code);
return { code };
}
/** @param {string} dir */
function rmDir(dir) {
if(fs.existsSync(dir)) {
fs.rmSync(dir, {
recursive: true
});
}
}
/**
* @param {object} importMap
* @returns {string}
*/
function addImportReplacementsToImportMap(importMap) {
importMap["imports"] ??= {};
scriptImportReplacements.forEach(([oldName, newName]) => {
importMap["imports"][`./${oldName}`] = `./${newName}`;
});
return `<script type="importmap">${JSON.stringify(importMap)}</script>`;
}
/**
* @param {string} str
* @param {RegExp} regexp
* @param {(substring: string, ...args: string[]) => Promise<string>} replacer
* @returns {Promise<string>}
*/
async function replaceAllAsync(str, regexp, replacer) {
/** @type {Promise<string>[]} */
let promises = [];
str.replaceAll(regexp, (substring, ...args) => {
promises.push(replacer(substring, ...args));
return substring;
});
let replacements = await Promise.all(promises);
let i = 0;
return str.replaceAll(regexp, () => replacements[i++]);
}
/**
* @template T
* @typedef {Promise<T> | T} MaybePromise
*/