UNPKG

html-validate

Version:

Offline HTML5 validator and linter

1,521 lines (1,457 loc) 94.6 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 */ /* Excluded from this release type: BaseToken */ /** * @public */ export declare type CategoryOrTag = string; /** * 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; /* Excluded from this release type: CommentToken */ /** * 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 using `import(..)`. * * @public * @since 9.0.0 */ export declare function esmResolver(): 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 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 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(ruleId: string, config?: ResolvedConfig | null, context?: unknown | null): RuleDocumentation | null; /* Excluded from this release type: getParserFor */ /** * Get configuration for given filename. * * See [[FileSystemConfigLoader]] for details. * * @public * @param filename - Filename to get configuration for. * @param configOverride - Configuration to apply last. */ getConfigFor(filename: string, configOverride?: ConfigData): Promise<ResolvedConfig>; /** * Get configuration for given filename. * * See [[FileSystemConfigLoader]] for details. * * @public * @param filename - Filename to get configuration for. * @param configOverride - Configuration to apply last. */ getConfigForSync(filename: string, configOverride?: ConfigData): ResolvedConfig; /** * Get current configuration loader. * * @public * @since %version% * @returns Current configuration loader. */ getConfigLoader(): ConfigLoader; /** * Set configuration loader. * * @public * @since %version% * @param loader - New configuration loader to use. */ setConfigLoader(loader: ConfigLoader): void; /** * Flush configuration cache. Clears full cache unless a filename is given. * * See [[FileSystemConfigLoader]] for details. * * @public * @param filename - If set, only flush cache for given filename. */ flushConfigCache(filename?: string): void; } /** * @public */ export declare interface IncludeExcludeOptions { include: string[] | null; exclude: string[] | null; } /** * Returns `true` if the error is a `UserError`, i.e. it is an error thrown that * is caused by something the end user caused such as a misconfiguration. * * @public */ export declare function isUserError(error: unknown): error is UserErrorData; /* Excluded from this release type: keywordPatternMatcher */ /** * @public */ export declare interface ListenEventMap { "config:ready": ConfigReadyEvent; "source:ready": SourceReadyEvent; /* Excluded from this release type: token */ "tag:start": TagStartEvent; "tag:end": TagEndEvent; "tag:ready": TagReadyEvent; "element:ready": ElementReadyEvent; "dom:load": DOMLoadEvent; "dom:ready": DOMReadyEvent; doctype: DoctypeEvent; attr: AttributeEvent; whitespace: WhitespaceEvent; conditional: ConditionalEvent; directive: DirectiveEvent; /* Excluded from this release type: "rule:error" */ /* Excluded from this release type: "parse:begin" */ /* Excluded from this release type: "parse:end" */ "*": Event_2; } /* Excluded from this release type: LoadedPlugin */ /** * @public */ declare interface Location_2 { /** * The filemane this location refers to. */ readonly filename: string; /** * The string offset (number of characters into the string) this location * refers to. */ readonly offset: number; /** * The line number in the file. */ readonly line: number; /** * The column number in the file. Tabs counts as 1 (not expanded). */ readonly column: number; /** * The number of characters this location refers to. This includes any * whitespace characters such as newlines. */ readonly size: number; } export { Location_2 as Location } /** * Reported error message. * * @public */ export declare interface Message { /** Rule that triggered this message */ ruleId: string; /** URL to description of error */ ruleUrl?: string; /** Severity of the message */ severity: number; /** Message text */ message: string; /** Offset (number of characters) into the source */ offset: number; /** Line number */ line: number; /** Column number */ column: number; /** From start offset, how many characters is this message relevant for */ size: number; /** DOM selector */ selector: string | null; /** * Optional error context used to provide context-aware documentation. * * This context can be passed to [[HtmlValidate#getRuleDocumentation]]. */ context?: any; } /** * Element ARIA metadata. * * @public * @since 8.11.0 */ export declare interface MetaAria { /** * Implicit ARIA role. * * Can be set either to a string (element unconditionally has given role) or a * callback (role depends on the context the element is used in). * * @since 8.11.0 */ implicitRole?: string | MetaImplicitRoleCallback; /** * If set to `"prohibited"` this element may not specify an accessible name * with `aria-label` or `aria-labelledby`. Defaults to `"allowed"` if unset. * * Note: if the element overrides the `role` (i.e. the `role` attribute is set to * something other than the implicit role) naming may or may not be allowed * depending on the given role instead. * * @since 8.11.0 */ naming?: "allowed" | "prohibited" | ((node: HtmlElementLike) => "allowed" | "prohibited"); } /** * @public */ export declare interface MetaAttribute { /** * If set it should be a function evaluating to an error message or `null` if * the attribute is allowed. */ allowed?: MetaAttributeAllowedCallback; /** * If true this attribute can only take boolean values: `my-attr`, `my-attr="` * or `my-attr="my-attr"`. */ boolean?: boolean; /** * If set this attribute is considered deprecated, set to `true` or a string * with more descriptive message. */ deprecated?: boolean | string; /** * If set it is an exhaustive list of all possible values (as `string` or * `RegExp`) this attribute can have (each token if list is set) */ enum?: Array<string | RegExp>; /** * If `true` this attribute contains space-separated tokens and each token must * be valid by itself. */ list?: boolean; /** * If `true` this attribute can omit the value. */ omit?: boolean; /** * If set this attribute is required to be present on the element. */ required?: boolean | MetaAttributeRequiredCallback; } /** * Callback for the `allowed` property of `MetaAttribute`. It takes a node and * should return `null` if there is no errors and a string with an error * description if there is an error. * * @public * @param node - The node the attribute belongs to. * @param attr - The current attribute value being validated. */ export declare type MetaAttributeAllowedCallback = (node: HtmlElementLike, attr: string | DynamicValue | null | undefined) => string | null | undefined; /** *