1
Fork 0
userstyles/source/utilities.js

66 lines
1.8 KiB
JavaScript

const {promises: fsp} = require('fs');
const {join} = require('path');
const sass = require('sass');
const usercss = require('usercss-meta');
/**
* Creates the userstyle for a given style.
* @param {string} style The style's source directory.
* @param {string} dir The style's output directory.
*/
async function createUserstyle(style, dir) {
// Read the style's metadata.
const metadata = await readStyleMetadata(style);
// Build the style's CSS.
const scss = sass.renderSync({
file: join(__dirname, style, `${style}.scss`),
outputStyle: 'expanded'
});
// Insert the `@-moz-document domain()` into the CSS.
const domain = metadata.domain;
const css = `\n@-moz-document domain("${domain}") {\n${scss.css.toString()}\n}\n`;
// Remove the domain from the metadata, as it's not needed in the usercss data.
delete metadata.domain;
// Create the userstyle.
const userstyle = usercss.stringify(metadata, {alignKeys: true}) + css;
// Create the destination path for the userstyle.
const destination = join(__dirname, '..', dir, `${style}.user.css`);
// Write the userstyle to file.
return fsp.writeFile(destination, userstyle);
}
/**
* Reads and parses the `metadata.json` file from a given style.
* @param {string} style The style's source directory.
*/
async function readStyleMetadata(style) {
return JSON.parse(
await fsp.readFile(join(__dirname, style, 'metadata.json'), 'utf8')
);
}
/**
* Returns whether the given style has an `images/` directory.
* @param {string} style The style's source directory.
*/
async function styleHasImages(style) {
try {
const styleStat = await fsp.stat(join(__dirname, style, 'images'));
return styleStat.isDirectory();
} catch {
return false;
}
}
module.exports = {
createUserstyle,
readStyleMetadata,
styleHasImages
};