UNPKG

html-validate

Version:

Offline HTML5 validator and linter

1,520 lines (1,455 loc) 102 kB
import { ErrorObject } from 'ajv'; import { SchemaObject } from 'ajv'; /** * Returns the normalized metadata property `aria.naming`. * * - Returns `allowed` if this element allows naming. * - Returns `prohibited` if this element does not allow naming. * - If the element doesn't have metadata `allowed` is returned. * * If the element contains an explicit `role` the role is used to determine * whenever the element allows naming or not. Otherwise it uses metadata to * determine. * * @public * @param element - Element to get `aria.naming` from. */ export declare function ariaNaming(element: HtmlElement): "allowed" | "prohibited"; /** * DOM Attribute. * * Represents a HTML attribute. Can contain either a fixed static value or a * placeholder for dynamic values (e.g. interpolated). * * @public */ export declare class Attribute { /** Attribute name */ readonly key: string; readonly value: string | DynamicValue | null; readonly keyLocation: Location_2; readonly valueLocation: Location_2 | null; readonly originalAttribute?: string; /** * @param key - Attribute name. * @param value - Attribute value. Set to `null` for boolean attributes. * @param keyLocation - Source location of attribute name. * @param valueLocation - Source location of attribute value. * @param originalAttribute - If this attribute was dynamically added via a * transformation (e.g. vuejs `:id` generating the `id` attribute) this * parameter should be set to the attribute name of the source attribute (`:id`). */ constructor(key: string, value: string | DynamicValue | null, keyLocation: Location_2, valueLocation: Location_2 | null, originalAttribute?: string); /** * Flag set to true if the attribute value is static. */ get isStatic(): boolean; /** * Flag set to true if the attribute value is dynamic. */ get isDynamic(): boolean; /** * Test attribute value. * * @param pattern - Pattern to match value against. Can be a RegExp, literal * string or an array of strings (returns true if any value matches the * array). * @param dynamicMatches - If true `DynamicValue` will always match, if false * it never matches. * @returns `true` if attribute value matches pattern. */ valueMatches(pattern: RegExp | string | string[], dynamicMatches?: boolean): boolean; } /** * Raw attribute data. * * @public */ export declare interface AttributeData { /** Attribute name */ key: string; /** Attribute value */ value: string | DynamicValue | null; /** Quotation mark (if present) */ quote: '"' | "'" | null; /** Original attribute name (when a dynamic attribute is used), e.g * "ng-attr-foo" or "v-bind:foo" */ originalAttribute?: string; } /** * Event emitted when attributes are encountered. * * @public */ export declare interface AttributeEvent extends Event_2 { /** Location of the full attribute (key, quotes and value) */ location: Location_2; /** Attribute name. */ key: string; /** Attribute value. */ value: string | DynamicValue | null; /** Quotemark used. */ quote: '"' | "'" | null; /** Set to original attribute when a transformer dynamically added this * attribute. */ originalAttribute?: string; /** HTML element this attribute belongs to. */ target: HtmlElement; /** Location of the attribute key */ keyLocation: Location_2; /** Location of the attribute value */ valueLocation: Location_2 | null; /** Attribute metadata if present */ meta: MetaAttribute | null; } /* Excluded from this release type: AttrNameToken */ /* Excluded from this release type: AttrValueToken */ /** * @public */ export declare interface AvailableFormatters { checkstyle: Formatter; codeframe: Formatter; json: Formatter; stylish: Formatter; text: Formatter; } /* Excluded from this release type: BaseToken */ /** * @public */ export declare type CategoryOrTag = string; /** * Create a new resolver for NodeJS packages using `require(..)`. * * If the module name contains `<rootDir>` (e.g. `<rootDir/foo`) it will be * expanded relative to the root directory either explicitly set by the * `rootDir` parameter or determined automatically by the closest `package.json` * file (starting at the current working directory). * * @public * @since 8.8.0 */ export declare function cjsResolver(options?: { rootDir?: string; }): CommonJSResolver; /** * Checks text content of an element. * * Any text is considered including text from descendant elements. Whitespace is * ignored. * * If any text is dynamic `TextClassification.DYNAMIC_TEXT` is returned. * * @public */ export declare function classifyNodeText(node: HtmlElement, options?: TextClassificationOptions): TextClassification; /** * @public */ export declare class CLI { private options; private config; private loader; private ignored; /** * Create new CLI helper. * * Can be used to create tooling with similar properties to bundled CLI * script. */ constructor(options?: CLIOptions); /** * Returns list of files matching patterns and are not ignored. Filenames will * have absolute paths. * * @public */ expandFiles(patterns: string[], options?: ExpandOptions): Promise<string[]>; getFormatter(formatters: string): Promise<(report: Report_2) => string>; /** * Initialize project with a new configuration. * * A new `.htmlvalidate.json` file will be placed in the path provided by * `cwd`. */ init(cwd: string): Promise<InitResult>; /** * Clear cache. * * Previously fetched [[HtmlValidate]] instances must either be fetched again * or call [[HtmlValidate.flushConfigCache]]. */ clearCache(): Promise<void>; /* Excluded from this release type: getLoader */ /** * Get HtmlValidate instance with configuration based on options passed to the * constructor. * * @public */ getValidator(): Promise<HtmlValidate>; /* Excluded from this release type: getConfig */ /** * Searches ".htmlvalidateignore" files from filesystem and returns `true` if * one of them contains a pattern matching given filename. */ private isIgnored; private resolveConfig; } /** * @public */ export declare interface CLIOptions { configFile?: string; /** Comma-separated list of presets to use */ preset?: string; rules?: string | string[]; } /* Excluded from this release type: CommentToken */ /** * CommonJS resolver. * * @public * @since 8.8.0 */ export declare type CommonJSResolver = Required<Resolver>; /** * Tests if plugin is compatible with html-validate library. Unless the `silent` * option is used a warning is displayed on the console. * * @public * @since v5.0.0 * @param name - Name of plugin * @param declared - What library versions the plugin support (e.g. declared peerDependencies) * @returns - `true` if version is compatible */ export declare function compatibilityCheck(name: string, declared: string, options?: Partial<CompatibilityOptions>): boolean; /** * Options for {@link compatibilityCheck}. * * @public */ export declare interface CompatibilityOptions { /** If `true` nothing no output will be generated on console. Default: `false` */ silent: boolean; /* Excluded from this release type: version */ /** Use custom logging callback. Default: `console.error` */ logger(this: void, message: string): void; } /** * Event emitted when Internet Explorer conditionals `<![if ...]>` are * encountered. * * @public */ export declare interface ConditionalEvent extends Event_2 { /** Event location. */ location: Location_2; /** Condition including markers. */ condition: string; /** The element containing the conditional, if any. */ parent: HtmlElement | null; } /* Excluded from this release type: ConditionalToken */ /** * Configuration holder. * * Each file being validated will have a unique instance of this class. * * @public */ export declare class Config { private config; private configurations; private resolvers; private metaTable; private plugins; private transformers; /** * Create a new blank configuration. See also `Config.defaultConfig()`. */ static empty(): Config; /** * Create configuration from object. */ static fromObject(resolvers: Resolver | Resolver[], options: ConfigData, filename?: string | null): Config | Promise<Config>; /* Excluded from this release type: fromFile */ /* Excluded from this release type: validate */ /** * Load a default configuration object. */ static defaultConfig(): Config; /* Excluded from this release type: create */ private init; /* Excluded from this release type: __constructor */ /** * Returns true if this configuration is marked as "root". */ isRootFound(): boolean; /** * Returns a new configuration as a merge of the two. Entries from the passed * object takes priority over this object. * * @public * @param rhs - Configuration to merge with this one. */ merge(resolvers: Resolver[], rhs: Config): Config | Promise<Config>; private extendConfig; private extendConfigAsync; /* Excluded from this release type: getMetaTable */ private getElementsFromEntry; /* Excluded from this release type: get */ /* Excluded from this release type: getRules */ private static getRulesObject; /* Excluded from this release type: getPlugins */ /* Excluded from this release type: getTransformers */ private loadPlugins; private loadConfigurations; private extendMeta; /** * Resolve all configuration and return a [[ResolvedConfig]] instance. * * A resolved configuration will merge all extended configs and load all * plugins and transformers, and normalize the rest of the configuration. * * @public */ resolve(): ResolvedConfig | Promise<ResolvedConfig>; /* Excluded from this release type: resolveData */ } /** * @public */ export declare interface ConfigData { /** * If set to true no new configurations will be searched. */ root?: boolean; /** * List of configuration presets to extend. * * The following sources are allowed: * * - One of the [predefined presets](http://html-validate.org/rules/presets.html). * - Node module exporting a preset. * - Plugin exporting a named preset. * - Local path to a json or js file exporting a preset. */ extends?: string[]; /** * List of sources for element metadata. * * The following sources are allowed: * * - "html5" (default) for the builtin metadata. * - node module which export metadata * - local path to json or js file exporting metadata. * - object with inline metadata * * If elements isn't specified it defaults to `["html5"]` */ elements?: Array<string | Record<string, unknown>>; /** * List of plugins. * * Each plugin must be resolvable be require and export the plugin interface. */ plugins?: Array<string | Plugin_2>; /** * List of source file transformations. A transformer takes a filename and * returns Source instances with extracted HTML-templates. * * Example: * * ```js * "transform": { * "^.*\\.foo$": "my-transform" * } * ``` * * To run the "my-transform" module on all .foo files. */ transform?: TransformMap; rules?: RuleConfig; } /* Excluded from this release type: ConfigError */ /** * Configuration loader interface. * * A configuration loader takes a handle (typically a filename) and returns a * configuration for it. * * @public */ export declare abstract class ConfigLoader { private _globalConfig; private _configData; protected readonly resolvers: Resolver[]; /** * Create a new ConfigLoader. * * @param resolvers - Sorted list of resolvers to use (in order). * @param configData - Default configuration (which all configurations will inherit from). */ constructor(resolvers: Resolver[], configData?: ConfigData); /* Excluded from this release type: setConfigData */ /** * Get the global configuration. * * @returns A promise resolving to the global configuration. */ protected getGlobalConfig(): Config | Promise<Config>; /** * Get the global configuration. * * The synchronous version does not support async resolvers. * * @returns The global configuration. */ protected getGlobalConfigSync(): Config; /** * Get configuration for given handle. * * Handle is typically a filename but it is up to the loader to interpret the * handle as something useful. * * If [[configOverride]] is set it is merged with the final result. * * @param handle - Unique handle to get configuration for. * @param configOverride - Optional configuration to merge final results with. */ abstract getConfigFor(handle: string, configOverride?: ConfigData): ResolvedConfig | Promise<ResolvedConfig>; /* Excluded from this release type: getResolvers */ /** * Flush configuration cache. * * Flushes all cached entries unless a specific handle is given. * * @param handle - If given only the cache for given handle will be flushed. */ abstract flushCache(handle?: string): void; /* Excluded from this release type: _getGlobalConfig */ /** * Default configuration used when no explicit configuration is passed to constructor. */ protected abstract defaultConfig(): Config | Promise<Config>; protected empty(): Config; /** * Load configuration from object. */ protected loadFromObject(options: ConfigData, filename?: string | null): Config | Promise<Config>; /** * Load configuration from filename. */ protected loadFromFile(filename: string): Config | Promise<Config>; } /* Excluded from this release type: configPresets */ /** * Configuration ready event. * * @public */ export declare interface ConfigReadyEvent extends Event_2 { config: ResolvedConfig; rules: Record<string, Rule<unknown, unknown>>; } /** * @public */ declare type CSSStyleDeclaration_2 = Record<string, string>; export { CSSStyleDeclaration_2 as CSSStyleDeclaration } /** * @public */ export declare interface DeferredMessage extends Omit<Message, "selector"> { selector: () => string | null; } /** * Helper function to assist IDE with completion and type-checking. * * @public * @since */ export declare function defineConfig(config: ConfigData): ConfigData; /** * Helper function to assist IDE with completion and type-checking. * * @public */ export declare function defineMetadata(metatable: MetaDataTable): MetaDataTable; /** * Helper function to assist IDE with completion and type-checking. * * @public */ export declare function definePlugin(plugin: Plugin_2): Plugin_2; /** * @public */ export declare interface DeprecatedElement { message?: string; documentation?: string; source?: string; } /** * Event emitted when html-validate directives `<!-- [html-validate-...] -->` * are encountered. * * @public */ export declare interface DirectiveEvent extends Event_2 { /** Event location. */ location: Location_2; /** Action location */ actionLocation: Location_2; /** Options location */ optionsLocation?: Location_2; /** Comment location */ commentLocation?: Location_2; /** Directive action. */ action: "enable" | "disable" | "disable-block" | "disable-next"; /** Directive options. */ data: string; /** Directive comment. */ comment: string; } /* Excluded from this release type: DirectiveToken */ /* Excluded from this release type: DoctypeCloseToken */ /** * Event emitted when doctypes `<!DOCTYPE ..>` are encountered. * * @public */ export declare interface DoctypeEvent extends Event_2 { /** Event location. */ location: Location_2; /** Tag */ tag: string; /** Selected doctype */ value: string; /** Location of doctype value */ valueLocation: Location_2; } /* Excluded from this release type: DoctypeOpenToken */ /* Excluded from this release type: DoctypeValueToken */ /** * @public */ export declare type DOMInternalID = number; /** * Event emitted after initialization but before tokenization and parsing occurs. * Can be used to initialize state in rules. * * @public */ export declare interface DOMLoadEvent extends Event_2 { source: Source; } /** * @public */ export declare class DOMNode { readonly nodeName: string; readonly nodeType: NodeType; readonly childNodes: DOMNode[]; readonly location: Location_2; /* Excluded from this release type: unique */ private cache; /** * Set of disabled rules for this node. * * Rules disabled by using directives are added here. */ private disabledRules; /** * Set of blocked rules for this node. * * Rules blocked by using directives are added here. */ private blockedRules; /* Excluded from this release type: __constructor */ /* Excluded from this release type: cacheEnable */ /** * Fetch cached value from this DOM node. * * Cache is not enabled until `cacheEnable()` is called by [[Parser]] (when * the element is fully constructed). * * @returns value or `undefined` if the value doesn't exist. */ cacheGet<K extends keyof DOMNodeCache>(key: K): DOMNodeCache[K] | undefined; cacheGet(key: string | number | symbol): any | undefined; /** * Store a value in cache. * * @returns the value itself is returned. */ cacheSet<K extends keyof DOMNodeCache>(key: K, value: DOMNodeCache[K]): DOMNodeCache[K]; cacheSet<T>(key: string | number | symbol, value: T): T; /** * Remove a value by key from cache. * * @returns `true` if the entry existed and has been removed. */ cacheRemove(key: string | number | symbol): boolean; /** * Check if key exists in cache. */ cacheExists(key: string | number | symbol): boolean; /** * Get the text (recursive) from all child nodes. */ get textContent(): string; append(node: DOMNode): void; /* Excluded from this release type: insertBefore */ isRootElement(): boolean; /** * Tests if two nodes are the same (references the same object). * * @since v4.11.0 */ isSameNode(otherNode: DOMNode): boolean; /** * Returns a DOMNode representing the first direct child node or `null` if the * node has no children. */ get firstChild(): DOMNode; /** * Returns a DOMNode representing the last direct child node or `null` if the * node has no children. */ get lastChild(): DOMNode; /* Excluded from this release type: removeChild */ /* Excluded from this release type: blockRule */ /* Excluded from this release type: blockRules */ /* Excluded from this release type: disableRule */ /* Excluded from this release type: disableRules */ /** * Enable a previously disabled rule for this node. */ enableRule(ruleId: string): void; /** * Enables multiple rules. */ enableRules(rules: string[]): void; /* Excluded from this release type: ruleEnabled */ /* Excluded from this release type: ruleBlockers */ generateSelector(): string | null; /* Excluded from this release type: _setParent */ private _removeChild; } /** * @public */ export declare interface DOMNodeCache { } /** * Event emitted when DOM tree is fully constructed. * * @public */ export declare interface DOMReadyEvent extends Event_2 { /** DOM Tree */ document: DOMTree; source: Source; } /** * @public */ declare class DOMTokenList_2 extends Array<string> { readonly value: string; private readonly locations; constructor(value: string | DynamicValue | null, location: Location_2 | null); item(n: number): string | undefined; location(n: number): Location_2 | undefined; contains(token: string): boolean; iterator(): Generator<{ index: number; item: string; location: Location_2; }>; } export { DOMTokenList_2 as DOMTokenList } /** * @public */ export declare class DOMTree { readonly root: HtmlElement; private active; private _readyState; doctype: string | null; /* Excluded from this release type: __constructor */ /* Excluded from this release type: pushActive */ /* Excluded from this release type: popActive */ /* Excluded from this release type: getActive */ /** * Describes the loading state of the document. * * When `"loading"` it is still not safe to use functions such as * `querySelector` or presence of attributes, child nodes, etc. */ get readyState(): "loading" | "complete"; /* Excluded from this release type: resolveMeta */ getElementsByTagName(tagName: string): HtmlElement[]; /** * @deprecated use utility function `walk.depthFirst(..)` instead (since 8.21.0). */ visitDepthFirst(callback: (node: HtmlElement) => void): void; /** * @deprecated use `querySelector(..)` instead (since 8.21.0) */ find(callback: (node: HtmlElement) => boolean): HtmlElement | null; querySelector(selector: string): HtmlElement | null; querySelectorAll(selector: string): HtmlElement[]; } /** * @public */ export declare class DynamicValue { readonly expr: string; constructor(expr: string); toString(): string; } /** * Event emitted when an element is fully constructed (including its children). * * @public */ export declare interface ElementReadyEvent extends Event_2 { /** Event location. */ location: Location_2; /** HTML element */ target: HtmlElement; } /* Excluded from this release type: EOFToken */ /** * @public */ export declare interface ErrorDescriptor<ContextType> { node: DOMNode | null; message: string; location?: Location_2 | null; context?: ContextType; } /** * ESM resolver. * * @public * @since 9.0.0 */ export declare type ESMResolver = Required<Resolver>; /** * Create a new resolver for NodeJS packages using `import(..)`. * * If the module name contains `<rootDir>` (e.g. `<rootDir/foo`) it will be * expanded relative to the root directory either explicitly set by the * `rootDir` parameter or determined automatically by the closest `package.json` * file (starting at the current working directory). * * @public * @since 9.0.0 */ export declare function esmResolver(options?: { rootDir?: string; }): ESMResolver; /** * @public */ declare interface Event_2 { /** Event location. */ location: Location_2 | null; } export { Event_2 as Event } /** * @public */ export declare type EventCallback = (event: string, data: any) => void; /* Excluded from this release type: EventDump */ /** * @public */ export declare class EventHandler { private listeners; constructor(); /** * Add an event listener. * * @param event - Event names (comma separated) or '*' for any event. * @param callback - Called any time even triggers. * @returns Unregistration function. */ on(event: string, callback: EventCallback): () => void; /** * Add a onetime event listener. The listener will automatically be removed * after being triggered once. * * @param event - Event names (comma separated) or '*' for any event. * @param callback - Called any time even triggers. * @returns Unregistration function. */ once(event: string, callback: EventCallback): () => void; /** * Trigger event causing all listeners to be called. * * @param event - Event name. * @param data - Event data. */ trigger(event: string, data: any): void; private getCallbacks; } /** * @public */ export declare interface ExpandOptions { /** * Working directory. Defaults to `process.cwd()`. */ cwd?: string; /** * List of extensions to search for when expanding directories. Extensions * should be passed without leading dot, e.g. "html" instead of ".html". */ extensions?: string[]; } /** * Loads configuration by traversing filesystem. * * Configuration is read from three sources and in the following order: * * 1. Global configuration passed to constructor. * 2. Configuration files found when traversing the directory structure. * 3. Override passed to this function. * * The following configuration filenames are searched: * * - `.htmlvalidate.json` * - `.htmlvalidate.js` * - `.htmlvalidate.cjs` * - `.htmlvalidate.mjs` * * Global configuration is used when no configuration file is found. The * result is always merged with override if present. * * The `root` property set to `true` affects the configuration as following: * * 1. If set in override the override is returned as-is. * 2. If set in the global config the override is merged into global and * returned. No configuration files are searched. * 3. Setting `root` in configuration file only stops directory traversal. * * @public */ export declare class FileSystemConfigLoader extends ConfigLoader { protected cache: Map<string, Config | null>; private fs; /** * Create a filesystem configuration loader with default resolvers. * * @param fs - `fs` implementation, * @param config - Global configuration. * @param configFactory - Optional configuration factory. */ constructor(config?: ConfigData, options?: Partial<FileSystemConfigLoaderOptions>); /** * Create a filesystem configuration loader with custom resolvers. * * @param fs - `fs` implementation, * @param resolvers - Resolvers to use. * @param config - Global configuration. * @param configFactory - Optional configuration factory. */ constructor(resolvers: Resolver[], config?: ConfigData, options?: Partial<FileSystemConfigLoaderOptions>); /** * Get configuration for given filename. * * @param filename - Filename to get configuration for. * @param configOverride - Configuration to merge final result with. */ getConfigFor(filename: string, configOverride?: ConfigData): ResolvedConfig | Promise<ResolvedConfig>; /** * Flush configuration cache. * * @param filename - If given only the cache for that file is flushed. */ flushCache(filename?: string): void; /** * Load raw configuration from directory traversal. * * This configuration is not merged with global configuration and may return * `null` if no configuration files are found. */ fromFilename(filename: string): Config | Promise<Config | null> | null; /* Excluded from this release type: fromFilenameAsync */ private _merge; private _resolveSync1; private _resolveSync2; private _resolveAsync; /* Excluded from this release type: _getInternalCache */ protected defaultConfig(): Config | Promise<Config>; } /** * Options for [[FileSystemConfigLoader]]. * * @public */ export declare interface FileSystemConfigLoaderOptions { /** An implementation of `fs` as needed by [[FileSystemConfigLoader]] */ fs: FSLike; } /** * @public */ export declare interface FormAssociated { /** This element can be disabled using the `disabled` attribute */ disablable: boolean; /** Listed elements have a name attribute and is listed in the form and fieldset elements property. */ listed: boolean; } /** * @public */ export declare type Formatter = (results: Result[]) => string; /** * Get formatter function by name. * * @public * @param name - Name of formatter. * @returns Formatter function or null if it doesn't exist. */ export declare function formatterFactory(name: keyof AvailableFormatters): Formatter; /** * @public */ export declare function formatterFactory(name: string): Formatter | null; /** * @public */ export declare interface FSLike { existsSync(path: string): boolean; } /** * @public */ export declare class HtmlElement extends DOMNode { readonly tagName: string; readonly voidElement: boolean; readonly depth: number; closed: NodeClosed; protected readonly attr: Record<string, Attribute[]>; private metaElement; private annotation; private _parent; /* Excluded from this release type: _adapter */ private constructor(); /** * Manually create a new element. This is primary useful for test-cases. While * the API is public it is not meant for general consumption and is not * guaranteed to be stable across versions. * * Use at your own risk. Prefer to use [[Parser]] to parse a string of markup * instead. * * @public * @since 8.22.0 * @param tagName - Element tagname. * @param location - Element location. * @param details - Additional element details. */ static createElement(tagName: string, location: Location_2, details?: { closed?: NodeClosed; meta?: MetaElement | null; parent?: HtmlElement; }): HtmlElement; /* Excluded from this release type: rootNode */ /* Excluded from this release type: fromTokens */ /** * Returns annotated name if set or defaults to `<tagName>`. * * E.g. `my-annotation` or `<div>`. */ get annotatedName(): string; /** * Get list of IDs referenced by `aria-labelledby`. * * If the attribute is unset or empty this getter returns null. * If the attribute is dynamic the original {@link DynamicValue} is returned. * * @public */ get ariaLabelledby(): string[] | DynamicValue | null; /** * Similar to childNodes but only elements. */ get childElements(): HtmlElement[]; /** * Find the first ancestor matching a selector. * * Implementation of DOM specification of Element.closest(selectors). */ closest(selectors: string): HtmlElement | null; /** * Generate a DOM selector for this element. The returned selector will be * unique inside the current document. */ generateSelector(): string | null; /** * Tests if this element has given tagname. * * If passing "*" this test will pass if any tagname is set. */ is(tagName: string): boolean; /** * Load new element metadata onto this element. * * Do note that semantics such as `void` cannot be changed (as the element has * already been created). In addition the element will still "be" the same * element, i.e. even if loading meta for a `<p>` tag upon a `<div>` tag it * will still be a `<div>` as far as the rest of the validator is concerned. * * In fact only certain properties will be copied onto the element: * * - content categories (flow, phrasing, etc) * - required attributes * - attribute allowed values * - permitted/required elements * * Properties *not* loaded: * * - inherit * - deprecated * - foreign * - void * - implicitClosed * - scriptSupporting * - deprecatedAttributes * * Changes to element metadata will only be visible after `element:ready` (and * the subsequent `dom:ready` event). */ loadMeta(meta: MetaElement): void; /** * Match this element against given selectors. Returns true if any selector * matches. * * Implementation of DOM specification of Element.matches(selectors). */ matches(selectorList: string): boolean; get meta(): MetaElement | null; get parent(): HtmlElement | null; /** * Get current role for this element (explicit with `role` attribute or mapped * with implicit role). * * @since 8.9.1 */ get role(): string | DynamicValue | null; /** * Set annotation for this element. */ setAnnotation(text: string): void; /** * Set attribute. Stores all attributes set even with the same name. * * @param key - Attribute name * @param value - Attribute value. Use `null` if no value is present. * @param keyLocation - Location of the attribute name. * @param valueLocation - Location of the attribute value (excluding quotation) * @param originalAttribute - If attribute is an alias for another attribute * (dynamic attributes) set this to the original attribute name. */ setAttribute(key: string, value: string | DynamicValue | null, keyLocation: Location_2, valueLocation: Location_2 | null, originalAttribute?: string): void; /** * Get parsed tabindex for this element. * * - If `tabindex` attribute is not present `null` is returned. * - If attribute value is omitted or the empty string `null` is returned. * - If attribute value cannot be parsed `null` is returned. * - If attribute value is dynamic `0` is returned. * - Otherwise the parsed value is returned. * * This property does *NOT* take into account if the element have a default * `tabindex` (such as `<input>` have). Instead use the `focusable` metadata * property to determine this. * * @public * @since 8.16.0 */ get tabIndex(): number | null; /* Excluded from this release type: textType */ /** * Get a list of all attributes on this node. */ get attributes(): Attribute[]; hasAttribute(key: string): boolean; /** * Get attribute. * * By default only the first attribute is returned but if the code needs to * handle duplicate attributes the `all` parameter can be set to get all * attributes with given key. * * This usually only happens when code contains duplicate attributes (which * `no-dup-attr` will complain about) or when a static attribute is combined * with a dynamic, consider: * * <p class="foo" dynamic-class="bar"> * * @param key - Attribute name * @param all - Return single or all attributes. */ getAttribute(key: string): Attribute | null; getAttribute(key: string, all: true): Attribute[]; /** * Get attribute value. * * Returns the attribute value if present. * * - Missing attributes return `null`. * - Boolean attributes return `null`. * - `DynamicValue` returns attribute expression. * * @param key - Attribute name * @returns Attribute value or null. */ getAttributeValue(key: string): string | null; /** * Add text as a child node to this element. * * @param text - Text to add. * @param location - Source code location of this text. */ appendText(text: string | DynamicValue, location: Location_2): void; /** * Return a list of all known classes on the element. Dynamic values are * ignored. */ get classList(): DOMTokenList_2; /** * Get element ID if present. */ get id(): string | null; get style(): CSSStyleDeclaration_2; /** * Returns the first child element or null if there are no child elements. */ get firstElementChild(): HtmlElement | null; /** * Returns the last child element or null if there are no child elements. */ get lastElementChild(): HtmlElement | null; get siblings(): HtmlElement[]; get previousSibling(): HtmlElement | null; get nextSibling(): HtmlElement | null; getElementsByTagName(tagName: string): HtmlElement[]; querySelector(selector: string): HtmlElement | null; querySelectorAll(selector: string): HtmlElement[]; private querySelectorImpl; /* Excluded from this release type: someChildren */ /* Excluded from this release type: everyChildren */ /* Excluded from this release type: find */ /* Excluded from this release type: _setParent */ } /** * HTML5 interface for HTMLElement. Contains all the needed methods the * HTML-Validate metadata requires to determine if usage is valid. * * While not officially supported, changes to this interface should be verified * against browsers and/or jsdom, i.e. it should be possible to pass in either * implementation and the element metadata should still work. * * @public * @since 8.2.0 */ export declare interface HtmlElementLike { closest(selectors: string): HtmlElementLike | null | undefined; getAttribute(name: string): string | DynamicValue | null | undefined; hasAttribute(name: string): boolean; } /** * Primary API for using HTML-validate. * * Provides high-level abstractions for common operations. * * @public */ export declare class HtmlValidate { protected configLoader: ConfigLoader; /** * Create a new validator. * * @public * @param configLoader - Use a custom configuration loader. * @param config - If set it provides the global default configuration. By * default `Config.defaultConfig()` is used. */ constructor(config?: ConfigData); constructor(configLoader: ConfigLoader); /** * Parse and validate HTML from string. * * @public * @param str - Text to parse. * @param filename - If set configuration is loaded for given filename. * @param hooks - Optional hooks (see [[Source]]) for definition. * @returns Report output. */ validateString(str: string): Promise<Report_2>; validateString(str: string, filename: string): Promise<Report_2>; validateString(str: string, hooks: SourceHooks): Promise<Report_2>; validateString(str: string, options: ConfigData): Promise<Report_2>; validateString(str: string, filename: string, hooks: SourceHooks): Promise<Report_2>; validateString(str: string, filename: string, options: ConfigData): Promise<Report_2>; validateString(str: string, filename: string, options: ConfigData, hooks: SourceHooks): Promise<Report_2>; /** * Parse and validate HTML from string. * * @public * @param str - Text to parse. * @param filename - If set configuration is loaded for given filename. * @param hooks - Optional hooks (see [[Source]]) for definition. * @returns Report output. */ validateStringSync(str: string): Report_2; validateStringSync(str: string, filename: string): Report_2; validateStringSync(str: string, hooks: SourceHooks): Report_2; validateStringSync(str: string, options: ConfigData): Report_2; validateStringSync(str: string, filename: string, hooks: SourceHooks): Report_2; validateStringSync(str: string, filename: string, options: ConfigData): Report_2; validateStringSync(str: string, filename: string, options: ConfigData, hooks: SourceHooks): Report_2; /** * Parse and validate HTML from [[Source]]. * * @public * @param input - Source to parse. * @returns Report output. */ validateSource(input: Source, configOverride?: ConfigData): Promise<Report_2>; /** * Parse and validate HTML from [[Source]]. * * @public * @param input - Source to parse. * @returns Report output. */ validateSourceSync(input: Source, configOverride?: ConfigData): Report_2; /** * Parse and validate HTML from file. * * @public * @param filename - Filename to read and parse. * @returns Report output. */ validateFile(filename: string, fs?: TransformFS): Promise<Report_2>; /** * Parse and validate HTML from file. * * @public * @param filename - Filename to read and parse. * @returns Report output. */ validateFileSync(filename: string, fs?: TransformFS): Report_2; /** * Parse and validate HTML from multiple files. Result is merged together to a * single report. * * @param filenames - Filenames to read and parse. * @returns Report output. */ validateMultipleFiles(filenames: string[], fs?: TransformFS): Promise<Report_2>; /** * Parse and validate HTML from multiple files. Result is merged together to a * single report. * * @param filenames - Filenames to read and parse. * @returns Report output. */ validateMultipleFilesSync(filenames: string[], fs?: TransformFS): Report_2; /** * Returns true if the given filename can be validated. * * A file is considered to be validatable if the extension is `.html` or if a * transformer matches the filename. * * This is mostly useful for tooling to determine whenever to validate the * file or not. CLI tools will run on all the given files anyway. */ canValidate(filename: string): Promise<boolean>; /** * Returns true if the given filename can be validated. * * A file is considered to be validatable if the extension is `.html` or if a * transformer matches the filename. * * This is mostly useful for tooling to determine whenever to validate the * file or not. CLI tools will run on all the given files anyway. */ canValidateSync(filename: string): boolean; /* Excluded from this release type: dumpTokens */ /* Excluded from this release type: dumpEvents */ /* Excluded from this release type: dumpTree */ /* Excluded from this release type: dumpSource */ /** * Get effective configuration schema. */ getConfigurationSchema(): Promise<SchemaObject>; /** * Get effective metadata element schema. * * If a filename is given the configured plugins can extend the * schema. Filename must not be an existing file or a filetype normally * handled by html-validate but the path will be used when resolving * configuration. As a rule-of-thumb, set it to the elements json file. */ getElementsSchema(filename?: string): Promise<SchemaObject>; /** * Get effective metadata element schema. * * If a filename is given the configured plugins can extend the * schema. Filename must not be an existing file or a filetype normally * handled by html-validate but the path will be used when resolving * configuration. As a rule-of-thumb, set it to the elements json file. */ getElementsSchemaSync(filename?: string): SchemaObject; /** * Get contextual documentation for the given rule. Configuration will be * resolved for given filename. * * @example * * ```js * const report = await htmlvalidate.validateFile("my-file.html"); * for (const result of report.results){ * for (const message of result.messages){ * const documentation = await htmlvalidate.getContextualDocumentation(message, result.filePath); * // do something with documentation * } * } * ``` * * @public * @since 8.0.0 * @param message - Message reported during validation * @param filename - Filename used to resolve configuration. * @returns Contextual documentation or `null` if the rule does not exist. */ getContextualDocumentation(message: Pick<Message, "ruleId" | "context">, filename?: string): Promise<RuleDocumentation | null>; /** * Get contextual documentation for the given rule using provided * configuration. * * @example * * ```js * const report = await htmlvalidate.validateFile("my-file.html"); * for (const result of report.results){ * for (const message of result.messages){ * const documentation = await htmlvalidate.getRuleDocumentation(message, result.filePath); * // do something with documentation * } * } * ``` * * @public * @since 8.0.0 * @param message - Message reported during validation * @param config - Configuration to use. * @returns Contextual documentation or `null` if the rule does not exist. */ getContextualDocumentation(message: Pick<Message, "ruleId" | "context">, config: ResolvedConfig | Promise<ResolvedConfig>): Promise<RuleDocumentation | null>; /** * Get contextual documentation for the given rule. Configuration will be * resolved for given filename. * * @example * * ```js * const report = htmlvalidate.validateFileSync("my-file.html"); * for (const result of report.results){ * for (const message of result.messages){ * const documentation = htmlvalidate.getRuleDocumentationSync(message, result.filePath); * // do something with documentation * } * } * ``` * * @public * @since 8.0.0 * @param message - Message reported during validation * @param filename - Filename used to resolve configuration. * @returns Contextual documentation or `null` if the rule does not exist. */ getContextualDocumentationSync(message: Pick<Message, "ruleId" | "context">, filename?: string): RuleDocumentation | null; /** * Get contextual documentation for the given rule using provided * configuration. * * @example * * ```js * const report = htmlvalidate.validateFileSync("my-file.html"); * for (const result of report.results){ * for (const message of result.messages){ * const documentation = htmlvalidate.getRuleDocumentationSync(message, result.filePath); * // do something with documentation * } * } * ``` * * @public * @since 8.0.0 * @param message - Message reported during validation * @param config - Configuration to use. * @returns Contextual documentation or `null` if the rule does not exist. */ getContextualDocumentationSync(message: Pick<Message, "ruleId" | "context">, config: ResolvedConfig): RuleDocumentation | null; /** * Get contextual documentation for the given rule. * * Typical usage: * * ```js * const report = await htmlvalidate.validateFile("my-file.html"); * for (const result of report.results){ * const config = await htmlvalidate.getConfigFor(result.filePath); * for (const message of result.messages){ * const documentation = await htmlvalidate.getRuleDocumentation(message.ruleId, config, message.context); * // do something with documentation * } * } * ``` * * @public * @deprecated Deprecated since 8.0.0, use [[getContextualDocumentation]] instead. * @param ruleId - Rule to get documentation for. * @param config - If set it provides more accurate description by using the * correct configuration for the file. * @param context - If set to `Message.context` some rules can provide * contextual details and suggestions. */ getRuleDocumentation(ruleId: string, config?: ResolvedConfig | Promise<ResolvedConfig> | null, context?: unknown | null): Promise<RuleDocumentation | null>; /** * Get contextual documentation for the given rule. * * Typical usage: * * ```js * const report = htmlvalidate.validateFileSync("my-file.html"); * for (const result of report.results){ * const config = htmlvalidate.getConfigForSync(result.filePath); * for (const message of result.messages){ * const documentation = htmlvalidate.getRuleDocumentationSync(message.ruleId, config, message.context); * // do something with documentation * } * } * ``` * * @public * @deprecated Deprecated since 8.0.0, use [[getContextualDocumentationSync]] instead. * @param ruleId - Rule to get documentation for. * @param config - If set it provides more accurate description by using the * correct configuration for the file. * @param context - If set to `Message.context` some rules can provide * contextual details and suggestions. */ getRuleDocumentationSync(r