feat: modernize static site generator stack
- Node.js: Upgraded from v16 to v22 (latest LTS) - SASS: Replaced deprecated node-sass with Dart Sass (sass package) - Metalsmith plugins: Migrated to modern scoped packages: - @metalsmith/markdown (v1.10) replacing metalsmith-markdownit - @metalsmith/in-place (v5) replacing metalsmith-in-place v1 - @metalsmith/layouts (v3) replacing metalsmith-layouts v1 - @metalsmith/collections (v2) replacing metalsmith-collections v0 - Added metalsmith-define for site metadata - Added gray-matter for YAML front matter extraction - Markdown rendering: Updated to marked v18 for GFM support - Express: Kept at v4.x (stable, compatible) - Handlebars: Updated to v4.7 (latest) - Custom plugins: Created local permalinks and handlebars-html plugins - Custom permalinks plugin replaces metalsmith-permalinks (broken substitute dep) - Custom handlebars jstransformer wrapper supports .html extension - Feed generation: Custom RSS plugin (replaces deprecated metalsmith-feed) - filterRoutes: Updated regex patterns for Express compatibility - Template changes: Removed deprecated markdown="1" from partials - Docker: Updated Dockerfile to use Node 22 Alpine - Collection patterns: Updated to support both .md and .markdown extensions - Pipeline: Reordered for correct metadata flow (front matter → markdown → layouts → permalinks)
This commit is contained in:
1 parent
35e9dfe24b
commit
7a5c031b1d
9 files changed
+855
-231
No files matched your search
@@ -0,0 +1,99 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const Handlebars = require("handlebars");
|
||||
const moment = require("moment");
|
||||
const striptags = require("striptags");
|
||||
const { marked } = require("marked");
|
||||
|
||||
// Setup marked renderer
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
const renderer = new marked.Renderer();
|
||||
const originalTable = renderer.table.bind(renderer);
|
||||
renderer.table = function (e) {
|
||||
let result = originalTable(e);
|
||||
return result.replace("<table>", '<table role="grid">');
|
||||
};
|
||||
|
||||
// Register helpers on Handlebars
|
||||
Handlebars.registerHelper("markdown", function (text) {
|
||||
if (!text) return "";
|
||||
return marked.parse(text, { renderer });
|
||||
});
|
||||
Handlebars.registerHelper("moment", function (date, format) {
|
||||
return new moment(date).format(format);
|
||||
});
|
||||
Handlebars.registerHelper("striptags", function (text) {
|
||||
return striptags(text);
|
||||
});
|
||||
Handlebars.registerHelper("buildTitle", function (title, siteTitle) {
|
||||
if (title.indexOf(siteTitle) < 0) {
|
||||
title = "'" + title + "' by " + siteTitle;
|
||||
}
|
||||
return title;
|
||||
});
|
||||
Handlebars.registerHelper("jointags", function (tags) {
|
||||
return (tags || "").split(" ").join(",");
|
||||
});
|
||||
Handlebars.registerHelper("encodetitle", function (str) {
|
||||
return (str || "").replaceAll(" ", "%2B");
|
||||
});
|
||||
|
||||
// Load all partials from templates/partials directory
|
||||
const partialsDir = path.join(__dirname, "..", "templates", "partials");
|
||||
if (fs.existsSync(partialsDir)) {
|
||||
fs.readdirSync(partialsDir).forEach((file) => {
|
||||
const name = path.parse(file).name;
|
||||
const content = fs.readFileSync(path.join(partialsDir, file), "utf8");
|
||||
Handlebars.registerPartial(name, content);
|
||||
});
|
||||
}
|
||||
|
||||
// Compile a template file (used by renderFileAsync)
|
||||
function compile(filePath) {
|
||||
const template = fs.readFileSync(filePath, "utf8");
|
||||
return {
|
||||
fn: Handlebars.compile(template),
|
||||
dependencies: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Render a template string with locals
|
||||
function render(templateStr, opts, locals) {
|
||||
const template = Handlebars.compile(templateStr);
|
||||
const output = template(locals);
|
||||
return { body: output, dependencies: [] };
|
||||
}
|
||||
|
||||
// Render a template file with locals
|
||||
async function renderFileAsync(filePath, opts, locals) {
|
||||
const template = fs.readFileSync(filePath, "utf8");
|
||||
const compiled = Handlebars.compile(template);
|
||||
const output = compiled(locals);
|
||||
return { body: output, dependencies: [] };
|
||||
}
|
||||
|
||||
// Assemble the jstransformer interface
|
||||
const jstransformer = {
|
||||
name: "handlebars",
|
||||
inputFormats: ["hbs", "handlebars", "html"],
|
||||
outputFormat: "html",
|
||||
compile: function (templateStr) {
|
||||
const compiled = Handlebars.compile(templateStr);
|
||||
return { fn: compiled, dependencies: [] };
|
||||
},
|
||||
render: function (templateStr, opts, locals) {
|
||||
return render(templateStr, opts, locals);
|
||||
},
|
||||
renderAsync: async function (templateStr, opts, locals) {
|
||||
return render(templateStr, opts, locals);
|
||||
},
|
||||
renderFileAsync: async function (filePath, opts, locals) {
|
||||
return renderFileAsync(filePath, opts, locals);
|
||||
},
|
||||
registerPartial: Handlebars.registerPartial.bind(Handlebars),
|
||||
registerHelper: Handlebars.registerHelper.bind(Handlebars),
|
||||
partials: Handlebars.partials,
|
||||
helpers: Handlebars.helpers,
|
||||
};
|
||||
|
||||
module.exports = jstransformer;
|
||||
@@ -0,0 +1,195 @@
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
/**
|
||||
* Custom Metalsmith permalinks plugin.
|
||||
* Preserves source directory structure for posts, applies custom patterns for pages.
|
||||
*/
|
||||
function permalinks(options) {
|
||||
const defaultOptions = {
|
||||
pattern: ":date-:title",
|
||||
date: {
|
||||
format: "YYYY-MM-DD",
|
||||
locale: "en",
|
||||
},
|
||||
linksets: [],
|
||||
slug: {
|
||||
lowercase: true,
|
||||
remove: /[<>:"'\|?*]|[^\w\s$_+~.()!\-@\/]+/g,
|
||||
extend: { ":": "-", "|": "-", "/": "-", "<": "", ">": "" },
|
||||
},
|
||||
trailingSlash: false,
|
||||
directoryIndex: "index.html",
|
||||
};
|
||||
|
||||
const opts = { ...defaultOptions, ...options };
|
||||
|
||||
function formatDate(date) {
|
||||
if (!date || !(date instanceof Date)) return "";
|
||||
const d = date;
|
||||
const format = opts.date.format || "YYYY-MM-DD";
|
||||
return format
|
||||
.replace("YYYY", d.getFullYear())
|
||||
.replace("MM", String(d.getMonth() + 1).padStart(2, "0"))
|
||||
.replace("DD", String(d.getDate()).padStart(2, "0"))
|
||||
.replace("D", String(d.getDate()))
|
||||
.replace("H", String(d.getHours()).padStart(2, "0"))
|
||||
.replace("m", String(d.getMinutes()).padStart(2, "0"))
|
||||
.replace("s", String(d.getSeconds()).padStart(2, "0"));
|
||||
}
|
||||
|
||||
function slugify(str) {
|
||||
if (!str) return "";
|
||||
let s = str.toString();
|
||||
if (opts.slug.lowercase) s = s.toLowerCase();
|
||||
if (opts.slug.extend) {
|
||||
for (const [from, to] of Object.entries(opts.slug.extend)) {
|
||||
s = s.split(from).join(to);
|
||||
}
|
||||
}
|
||||
// Replace spaces with dashes and remove special chars
|
||||
s = s.replace(/\s+/g, "-");
|
||||
if (opts.slug.remove) {
|
||||
s = s.replace(new RegExp(opts.slug.remove, "g"), "");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function replacePattern(pattern, data) {
|
||||
return pattern.replace(/:(\w+)(\??)/g, (match, key, optional) => {
|
||||
let value = data[key];
|
||||
if (value === undefined || value === null) {
|
||||
if (optional) return "";
|
||||
throw new Error(
|
||||
`Could not substitute ':${key}' in pattern '${pattern}', '${key}' is undefined`
|
||||
);
|
||||
}
|
||||
// For date in permalink, use _filenameDate if available (to avoid collisions
|
||||
// when front matter date differs from filename date)
|
||||
if (key === 'date' && data._filenameDate) {
|
||||
return formatDate(data._filenameDate);
|
||||
}
|
||||
// For title in permalink, use _filenameTitle if available (to match source filenames)
|
||||
if (key === 'title' && data._filenameTitle) {
|
||||
return slugify(data._filenameTitle);
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return formatDate(value);
|
||||
}
|
||||
return slugify(value.toString());
|
||||
});
|
||||
}
|
||||
|
||||
function getMatchedLinkset(data, linksets) {
|
||||
for (const linkset of linksets) {
|
||||
if (linkset.match) {
|
||||
let matched = false;
|
||||
for (const [key, val] of Object.entries(linkset.match)) {
|
||||
const fileVal = data[key];
|
||||
if (Array.isArray(fileVal)) {
|
||||
if (fileVal.includes(val)) {
|
||||
matched = true;
|
||||
}
|
||||
} else if (fileVal === val) {
|
||||
matched = true;
|
||||
} else {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched) return linkset;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return function (files, metalsmith, done) {
|
||||
const keys = Object.keys(files);
|
||||
|
||||
for (const file of keys) {
|
||||
const data = files[file];
|
||||
|
||||
// Skip non-HTML files
|
||||
if (!file.endsWith(".html")) continue;
|
||||
|
||||
// Skip if permalink is explicitly disabled
|
||||
if (data.permalink === false) continue;
|
||||
|
||||
// Skip if this is a layout/template file (has layout that matches filename)
|
||||
// e.g., index.html with layout: 'index.html' should not be permalinked
|
||||
const baseName = path.basename(file, '.html');
|
||||
if (data.layout === baseName || data.layout === `${baseName}.html`) continue;
|
||||
|
||||
// Determine which linkset to use (or default)
|
||||
const linkset = getMatchedLinkset(data, opts.linksets) || opts;
|
||||
const pattern = linkset.pattern || opts.pattern;
|
||||
|
||||
// Check file-specific permalink first
|
||||
if (data.permalink) {
|
||||
data.permalink = replacePattern(data.permalink, data);
|
||||
if (opts.trailingSlash) data.permalink = data.permalink.replace(/\/+$/, "");
|
||||
continue;
|
||||
}
|
||||
|
||||
// For posts: preserve the "posts/" prefix
|
||||
// For other files: use the pattern as-is
|
||||
let sourcePrefix = "";
|
||||
if (file.startsWith("posts/")) {
|
||||
sourcePrefix = "posts/";
|
||||
} else if (file.startsWith("pages/")) {
|
||||
sourcePrefix = "pages/";
|
||||
}
|
||||
|
||||
// Replace pattern placeholders
|
||||
let result = replacePattern(pattern, data);
|
||||
|
||||
// Remove trailing slashes if not desired
|
||||
if (!opts.trailingSlash) {
|
||||
result = result.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
// Add directory index
|
||||
if (path.extname(result) === "" || path.extname(result) === ".html") {
|
||||
if (!path.extname(result)) {
|
||||
result = path.join(result, opts.directoryIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Prepend source directory prefix
|
||||
data.permalink = sourcePrefix + result;
|
||||
|
||||
// Set path metadata for templates (permalink without index.html)
|
||||
if (data.permalink.endsWith("/index.html")) {
|
||||
data.path = data.permalink.replace(/\/index\.html$/, "");
|
||||
} else if (path.extname(data.permalink) === ".html") {
|
||||
data.path = data.permalink.replace(/\.html$/, "");
|
||||
} else {
|
||||
data.path = data.permalink;
|
||||
}
|
||||
}
|
||||
|
||||
// Now rename files based on permalink metadata
|
||||
const renames = [];
|
||||
for (const [file, data] of Object.entries(files)) {
|
||||
if (!data.permalink) continue;
|
||||
if (data.permalink === file) continue; // No change needed
|
||||
|
||||
renames.push([file, data.permalink]);
|
||||
}
|
||||
|
||||
for (const [oldName, newName] of renames) {
|
||||
// Create target directory if needed
|
||||
const targetDir = path.dirname(newName);
|
||||
if (!fs.existsSync(targetDir)) {
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
// Move file
|
||||
files[newName] = files[oldName];
|
||||
delete files[oldName];
|
||||
}
|
||||
|
||||
done();
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = permalinks;
|
||||
Reference in new issue
Block a user