next-dynamic-sitemap
Version:
A lightweight, zero-touch sitemap generator for any nextjs project
63 lines (62 loc) • 2.99 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recursePagesDir = recursePagesDir;
const promises_1 = require("fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const util_1 = require("./util");
const constants_1 = require("./constants");
const build_1 = require("./build");
const API_PATH_RE = /^api\//;
const META_PATH_RE = /^_[A-z0-9]+\.[tj]sx?$/;
function introspectPage(root, page) {
return __awaiter(this, void 0, void 0, function* () {
const pagePath = node_path_1.default.join(root, page);
const pageURLPath = page.replace(constants_1.PAGE_SUFFIX_RE, "");
const pageStats = yield (0, promises_1.stat)(node_path_1.default.join(process.cwd(), pagePath));
const lastmod = new Date(pageStats.mtime).toISOString();
if (/\[/.test(pagePath)) {
const bundle = yield (0, build_1.bundlePage)(pagePath);
if ("getStaticPaths" in bundle &&
typeof bundle.getStaticPaths === "function") {
const result = yield bundle.getStaticPaths();
return result.paths.map((params) => (0, util_1.parameterizePath)(pageURLPath, lastmod, params.params));
}
}
return [
{
loc: (0, util_1.generateURL)(pageURLPath),
lastmod,
priority: pageURLPath ? 0.8 : 1, // home page gets higher priority
},
];
});
}
function recursePagesDir(root) {
return __awaiter(this, void 0, void 0, function* () {
const contents = yield (0, promises_1.readdir)(node_path_1.default.join(process.cwd(), root), {
recursive: true,
});
const pages = contents
.filter((p) => !API_PATH_RE.test(p))
.filter((p) => !META_PATH_RE.test(p))
.filter((p) => constants_1.PAGE_SUFFIX_RE.test(p));
const metadata = yield Promise.all(pages.map((page) => introspectPage(root, page)));
const metadataFlattened = [];
metadata.forEach((page) => {
metadataFlattened.push(...page);
});
return metadataFlattened;
});
}