sitemap
Version:
Sitemap-generating lib/cli
369 lines (368 loc) • 15.2 kB
JavaScript
import { WriteStream } from 'node:fs';
import { Transform, } from 'node:stream';
import { finished } from 'node:stream/promises';
import { ErrorLevel, IndexTagNames, } from './types.js';
import { resolveLogger } from './logger.js';
import { errorMessage } from './utils.js';
import { SitemapStream, stylesheetInclude } from './sitemap-stream.js';
import { element, otag, ctag } from './sitemap-xml.js';
import { LIMITS, DEFAULT_SITEMAP_ITEM_LIMIT } from './constants.js';
import { validateURL, validateXSLUrl } from './validation.js';
import { toError } from './utils.js';
// Re-export IndexTagNames for backward compatibility
export { IndexTagNames };
const xmlDec = '<?xml version="1.0" encoding="UTF-8"?>';
const sitemapIndexTagStart = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
const closetag = '</sitemapindex>';
const defaultStreamOpts = {};
/**
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
*
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
*
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
* before `finish` will be emitted. Failure to read the stream will result in hangs.
*
* @extends {Transform}
*/
export class SitemapIndexStream extends Transform {
lastmodDateOnly;
level;
xslUrl;
logger;
hasHeadOutput;
/**
* `SitemapIndexStream` is a Transform stream that takes `IndexItem`s or sitemap URL strings and outputs a stream of sitemap index XML.
*
* It automatically handles the XML declaration and the opening and closing tags for the sitemap index.
*
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
* before `finish` will be emitted. Failure to read the stream will result in hangs.
*
* @param {SitemapIndexStreamOptions} [opts=defaultStreamOpts] - Stream options.
*/
constructor(opts = defaultStreamOpts) {
opts.objectMode = true;
super(opts);
this.hasHeadOutput = false;
this.lastmodDateOnly = opts.lastmodDateOnly || false;
this.level = opts.level ?? ErrorLevel.WARN;
// Resolve without the level: `level` is a public field that callers may
// change after construction, so warn() checks it at call time instead
this.logger = resolveLogger(ErrorLevel.WARN, opts.logger);
if (opts.xslUrl !== undefined) {
validateXSLUrl(opts.xslUrl);
}
this.xslUrl = opts.xslUrl;
}
/** Log a warning unless the current level is SILENT */
warn(...message) {
if (this.level !== ErrorLevel.SILENT) {
this.logger('warn', ...message);
}
}
writeHeadOutput() {
this.hasHeadOutput = true;
let stylesheet = '';
if (this.xslUrl) {
stylesheet = stylesheetInclude(this.xslUrl);
}
this.push(xmlDec + stylesheet + sitemapIndexTagStart);
}
_transform(item, encoding, callback) {
if (!this.hasHeadOutput) {
this.writeHeadOutput();
}
try {
// Validate URL using centralized validation (checks protocol, length, format)
const url = typeof item === 'string' ? item : item.url;
if (!url || typeof url !== 'string') {
const error = new Error('Invalid sitemap index item: URL must be a non-empty string');
if (this.level === ErrorLevel.THROW) {
callback(error);
return;
}
else {
this.warn(error.message, item);
}
// The logger is a no-op at SILENT; skip this item
callback();
return;
}
// Security: Use centralized validation to enforce protocol restrictions,
// length limits, and prevent injection attacks
try {
validateURL(url, 'Sitemap index URL');
}
catch (error) {
// Wrap the validation error with consistent message format
const validationMsg = error instanceof Error ? error.message : String(error);
const err = new Error(`Invalid URL in sitemap index: ${validationMsg}`);
if (this.level === ErrorLevel.THROW) {
callback(err);
return;
}
else {
this.warn(err.message);
}
// The logger is a no-op at SILENT; skip this item
callback();
return;
}
// Check lastmod before pushing anything, so a rejected item leaves no
// partial <sitemap> element in the output.
let lastmod;
if (typeof item !== 'string' && item.lastmod) {
try {
lastmod = new Date(item.lastmod).toISOString();
if (this.lastmodDateOnly) {
lastmod = lastmod.slice(0, 10);
}
}
catch {
const error = new Error(`Invalid lastmod date in sitemap index: ${item.lastmod}`);
if (this.level === ErrorLevel.THROW) {
callback(error);
return;
}
else {
this.warn(error.message);
}
// The logger is a no-op at SILENT; continue without lastmod
}
}
this.push(otag(IndexTagNames.sitemap));
this.push(element(IndexTagNames.loc, url));
if (lastmod) {
this.push(element(IndexTagNames.lastmod, lastmod));
}
this.push(ctag(IndexTagNames.sitemap));
callback();
}
catch (error) {
callback(toError(error));
}
}
_flush(cb) {
if (!this.hasHeadOutput) {
this.writeHeadOutput();
}
this.push(closetag);
cb();
}
}
/**
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
* writes them to sitemap files, adds the sitemap files to a sitemap index,
* and creates new sitemap files when the count limit is reached.
*
* It waits for the target stream of the current sitemap file to finish before
* moving on to the next if the target stream is returned by the `getSitemapStream`
* callback in the 3rd position of the tuple.
*
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
* before `finish` will be emitted. Failure to read the stream will result in hangs.
*
* @extends {SitemapIndexStream}
*/
export class SitemapAndIndexStream extends SitemapIndexStream {
itemsWritten;
getSitemapStream;
limit;
/**
* The open sitemap, its pipe target, if any, and a promise that settles
* once both have finished. The promise rejects if either errors or is
* destroyed first.
*/
current;
/**
* `SitemapAndIndexStream` is a Transform stream that takes in sitemap items,
* writes them to sitemap files, adds the sitemap files to a sitemap index,
* and creates new sitemap files when the count limit is reached.
*
* It waits for the target stream of the current sitemap file to finish before
* moving on to the next if the target stream is returned by the `getSitemapStream`
* callback in the 3rd position of the tuple.
*
* ⚠️ CAUTION: This object is `readable` and must be read (e.g. piped to a file or to /dev/null)
* before `finish` will be emitted. Failure to read the stream will result in hangs.
*
* @param {SitemapAndIndexStreamOptions} opts - Stream options.
*/
constructor(opts) {
opts.objectMode = true;
super(opts);
this.itemsWritten = 0;
this.getSitemapStream = opts.getSitemapStream;
this.limit = opts.limit ?? DEFAULT_SITEMAP_ITEM_LIMIT;
// Validate limit is within acceptable range per sitemaps.org spec
// See: https://www.sitemaps.org/protocol.html#index
if (this.limit < LIMITS.MIN_SITEMAP_ITEM_LIMIT ||
this.limit > LIMITS.MAX_SITEMAP_ITEM_LIMIT) {
throw new Error(`limit must be between ${LIMITS.MIN_SITEMAP_ITEM_LIMIT} and ${LIMITS.MAX_SITEMAP_ITEM_LIMIT} per sitemaps.org spec, got ${this.limit}`);
}
}
_transform(item, encoding, callback) {
if (this.current && this.itemsWritten % this.limit !== 0) {
this.writeItem(this.current.sitemap, item, callback);
return;
}
const startNextSitemap = () => {
// The stream may have been destroyed while the last sitemap closed.
if (this.destroyed) {
return;
}
// Catch here rather than relying on the caller: after rotation this
// runs inside a promise callback, where a throw would become an
// unhandled rejection.
try {
this.writeItem(this.createSitemap(encoding), item, callback);
}
catch (err) {
callback(err);
}
};
if (!this.current) {
startNextSitemap();
return;
}
// Transform delivers items one at a time, so no other item can
// arrive until this rotation calls back.
this.closeCurrentSitemap().then(startNextSitemap, callback);
}
/**
* Ends the current sitemap and waits until it and its pipe target, if any,
* have finished, so each sitemap file is fully written before the next one
* starts. Rejects if either stream errors or is destroyed before finishing.
*/
async closeCurrentSitemap() {
const current = this.current;
if (!current) {
return;
}
// The pipe target gets its end() call from the sitemap stream ending.
current.sitemap.end();
await current.finished;
this.current = undefined;
}
writeItem(sitemap, item, callback) {
// SitemapStream reports a bad item (such as a relative URL with no
// hostname) through its 'error' event, which createSitemap's listener
// turns into this stream's error. The sitemap comes from
// getSitemapStream, though, so a caller's subclass or wrapper may still
// throw from write(); report that as a stream error too.
let writable;
try {
writable = sitemap.write(item);
}
catch (err) {
callback(err);
return;
}
if (!writable) {
sitemap.once('drain', callback);
}
else {
process.nextTick(callback);
}
// Increment the count of items written
this.itemsWritten++;
}
/**
* Destroys the open sitemap and its target, if any, so a stopped stream
* does not leave a file descriptor open.
*/
_destroy(err, cb) {
this.current?.sitemap.destroy();
this.current?.target?.destroy();
super._destroy(err, cb);
}
/**
* Called when the stream is finished.
* Closes the last sitemap before writing the end of the sitemap index.
*
* @param cb - The callback to invoke when flushing is complete
*/
_flush(cb) {
this.closeCurrentSitemap()
.then(() => {
super._flush(cb);
})
.catch(cb);
}
/**
* Asks `getSitemapStream` for the next sitemap, adds it to the index and
* makes it current. Throws if the callback throws or returns an invalid
* tuple, or if the index rejects the sitemap's index item, after destroying
* any streams the callback returned.
*/
createSitemap(encoding) {
const sitemapIndex = this.itemsWritten / this.limit;
let result;
try {
result = this.getSitemapStream(sitemapIndex);
}
catch (err) {
throw new Error(`getSitemapStream callback threw an error for index ${sitemapIndex}: ${errorMessage(err)}`, { cause: err });
}
// Validate the return value
if (!Array.isArray(result) || result.length !== 3) {
throw new Error(`getSitemapStream must return a 3-element array [IndexItem | string, SitemapStream, WriteStream], got: ${typeof result}`);
}
const [idxItem, sitemap, target] = result;
try {
this.addToIndex(idxItem, sitemap, target, encoding);
}
catch (err) {
// The callback has already opened these streams, so a rejected tuple
// must not leave them, or the file they write to, open.
for (const stream of [sitemap, target]) {
if (typeof stream?.destroy === 'function') {
stream.destroy();
}
}
throw err;
}
// Stays attached after rotation too, so an error a retired sitemap emits
// later is reported rather than crashing the process as unhandled.
sitemap.on('error', (err) => this.destroy(err));
// Watch both streams from the start, not only while closing, so a target
// that fails or goes away mid-sitemap stops this stream instead of
// leaving a write waiting for 'drain' or crashing on an unhandled error.
const opts = { readable: false, cleanup: true };
const finishedBoth = Promise.all([
finished(sitemap, opts),
target && finished(target, opts),
]).then(() => undefined);
finishedBoth.catch((err) => this.destroy(err));
this.current = { sitemap, target, finished: finishedBoth };
return sitemap;
}
/**
* Validates the rest of the tuple `getSitemapStream` returned and adds the
* index item to the index. Throws if any element is invalid, or if the
* index rejects the index item.
*/
addToIndex(idxItem, sitemap, target, encoding) {
if (!idxItem ||
(typeof idxItem !== 'string' && typeof idxItem !== 'object')) {
throw new Error('getSitemapStream must return an IndexItem or string as the first element');
}
if (!sitemap || typeof sitemap.write !== 'function') {
throw new Error('getSitemapStream must return a SitemapStream as the second element');
}
if (target && typeof target.write !== 'function') {
throw new Error('getSitemapStream must return a WriteStream or undefined as the third element');
}
// SitemapIndexStream._transform calls back synchronously, and at
// ErrorLevel.THROW it calls back with an error for an invalid index item,
// which fails this sitemap too.
let indexItemError;
super._transform(idxItem, encoding, (err) => {
indexItemError = err;
});
if (indexItemError) {
throw indexItemError;
}
}
}