Skip to content

Commit

Permalink
feat: Add Plausible Analytics (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nesqwik authored May 3, 2022
1 parent dded296 commit 54e8bbd
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 89 deletions.
175 changes: 87 additions & 88 deletions src/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const Views = require('./utils/views');
const Utils = require('./utils/common');
// const minify = require('minify');

const {languagePriority} = require('./config.json');
const { languagePriority } = require('./config.json');
const minify = require('minify');

const srcPath = Path.join(__dirname);
Expand All @@ -21,92 +21,91 @@ const languageFileRegex = /^(.+)[.]([a-z]{2})([.]pug)$/
fs.mkdirsSync(Path.join(wwwPath));
// copy static directory
getFilesRecursively(staticSrcPath)
.map(file => {
const relativePath = Path.relative(staticSrcPath, file);
const destinationPath = Path.join(staticDestPath, relativePath);
const destinationDir = Path.dirname(destinationPath);
const ext = Path.extname(file).toLowerCase();
if (/^.*\/\.[^/]+$/.test(file)) return;
fs.mkdirsSync(destinationDir);
switch (ext) {
case '.html':
case '.js':
return minify(file)
.then(content => fs.writeFile(destinationPath, content));
case '.css':
const content = minify.css(`@import "${Path.relative(process.cwd(), file)}";`, {
css: {
rebase: false
},
img: {
maxSize: 1
}
});
return fs.writeFile(destinationPath, content);
default:
return fs.copyFile(file, destinationPath);
}
});
.map(file => {
const relativePath = Path.relative(staticSrcPath, file);
const destinationPath = Path.join(staticDestPath, relativePath);
const destinationDir = Path.dirname(destinationPath);
const ext = Path.extname(file).toLowerCase();
if (/^.*\/\.[^/]+$/.test(file)) return;
fs.mkdirsSync(destinationDir);
switch (ext) {
case '.html':
case '.js':
return minify(file)
.then(content => fs.writeFile(destinationPath, content));
case '.css':
const content = minify.css(`@import "${Path.relative(process.cwd(), file)}";`, {
css: {
rebase: false
},
img: {
maxSize: 1
}
});
return fs.writeFile(destinationPath, content);
default:
return fs.copyFile(file, destinationPath);
}
});
// list pug files
const viewsDirPath = Path.join(srcPath, 'views');
const langViews = {};
const views = getFilesRecursively(viewsDirPath)
.filter(file => !Path.basename(file).startsWith('.'))
.map(file => Path.relative(viewsDirPath, file))
.filter(file => {
const match = file.match(languageFileRegex);
if (!match) return true;
const lang = match[2];
const f = match[1]+match[3];
if (!langViews[lang]) langViews[lang] = {};
langViews[lang][f] = file;
});
.filter(file => !Path.basename(file).startsWith('.'))
.map(file => Path.relative(viewsDirPath, file))
.filter(file => {
const match = file.match(languageFileRegex);
if (!match) return true;
const lang = match[2];
const f = match[1] + match[3];
if (!langViews[lang]) langViews[lang] = {};
langViews[lang][f] = file;
});
// list all the available languages
Translations.loadTranslations()
.then(ts => {
const languages = Object.keys(ts);
for (const lang in ts) {
fs.mkdirs(Path.join(wwwPath, lang)).then(() => {
const props = Utils.mergeDeep({}, common, ts[lang], {language: lang, languages: languages, otherLanguages: languages.filter(l => l!=lang)});
views.map(file => ({
file: file.replace(/[.]pug$/, ""),
.then(ts => {
const languages = Object.keys(ts);
for (const lang in ts) {
fs.mkdirs(Path.join(wwwPath, lang)).then(() => {
const props = Utils.mergeDeep({}, common, ts[lang], { language: lang, languages: languages, otherLanguages: languages.filter(l => l != lang) });
views.map(file => ({
file: file.replace(/[.]pug$/, ""),
pugFile: (lang in langViews && file in langViews[lang])
? langViews[lang][file]
: file
}))
.map(({file, pugFile}) => ({
file,
html: pug.renderFile(Path.join(viewsDirPath, pugFile), { ...props, currentPage: { ...props.page[file], path: file }})
}))
.map(async ({file, html}) => {
const filePath = Path.join(wwwPath, lang, `${file}.html`);
html = await minify.html(html);
await fs.writeFile(filePath, html);
});
// TODO: generate page previews "index.html.jpg" for each social network dimension
});
}

.map(({ file, pugFile }) => ({
file,
html: pug.renderFile(Path.join(viewsDirPath, pugFile), { ...props, currentPage: { ...props.page[file], path: file } })
}))
.map(async ({ file, html }) => {
const filePath = Path.join(wwwPath, lang, `${file}.html`);
html = await minify.html(html);
await fs.writeFile(filePath, html);
});
// TODO: generate page previews "index.html.jpg" for each social network dimension
});
}

// generate the nginx.conf file
const langs = Object.keys(ts).sort((a, b) => {
const posA = languagePriority.indexOf(a);
const posB = languagePriority.indexOf(b);
if (posA!=-1 && posB!=-1) return posA - posB;
if (posA!=-1) return -1;
if (posB!=-1) return +1;
if (a < b) return -1;
return 1;
});
const conf =
`map $http_accept_language $lang {

// generate the nginx.conf file
const langs = Object.keys(ts).sort((a, b) => {
const posA = languagePriority.indexOf(a);
const posB = languagePriority.indexOf(b);
if (posA != -1 && posB != -1) return posA - posB;
if (posA != -1) return -1;
if (posB != -1) return +1;
if (a < b) return -1;
return 1;
});
const conf =
`map $http_accept_language $lang {
default ${langs[0]};
${
langs
.map(((lang, i) => acceptLangMapper(langs, lang, i)))
.join('\n ')
}
${langs
.map(((lang, i) => acceptLangMapper(langs, lang, i)))
.join('\n ')
}
}
map $http_x_forwarded_proto $initial_scheme {
Expand All @@ -123,7 +122,7 @@ server {
charset_types text/css application/javascript;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; frame-src 'self' *.youtube-nocookie.com;";
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' plausible.io; object-src 'none'; base-uri 'self'; frame-src 'self' *.youtube-nocookie.com;";
add_header Vary "Accept-Encoding";
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
Expand Down Expand Up @@ -152,21 +151,22 @@ server {
try_files /$lang$uri /$lang$uri$index /$lang$uri/$index /static$uri /$lang$index /$lang/$index =404;
sub_filter '!CURRENT_URL!' '$initial_scheme://$host$request_uri';
sub_filter '!DOMAIN!' '$host';
sub_filter '!BASE_URL!' '$initial_scheme://$host';
sub_filter '!CURRENT_URL!' '$initial_scheme://$host$request_uri';
sub_filter '!IMAGE_URL!' '$initial_scheme://$host$uri.jpg';
}
}
`;
fs.writeFile(Path.join(buildPath, `nginx.conf`), conf);
fs.writeFile(Path.join(buildPath, `nginx.conf`), conf);

// generate the sitemap.txt file
// fs.writeFile(Path.join(staticDestPath, `sitemap.txt`),
// pages.flatMap(getPagesToGenerate)
// .map(page => `!BASE_URL!${page.path}`)
// .join('\n')
// );
});
// generate the sitemap.txt file
// fs.writeFile(Path.join(staticDestPath, `sitemap.txt`),
// pages.flatMap(getPagesToGenerate)
// .map(page => `!BASE_URL!${page.path}`)
// .join('\n')
// );
});

/**
*
Expand All @@ -176,11 +176,10 @@ server {
* @returns
*/
function acceptLangMapper(langs, lang, i) {
return `~${
i<langs.length-1
? `^(((?!(${langs.slice(i+1).join('|')})).)+,)*`
return `~${i < langs.length - 1
? `^(((?!(${langs.slice(i + 1).join('|')})).)+,)*`
: ''
}${lang}.* ${lang};`;
}${lang}.* ${lang};`;
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/views/.layout.pug
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ html(lang=language)
meta(name="description" content=currentPage.description)
meta(property="og:title" content=title)
meta(property="og:type" content="website")
meta(property="og:url" content="!BASE_URL!/")
meta(property="og:url" content="!CURRENT_URL!")
meta(property="og:image" content="!IMAGE_URL!")
meta(property="og:description" content=currentPage.description)
meta(property="og:locale" content=language)
Expand All @@ -21,6 +21,8 @@ html(lang=language)
link(rel='stylesheet' as='style' type='text/css' href='css/main.css')
link(rel='stylesheet' as='style' type='text/css' href='css/' + currentPage.path + '.css')
script(src='js/main.js' defer)
script(src="https://plausible.io/js/plausible.js" data-domain="!DOMAIN!" defer)

body
include .header.pug
main
Expand Down

0 comments on commit 54e8bbd

Please sign in to comment.