-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathwebpack-libs-plugin.js
More file actions
308 lines (256 loc) · 9.88 KB
/
Copy pathwebpack-libs-plugin.js
File metadata and controls
308 lines (256 loc) · 9.88 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
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
#!/usr/bin/env node
import { exec } from 'node:child_process';
import { createWriteStream, existsSync } from 'node:fs';
import fs from 'node:fs/promises';
import https from 'node:https';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { promisify } from 'node:util';
const execAsync = promisify(exec);
class OpenSCADLibrariesPlugin {
constructor(options = {}) {
this.configFile = options.configFile || 'libs-config.json';
this.libsDir = options.libsDir || 'libs';
this.publicLibsDir = options.publicLibsDir || 'public/libraries';
this.srcWasmDir = options.srcWasmDir || 'src/wasm';
this.buildMode = options.buildMode || 'all'; // 'all', 'wasm', 'fonts', 'libs'
this.config = null;
}
apply(compiler) {
const pluginName = 'OpenSCADLibrariesPlugin';
compiler.hooks.beforeRun.tapAsync(pluginName, async (_, callback) => {
try {
await this.loadConfig();
switch (this.buildMode) {
case 'all':
await this.buildAll();
break;
case 'wasm':
await this.buildWasm();
break;
case 'fonts':
await this.buildFonts();
break;
case 'libs':
await this.buildAllLibraries();
break;
case 'clean':
await this.clean();
break;
}
callback();
} catch (error) {
callback(error);
}
});
}
async loadConfig() {
try {
const configContent = await fs.readFile(this.configFile, 'utf-8');
this.config = JSON.parse(configContent);
} catch (error) {
throw new Error(`Failed to load config from ${this.configFile}: ${error.message}`);
}
}
async ensureDir(dirPath) {
try {
await fs.mkdir(dirPath, { recursive: true });
} catch (error) {
if (error.code !== 'EEXIST') {
throw error;
}
}
}
async downloadFile(url, outputPath) {
console.log(`Downloading ${url} to ${outputPath}`);
return new Promise((resolve, reject) => {
https.get(url, (response) => {
if (response.statusCode === 302 || response.statusCode === 301) {
return this.downloadFile(response.headers.location, outputPath)
.then(resolve)
.catch(reject);
}
if (response.statusCode !== 200) {
reject(new Error(`Failed to download: ${response.statusCode}`));
return;
}
const fileStream = createWriteStream(outputPath);
pipeline(response, fileStream)
.then(resolve)
.catch(reject);
}).on('error', reject);
});
}
async cloneRepo(repo, targetDir, branch = 'master', shallow = true) {
const cloneArgs = [
'clone',
'--recurse',
shallow ? '--depth 1' : '',
`--branch ${branch}`,
'--single-branch',
repo,
targetDir
].filter(Boolean);
console.log(`Cloning ${repo} to ${targetDir}`);
try {
await execAsync(`git ${cloneArgs.join(' ')}`);
} catch (error) {
console.error(`Failed to clone ${repo}:`, error.message);
throw error;
}
}
async createZip(sourceDir, outputPath, includes = [], excludes = [], workingDir = '.') {
await this.ensureDir(path.dirname(outputPath));
const fullSourceDir = path.join(sourceDir, workingDir);
// Build find command for includes
let findCmd = '';
if (includes.length > 0) {
const findPatterns = includes.map(pattern => {
if (pattern.includes('**/*.')) {
const parts = pattern.split('/');
const dir = parts[0];
const filePattern = parts[parts.length - 1];
return `-path "./${dir}/*" -name "${filePattern}"`;
} else if (pattern.includes('**')) {
const filePattern = pattern.replace('**/', '');
return `-name "${filePattern}"`;
} else if (pattern.includes('*')) {
return `-name "${pattern}"`;
} else if (pattern.includes('/')) {
return `-path "./${pattern}"`;
} else {
return `-name "${pattern}" -o -path "./${pattern}/*"`;
}
}).join(' -o ');
findCmd = `find . \\( ${findPatterns} \\)`;
} else {
findCmd = 'find . -name "*.scad"';
}
// Add excludes
if (excludes.length > 0) {
const excludePatterns = excludes.map(pattern => {
const cleanPattern = pattern.replace('**/', '').replace('/**', '');
return `-not -path "*/${cleanPattern}*"`;
}).join(' ');
findCmd += ` ${excludePatterns}`;
}
const zipCmd = `cd ${fullSourceDir} && ${findCmd} | zip -r ${path.resolve(outputPath)} -@`;
console.log(`Creating zip: ${outputPath}`);
try {
await execAsync(zipCmd);
} catch (error) {
console.error(`Failed to create zip ${outputPath}:`, error.message);
throw error;
}
}
async buildWasm() {
const { wasmBuild } = this.config;
const wasmDir = wasmBuild.target;
const wasmZip = `${wasmDir}.zip`;
await this.ensureDir(this.libsDir);
if (!existsSync(wasmDir)) {
await this.ensureDir(wasmDir);
await this.downloadFile(wasmBuild.url, wasmZip);
console.log(`Extracting WASM to ${wasmDir}`);
await execAsync(`cd ${wasmDir} && unzip ../${path.basename(wasmZip)}`);
}
await this.ensureDir('public');
const jsTarget = 'public/openscad.js';
const wasmTarget = 'public/openscad.wasm';
// Remove existing symlinks/files
try {
await fs.unlink(jsTarget);
} catch { /* ignore */ }
try {
await fs.unlink(wasmTarget);
} catch { /* ignore */ }
// Create new symlinks
await fs.symlink(path.relative('public', path.join(wasmDir, 'openscad.js')), jsTarget);
await fs.symlink(path.relative('public', path.join(wasmDir, 'openscad.wasm')), wasmTarget);
// Create src/wasm symlink
try {
await fs.unlink(this.srcWasmDir);
} catch { /* ignore */ }
await fs.symlink(path.relative('src', wasmDir), this.srcWasmDir);
console.log('WASM setup completed');
}
async buildFonts() {
const { fonts } = this.config;
const notoDir = path.join(this.libsDir, 'noto');
const liberationDir = path.join(this.libsDir, 'liberation');
await this.ensureDir(notoDir);
// Download Noto fonts
for (const font of fonts.notoFonts) {
const fontPath = path.join(notoDir, font);
if (!existsSync(fontPath)) {
const url = fonts.notoBaseUrl + font;
await this.downloadFile(url, fontPath);
}
}
// Clone liberation fonts if not exists
if (!existsSync(liberationDir)) {
await this.cloneRepo(fonts.liberationRepo, liberationDir, fonts.liberationBranch);
}
// Create fonts zip
const fontsZip = path.join(this.publicLibsDir, 'fonts.zip');
await this.ensureDir(this.publicLibsDir);
console.log('Creating fonts.zip');
const fontsCmd = `zip -r ${fontsZip} -j fonts.conf libs/noto/*.ttf libs/liberation/*.ttf libs/liberation/LICENSE libs/liberation/AUTHORS`;
await execAsync(fontsCmd);
console.log('Fonts setup completed');
}
async buildLibrary(library) {
const libDir = path.join(this.libsDir, library.name);
const zipPath = path.join(this.publicLibsDir, `${library.name}.zip`);
// Clone repository if not exists
if (!existsSync(libDir)) {
await this.cloneRepo(library.repo, libDir, library.branch);
}
// Create zip
await this.createZip(
libDir,
zipPath,
library.zipIncludes || ['*.scad'],
library.zipExcludes || [],
library.workingDir || '.'
);
console.log(`Built ${library.name}`);
}
async buildAllLibraries() {
await this.ensureDir(this.publicLibsDir);
for (const library of this.config.libraries) {
await this.buildLibrary(library);
}
}
async clean() {
console.log('Cleaning build artifacts...');
const cleanPaths = [
this.libsDir,
'build',
'public/openscad.js',
'public/openscad.wasm',
`${this.publicLibsDir}/*.zip`,
this.srcWasmDir
];
for (const cleanPath of cleanPaths) {
try {
if (cleanPath.includes('*')) {
await execAsync(`rm -f ${cleanPath}`);
} else {
await fs.rm(cleanPath, { recursive: true, force: true });
}
} catch {
// Ignore errors for files that don't exist
}
}
console.log('Clean completed');
}
async buildAll() {
console.log('Building all libraries...');
await this.buildWasm();
await this.buildFonts();
await this.buildAllLibraries();
console.log('Build completed successfully!');
}
}
export default OpenSCADLibrariesPlugin;