-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbundle.js
More file actions
271 lines (228 loc) · 7.56 KB
/
Copy pathbundle.js
File metadata and controls
271 lines (228 loc) · 7.56 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import fs from 'fs';
import path from 'path';
import zlib from 'zlib';
const version = process.env.npm_package_version;
const buildDir = './public/build/';
const book3dFile = './public/micrio-book3d.js';
const hasBook3d = fs.existsSync(book3dFile);
if(hasBook3d) console.log(`Including optional module: ${book3dFile}`);
/** Deduplicate repeated classname hash selectors in CSS */
function dedupeCssSelectors(cssContent) {
const matches = cssContent.match(/\.([^\d\.{ ):>,]+)/mig);
if (matches) {
[...new Set(matches)].forEach(sel => {
const reg = new RegExp(`(${sel.replace('.', '\\.')}){2,}`, 'mig');
cssContent = cssContent.replace(reg, sel);
});
}
return cssContent;
}
/** Minify CSS */
function minifyCss(cssContent) {
return cssContent
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\s*([{};,])\s*/g, '$1')
.replace(/:\s+/g, ':')
.replace(/;}/g, '}')
.replace(/\s+/g, ' ');
}
function licenseHeader() {
return [
`/* Micrio Client ${version}`,
...fs.readFileSync('./LICENSE').toString().trim().split('\n').map(r => ' * ' + r.trim()),
' */\n\n'
].join('\n');
}
/** Process a single build: strip static styles, prepend minified CSS, write the final dist file. */
function processBuild({ jsName, cssName, outFile, withBook3d }) {
const jsPath = buildDir + jsName;
const cssPath = buildDir + cssName;
// Deduplicate repeated classname hash selectors in CSS
let cssContent = dedupeCssSelectors(fs.readFileSync(cssPath, 'utf-8'));
cssContent = minifyCss(cssContent);
// Strip `static styles="..."` / `static styles='...'` / `static styles=\`...\`` from compiled JS & prepend CSS
let jsRaw = fs.readFileSync(jsPath).toString();
jsRaw = jsRaw.replace(/static\s+styles\s*=\s*(['"`])(?:(?!\1)[\s\S])*?\1\s*;?/g, '');
const escapedCss = cssContent.replace(/[$`]/g, '\\$&');
const jsContent = `const _style=document.createElement('style');_style.className='micrio-interface';_style.textContent=\`${escapedCss}\`;document.head.insertBefore(_style,document.head.firstChild);
${jsRaw}`;
fs.writeFileSync(jsPath, jsContent);
fs.mkdirSync(path.dirname(outFile), { recursive: true });
fs.writeFileSync(outFile, Buffer.concat([
Buffer.from(licenseHeader()),
Buffer.from(fs.readFileSync(jsPath)),
...(withBook3d ? [Buffer.from('\n'), Buffer.from(fs.readFileSync(book3dFile))] : [])
]));
fs.rmSync(jsPath);
fs.rmSync(cssPath);
}
processBuild({
jsName: 'micrio.prod.iife.js',
cssName: 'micrio.prod.css',
outFile: './public/dist/micrio.min.js',
withBook3d: hasBook3d,
});
processBuild({
jsName: 'micrio.prod.core.iife.js',
cssName: 'micrio.prod.core.css',
outFile: './public/dist/micrio.core.min.js',
withBook3d: false,
});
// Generate .d.ts
const dFile = './public/dist/micrio.min.d.ts';
const dtsInput = fs.readFileSync('./out.d.ts', 'utf-8');
const modules = parseDeclareModules(dtsInput);
const internalNames = new Set(modules.keys());
const dtsBundled = bundleDts(modules, internalNames);
fs.writeFileSync(dFile, dtsBundled);
fs.rmSync('./out.d.ts');
fs.rmdirSync(buildDir);
const formatSize = (bytes) => {
const k = 1024;
const sizes = ['B', 'kB', 'MB'];
const i = bytes === 0 ? 0 : Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};
const gzipSize = (filePath) => zlib.gzipSync(fs.readFileSync(filePath)).length;
console.info();
console.info(`\x1b[2mFinal output:\x1b[0m`);
for (const f of ['./public/dist/micrio.min.js', './public/dist/micrio.core.min.js']) {
const raw = fs.statSync(f).size;
const gz = gzipSize(f);
console.info(` \x1b[38;2;0;212;238m\u25C8\x1b[0m \x1b[32m${path.relative('.', f)}\x1b[0m \x1b[1m${formatSize(raw).padStart(9)}\x1b[0m \u2502 gzip: ${formatSize(gz)}`);
}
function parseDeclareModules(input) {
const modules = new Map();
const lines = input.split('\n');
let currentName = null;
let braceDepth = 0;
let contentLines = [];
let insideModule = false;
for (const line of lines) {
const singleMatch = line.match(/^declare module "([^"]+)" \{(.*)\}$/);
if (singleMatch) {
modules.set(singleMatch[1], singleMatch[2] === '' ? '' : singleMatch[2]);
continue;
}
const multiMatch = line.match(/^declare module "([^"]+)" \{$/);
if (multiMatch && !insideModule) {
currentName = multiMatch[1];
insideModule = true;
braceDepth = 1;
contentLines = [];
continue;
}
if (insideModule) {
for (const ch of line) {
if (ch === '{') braceDepth++;
if (ch === '}') braceDepth--;
}
if (braceDepth <= 0) {
modules.set(currentName, contentLines.join('\n'));
insideModule = false;
currentName = null;
contentLines = [];
} else {
contentLines.push(line);
}
}
}
return modules;
}
function bundleDts(modules, internalNames) {
const inlining = new Set();
const inlinedModules = new Set();
function inlineModule(name, extraIndent) {
extraIndent = extraIndent || 0;
if (inlining.has(name)) return '';
if (inlinedModules.has(name)) return '';
inlining.add(name);
const content = modules.get(name);
if (!content || content.trim() === '') {
inlining.delete(name);
inlinedModules.add(name);
return '';
}
const lines = content.split('\n');
const result = [];
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) {
result.push(line);
continue;
}
const indent = line.match(/^\s*/)[0];
const nsExport = trimmed.match(/^export \* as (\w+) from "([^"]+)"\s*;?$/);
if (nsExport) {
const srcModule = nsExport[2];
if (internalNames.has(srcModule)) {
const childContent = inlineModule(srcModule, extraIndent + 1);
if (childContent) {
result.push(`${indent}export namespace ${nsExport[1]} {`);
result.push(childContent);
result.push(`${indent}}`);
}
continue;
}
result.push(line);
continue;
}
const starExport = trimmed.match(/^export \* from "([^"]+)"\s*;?$/);
if (starExport) {
const srcModule = starExport[1];
if (internalNames.has(srcModule)) {
const childContent = inlineModule(srcModule, extraIndent);
if (childContent) {
result.push(childContent);
}
continue;
}
result.push(line);
continue;
}
if (trimmed.startsWith('import "') || trimmed.startsWith("import '")) {
continue;
}
const importAliasMatch = trimmed.match(/^import(?:\s+type)?\s+\{\s*(\w+)\s+as\s+(\w+)\s*\}\s+from\s+"([^"]+)"\s*;?$/);
if (importAliasMatch) {
const srcModule = importAliasMatch[3];
if (internalNames.has(srcModule)) {
result.push(`${indent}type ${importAliasMatch[2]} = ${importAliasMatch[1]};`);
continue;
}
result.push(line);
continue;
}
const importMatch = trimmed.match(/^import(?:\s+type)?\s+(?:\{[^}]*\}|[^\s]+)\s+from\s+"([^"]+)"\s*;?$/);
if (importMatch) {
const srcModule = importMatch[1];
if (internalNames.has(srcModule)) {
continue;
}
result.push(line);
continue;
}
result.push(line);
}
inlining.delete(name);
inlinedModules.add(name);
const output = result.join('\n');
if (extraIndent > 0 && output) {
const indentStr = '\t'.repeat(extraIndent);
return output.split('\n').map(l => l ? indentStr + l : l).join('\n');
}
return output;
}
const modelsContent = inlineModule('types/models', 0);
const processed = [];
for (const name of internalNames) {
if (name === 'types/models' || name === 'types/models/index') continue;
if (inlinedModules.has(name)) continue;
const content = inlineModule(name, 0);
if (content) {
processed.push(content);
}
}
if (modelsContent) processed.unshift(modelsContent);
return `declare module '@micrio/client' {\n${processed.join('\n\n')}\n}`;
}