Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cheerio

Package Overview
Dependencies
Maintainers
4
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cheerio - npm Package Compare versions

Comparing version 1.0.0-rc.9 to 1.0.0-rc.10

lib/parsers/htmlparser2-adapter.d.ts

13

lib/api/attributes.d.ts

@@ -316,16 +316,3 @@ /**

export declare function toggleClass<T extends Node, R extends ArrayLike<T>>(this: R, value?: string | ((this: Element, i: number, className: string, stateVal?: boolean) => string), stateVal?: boolean): R;
/**
* Checks the current list of elements and returns `true` if *any* of the
* elements match the selector. If using an element or Cheerio selection,
* returns `true` if *any* of the elements match. If using a predicate function,
* the function is executed in the context of the selected element, so `this`
* refers to the current element.
*
* @category Attributes
* @param selector - Selector for the selection.
* @returns Whether or not the selector matches an element of the instance.
* @see {@link https://api.jquery.com/is/}
*/
export declare function is<T extends Node>(this: Cheerio<T>, selector?: string | ((this: Element, i: number, el: Element) => boolean) | Cheerio<T> | T | null): boolean;
export {};
//# sourceMappingURL=attributes.d.ts.map

76

lib/api/attributes.js

@@ -8,3 +8,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.is = exports.toggleClass = exports.removeClass = exports.addClass = exports.hasClass = exports.removeAttr = exports.val = exports.data = exports.prop = exports.attr = void 0;
exports.toggleClass = exports.removeClass = exports.addClass = exports.hasClass = exports.removeAttr = exports.val = exports.data = exports.prop = exports.attr = void 0;
var static_1 = require("../static");

@@ -27,4 +27,4 @@ var utils_1 = require("../utils");

// Matches strings that look like JSON objects or arrays
var rbrace = /^(?:{[\w\W]*}|\[[\w\W]*])$/;
function getAttr(elem, name) {
var rbrace = /^{[^]*}$|^\[[^]*]$/;
function getAttr(elem, name, xmlMode) {
var _a;

@@ -40,3 +40,3 @@ if (!elem || !utils_1.isTag(elem))

// Get the (decoded) attribute
return rboolean.test(name) ? name : elem.attribs[name];
return !xmlMode && rboolean.test(name) ? name : elem.attribs[name];
}

@@ -80,3 +80,3 @@ // Mimic the DOM and return text content as value for `option's`

}
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
if (utils_1.isTag(el))

@@ -86,3 +86,3 @@ setAttr(el, name, value.call(el, i, el.attribs[name]));

}
return utils_1.domEach(this, function (_, el) {
return utils_1.domEach(this, function (el) {
if (!utils_1.isTag(el))

@@ -101,3 +101,5 @@ return;

}
return arguments.length > 1 ? this : getAttr(this[0], name);
return arguments.length > 1
? this
: getAttr(this[0], name, this.options.xmlMode);
}

@@ -114,3 +116,3 @@ exports.attr = attr;

*/
function getProp(el, name) {
function getProp(el, name, xmlMode) {
if (!el || !utils_1.isTag(el))

@@ -121,5 +123,5 @@ return;

el[name]
: rboolean.test(name)
? getAttr(el, name) !== undefined
: getAttr(el, name);
: !xmlMode && rboolean.test(name)
? getAttr(el, name, false) !== undefined
: getAttr(el, name, xmlMode);
}

@@ -134,3 +136,3 @@ /**

*/
function setProp(el, name, value) {
function setProp(el, name, value, xmlMode) {
if (name in el) {

@@ -141,6 +143,7 @@ // @ts-expect-error Overriding value

else {
setAttr(el, name, rboolean.test(name) ? (value ? '' : null) : "" + value);
setAttr(el, name, !xmlMode && rboolean.test(name) ? (value ? '' : null) : "" + value);
}
}
function prop(name, value) {
var _this = this;
if (typeof name === 'string' && value === undefined) {

@@ -167,3 +170,3 @@ switch (name) {

default:
return getProp(this[0], name);
return getProp(this[0], name, this.options.xmlMode);
}

@@ -176,8 +179,8 @@ }

}
return utils_1.domEach(this, function (j, el) {
return utils_1.domEach(this, function (el, i) {
if (utils_1.isTag(el))
setProp(el, name, value.call(el, j, getProp(el, name)));
setProp(el, name, value.call(el, i, getProp(el, name, _this.options.xmlMode)), _this.options.xmlMode);
});
}
return utils_1.domEach(this, function (__, el) {
return utils_1.domEach(this, function (el) {
if (!utils_1.isTag(el))

@@ -188,7 +191,7 @@ return;

var val = name[key];
setProp(el, key, val);
setProp(el, key, val, _this.options.xmlMode);
});
}
else {
setProp(el, name, value);
setProp(el, name, value, _this.options.xmlMode);
}

@@ -283,3 +286,3 @@ });

if (typeof name === 'object' || value !== undefined) {
utils_1.domEach(this, function (_, el) {
utils_1.domEach(this, function (el) {
if (utils_1.isTag(el))

@@ -377,3 +380,3 @@ if (typeof name === 'object')

var _loop_1 = function (i) {
utils_1.domEach(this_1, function (_, elem) {
utils_1.domEach(this_1, function (elem) {
if (utils_1.isTag(elem))

@@ -449,3 +452,3 @@ removeAttribute(elem, attrNames[i]);

if (typeof value === 'function') {
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
if (utils_1.isTag(el)) {

@@ -467,4 +470,4 @@ var className = el.attribs.class || '';

continue;
// If we don't already have classes
var className = getAttr(el, 'class');
// If we don't already have classes — always set xmlMode to false here, as it doesn't matter for classes
var className = getAttr(el, 'class', false);
if (!className) {

@@ -509,3 +512,3 @@ setAttr(el, 'class', classNames.join(' ').trim());

if (typeof name === 'function') {
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
if (utils_1.isTag(el))

@@ -518,3 +521,3 @@ removeClass.call([el], name.call(el, i, el.attribs.class || ''));

var removeAll = arguments.length === 0;
return utils_1.domEach(this, function (_, el) {
return utils_1.domEach(this, function (el) {
if (!utils_1.isTag(el))

@@ -571,3 +574,3 @@ return;

if (typeof value === 'function') {
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
if (utils_1.isTag(el)) {

@@ -609,20 +612,1 @@ toggleClass.call([el], value.call(el, i, el.attribs.class || '', stateVal), stateVal);

exports.toggleClass = toggleClass;
/**
* Checks the current list of elements and returns `true` if *any* of the
* elements match the selector. If using an element or Cheerio selection,
* returns `true` if *any* of the elements match. If using a predicate function,
* the function is executed in the context of the selected element, so `this`
* refers to the current element.
*
* @category Attributes
* @param selector - Selector for the selection.
* @returns Whether or not the selector matches an element of the instance.
* @see {@link https://api.jquery.com/is/}
*/
function is(selector) {
if (selector) {
return this.filter(selector).length > 0;
}
return false;
}
exports.is = is;

@@ -9,6 +9,6 @@ "use strict";

(typeof prop === 'object' && !Array.isArray(prop))) {
return utils_1.domEach(this, function (idx, el) {
return utils_1.domEach(this, function (el, i) {
if (utils_1.isTag(el)) {
// `prop` can't be an array here anymore.
setCss(el, prop, val, idx);
setCss(el, prop, val, i);
}

@@ -15,0 +15,0 @@ });

@@ -45,6 +45,6 @@ "use strict";

function serializeArray() {
var _this = this;
// Resolve all form elements from either forms or collections of form elements
var Cheerio = this.constructor;
return this.map(function (_, elem) {
var $elem = Cheerio(elem);
var $elem = _this._make(elem);
if (utils_1.isTag(elem) && elem.name === 'form') {

@@ -66,3 +66,3 @@ return $elem.find(submittableSelector).toArray();

var _a;
var $elem = Cheerio(elem);
var $elem = _this._make(elem);
var name = $elem.attr('name'); // We have filtered for elements with a name before.

@@ -69,0 +69,0 @@ // If there is no value set (e.g. `undefined`, `null`), then default value to empty

@@ -50,3 +50,3 @@ "use strict";

var lastIdx = this.length - 1;
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
if (!domhandler_1.hasChildren(el))

@@ -139,5 +139,3 @@ return;

function appendTo(target) {
var appendTarget = utils_1.isCheerio(target)
? target
: this._make(target, null, this._originalRoot);
var appendTarget = utils_1.isCheerio(target) ? target : this._make(target);
appendTarget.append(this);

@@ -169,5 +167,3 @@ return this;

function prependTo(target) {
var prependTarget = utils_1.isCheerio(target)
? target
: this._make(target, null, this._originalRoot);
var prependTarget = utils_1.isCheerio(target) ? target : this._make(target);
prependTarget.prepend(this);

@@ -521,3 +517,3 @@ return this;

var lastIdx = this.length - 1;
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
var parent = el.parent;

@@ -567,7 +563,7 @@ if (!htmlparser2_1.DomUtils.hasChildren(el) || !parent) {

if (typeof target === 'string') {
target = this._make(target, null, this._originalRoot);
target = this._make(target);
}
this.remove();
var clones = [];
utils_1.domEach(this._makeDomArray(target), function (_, el) {
this._makeDomArray(target).forEach(function (el) {
var clonedSelf = _this.clone().toArray();

@@ -621,3 +617,3 @@ var parent = el.parent;

var lastIdx = this.length - 1;
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
var parent = el.parent;

@@ -666,6 +662,6 @@ if (!htmlparser2_1.DomUtils.hasChildren(el) || !parent) {

var _this = this;
var targetArr = this._make(target, null, this._originalRoot);
var targetArr = this._make(target);
this.remove();
var clones = [];
utils_1.domEach(targetArr, function (_, el) {
utils_1.domEach(targetArr, function (el) {
var clonedSelf = _this.clone().toArray();

@@ -712,3 +708,3 @@ var parent = el.parent;

var elems = selector ? this.filter(selector) : this;
utils_1.domEach(elems, function (_, el) {
utils_1.domEach(elems, function (el) {
htmlparser2_1.DomUtils.removeElement(el);

@@ -743,3 +739,3 @@ el.prev = el.next = el.parent = null;

var _this = this;
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
var parent = el.parent;

@@ -782,3 +778,3 @@ if (!parent) {

function empty() {
return utils_1.domEach(this, function (_, el) {
return utils_1.domEach(this, function (el) {
if (!htmlparser2_1.DomUtils.hasChildren(el))

@@ -802,3 +798,3 @@ return;

var opts = tslib_1.__assign(tslib_1.__assign({}, this.options), { context: null });
return utils_1.domEach(this, function (_, el) {
return utils_1.domEach(this, function (el) {
if (!htmlparser2_1.DomUtils.hasChildren(el))

@@ -811,3 +807,3 @@ return;

var content = utils_1.isCheerio(str)
? str.clone().get()
? str.toArray()
: parse_1.default("" + str, opts, false).children;

@@ -836,3 +832,3 @@ parse_1.update(content, el);

// Function support
return utils_1.domEach(this, function (i, el) {
return utils_1.domEach(this, function (el, i) {
text.call(_this._make(el), str.call(el, i, static_1.text([el])));

@@ -842,3 +838,3 @@ });

// Append text node to each selected elements
return utils_1.domEach(this, function (_, el) {
return utils_1.domEach(this, function (el) {
if (!htmlparser2_1.DomUtils.hasChildren(el))

@@ -845,0 +841,0 @@ return;

@@ -6,5 +6,5 @@ /**

*/
import { Node, Element } from 'domhandler';
import { Node, Element, Document } from 'domhandler';
import type { Cheerio } from '../cheerio';
import type { FilterFunction, AcceptedFilters } from '../types';
import type { AcceptedFilters } from '../types';
/**

@@ -45,3 +45,3 @@ * Get the descendants of each element in the current set of matched elements,

*/
export declare function parent<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const parent: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -65,3 +65,3 @@ * Get a set of parents filtered by `selector` of each element in the current

*/
export declare function parents<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const parents: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -80,7 +80,7 @@ * Get the ancestors of each element in the current set of matched elements, up

* @param selector - Selector for element to stop at.
* @param filterBy - Optional filter for parents.
* @param filterSelector - Optional filter for parents.
* @returns The parents.
* @see {@link https://api.jquery.com/parentsUntil/}
*/
export declare function parentsUntil<T extends Node>(this: Cheerio<T>, selector?: string | Node | Cheerio<Node>, filterBy?: AcceptedFilters): Cheerio<Element>;
export declare const parentsUntil: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | null | undefined, filterSelector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -111,3 +111,3 @@ * For each element in the set, get the first element that matches the selector

*/
export declare function closest<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Node>;
export declare function closest<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Node>): Cheerio<Node>;
/**

@@ -128,3 +128,3 @@ * Gets the next sibling of the first selected element, optionally filtered by a selector.

*/
export declare function next<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const next: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -148,3 +148,3 @@ * Gets all the following siblings of the first selected element, optionally

*/
export declare function nextAll<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const nextAll: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -167,3 +167,3 @@ * Gets all the following siblings up to but not including the element matched

*/
export declare function nextUntil<T extends Node>(this: Cheerio<T>, selector?: string | Cheerio<Node> | Node | null, filterSelector?: AcceptedFilters): Cheerio<Element>;
export declare const nextUntil: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | null | undefined, filterSelector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -185,3 +185,3 @@ * Gets the previous sibling of the first selected element optionally filtered

*/
export declare function prev<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const prev: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -206,3 +206,3 @@ * Gets all the preceding siblings of the first selected element, optionally

*/
export declare function prevAll<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const prevAll: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -225,3 +225,3 @@ * Gets all the preceding siblings up to but not including the element matched

*/
export declare function prevUntil<T extends Node>(this: Cheerio<T>, selector?: string | Cheerio<Node> | Node | null, filterSelector?: AcceptedFilters): Cheerio<Element>;
export declare const prevUntil: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | null | undefined, filterSelector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -246,3 +246,3 @@ * Get the siblings of each element (excluding the element) in the set of

*/
export declare function siblings<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const siblings: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -266,3 +266,3 @@ * Gets the children of the first selected element.

*/
export declare function children<T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters): Cheerio<Element>;
export declare const children: <T extends Node>(this: Cheerio<T>, selector?: AcceptedFilters<Element> | undefined) => Cheerio<Element>;
/**

@@ -339,10 +339,37 @@ * Gets the children of each element in the set of matched elements, including

* Iterates over a cheerio object, reducing the set of selector elements to
* those that match the selector or pass the function's test. When a Cheerio
* selection is specified, return only the elements contained in that selection.
* When an element is specified, return only that element (if it is contained in
* the original selection). If using the function method, the function is
* executed in the context of the selected element, so `this` refers to the
* current element.
* those that match the selector or pass the function's test.
*
* This is the definition for using type guards; have a look below for other
* ways to invoke this method. The function is executed in the context of the
* selected element, so `this` refers to the current element.
*
* @category Traversing
* @example <caption>Function</caption>
*
* ```js
* $('li')
* .filter(function (i, el) {
* // this === el
* return $(this).attr('class') === 'orange';
* })
* .attr('class'); //=> orange
* ```
*
* @param match - Value to look for, following the rules above.
* @returns The filtered collection.
* @see {@link https://api.jquery.com/filter/}
*/
export declare function filter<T, S extends T>(this: Cheerio<T>, match: (this: T, index: number, value: T) => value is S): Cheerio<S>;
/**
* Iterates over a cheerio object, reducing the set of selector elements to
* those that match the selector or pass the function's test.
*
* - When a Cheerio selection is specified, return only the elements contained in
* that selection.
* - When an element is specified, return only that element (if it is contained in
* the original selection).
* - If using the function method, the function is executed in the context of the
* selected element, so `this` refers to the current element.
*
* @category Traversing
* @example <caption>Selector</caption>

@@ -366,9 +393,23 @@ *

*
* @param match - Value to look for, following the rules above.
* @param container - Optional node to filter instead.
* @param match - Value to look for, following the rules above. See
* {@link AcceptedFilters}.
* @returns The filtered collection.
* @see {@link https://api.jquery.com/filter/}
*/
export declare function filter(this: Cheerio<Node> | Node[], match: AcceptedFilters, container?: Node[] | Cheerio<Node>): Cheerio<Element>;
export declare function filter<T, S extends AcceptedFilters<T>>(this: Cheerio<T>, match: S): Cheerio<S extends string ? Element : T>;
export declare function filterArray<T>(nodes: T[], match: AcceptedFilters<T>, xmlMode?: boolean, root?: Document): Element[] | T[];
/**
* Checks the current list of elements and returns `true` if *any* of the
* elements match the selector. If using an element or Cheerio selection,
* returns `true` if *any* of the elements match. If using a predicate function,
* the function is executed in the context of the selected element, so `this`
* refers to the current element.
*
* @category Attributes
* @param selector - Selector for the selection.
* @returns Whether or not the selector matches an element of the instance.
* @see {@link https://api.jquery.com/is/}
*/
export declare function is<T>(this: Cheerio<T>, selector?: AcceptedFilters<T>): boolean;
/**
* Remove elements from the set of matched elements. Given a Cheerio object that

@@ -406,3 +447,3 @@ * represents a set of DOM elements, the `.not()` method constructs a new

*/
export declare function not<T extends Node>(this: Cheerio<T> | T[], match: Node | Cheerio<Node> | string | FilterFunction<T>, container?: Cheerio<T> | T[]): Cheerio<T>;
export declare function not<T extends Node>(this: Cheerio<T>, match: AcceptedFilters<T>): Cheerio<T>;
/**

@@ -515,2 +556,15 @@ * Filters the set of matched elements to only those which have the given DOM

/**
* Retrieve all the DOM elements contained in the jQuery set as an array.
*
* @example
*
* ```js
* $('li').toArray();
* //=> [ {...}, {...}, {...} ]
* ```
*
* @returns The contained items.
*/
export declare function toArray<T>(this: Cheerio<T>): T[];
/**
* Search for a given element from among the matched elements.

@@ -517,0 +571,0 @@ *

@@ -8,3 +8,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.addBack = exports.add = exports.end = exports.slice = exports.index = exports.get = exports.eq = exports.last = exports.first = exports.has = exports.not = exports.filter = exports.map = exports.each = exports.contents = exports.children = exports.siblings = exports.prevUntil = exports.prevAll = exports.prev = exports.nextUntil = exports.nextAll = exports.next = exports.closest = exports.parentsUntil = exports.parents = exports.parent = exports.find = void 0;
exports.addBack = exports.add = exports.end = exports.slice = exports.index = exports.toArray = exports.get = exports.eq = exports.last = exports.first = exports.has = exports.not = exports.is = exports.filterArray = exports.filter = exports.map = exports.each = exports.contents = exports.children = exports.siblings = exports.prevUntil = exports.prevAll = exports.prev = exports.nextUntil = exports.nextAll = exports.next = exports.closest = exports.parentsUntil = exports.parents = exports.parent = exports.find = void 0;
var tslib_1 = require("tslib");

@@ -14,2 +14,3 @@ var domhandler_1 = require("domhandler");

var utils_1 = require("../utils");
var static_1 = require("../static");
var htmlparser2_1 = require("htmlparser2");

@@ -37,2 +38,3 @@ var uniqueSort = htmlparser2_1.DomUtils.uniqueSort;

function find(selectorOrHaystack) {
var _a;
if (!selectorOrHaystack) {

@@ -43,16 +45,15 @@ return this._make([]);

if (typeof selectorOrHaystack !== 'string') {
var contains_1 = this.constructor.contains;
var haystack = utils_1.isCheerio(selectorOrHaystack)
? selectorOrHaystack.get()
? selectorOrHaystack.toArray()
: [selectorOrHaystack];
return this._make(haystack.filter(function (elem) { return context.some(function (node) { return contains_1(node, elem); }); }));
return this._make(haystack.filter(function (elem) { return context.some(function (node) { return static_1.contains(node, elem); }); }));
}
var elems = reSiblingSelector.test(selectorOrHaystack)
? context
: context.reduce(function (newElems, elem) {
return domhandler_1.hasChildren(elem)
? newElems.concat(elem.children.filter(utils_1.isTag))
: newElems;
}, []);
var options = { context: context, xmlMode: this.options.xmlMode };
: this.children().toArray();
var options = {
context: context,
root: (_a = this._root) === null || _a === void 0 ? void 0 : _a[0],
xmlMode: this.options.xmlMode,
};
return this._make(select.select(selectorOrHaystack, elems, options));

@@ -62,2 +63,93 @@ }

/**
* Creates a matcher, using a particular mapping function. Matchers provide a
* function that finds elements using a generating function, supporting filtering.
*
* @private
* @param matchMap - Mapping function.
* @returns - Function for wrapping generating functions.
*/
function _getMatcher(matchMap) {
return function (fn) {
var postFns = [];
for (var _i = 1; _i < arguments.length; _i++) {
postFns[_i - 1] = arguments[_i];
}
return function (selector) {
var _a;
var matched = matchMap(fn, this);
if (selector) {
matched = filterArray(matched, selector, this.options.xmlMode, (_a = this._root) === null || _a === void 0 ? void 0 : _a[0]);
}
return this._make(
// Post processing is only necessary if there is more than one element.
this.length > 1 && matched.length > 1
? postFns.reduce(function (elems, fn) { return fn(elems); }, matched)
: matched);
};
};
}
/** Matcher that adds multiple elements for each entry in the input. */
var _matcher = _getMatcher(function (fn, elems) {
var _a;
var ret = [];
for (var i = 0; i < elems.length; i++) {
var value = fn(elems[i]);
ret.push(value);
}
return (_a = new Array()).concat.apply(_a, ret);
});
/** Matcher that adds at most one element for each entry in the input. */
var _singleMatcher = _getMatcher(function (fn, elems) {
var ret = [];
for (var i = 0; i < elems.length; i++) {
var value = fn(elems[i]);
if (value !== null) {
ret.push(value);
}
}
return ret;
});
/**
* Matcher that supports traversing until a condition is met.
*
* @returns A function usable for `*Until` methods.
*/
function _matchUntil(nextElem) {
var postFns = [];
for (var _i = 1; _i < arguments.length; _i++) {
postFns[_i - 1] = arguments[_i];
}
// We use a variable here that is used from within the matcher.
var matches = null;
var innerMatcher = _getMatcher(function (nextElem, elems) {
var matched = [];
utils_1.domEach(elems, function (elem) {
for (var next_1; (next_1 = nextElem(elem)); elem = next_1) {
// FIXME: `matched` might contain duplicates here and the index is too large.
if (matches === null || matches === void 0 ? void 0 : matches(next_1, matched.length))
break;
matched.push(next_1);
}
});
return matched;
}).apply(void 0, tslib_1.__spreadArray([nextElem], postFns));
return function (selector, filterSelector) {
var _this = this;
// Override `matches` variable with the new target.
matches =
typeof selector === 'string'
? function (elem) { return select.is(elem, selector, _this.options); }
: selector
? getFilterFn(selector)
: null;
var ret = innerMatcher.call(this, filterSelector);
// Set `matches` to `null`, so we don't waste memory.
matches = null;
return ret;
};
}
function _removeDuplicates(elems) {
return Array.from(new Set(elems));
}
/**
* Get the parent of each element in the current set of matched elements,

@@ -78,15 +170,6 @@ * optionally filtered by a selector.

*/
function parent(selector) {
var set = [];
utils_1.domEach(this, function (_, elem) {
var parentElem = elem.parent;
if (parentElem &&
parentElem.type !== 'root' &&
!set.includes(parentElem)) {
set.push(parentElem);
}
});
return selector ? filter.call(set, selector, this) : this._make(set);
}
exports.parent = parent;
exports.parent = _singleMatcher(function (_a) {
var parent = _a.parent;
return (parent && !domhandler_1.isDocument(parent) ? parent : null);
}, _removeDuplicates);
/**

@@ -110,23 +193,10 @@ * Get a set of parents filtered by `selector` of each element in the current

*/
function parents(selector) {
var _this = this;
var parentNodes = [];
/*
* When multiple DOM elements are in the original set, the resulting set will
* be in *reverse* order of the original elements as well, with duplicates
* removed.
*/
this.get()
.reverse()
.forEach(function (elem) {
return traverseParents(_this, elem.parent, selector, Infinity).forEach(function (node) {
// We know these must be `Element`s, as we filter out root nodes.
if (!parentNodes.includes(node)) {
parentNodes.push(node);
}
});
});
return this._make(parentNodes);
}
exports.parents = parents;
exports.parents = _matcher(function (elem) {
var matched = [];
while (elem.parent && !domhandler_1.isDocument(elem.parent)) {
matched.push(elem.parent);
elem = elem.parent;
}
return matched;
}, uniqueSort, function (elems) { return elems.reverse(); });
/**

@@ -145,46 +215,10 @@ * Get the ancestors of each element in the current set of matched elements, up

* @param selector - Selector for element to stop at.
* @param filterBy - Optional filter for parents.
* @param filterSelector - Optional filter for parents.
* @returns The parents.
* @see {@link https://api.jquery.com/parentsUntil/}
*/
function parentsUntil(selector, filterBy) {
var parentNodes = [];
var untilNode;
var untilNodes;
if (typeof selector === 'string') {
untilNodes = this.parents(selector).toArray();
}
else if (selector && utils_1.isCheerio(selector)) {
untilNodes = selector.toArray();
}
else if (selector) {
untilNode = selector;
}
/*
* When multiple DOM elements are in the original set, the resulting set will
* be in *reverse* order of the original elements as well, with duplicates
* removed.
*/
this.toArray()
.reverse()
.forEach(function (elem) {
while (elem.parent) {
elem = elem.parent;
if ((untilNode && elem !== untilNode) ||
(untilNodes && !untilNodes.includes(elem)) ||
(!untilNode && !untilNodes)) {
if (utils_1.isTag(elem) && !parentNodes.includes(elem)) {
parentNodes.push(elem);
}
}
else {
break;
}
}
}, this);
return filterBy
? filter.call(parentNodes, filterBy, this)
: this._make(parentNodes);
}
exports.parentsUntil = parentsUntil;
exports.parentsUntil = _matchUntil(function (_a) {
var parent = _a.parent;
return (parent && !domhandler_1.isDocument(parent) ? parent : null);
}, uniqueSort, function (elems) { return elems.reverse(); });
/**

@@ -221,7 +255,15 @@ * For each element in the set, get the first element that matches the selector

}
utils_1.domEach(this, function (_, elem) {
var closestElem = traverseParents(_this, elem, selector, 1)[0];
// Do not add duplicate elements to the set
if (closestElem && !set.includes(closestElem)) {
set.push(closestElem);
utils_1.domEach(this, function (elem) {
var _a;
while (elem && elem.type !== 'root') {
if (!selector ||
filterArray([elem], selector, _this.options.xmlMode, (_a = _this._root) === null || _a === void 0 ? void 0 : _a[0])
.length) {
// Do not add duplicate elements to the set
if (elem && !set.includes(elem)) {
set.push(elem);
}
break;
}
elem = elem.parent;
}

@@ -247,16 +289,3 @@ });

*/
function next(selector) {
var elems = [];
utils_1.domEach(this, function (_, elem) {
while (elem.next) {
elem = elem.next;
if (utils_1.isTag(elem)) {
elems.push(elem);
return;
}
}
});
return selector ? filter.call(elems, selector, this) : this._make(elems);
}
exports.next = next;
exports.next = _singleMatcher(function (elem) { return htmlparser2_1.DomUtils.nextElementSibling(elem); });
/**

@@ -280,15 +309,11 @@ * Gets all the following siblings of the first selected element, optionally

*/
function nextAll(selector) {
var elems = [];
utils_1.domEach(this, function (_, elem) {
while (elem.next) {
elem = elem.next;
if (utils_1.isTag(elem) && !elems.includes(elem)) {
elems.push(elem);
}
}
});
return selector ? filter.call(elems, selector, this) : this._make(elems);
}
exports.nextAll = nextAll;
exports.nextAll = _matcher(function (elem) {
var matched = [];
while (elem.next) {
elem = elem.next;
if (utils_1.isTag(elem))
matched.push(elem);
}
return matched;
}, _removeDuplicates);
/**

@@ -311,35 +336,3 @@ * Gets all the following siblings up to but not including the element matched

*/
function nextUntil(selector, filterSelector) {
var elems = [];
var untilNode;
var untilNodes;
if (typeof selector === 'string') {
untilNodes = this.nextAll(selector).toArray();
}
else if (selector && utils_1.isCheerio(selector)) {
untilNodes = selector.get();
}
else if (selector) {
untilNode = selector;
}
utils_1.domEach(this, function (_, elem) {
while (elem.next) {
elem = elem.next;
if ((untilNode && elem !== untilNode) ||
(untilNodes && !untilNodes.includes(elem)) ||
(!untilNode && !untilNodes)) {
if (utils_1.isTag(elem) && !elems.includes(elem)) {
elems.push(elem);
}
}
else {
break;
}
}
});
return filterSelector
? filter.call(elems, filterSelector, this)
: this._make(elems);
}
exports.nextUntil = nextUntil;
exports.nextUntil = _matchUntil(function (el) { return htmlparser2_1.DomUtils.nextElementSibling(el); }, _removeDuplicates);
/**

@@ -361,16 +354,3 @@ * Gets the previous sibling of the first selected element optionally filtered

*/
function prev(selector) {
var elems = [];
utils_1.domEach(this, function (_, elem) {
while (elem.prev) {
elem = elem.prev;
if (utils_1.isTag(elem)) {
elems.push(elem);
return;
}
}
});
return selector ? filter.call(elems, selector, this) : this._make(elems);
}
exports.prev = prev;
exports.prev = _singleMatcher(function (elem) { return htmlparser2_1.DomUtils.prevElementSibling(elem); });
/**

@@ -395,15 +375,11 @@ * Gets all the preceding siblings of the first selected element, optionally

*/
function prevAll(selector) {
var elems = [];
utils_1.domEach(this, function (_, elem) {
while (elem.prev) {
elem = elem.prev;
if (utils_1.isTag(elem) && !elems.includes(elem)) {
elems.push(elem);
}
}
});
return selector ? filter.call(elems, selector, this) : this._make(elems);
}
exports.prevAll = prevAll;
exports.prevAll = _matcher(function (elem) {
var matched = [];
while (elem.prev) {
elem = elem.prev;
if (utils_1.isTag(elem))
matched.push(elem);
}
return matched;
}, _removeDuplicates);
/**

@@ -426,35 +402,3 @@ * Gets all the preceding siblings up to but not including the element matched

*/
function prevUntil(selector, filterSelector) {
var elems = [];
var untilNode;
var untilNodes;
if (typeof selector === 'string') {
untilNodes = this.prevAll(selector).toArray();
}
else if (selector && utils_1.isCheerio(selector)) {
untilNodes = selector.get();
}
else if (selector) {
untilNode = selector;
}
utils_1.domEach(this, function (_, elem) {
while (elem.prev) {
elem = elem.prev;
if ((untilNode && elem !== untilNode) ||
(untilNodes && !untilNodes.includes(elem)) ||
(!untilNode && !untilNodes)) {
if (utils_1.isTag(elem) && !elems.includes(elem)) {
elems.push(elem);
}
}
else {
break;
}
}
});
return filterSelector
? filter.call(elems, filterSelector, this)
: this._make(elems);
}
exports.prevUntil = prevUntil;
exports.prevUntil = _matchUntil(function (el) { return htmlparser2_1.DomUtils.prevElementSibling(el); }, _removeDuplicates);
/**

@@ -479,14 +423,5 @@ * Get the siblings of each element (excluding the element) in the set of

*/
function siblings(selector) {
var _this = this;
// TODO Still get siblings if `parent` is null; see DomUtils' `getSiblings`.
var parent = this.parent();
var elems = parent
.children()
.toArray()
// TODO: This removes all elements in the selection. Note that they could be added here, if siblings are part of the selection.
.filter(function (elem) { return !_this.is(elem); });
return selector ? filter.call(elems, selector, this) : this._make(elems);
}
exports.siblings = siblings;
exports.siblings = _matcher(function (elem) {
return htmlparser2_1.DomUtils.getSiblings(elem).filter(function (el) { return utils_1.isTag(el) && el !== elem; });
}, uniqueSort);
/**

@@ -510,11 +445,3 @@ * Gets the children of the first selected element.

*/
function children(selector) {
var elems = this.toArray().reduce(function (newElems, elem) {
return domhandler_1.hasChildren(elem)
? newElems.concat(elem.children.filter(utils_1.isTag))
: newElems;
}, []);
return selector ? filter.call(elems, selector, this) : this._make(elems);
}
exports.children = children;
exports.children = _matcher(function (elem) { return htmlparser2_1.DomUtils.getChildren(elem).filter(utils_1.isTag); }, _removeDuplicates);
/**

@@ -613,10 +540,14 @@ * Gets the children of each element in the set of matched elements, including

exports.map = map;
/**
* Creates a function to test if a filter is matched.
*
* @param match - A filter.
* @returns A function that determines if a filter has been matched.
*/
function getFilterFn(match) {
if (typeof match === 'function') {
return function (el, i) {
return match.call(el, i, el);
};
return function (el, i) { return match.call(el, i, el); };
}
if (utils_1.isCheerio(match)) {
return match.is.bind(match);
return function (el) { return Array.prototype.includes.call(match, el); };
}

@@ -627,49 +558,34 @@ return function (el) {

}
function filter(match) {
var _a;
return this._make(filterArray(this.toArray(), match, this.options.xmlMode, (_a = this._root) === null || _a === void 0 ? void 0 : _a[0]));
}
exports.filter = filter;
function filterArray(nodes, match, xmlMode, root) {
return typeof match === 'string'
? select.filter(match, nodes, { xmlMode: xmlMode, root: root })
: nodes.filter(getFilterFn(match));
}
exports.filterArray = filterArray;
/**
* Iterates over a cheerio object, reducing the set of selector elements to
* those that match the selector or pass the function's test. When a Cheerio
* selection is specified, return only the elements contained in that selection.
* When an element is specified, return only that element (if it is contained in
* the original selection). If using the function method, the function is
* executed in the context of the selected element, so `this` refers to the
* current element.
* Checks the current list of elements and returns `true` if *any* of the
* elements match the selector. If using an element or Cheerio selection,
* returns `true` if *any* of the elements match. If using a predicate function,
* the function is executed in the context of the selected element, so `this`
* refers to the current element.
*
* @category Traversing
* @example <caption>Selector</caption>
*
* ```js
* $('li').filter('.orange').attr('class');
* //=> orange
* ```
*
* @example <caption>Function</caption>
*
* ```js
* $('li')
* .filter(function (i, el) {
* // this === el
* return $(this).attr('class') === 'orange';
* })
* .attr('class'); //=> orange
* ```
*
* @param match - Value to look for, following the rules above.
* @param container - Optional node to filter instead.
* @returns The filtered collection.
* @see {@link https://api.jquery.com/filter/}
* @category Attributes
* @param selector - Selector for the selection.
* @returns Whether or not the selector matches an element of the instance.
* @see {@link https://api.jquery.com/is/}
*/
function filter(match, container) {
if (container === void 0) { container = this; }
if (!utils_1.isCheerio(container)) {
throw new Error('Not able to create a Cheerio instance.');
}
var nodes = utils_1.isCheerio(this) ? this.toArray() : this;
var elements = nodes.filter(utils_1.isTag);
elements =
typeof match === 'string'
? select.filter(match, elements, container.options)
: elements.filter(getFilterFn(match));
return container._make(elements);
function is(selector) {
var nodes = this.toArray();
return typeof selector === 'string'
? select.some(nodes.filter(utils_1.isTag), selector, this.options)
: selector
? nodes.some(getFilterFn(selector))
: false;
}
exports.filter = filter;
exports.is = is;
/**

@@ -708,11 +624,6 @@ * Remove elements from the set of matched elements. Given a Cheerio object that

*/
function not(match, container) {
if (container === void 0) { container = this; }
if (!utils_1.isCheerio(container)) {
throw new Error('Not able to create a Cheerio instance.');
}
var nodes = utils_1.isCheerio(this) ? this.toArray() : this;
function not(match) {
var nodes = this.toArray();
if (typeof match === 'string') {
var elements = nodes.filter(utils_1.isTag);
var matches_1 = new Set(select.filter(match, elements, container.options));
var matches_1 = new Set(select.filter(match, nodes, this.options));
nodes = nodes.filter(function (el) { return !matches_1.has(el); });

@@ -724,3 +635,3 @@ }

}
return container._make(nodes);
return this._make(nodes);
}

@@ -754,3 +665,3 @@ exports.not = not;

var _this = this;
return filter.call(this, typeof selectorOrHaystack === 'string'
return this.filter(typeof selectorOrHaystack === 'string'
? // Using the `:has` selector here short-circuits searches.

@@ -829,3 +740,3 @@ ":has(" + selectorOrHaystack + ")"

if (i == null) {
return Array.prototype.slice.call(this);
return this.toArray();
}

@@ -836,2 +747,18 @@ return this[i < 0 ? this.length + i : i];

/**
* Retrieve all the DOM elements contained in the jQuery set as an array.
*
* @example
*
* ```js
* $('li').toArray();
* //=> [ {...}, {...}, {...} ]
* ```
*
* @returns The contained items.
*/
function toArray() {
return Array.prototype.slice.call(this);
}
exports.toArray = toArray;
/**
* Search for a given element from among the matched elements.

@@ -871,3 +798,3 @@ *

}
return $haystack.get().indexOf(needle);
return Array.prototype.indexOf.call($haystack, needle);
}

@@ -901,12 +828,2 @@ exports.index = index;

exports.slice = slice;
function traverseParents(self, elem, selector, limit) {
var elems = [];
while (elem && elems.length < limit && elem.type !== 'root') {
if (!selector || filter.call([elem], selector, self).length) {
elems.push(elem);
}
elem = elem.parent;
}
return elems;
}
/**

@@ -913,0 +830,0 @@ * End the most recent filtering operation in the current chain and return the

@@ -1,6 +0,4 @@

import { CheerioOptions, InternalOptions } from './options';
import type { Node, Document, Element } from 'domhandler';
import * as Static from './static';
import type { load } from './load';
import { SelectorType, BasicAcceptedElems } from './types';
import { InternalOptions } from './options';
import type { Node, Document } from 'domhandler';
import { BasicAcceptedElems } from './types';
import * as Attributes from './api/attributes';

@@ -21,4 +19,3 @@ import * as Traversing from './api/traversing';

/**
* The root of the document. Can be overwritten by using the `root` argument
* of the constructor.
* The root of the document. Can be set by using the `root` argument of the constructor.
*

@@ -31,31 +28,2 @@ * @private

/**
* The root the document was originally loaded with. Same as the static
* `_root` property.
*
* @private
*/
_originalRoot: Document | undefined;
/**
* The root the document was originally loaded with. Set in `.load`.
*
* @private
*/
static _root: Document | undefined;
/**
* The options the document was originally loaded with. Set in `.load`.
*
* @private
*/
static _options: InternalOptions | undefined;
static html: typeof Static.html;
static xml: typeof Static.xml;
static text: typeof Static.text;
static parseHTML: typeof Static.parseHTML;
static root: typeof Static.root;
static contains: typeof Static.contains;
static merge: typeof Static.merge;
static load: typeof load;
/** Mimic jQuery's prototype alias for plugin authors. */
static fn: Cheerio<any>;
/**
* Instance of cheerio. Methods are specified in the modules. Usage of this

@@ -70,3 +38,3 @@ * constructor is not recommended. Please use $.load instead.

*/
constructor(selector?: T extends Node ? BasicAcceptedElems<T> : Cheerio<T> | T[], context?: BasicAcceptedElems<Node> | null, root?: BasicAcceptedElems<Document>, options?: CheerioOptions);
constructor(selector?: T extends Node ? BasicAcceptedElems<T> : Cheerio<T> | T[], context?: BasicAcceptedElems<Node> | null, root?: BasicAcceptedElems<Document> | null, options?: InternalOptions);
prevObject: Cheerio<Node> | undefined;

@@ -81,32 +49,9 @@ /**

*/
_make<T>(dom: Cheerio<T> | T[] | T | string, context?: BasicAcceptedElems<Node> | null, root?: BasicAcceptedElems<Document> | undefined): Cheerio<T>;
/**
* Retrieve all the DOM elements contained in the jQuery set as an array.
*
* @example
*
* ```js
* $('li').toArray();
* //=> [ {...}, {...}, {...} ]
* ```
*
* @returns The contained items.
*/
toArray(): T[];
_make<T>(dom: Cheerio<T> | T[] | T | string, context?: BasicAcceptedElems<Node>): Cheerio<T>;
}
export interface Cheerio<T> extends AttributesType, TraversingType, ManipulationType, CssType, FormsType {
export interface Cheerio<T> extends AttributesType, TraversingType, ManipulationType, CssType, FormsType, Iterable<T> {
cheerio: '[cheerio object]';
splice: typeof Array.prototype.slice;
[Symbol.iterator](): Iterator<T>;
}
declare type CheerioClassType = typeof Cheerio;
/**
* Wrapper around the `Cheerio` class, making it possible to create a new
* instance without using `new`.
*/
export interface CheerioAPI extends CheerioClassType {
<T extends Node, S extends string>(selector?: S | BasicAcceptedElems<T>, context?: BasicAcceptedElems<Node> | null, root?: BasicAcceptedElems<Document>, options?: CheerioOptions): Cheerio<S extends SelectorType ? Element : T>;
}
declare const _default: CheerioAPI;
export default _default;
export {};
//# sourceMappingURL=cheerio.d.ts.map

@@ -6,5 +6,4 @@ "use strict";

var parse_1 = tslib_1.__importDefault(require("./parse"));
var options_1 = tslib_1.__importStar(require("./options"));
var options_1 = tslib_1.__importDefault(require("./options"));
var utils_1 = require("./utils");
var Static = tslib_1.__importStar(require("./static"));
var Attributes = tslib_1.__importStar(require("./api/attributes"));

@@ -15,6 +14,2 @@ var Traversing = tslib_1.__importStar(require("./api/traversing"));

var Forms = tslib_1.__importStar(require("./api/forms"));
/*
* The API
*/
var api = [Attributes, Traversing, Manipulation, Css, Forms];
var Cheerio = /** @class */ (function () {

@@ -33,7 +28,5 @@ /**

var _this = this;
if (!(this instanceof Cheerio)) {
return new Cheerio(selector, context, root, options);
}
if (options === void 0) { options = options_1.default; }
this.length = 0;
this.options = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options_1.default), this.options), options_1.flatten(options));
this.options = options;
// $(), $(null), $(undefined), $(false)

@@ -45,3 +38,5 @@ if (!selector)

root = parse_1.default(root, this.options, false);
this._root = Cheerio.call(this, root);
this._root = new this.constructor(root, null, null, this.options);
// Add a cyclic reference, so that calling methods on `_root` never fails.
this._root._root = this._root;
}

@@ -76,3 +71,3 @@ // $($)

? // $('li', '<ul>...</ul>')
new Cheerio(parse_1.default(context, this.options, false))
this._make(parse_1.default(context, this.options, false))
: // $('li', 'ul')

@@ -84,3 +79,3 @@ ((search = context + " " + search), this._root)

: // $('li', node), $('li', [nodes])
new Cheerio(context);
this._make(context);
// If we still don't have a context, return

@@ -103,32 +98,7 @@ if (!searchContext)

*/
Cheerio.prototype._make = function (dom, context, root) {
if (root === void 0) { root = this._root; }
var cheerio = new this.constructor(dom, context, root, this.options);
Cheerio.prototype._make = function (dom, context) {
var cheerio = new this.constructor(dom, context, this._root, this.options);
cheerio.prevObject = this;
return cheerio;
};
/**
* Retrieve all the DOM elements contained in the jQuery set as an array.
*
* @example
*
* ```js
* $('li').toArray();
* //=> [ {...}, {...}, {...} ]
* ```
*
* @returns The contained items.
*/
Cheerio.prototype.toArray = function () {
return this.get();
};
Cheerio.html = Static.html;
Cheerio.xml = Static.xml;
Cheerio.text = Static.text;
Cheerio.parseHTML = Static.parseHTML;
Cheerio.root = Static.root;
Cheerio.contains = Static.contains;
Cheerio.merge = Static.merge;
/** Mimic jQuery's prototype alias for plugin authors. */
Cheerio.fn = Cheerio.prototype;
return Cheerio;

@@ -146,3 +116,3 @@ }());

// Plug in the API
api.forEach(function (mod) { return Object.assign(Cheerio.prototype, mod); });
Object.assign(Cheerio.prototype, Attributes, Traversing, Manipulation, Css, Forms);
function isNode(obj) {

@@ -154,3 +124,1 @@ return (!!obj.name ||

}
// Make it possible to call Cheerio without using `new`.
exports.default = Cheerio;

@@ -1,9 +0,2 @@

import Cheerio from './cheerio';
/**
* The default cheerio instance.
*
* @deprecated Use the function returned by `load` instead.
*/
export default Cheerio;
/**
* The main types of Cheerio objects.

@@ -13,3 +6,3 @@ *

*/
export type { Cheerio, CheerioAPI } from './cheerio';
export type { Cheerio } from './cheerio';
/**

@@ -29,2 +22,9 @@ * Types used in signatures of Cheerio methods.

export * from './load';
declare const _default: import("./load").CheerioAPI;
/**
* The default cheerio instance.
*
* @deprecated Use the function returned by `load` instead.
*/
export default _default;
import * as staticMethods from './static';

@@ -31,0 +31,0 @@ /**

@@ -5,10 +5,3 @@ "use strict";

var tslib_1 = require("tslib");
var cheerio_1 = tslib_1.__importDefault(require("./cheerio"));
/**
* The default cheerio instance.
*
* @deprecated Use the function returned by `load` instead.
*/
exports.default = cheerio_1.default;
/**
* Types used in signatures of Cheerio methods.

@@ -21,4 +14,8 @@ *

var load_1 = require("./load");
// We add this here, to avoid a cyclic depenency
cheerio_1.default.load = load_1.load;
/**
* The default cheerio instance.
*
* @deprecated Use the function returned by `load` instead.
*/
exports.default = load_1.load([]);
var staticMethods = tslib_1.__importStar(require("./static"));

@@ -25,0 +22,0 @@ /**

/// <reference types="node" />
import { CheerioOptions } from './options';
import { CheerioAPI } from './cheerio';
import type { Node } from 'domhandler';
import { CheerioOptions, InternalOptions } from './options';
import * as staticMethods from './static';
import { Cheerio } from './cheerio';
import type { Node, Document, Element } from 'domhandler';
import type * as Load from './load';
import { SelectorType, BasicAcceptedElems } from './types';
declare type StaticType = typeof staticMethods;
declare type LoadType = typeof Load;
/**
* A querying function, bound to a document created from the provided markup.
*
* Also provides several helper methods for dealing with the document as a whole.
*/
export interface CheerioAPI extends StaticType, LoadType {
/**
* This selector method is the starting point for traversing and manipulating
* the document. Like jQuery, it's the primary method for selecting elements
* in the document.
*
* `selector` searches within the `context` scope which searches within the
* `root` scope.
*
* @example
*
* ```js
* $('.apple', '#fruits').text();
* //=> Apple
*
* $('ul .pear').attr('class');
* //=> pear
*
* $('li[class=orange]').html();
* //=> Orange
* ```
*
* @param selector - Either a selector to look for within the document, or the
* contents of a new Cheerio instance.
* @param context - Either a selector to look for within the root, or the
* contents of the document to query.
* @param root - Optional HTML document string.
*/
<T extends Node, S extends string>(selector?: S | BasicAcceptedElems<T>, context?: BasicAcceptedElems<Node> | null, root?: BasicAcceptedElems<Document>, options?: CheerioOptions): Cheerio<S extends SelectorType ? Element : T>;
/**
* The root the document was originally loaded with.
*
* @private
*/
_root: Document;
/**
* The options the document was originally loaded with.
*
* @private
*/
_options: InternalOptions;
/** Mimic jQuery's prototype alias for plugin authors. */
fn: typeof Cheerio.prototype;
}
/**
* Create a querying function, bound to a document created from the provided

@@ -11,4 +65,2 @@ * markup. Note that similar to web browser contexts, this operation may

*
* See the README section titled "Loading" for additional usage information.
*
* @param content - Markup to be loaded.

@@ -18,4 +70,6 @@ * @param options - Options for the created instance.

* @returns The loaded document.
* @see {@link https://cheerio.js.org#loading} for additional usage information.
*/
export declare function load(content: string | Node | Node[] | Buffer, options?: CheerioOptions | null, isDocument?: boolean): CheerioAPI;
export {};
//# sourceMappingURL=load.d.ts.map

@@ -15,4 +15,2 @@ "use strict";

*
* See the README section titled "Loading" for additional usage information.
*
* @param content - Markup to be loaded.

@@ -22,40 +20,36 @@ * @param options - Options for the created instance.

* @returns The loaded document.
* @see {@link https://cheerio.js.org#loading} for additional usage information.
*/
function load(content, options, isDocument) {
if (isDocument === void 0) { isDocument = true; }
if (content == null) {
throw new Error('cheerio.load() expects a string');
}
options = tslib_1.__assign(tslib_1.__assign({}, options_1.default), options_1.flatten(options));
if (typeof isDocument === 'undefined')
isDocument = true;
var root = parse_1.default(content, options, isDocument);
var initialize = /** @class */ (function (_super) {
tslib_1.__extends(initialize, _super);
function initialize(selector, context, r, opts) {
if (r === void 0) { r = root; }
var _this = this;
// @ts-expect-error Using `this` before calling the constructor.
if (!(_this instanceof initialize)) {
return new initialize(selector, context, r, opts);
}
_this = _super.call(this, selector, context, r, tslib_1.__assign(tslib_1.__assign({}, options), opts)) || this;
return _this;
var internalOpts = tslib_1.__assign(tslib_1.__assign({}, options_1.default), options_1.flatten(options));
var root = parse_1.default(content, internalOpts, isDocument);
/** Create an extended class here, so that extensions only live on one instance. */
var LoadedCheerio = /** @class */ (function (_super) {
tslib_1.__extends(LoadedCheerio, _super);
function LoadedCheerio() {
return _super !== null && _super.apply(this, arguments) || this;
}
// Mimic jQuery's prototype alias for plugin authors.
initialize.fn = initialize.prototype;
return initialize;
return LoadedCheerio;
}(cheerio_1.Cheerio));
/*
* Keep a reference to the top-level scope so we can chain methods that implicitly
* resolve selectors; e.g. $("<span>").(".bar"), which otherwise loses ._root
*/
initialize.prototype._originalRoot = root;
// Add in the static methods
Object.assign(initialize, staticMethods, { load: load });
// Add in the root
initialize._root = root;
// Store options
initialize._options = options;
function initialize(selector, context, r, opts) {
if (r === void 0) { r = root; }
return new LoadedCheerio(selector, context, r, tslib_1.__assign(tslib_1.__assign({}, internalOpts), options_1.flatten(opts)));
}
// Add in static methods & properties
Object.assign(initialize, staticMethods, {
load: load,
// `_root` and `_options` are used in static methods.
_root: root,
_options: internalOpts,
// Add `fn` for plugins
fn: LoadedCheerio.prototype,
// Add the prototype here to maintain `instanceof` behavior.
prototype: LoadedCheerio.prototype,
});
return initialize;
}
exports.load = load;

@@ -18,4 +18,6 @@ import type { DomHandlerOptions } from 'domhandler';

/**
* Options accepted by Cheerio. Please note that parser-specific options are
* *only recognized* if the relevant parser is used.
* Options accepted by Cheerio.
*
* Please note that parser-specific options are *only recognized* if the
* relevant parser is used.
*/

@@ -22,0 +24,0 @@ export interface CheerioOptions extends HTMLParser2Options, Parse5Options {

@@ -5,4 +5,4 @@ "use strict";

var htmlparser2_1 = require("htmlparser2");
var htmlparser2_2 = require("./parsers/htmlparser2");
var parse5_1 = require("./parsers/parse5");
var htmlparser2_adapter_1 = require("./parsers/htmlparser2-adapter");
var parse5_adapter_1 = require("./parsers/parse5-adapter");
var domhandler_1 = require("domhandler");

@@ -18,4 +18,4 @@ /*

return options.xmlMode || options._useHtmlParser2
? htmlparser2_2.parse(content, options)
: parse5_1.parse(content, options, isDocument);
? htmlparser2_adapter_1.parse(content, options)
: parse5_adapter_1.parse(content, options, isDocument);
}

@@ -22,0 +22,0 @@ var doc = content;

@@ -1,2 +0,2 @@

import type { Cheerio } from './cheerio';
import type { CheerioAPI, Cheerio } from '.';
import { Node, Document } from 'domhandler';

@@ -10,3 +10,3 @@ import { CheerioOptions } from './options';

*/
export declare function html(this: typeof Cheerio | void, options?: CheerioOptions): string;
export declare function html(this: CheerioAPI | void, options?: CheerioOptions): string;
/**

@@ -19,3 +19,3 @@ * Renders the document.

*/
export declare function html(this: typeof Cheerio | void, dom?: string | ArrayLike<Node> | Node, options?: CheerioOptions): string;
export declare function html(this: CheerioAPI | void, dom?: string | ArrayLike<Node> | Node, options?: CheerioOptions): string;
/**

@@ -27,3 +27,3 @@ * Render the document as XML.

*/
export declare function xml(this: typeof Cheerio, dom?: string | ArrayLike<Node> | Node): string;
export declare function xml(this: CheerioAPI, dom?: string | ArrayLike<Node> | Node): string;
/**

@@ -35,3 +35,3 @@ * Render the document as text.

*/
export declare function text(this: typeof Cheerio | void, elements?: ArrayLike<Node>): string;
export declare function text(this: CheerioAPI | void, elements?: ArrayLike<Node>): string;
/**

@@ -49,4 +49,4 @@ * Parses a string into an array of DOM nodes. The `context` argument has no

*/
export declare function parseHTML(this: typeof Cheerio, data: string, context?: unknown | boolean, keepScripts?: boolean): Node[];
export declare function parseHTML(this: typeof Cheerio, data?: '' | null): null;
export declare function parseHTML(this: CheerioAPI, data: string, context?: unknown | boolean, keepScripts?: boolean): Node[];
export declare function parseHTML(this: CheerioAPI, data?: '' | null): null;
/**

@@ -66,3 +66,3 @@ * Sometimes you need to work with the top-level root element. To query it, you

*/
export declare function root(this: typeof Cheerio): Cheerio<Document>;
export declare function root(this: CheerioAPI): Cheerio<Document>;
/**

@@ -69,0 +69,0 @@ * Checks to see if the `contained` DOM element is a descendant of the

@@ -8,4 +8,4 @@ "use strict";

var htmlparser2_1 = require("htmlparser2");
var parse5_1 = require("./parsers/parse5");
var htmlparser2_2 = require("./parsers/htmlparser2");
var parse5_adapter_1 = require("./parsers/parse5-adapter");
var htmlparser2_adapter_1 = require("./parsers/htmlparser2-adapter");
/**

@@ -20,18 +20,13 @@ * Helper function to render a DOM.

function render(that, dom, options) {
var _a, _b;
if (!dom) {
if ((_a = that === null || that === void 0 ? void 0 : that._root) === null || _a === void 0 ? void 0 : _a.children) {
dom = that._root.children;
}
else {
return '';
}
}
else if (typeof dom === 'string') {
dom = cheerio_select_1.select(dom, (_b = that === null || that === void 0 ? void 0 : that._root) !== null && _b !== void 0 ? _b : [], options);
}
var _a;
var toRender = dom
? typeof dom === 'string'
? cheerio_select_1.select(dom, (_a = that === null || that === void 0 ? void 0 : that._root) !== null && _a !== void 0 ? _a : [], options)
: dom
: that === null || that === void 0 ? void 0 : that._root.children;
if (!toRender)
return '';
return options.xmlMode || options._useHtmlParser2
? // FIXME: Pull in new version of dom-serializer to fix this.
htmlparser2_2.render(dom, options)
: parse5_1.render(dom);
? htmlparser2_adapter_1.render(toRender, options)
: parse5_adapter_1.render(toRender);
}

@@ -65,4 +60,4 @@ /**

*/
options = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options_1.default), (this ? this._options : {})), options_1.flatten(options !== null && options !== void 0 ? options : {}));
return render(this || undefined, dom, options);
var opts = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options_1.default), (this ? this._options : {})), options_1.flatten(options !== null && options !== void 0 ? options : {}));
return render(this || undefined, dom, opts);
}

@@ -141,4 +136,3 @@ exports.html = html;

function root() {
var fn = this;
return fn(this._root);
return this(this._root);
}

@@ -145,0 +139,0 @@ exports.root = root;

@@ -10,3 +10,3 @@ declare type LowercaseLetters = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';

import type { Cheerio } from './cheerio';
import type { Node, Element } from 'domhandler';
import type { Node } from 'domhandler';
/** Elements that can be passed to manipulation methods. */

@@ -19,4 +19,4 @@ export declare type BasicAcceptedElems<T extends Node> = Cheerio<T> | T[] | T | string;

/** Supported filter types, for traversal methods. */
export declare type AcceptedFilters = string | FilterFunction<Element> | Node | Cheerio<Node>;
export declare type AcceptedFilters<T> = string | FilterFunction<T> | T | Cheerio<T>;
export {};
//# sourceMappingURL=types.d.ts.map

@@ -53,3 +53,3 @@ import { DomUtils } from 'htmlparser2';

*/
export declare function domEach<T extends Node, Arr extends ArrayLike<T> = Cheerio<T>>(array: Arr, fn: (index: number, elem: T) => void | false): Arr;
export declare function domEach<T extends Node, Arr extends ArrayLike<T> = Cheerio<T>>(array: Arr, fn: (elem: T, index: number) => void): Arr;
/**

@@ -56,0 +56,0 @@ * Create a deep copy of the given DOM structure. Sets the parents of the copies

@@ -66,4 +66,4 @@ "use strict";

var len = array.length;
for (var i = 0; i < len && fn(i, array[i]) !== false; i++)
;
for (var i = 0; i < len; i++)
fn(array[i], i);
return array;

@@ -70,0 +70,0 @@ }

{
"name": "cheerio",
"version": "1.0.0-rc.9",
"version": "1.0.0-rc.10",
"description": "Tiny, fast, and elegant implementation of core jQuery designed specifically for the server",
"author": "Matt Mueller <mattmuelle@gmail.com> (mat.io)",
"author": "Matt Mueller <mattmuelle@gmail.com>",
"maintainers": [
"Felix Boehm <me@feedic.com>"
],
"funding": "https://github.com/cheeriojs/cheerio?sponsor=1",

@@ -33,4 +36,4 @@ "license": "MIT",

"dependencies": {
"cheerio-select": "^1.4.0",
"dom-serializer": "^1.3.1",
"cheerio-select": "^1.5.0",
"dom-serializer": "^1.3.2",
"domhandler": "^4.2.0",

@@ -43,28 +46,28 @@ "htmlparser2": "^6.1.0",

"devDependencies": {
"@octokit/graphql": "^4.6.1",
"@octokit/graphql": "^4.6.2",
"@types/benchmark": "^2.1.0",
"@types/jest": "^26.0.23",
"@types/jsdom": "^16.2.10",
"@types/node": "^15.0.2",
"@types/node": "^15.12.1",
"@types/node-fetch": "^2.5.10",
"@types/parse5": "^6.0.0",
"@types/parse5-htmlparser2-tree-adapter": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^4.22.1",
"@typescript-eslint/parser": "^4.22.1",
"@typescript-eslint/eslint-plugin": "^4.26.0",
"@typescript-eslint/parser": "^4.26.0",
"benchmark": "^2.1.4",
"eslint": "^7.25.0",
"eslint": "^7.28.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-jest": "^24.3.6",
"eslint-plugin-jsdoc": "^33.1.0",
"eslint-plugin-jsdoc": "^35.1.3",
"eslint-plugin-node": "^11.1.0",
"husky": "^4.3.8",
"jest": "^26.6.3",
"jest": "^27.0.4",
"jquery": "^3.6.0",
"jsdom": "^16.5.3",
"lint-staged": "^10.5.4",
"jsdom": "^16.6.0",
"lint-staged": "^11.0.0",
"node-fetch": "^2.6.1",
"prettier": "^2.2.1",
"prettier": "^2.3.1",
"prettier-plugin-jsdoc": "0.3.22",
"ts-jest": "^26.5.6",
"ts-node": "^9.1.1",
"ts-jest": "^27.0.3",
"ts-node": "^10.0.0",
"typedoc": "^0.20.36",

@@ -71,0 +74,0 @@ "typescript": "^4.2.4"

@@ -103,3 +103,2 @@ <h1 align="center">cheerio</h1>

```js
const $ = require('cheerio');
$('ul', '<ul id="fruits">...</ul>');

@@ -111,3 +110,2 @@ ```

```js
const $ = require('cheerio');
$('li', 'ul', '<ul id="fruits">...</ul>');

@@ -171,3 +169,3 @@ ```

This selector method is the starting point for traversing and manipulating the document. Like jQuery, it's the primary method for selecting elements in the document, but unlike jQuery it's built on top of the CSSSelect library, which implements most of the Sizzle selectors.
This selector method is the starting point for traversing and manipulating the document. Like jQuery, it's the primary method for selecting elements in the document.

@@ -220,4 +218,6 @@ ```js

```xml
const $ = cheerio.load('<media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>');
```js
const $ = cheerio.load(
'<media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>'
);
```

@@ -229,3 +229,3 @@

$.xml();
//=> <media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>
//=> <media:thumbnail url="http://www.foo.com/keyframe.jpg" width="75" height="50" time="12:05:01.123"/>
```

@@ -254,2 +254,12 @@

If you're using TypeScript, you should also add a type definition for your new method:
```ts
declare module 'cheerio' {
interface Cheerio<T> {
logHtml(this: Cheerio<T>): void;
}
}
```
### The "DOM Node" object

@@ -278,13 +288,2 @@

## Testing
To run the test suite, download the repository, then within the cheerio directory, run:
```shell
make setup
make test
```
This will download the development packages and run the test suite.
## Sponsors

@@ -291,0 +290,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc