domutils4.1.210.8 kB
import { hasChildren, isTag, isText, } from "domhandler";
import { getElementsByTagName } from "./legacy.js";
import { textContent } from "./stringify.js";
/**
* Get the feed object from the root of a DOM tree.
*
* @category Feeds
* @param document The DOM to extract the feed from.
* @returns The feed.
*/
export function getFeed(document) {
const feedRoot = getOneElement(isValidFeed, document);
if (!feedRoot)
return null;
const isAtom = feedRoot.name === "feed";
const itemName = isAtom ? "entry" : "item";
// Items are the outermost item elements below the root, in document order.
const items = [];
// One child list and position per open level, searched depth-first.
const lists = [feedRoot.children];
const indices = [0];
while (lists.length > 0) {
const top = lists.length - 1;
if (indices[top] >= lists[top].length) {
lists.pop();
indices.pop();
continue;
}
const node = lists[top][indices[top]++];
if (isTag(node) && node.name === itemName) {
items.push(node);
}
else if (hasChildren(node)) {
lists.push(node.children);
indices.push(0);
}
}
if (isAtom)
return getAtomFeed(feedRoot, items);
return getRssFeed(feedRoot, items);
}
/**
* Parse an Atom feed.
*
* @param feedRoot The root of the feed.
* @param items The entries of the feed.
* @returns The parsed feed.
*/
function getAtomFeed(feedRoot, items) {
const childs = feedRoot.children;
const feed = {
type: "atom",
items: items.map((item) => {
const { children } = item;
const entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "id", children);
addConditionally(entry, "title", "title", children);
const href = getAtomLink(children);
if (href) {
entry.link = href;
}
const description = fetch("summary", children) || fetch("content", children);
if (description) {
entry.description = description;
}
const pubDate = fetch("published", children) || fetch("updated", children);
if (pubDate) {
entry.pubDate = new Date(pubDate);
}
return entry;
}),
};
addConditionally(feed, "id", "id", childs);
addConditionally(feed, "title", "title", childs);
const href = getAtomLink(childs);
if (href) {
feed.link = href;
}
addConditionally(feed, "description", "subtitle", childs);
const updated = fetch("updated", childs);
if (updated) {
feed.updated = new Date(updated);
}
const author = getAtomFeedAuthorEmail(childs);
if (author) {
feed.author = author;
}
return feed;
}
/**
* Get the email of the feed's author: the first direct feed author with an
* email, else the first author with one inside the feed's other elements.
*
* In HTML mode, an element written self-closing, such as
* `<category term="x"/>`, stays open around the elements after it, so the
* feed's author can end up inside it. Authors of entries and of embedded
* feeds, and authors inside authors, are never used.
*
* @param nodes Children of the feed.
* @returns The email, if any.
*/
function getAtomFeedAuthorEmail(nodes) {
for (const node of nodes) {
if (!isTag(node) || node.name !== "author")
continue;
const email = getAuthorEmail(node);
if (email)
return email;
}
const stack = [];
let children = nodes;
let index = 0;
while (true) {
if (index === children.length) {
const frame = stack.pop();
if (!frame)
return undefined;
({ children, index } = frame);
continue;
}
const node = children[index++];
if (isTag(node)) {
const { name } = node;
if (name === "entry" || name === "feed")
continue;
if (name === "author") {
if (children !== nodes) {
const email = getAuthorEmail(node);
if (email)
return email;
}
continue;
}
}
else if (!hasChildren(node)) {
continue;
}
const descendants = node.children;
if (descendants.length === 0)
continue;
// Save the scan only when there are siblings left to visit.
if (index < children.length)
stack.push({ children, index });
children = descendants;
index = 0;
}
}
/**
* Get the email of an Atom author. In HTML mode, an element written
* self-closing before the email stays open, so the email can end up inside
* it; authors inside the author are skipped, also within the email's text.
*
* @param author The author element.
* @returns The email, or an empty string.
*/
function getAuthorEmail(author) {
const stack = [author];
let isInEmail = false;
let text = "";
for (let node = stack.pop(); node; node = stack.pop()) {
if (isInEmail) {
if (isText(node))
text += node.data;
}
else if (isTag(node) && node.name === "email") {
// Only the email's own subtree is left to visit.
isInEmail = true;
stack.length = 0;
}
if (!hasChildren(node))
continue;
const { children } = node;
for (let index = children.length - 1; index >= 0; index--) {
const child = children[index];
if (!isTag(child) || child.name !== "author")
stack.push(child);
}
}
return trimCopy(text);
}
/**
* Parse a RSS feed.
*
* @param feedRoot The root of the feed.
* @param items The items of the feed.
* @returns The parsed feed.
*/
function getRssFeed(feedRoot, items) {
const childs = getOneElement("channel", feedRoot.children)?.children ?? [];
const feed = {
type: feedRoot.name.substr(0, 3),
id: "",
items: items.map((item) => {
const { children } = item;
const entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "guid", children);
addConditionally(entry, "title", "title", children);
addConditionally(entry, "link", "link", children);
addConditionally(entry, "description", "description", children);
const pubDate = fetch("pubDate", children) || fetch("dc:date", children);
if (pubDate)
entry.pubDate = new Date(pubDate);
return entry;
}),
};
addConditionally(feed, "title", "title", childs);
addConditionally(feed, "link", "link", childs);
addConditionally(feed, "description", "description", childs);
const updated = fetch("lastBuildDate", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "managingEditor", childs, true);
return feed;
}
const MEDIA_KEYS_STRING = ["url", "type", "lang"];
const MEDIA_NUMBERS = [
["fileSize", Number.parseInt],
["bitrate", Number.parseFloat],
["framerate", Number.parseFloat],
["samplingrate", Number.parseFloat],
["channels", Number.parseInt],
["duration", Number.parseFloat],
["height", Number.parseInt],
["width", Number.parseInt],
];
/**
* Get all media elements of a feed item.
*
* @param where Nodes to search in.
* @returns Media elements.
*/
function getMediaElements(where) {
return getElementsByTagName("media:content", where).map((element) => {
const { attribs } = element;
const media = {
medium: attribs["medium"],
isDefault: !!attribs["isDefault"],
};
for (const attrib of MEDIA_KEYS_STRING) {
const value = attribs[attrib];
if (value)
media[attrib] = value;
}
for (const [attrib, parse] of MEDIA_NUMBERS) {
const value = attribs[attrib];
if (value)
media[attrib] = parse(value, 10);
}
if (attribs["expression"]) {
media.expression = attribs["expression"];
}
return media;
});
}
/**
* Get one element by tag name.
*
* @param tagName Tag name to look for
* @param node Node to search in
* @returns The element or null
*/
function getOneElement(tagName, node) {
return getElementsByTagName(tagName, node, true, 1)[0];
}
// eslint-disable-next-line unicorn/prefer-https -- RFC 4287 spells this relation with HTTP.
const ATOM_ALTERNATE = "http://www.iana.org/assignments/relation/alternate";
/**
* Get the page an Atom feed or entry points to: the first `alternate` link
* (a link without `rel` is `alternate`, and RFC 4287 also writes it as an
* IANA URI), else the first link.
*
* @param nodes Children of the feed or entry.
* @returns The link's `href`, if any.
*/
function getAtomLink(nodes) {
let first;
for (const node of nodes) {
if (!isTag(node) || node.name !== "link")
continue;
const { rel: relation } = node.attribs;
if (!relation ||
relation === "alternate" ||
relation === ATOM_ALTERNATE) {
return node.attribs["href"];
}
first ??= node;
}
return first?.attribs["href"];
}
/**
* Get the text content of an element with a certain tag name.
*
* @param tagName Tag name to look for.
* @param where Node to search in.
* @param shouldRecurse Whether to recurse into child nodes.
* @returns The text content of the element.
*/
function fetch(tagName, where, shouldRecurse = false) {
return trimCopy(textContent(getElementsByTagName(tagName, where, shouldRecurse, 1)));
}
/**
* Trim the text of a feed field.
*
* @param text The text to trim.
* @returns The trimmed text.
*/
function trimCopy(text) {
const trimmed = text.trim();
// A trimmed string can share the memory of the whole text; copy it.
return trimmed.length === text.length ? trimmed : ` ${trimmed}`.slice(1);
}
/**
* Adds a property to an object if it has a value.
*
* @param object Object to be extended.
* @param property Property name.
* @param tagName Tag name that contains the conditionally added property.
* @param where Element to search for the property.
* @param shouldRecurse Whether to recurse into child nodes.
*/
function addConditionally(object, property, tagName, where, shouldRecurse = false) {
const value = fetch(tagName, where, shouldRecurse);
if (value)
object[property] = value;
}
/**
* Checks if an element is a feed root node.
*
* @param value The name of the element to check.
* @returns Whether an element is a feed root node.
*/
function isValidFeed(value) {
return ["rss", "feed", "rdf:RDF"].includes(value);
}
//# sourceMappingURL=feeds.js.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.