Files
vibemake/scripts/vendor.mjs
T
2026-10-30 18:43:45 +08:00

83 lines
4.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 把第三方库和字体下载到 vendor/,网站不再依赖外部 CDN(jsdelivr、Google Fonts 在国内经常慢或打不开)。
// 只在升级依赖时运行一次:node scripts/vendor.mjs
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const OUT = join(ROOT, 'vendor');
const CDN = 'https://cdn.jsdelivr.net/npm';
const PKGS = { three: 'three@0.160.0', 'urdf-loader': 'urdf-loader@0.12.3', marked: 'marked@12.0.2', dompurify: 'dompurify@3.1.6' };
// 入口文件(包内路径),import 到的其他文件会自动跟着下载
const ENTRIES = [
['three', 'build/three.module.min.js'], // 压缩版,体积约一半
['three', 'examples/jsm/controls/OrbitControls.js'],
['three', 'examples/jsm/environments/RoomEnvironment.js'],
['three', 'examples/jsm/loaders/GLTFLoader.js'],
['three', 'examples/jsm/loaders/DRACOLoader.js'],
['three', 'examples/jsm/loaders/RGBELoader.js'],
['three', 'examples/jsm/loaders/OBJLoader.js'],
['three', 'examples/jsm/loaders/STLLoader.js'],
['three', 'examples/jsm/loaders/ColladaLoader.js'],
['urdf-loader', 'src/URDFLoader.js'],
['urdf-loader', 'src/URDFDragControls.js'],
['marked', 'lib/marked.esm.js'],
['dompurify', 'dist/purify.es.mjs'],
];
// Draco 解码器(GLB 模型压缩用),不是 import 进来的,单独列出
const EXTRA = [
...['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js'].map((f) => ['three', `examples/jsm/libs/draco/gltf/${f}`]),
['three', 'LICENSE'],
];
const done = new Set();
async function get(pkg, path) {
const key = `${pkg}/${path}`;
if (done.has(key)) return;
done.add(key);
const res = await fetch(`${CDN}/${PKGS[pkg]}/${path}`);
if (!res.ok) throw new Error(`${res.status} ${key}`);
const buf = Buffer.from(await res.arrayBuffer());
// .mjs 存成 .js:很多服务器(如 1Panel 默认 nginx)不认识 .mjs,返回错误的类型,浏览器会拒绝执行
const file = join(OUT, pkg, path.replace(/\.mjs$/, '.js'));
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, buf);
if (!/\.m?js$/.test(path)) return;
// 跟着 import 下载依赖:相对路径在同一个包里;three/examples/jsm/… 这种跨包路径也下载
const text = buf.toString('utf8');
const specs = [...text.matchAll(/(?:import|export)\s[^'"]*?from\s*['"]([^'"]+)['"]|import\s*['"]([^'"]+)['"]/g)].map((m) => m[1] || m[2]);
for (const s of specs) {
if (s.startsWith('.')) await get(pkg, new URL(s, `http://x/${path}`).pathname.slice(1));
else if (s.startsWith('three/examples/jsm/') || s.startsWith('three/addons/')) await get('three', s.replace(/^three\/(addons|examples\/jsm)\//, 'examples/jsm/'));
}
}
// Google Fonts:只下载拉丁字符的 woff2(中文用系统字体),改写成本地地址
async function fonts() {
const css = await (await fetch('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap', {
headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36' },
})).text();
const blocks = css.split(/(?=\/\* [a-z-]+ \*\/)/).filter((b) => /^\/\* (latin|latin-ext) \*\//.test(b));
let out = '/* 本地字体(scripts/vendor.mjs 生成),只含拉丁字符,中文用系统字体 */\n';
let n = 0;
for (const b of blocks) {
let block = b;
for (const [, url] of b.matchAll(/url\((https:[^)]+)\)/g)) {
const name = `f${++n}.woff2`;
mkdirSync(join(OUT, 'fonts'), { recursive: true });
writeFileSync(join(OUT, 'fonts', name), Buffer.from(await (await fetch(url)).arrayBuffer()));
block = block.replace(url, `../vendor/fonts/${name}`);
}
out += block;
}
writeFileSync(join(ROOT, 'css/fonts.css'), out);
return n;
}
// Only replace downloaded packages; retain notices for locally adapted code.
for (const pkg of [...Object.keys(PKGS), 'fonts']) rmSync(join(OUT, pkg), { recursive: true, force: true });
for (const [pkg, path] of [...ENTRIES, ...EXTRA]) await get(pkg, path);
const n = await fonts();
console.log(`已下载 ${done.size} 个库文件、${n} 个字体文件到 vendor/`);