67 lines
2.0 KiB
JavaScript
67 lines
2.0 KiB
JavaScript
|
|
import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||
|
|
import { extname, join, resolve } from 'node:path';
|
||
|
|
|
||
|
|
const rawBase = process.argv[2];
|
||
|
|
|
||
|
|
if (!rawBase || !/^https:\/\//.test(rawBase)) {
|
||
|
|
throw new Error('Usage: npm run rewrite:oss -- https://bucket.example/path/');
|
||
|
|
}
|
||
|
|
|
||
|
|
const base = rawBase.endsWith('/') ? rawBase : `${rawBase}/`;
|
||
|
|
const distDir = resolve('dist');
|
||
|
|
const textExtensions = new Set(['.html', '.js', '.css']);
|
||
|
|
const files = [];
|
||
|
|
|
||
|
|
const collectFiles = (directory) => {
|
||
|
|
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||
|
|
const fullPath = join(directory, entry.name);
|
||
|
|
if (entry.isDirectory()) collectFiles(fullPath);
|
||
|
|
else if (textExtensions.has(extname(entry.name))) files.push(fullPath);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
collectFiles(distDir);
|
||
|
|
|
||
|
|
// Vite has already rewritten static template/CSS URLs. Only rewrite root asset
|
||
|
|
// paths that still begin immediately after a JavaScript quote or template tick.
|
||
|
|
const rootAssetPattern = /(["'`])\/(site|materials|sports-hall)\//g;
|
||
|
|
let changedFiles = 0;
|
||
|
|
|
||
|
|
for (const file of files.filter((item) => extname(item) === '.js')) {
|
||
|
|
const source = readFileSync(file, 'utf8');
|
||
|
|
const rewritten = source.replace(
|
||
|
|
rootAssetPattern,
|
||
|
|
(_match, quote, folder) => `${quote}${base}${folder}/`,
|
||
|
|
);
|
||
|
|
|
||
|
|
if (rewritten !== source) {
|
||
|
|
writeFileSync(file, rewritten, 'utf8');
|
||
|
|
changedFiles += 1;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const duplicatePrefix = `${base.slice(0, -1)}${base}`;
|
||
|
|
const unresolved = [];
|
||
|
|
const duplicated = [];
|
||
|
|
|
||
|
|
for (const file of files) {
|
||
|
|
const content = readFileSync(file, 'utf8');
|
||
|
|
if (content.includes(duplicatePrefix) || /https:\/\/[^\s"'`]+https:\/\//.test(content)) {
|
||
|
|
duplicated.push(file);
|
||
|
|
}
|
||
|
|
if (extname(file) === '.js' && rootAssetPattern.test(content)) {
|
||
|
|
unresolved.push(file);
|
||
|
|
}
|
||
|
|
rootAssetPattern.lastIndex = 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (duplicated.length) {
|
||
|
|
throw new Error(`Duplicated OSS prefix found in: ${duplicated.join(', ')}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (unresolved.length) {
|
||
|
|
throw new Error(`Root asset paths remain in: ${unresolved.join(', ')}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log(`OSS paths verified. Rewritten files: ${changedFiles}`);
|