full-stack-svelte-kit
Version:
This framework is built on top of `@sveltejs/kit`.
105 lines (84 loc) • 2.37 kB
JavaScript
import fs from "fs";
import path from "path";
/**
*
* @param {string} content
* @returns {Array<{attrs: any; content: string}>}
*/
export function getScripts(content, regex) {
const scripts = [];
let match;
while ((match = regex.exec(content))) {
const attrs = match[1]
.split(" ")
.map((str) => str.trim())
.filter(Boolean)
.map((str) => {
const [name, quoted_value] = str.split("=");
const value = quoted_value
? quoted_value.replace(/^['"]/, "").replace(/['"]$/, "")
: true;
return { name, value };
})
.reduce((attrs, { name, value }) => {
attrs[name] = value;
return attrs;
}, {});
scripts.push({ attrs, content: match[2] });
}
return scripts;
}
function isDirExisting(path) {
try {
fs.accessSync(path);
return true;
} catch {
return false;
}
}
/** @type {Map<string, Date>} */
export let ModifiedMap = new Map();
const generatedManifestFilePath = path.resolve("./.svelte-kit/generated.json");
export function getGeneratedManifestFromFile() {
try {
const manifest = fs.readFileSync(generatedManifestFilePath, "utf8");
if (!manifest) return;
const manifestJson = JSON.parse(manifest.toString());
ModifiedMap = new Map(
Object.entries(manifestJson).map(([filePath, date]) => [
filePath,
new Date(date),
])
);
} catch (error) {
}
}
export function writeFileIfChanged(filePath, data) {
try {
const dirname = path.dirname(filePath);
const exist = isDirExisting(dirname);
if (!exist) {
fs.mkdirSync(dirname, { recursive: true });
}
try {
const stats = fs.statSync(filePath);
if (stats.isFile()) {
if (ModifiedMap.has(filePath)) {
if (ModifiedMap.get(filePath).getTime() === stats.mtime.getTime()) {
return;
}
}
}
} catch (error) {}
fs.writeFileSync(filePath, data, "utf8");
ModifiedMap.set(filePath, fs.statSync(filePath).mtime);
fs.writeFileSync(
generatedManifestFilePath,
JSON.stringify(Object.fromEntries(ModifiedMap.entries())),
"utf8"
);
} catch (err) {
console.log(err);
throw new Error(err);
}
}