seo-crawl-audit 0.1.2 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +335 -228
- package/bin/seo-audit.js +18 -3
- package/bundle/cli.js +154 -0
- package/package.json +10 -8
- package/examples/quotes-toscrape-report.html +0 -423
- package/src/audit.js +0 -125
- package/src/baseline.js +0 -65
- package/src/checkpoint.js +0 -90
- package/src/cli.js +0 -850
- package/src/compare.js +0 -205
- package/src/crawler.js +0 -306
- package/src/html-report.js +0 -474
- package/src/html.js +0 -105
- package/src/report.js +0 -43
- package/src/request-gate.js +0 -27
- package/src/robots.js +0 -80
- package/src/sitemap.js +0 -212
- package/src/target.js +0 -35
- package/src/urls.js +0 -45
package/bundle/cli.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import{createHash}from"node:crypto";var DOCS_BASE="https://github.com/MelnixDev/seo-crawl-audit/blob/main/docs/rules.md";var definitions=[{id:"page-unreachable",severity:"error",owner:"developer",scope:"page",remediation:"Restore the page or remove references to it."},{id:"http-error",severity:"error",owner:"developer",scope:"page",remediation:"Return a successful response or a deliberate redirect."},{id:"noindex",severity:"info",owner:"seo",scope:"page",remediation:"Remove noindex when the page should appear in search."},{id:"x-robots-noindex",severity:"error",owner:"developer",scope:"page",remediation:"Remove the noindex X-Robots-Tag when indexing is intended."},{id:"robots-blocked",severity:"error",owner:"developer",scope:"page",remediation:"Allow the URL in robots.txt when it should be crawled."},{id:"missing-canonical",severity:"warning",owner:"seo",scope:"page",remediation:"Declare the preferred canonical URL when duplicate URL variants are possible."},{id:"invalid-canonical",severity:"error",owner:"developer",scope:"page",remediation:"Use an absolute or valid relative HTTP(S) canonical URL."},{id:"cross-domain-canonical",severity:"error",owner:"seo",scope:"page",remediation:"Confirm the external canonical or point it to the intended same-site URL."},{id:"canonical-target-error",severity:"error",owner:"developer",scope:"page",remediation:"Point the canonical to an accessible, indexable URL."},{id:"redirect-loop",severity:"error",owner:"developer",scope:"page",remediation:"Remove the circular redirect path."},{id:"long-redirect-chain",severity:"warning",owner:"developer",scope:"page",remediation:"Redirect directly to the final destination."},{id:"sitemap-unavailable",severity:"error",owner:"developer",scope:"site",remediation:"Restore a valid, reachable XML sitemap."},{id:"noindex-in-sitemap",severity:"error",owner:"seo",scope:"page",remediation:"Remove the URL from the sitemap or make it indexable."},{id:"redirect-in-sitemap",severity:"error",owner:"seo",scope:"page",remediation:"Replace the sitemap URL with its final canonical destination."},{id:"missing-title",severity:"error",owner:"content",scope:"page",remediation:"Add a unique, descriptive HTML title."},{id:"duplicate-title",severity:"warning",owner:"content",scope:"page",remediation:"Write a title that uniquely describes this page."},{id:"title-length",severity:"warning",owner:"content",scope:"page",remediation:"Keep the title concise and descriptive, usually 10\u201360 characters."},{id:"missing-description",severity:"warning",owner:"content",scope:"page",remediation:"Add a useful meta description."},{id:"duplicate-description",severity:"warning",owner:"content",scope:"page",remediation:"Write a unique meta description for this page."},{id:"description-length",severity:"warning",owner:"content",scope:"page",remediation:"Keep the description useful and usually between 50 and 160 characters."},{id:"missing-h1",severity:"warning",owner:"content",scope:"page",remediation:"Add one clear primary heading."},{id:"broken-internal-link",severity:"error",owner:"developer",scope:"page",remediation:"Update or remove the internal link, or restore its target."},{id:"orphan-sitemap-page",severity:"warning",owner:"seo",scope:"page",remediation:"Add meaningful internal links to the sitemap page."},{id:"crawlable-not-in-sitemap",severity:"warning",owner:"seo",scope:"page",remediation:"Add the indexable page to the sitemap or intentionally exclude it."},{id:"invalid-hreflang",severity:"warning",owner:"seo",scope:"page",remediation:"Use valid language tags and resolvable HTTP(S) alternate URLs."},{id:"malformed-json-ld",severity:"warning",owner:"developer",scope:"page",remediation:"Fix JSON syntax in the structured-data block."},{id:"http-on-https-site",severity:"warning",owner:"developer",scope:"page",remediation:"Use HTTPS for internal URLs and metadata references."},{id:"invalid-language",severity:"warning",owner:"developer",scope:"page",remediation:"Set a valid BCP 47 language tag on the html element."},{id:"duplicate-content",severity:"warning",owner:"content",scope:"page",remediation:"Consolidate duplicate pages or differentiate their main content."},{id:"multiple-h1",severity:"info",owner:"content",scope:"page",remediation:"Review whether one primary H1 would make the hierarchy clearer."},{id:"missing-open-graph",severity:"info",owner:"content",scope:"page",remediation:"Add Open Graph title, description, and image for social sharing."},{id:"missing-twitter-metadata",severity:"info",owner:"content",scope:"page",remediation:"Add Twitter card metadata when social previews matter."},{id:"image-missing-alt",severity:"info",owner:"content",scope:"page",remediation:"Add meaningful alt text, or an empty alt for decorative images."},{id:"low-word-count",severity:"info",owner:"content",scope:"page",remediation:"Review whether the page provides enough useful primary content."},{id:"robots-changed",severity:"warning",owner:"developer",scope:"site",remediation:"Review the robots.txt change and confirm that crawl access is intentional."},{id:"page-missing",severity:"error",owner:"developer",scope:"page",remediation:"Include the page in the scan or confirm that its removal is intentional."},{id:"status-regression",severity:"error",owner:"developer",scope:"page",remediation:"Restore the previous successful HTTP response."},{id:"new-noindex",severity:"error",owner:"seo",scope:"page",remediation:"Remove the newly introduced noindex unless it is intentional."},{id:"title-removed",severity:"error",owner:"content",scope:"page",remediation:"Restore a descriptive title."},{id:"title-changed",severity:"warning",owner:"content",scope:"page",remediation:"Review and approve the changed title."},{id:"description-removed",severity:"warning",owner:"content",scope:"page",remediation:"Restore a useful meta description."},{id:"canonical-removed",severity:"error",owner:"seo",scope:"page",remediation:"Restore the canonical declaration."},{id:"canonical-changed",severity:"warning",owner:"seo",scope:"page",remediation:"Confirm the new canonical target is deliberate and valid."},{id:"h1-removed",severity:"warning",owner:"content",scope:"page",remediation:"Restore a clear primary heading."},{id:"redirect-changed",severity:"warning",owner:"developer",scope:"page",remediation:"Confirm the new redirect destination is intentional."},{id:"sitemap-url-count-drop",severity:"error",owner:"seo",scope:"site",remediation:"Investigate the sitemap URL loss and restore omitted indexable pages."}];var RULE_REGISTRY=Object.freeze(definitions.map(definition=>Object.freeze({...definition})));var RULES=new Map(RULE_REGISTRY.map(rule=>[rule.id,rule]));function stableStringify(value){if(Array.isArray(value))return`[${value.map(stableStringify).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,child])=>`${key}:${stableStringify(child)}`).join(",")}}`;return JSON.stringify(value)}function issueFingerprint(ruleId,scope,url,identity){return createHash("sha256").update(`${ruleId}
|
|
2
|
+
${scope}
|
|
3
|
+
${url}
|
|
4
|
+
${stableStringify(identity??null)}`).digest("hex").slice(0,24)}function createIssue(ruleId,url,message,evidence={},identity){const definition=RULES.get(ruleId);if(!definition)throw new Error(`unknown rule: ${ruleId}`);return{fingerprint:issueFingerprint(ruleId,definition.scope,url,identity),ruleId,rule:ruleId,severity:definition.severity,scope:definition.scope,url,message,evidence,owner:definition.owner,remediation:definition.remediation,documentationUrl:`${DOCS_BASE}#${ruleId}`,after:evidence.actual}}function hasDirective(value,directive){return new RegExp(`(^|[\\s,])${directive}($|[\\s,])`,"i").test(value??"")}function validLanguage(language){if(language.toLowerCase()==="x-default")return true;try{new Intl.Locale(language);return true}catch{return false}}function duplicateMap(pages,select){const groups=new Map;for(const page of pages){const value=select(page)?.trim().toLowerCase();if(!value)continue;const urls=groups.get(value)??[];urls.push(page.url);groups.set(value,urls)}return new Map([...groups].filter(([,urls])=>urls.length>1))}function evaluateCurrentRules(snapshot){const issues=[];const add=candidate=>{issues.push(candidate)};const pageByUrl=new Map(snapshot.pages.map(page=>[page.url,page]));const sitemapUrls=new Set(snapshot.sitemap?.urls??[]);const titles=duplicateMap(snapshot.pages,page=>page.title);const descriptions=duplicateMap(snapshot.pages,page=>page.description);const content=duplicateMap(snapshot.pages,page=>page.contentHash);if(snapshot.sitemap?.error)add(createIssue("sitemap-unavailable",snapshot.sitemap.url,"The configured sitemap could not be loaded",{actual:snapshot.sitemap.error}));for(const page of snapshot.pages){if(page.blockedByRobots){add(createIssue("robots-blocked",page.url,"Page is blocked by robots.txt",{actual:true}));continue}if(page.error){add(createIssue(page.error.includes("redirect loop")?"redirect-loop":"page-unreachable",page.url,`Page request failed: ${page.error}`,{actual:page.error,redirectChain:page.redirectChain}));continue}if(page.status===null||page.status>=400)add(createIssue("http-error",page.url,`Page returned HTTP ${page.status??"unknown"}`,{actual:page.status}));if(hasDirective(page.robots,"noindex"))add(createIssue("noindex",page.url,"Page contains a noindex meta directive",{actual:page.robots}));if(hasDirective(page.xRobotsTag,"noindex"))add(createIssue("x-robots-noindex",page.url,"Page contains a noindex X-Robots-Tag",{actual:page.xRobotsTag}));if(!page.canonicalRaw&&!page.canonical)add(createIssue("missing-canonical",page.url,"Page does not declare a canonical URL",{actual:null}));if(page.canonicalRaw&&!page.canonical)add(createIssue("invalid-canonical",page.url,"Canonical URL is invalid",{actual:page.canonicalRaw}));if(page.canonical&&new URL(page.canonical).origin!==new URL(snapshot.siteUrl).origin)add(createIssue("cross-domain-canonical",page.url,"Canonical points to another origin",{actual:page.canonical}));if(page.canonical){const target=pageByUrl.get(page.canonical);if(target&&(target.error||(target.status??500)>=400))add(createIssue("canonical-target-error",page.url,"Canonical target is unavailable",{target:page.canonical,actual:target.status??target.error},page.canonical))}if(page.redirectChain.length>3)add(createIssue("long-redirect-chain",page.url,`Page uses ${page.redirectChain.length} redirects`,{actual:page.redirectChain.length,redirectChain:page.redirectChain}));if(sitemapUrls.has(page.url)&&(hasDirective(page.robots,"noindex")||hasDirective(page.xRobotsTag,"noindex")))add(createIssue("noindex-in-sitemap",page.url,"Sitemap URL is marked noindex",{actual:page.robots??page.xRobotsTag}));if(sitemapUrls.has(page.url)&&page.redirectChain.length>0)add(createIssue("redirect-in-sitemap",page.url,"Sitemap URL redirects",{actual:page.finalUrl,redirectChain:page.redirectChain}));if(!page.title)add(createIssue("missing-title",page.url,"Page does not have a title",{actual:null}));else{if(titles.get(page.title.trim().toLowerCase()))add(createIssue("duplicate-title",page.url,"Title is shared by multiple pages",{actual:page.title,urls:titles.get(page.title.trim().toLowerCase())},page.title.trim().toLowerCase()));if(page.title.length<10||page.title.length>60)add(createIssue("title-length",page.url,`Title length is ${page.title.length} characters`,{actual:page.title.length,value:page.title}))}if(!page.description)add(createIssue("missing-description",page.url,"Page does not have a meta description",{actual:null}));else{if(descriptions.get(page.description.trim().toLowerCase()))add(createIssue("duplicate-description",page.url,"Meta description is shared by multiple pages",{actual:page.description,urls:descriptions.get(page.description.trim().toLowerCase())},page.description.trim().toLowerCase()));if(page.description.length<50||page.description.length>160)add(createIssue("description-length",page.url,`Description length is ${page.description.length} characters`,{actual:page.description.length,value:page.description}))}if(page.h1Count===0)add(createIssue("missing-h1",page.url,"Page does not contain an H1 heading",{actual:0}));else if(page.h1Count>1)add(createIssue("multiple-h1",page.url,`Page contains ${page.h1Count} H1 headings`,{actual:page.h1Count}));for(const targetUrl of page.internalLinks){const target=pageByUrl.get(targetUrl);if(target&&(target.error||(target.status??500)>=400))add(createIssue("broken-internal-link",page.url,"Internal link points to an unavailable page",{target:targetUrl,actual:target.status??target.error},targetUrl))}if(sitemapUrls.has(page.url)&&page.url!==snapshot.siteUrl&&snapshot.linkGraph.orphanUrls.includes(page.url))add(createIssue("orphan-sitemap-page",page.url,"Sitemap page has no discovered internal links",{actual:true}));if(snapshot.sitemap&&!sitemapUrls.has(page.url)&&!hasDirective(page.robots,"noindex")&&(page.status??500)<400)add(createIssue("crawlable-not-in-sitemap",page.url,"Crawlable page is absent from the sitemap",{actual:false}));for(const alternate of page.hreflang)if(!validLanguage(alternate.lang)||!alternate.url)add(createIssue("invalid-hreflang",page.url,"Hreflang declaration is invalid",{actual:alternate},alternate));for(const[index,block]of page.jsonLd.entries())if(!block.valid)add(createIssue("malformed-json-ld",page.url,"JSON-LD block contains invalid JSON",{actual:block.error,index},index));if(snapshot.siteUrl.startsWith("https:")&&[page.url,page.canonical,...page.internalLinks].some(url=>url?.startsWith("http:")))add(createIssue("http-on-https-site",page.url,"HTTPS site references an internal HTTP URL",{actual:[page.url,page.canonical,...page.internalLinks].filter(url=>url?.startsWith("http:"))}));if(page.lang&&!validLanguage(page.lang))add(createIssue("invalid-language",page.url,"HTML language declaration is invalid",{actual:page.lang}));if(page.contentHash&&content.get(page.contentHash))add(createIssue("duplicate-content",page.url,"Main text is an exact duplicate of another page",{urls:content.get(page.contentHash)},page.contentHash));if(!page.openGraph.title||!page.openGraph.description||!page.openGraph.image)add(createIssue("missing-open-graph",page.url,"Open Graph metadata is incomplete",{actual:page.openGraph}));if(!page.twitter.card||!page.twitter.title||!page.twitter.description||!page.twitter.image)add(createIssue("missing-twitter-metadata",page.url,"Twitter card metadata is incomplete",{actual:page.twitter}));const missingAlt=page.images.filter(image=>image.alt===null).map(image=>image.src);if(missingAlt.length>0)add(createIssue("image-missing-alt",page.url,`${missingAlt.length} image(s) do not have an alt attribute`,{actual:missingAlt}));if(page.wordCount<200)add(createIssue("low-word-count",page.url,`Page contains approximately ${page.wordCount} visible words`,{actual:page.wordCount}))}return issues}var severityOrder={error:0,warning:1,info:2};function globMatches(url,pattern){const pathname=(()=>{try{return new URL(url).pathname}catch{return url}})();const expression=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replaceAll("**","\0").replaceAll("*","[^/]*").replaceAll("\0",".*");const regex=new RegExp(`^${expression}$`);return regex.test(pathname)||regex.test(url)}function activeSuppression(issue,suppressions,now){return suppressions.find(suppression=>{if(suppression.rule!==issue.ruleId||!globMatches(issue.url,suppression.urlPattern))return false;if(!suppression.expiresAt)return true;return new Date(`${suppression.expiresAt}T23:59:59.999Z`).getTime()>=now.getTime()})??null}function sortIssues(issues){return issues.sort((left,right)=>severityOrder[left.severity]-severityOrder[right.severity]||left.url.localeCompare(right.url)||left.ruleId.localeCompare(right.ruleId)||left.fingerprint.localeCompare(right.fingerprint))}function applyRulePolicy(issues,snapshot,ruleSet={}){const enabled=ruleSet.enabledRules??snapshot.config.enabledRules;const enabledSet=enabled?new Set(enabled):null;const overrides={...snapshot.config.severityOverrides,...ruleSet.severityOverrides??{}};const suppressions=ruleSet.suppressions??snapshot.config.suppressions;const now=new Date(ruleSet.now??Date.now());return sortIssues(issues.filter(candidate=>!enabledSet||enabledSet.has(candidate.ruleId)).map(candidate=>({...candidate,severity:overrides[candidate.ruleId]??candidate.severity})).filter(candidate=>!activeSuppression(candidate,suppressions,now)))}import{createHash as createHash2}from"node:crypto";var ENGINE_VERSION="0.7.2";var RULE_SET_VERSION="1.1.0";var PRODUCT_NAME="seo-crawl-audit";var DEFAULT_USER_AGENT=`${PRODUCT_NAME}/${ENGINE_VERSION}`;var DEFAULT_OPEN_GRAPH={title:null,description:null,image:null};var DEFAULT_TWITTER={card:null,title:null,description:null,image:null};function baselineInput(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("snapshot must be an object")}return value}function pageInput(value){if(!value||typeof value!=="object"||typeof value.url!=="string"){throw new Error("snapshot page URL must be a string")}return value}function stableJson(value){if(Array.isArray(value)){return`[${value.map(stableJson).join(",")}]`}if(value&&typeof value==="object"){return`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,child])=>`${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`}return JSON.stringify(value)}function hashConfiguration(config){return createHash2("sha256").update(stableJson(config)).digest("hex")}function normalizePage(page){return{url:page.url,finalUrl:page.finalUrl??null,status:page.status??null,contentType:page.contentType??null,blockedByRobots:page.blockedByRobots??false,error:page.error??null,title:page.title??null,description:page.description??null,canonical:page.canonical??null,canonicalRaw:page.canonicalRaw??page.canonical??null,robots:page.robots??null,xRobotsTag:page.xRobotsTag??null,lang:page.lang??null,h1Count:page.h1Count??0,openGraph:page.openGraph??DEFAULT_OPEN_GRAPH,twitter:page.twitter??DEFAULT_TWITTER,hreflang:page.hreflang??[],jsonLd:page.jsonLd??[],images:page.images??[],links:[...page.links??[]].sort(),internalLinks:[...page.internalLinks??[]].sort(),externalLinks:[...page.externalLinks??[]].sort(),wordCount:page.wordCount??0,contentHash:page.contentHash??null,depth:page.depth??0,redirectChain:page.redirectChain??[],responseBytes:page.responseBytes??0}}function defaultConfig(input){const source=input.source??{};const options=input.options??{};const firstPage=input.pages?.[0];const firstPageUrl=firstPage&&typeof firstPage==="object"?firstPage.url:void 0;const url=input.siteUrl??input.startUrl??source.startUrl??(typeof firstPageUrl==="string"?firstPageUrl:void 0);if(!url)throw new Error("snapshot site URL must be a string");return{schemaVersion:1,url,sitemap:options.sitemap??source.sitemap??"auto",maxPages:options.maxPages??source.maxPages??100,concurrency:options.concurrency??5,delay:options.requestDelay??source.requestDelay??100,timeout:options.timeout??1e4,respectRobots:options.respectRobots??source.respectRobots??true,includeQuery:options.includeQuery??source.includeQuery??false,maxRedirects:options.maxRedirects??10,maxResponseBytes:options.maxResponseBytes??5*1024*1024,enabledRules:options.enabledRules??null,severityOverrides:options.severityOverrides??{},suppressions:options.suppressions??[],regressionBudgets:options.regressionBudgets??{},report:options.report??{}}}function createLinkGraph(pages,sitemapUrls){const known=new Set(pages.map(page=>page.url));const linked=new Set(pages.flatMap(page=>page.internalLinks));const broken=new Set;for(const page of pages){if(page.error||page.blockedByRobots||(page.status??500)>=400){broken.add(page.url)}}return{internalEdges:pages.reduce((sum,page)=>sum+page.internalLinks.length,0),externalEdges:pages.reduce((sum,page)=>sum+page.externalLinks.length,0),orphanUrls:sitemapUrls.filter(url=>known.has(url)&&!linked.has(url)),brokenInternalUrls:[...broken].sort()}}function createStatistics(input,pages){const blockedByRobots=pages.filter(page=>page.blockedByRobots).length;const failed=pages.filter(page=>page.error||(page.status??500)>=400).length;return{requested:input.requested??pages.length,completed:pages.length,succeeded:pages.length-failed-blockedByRobots,failed,blockedByRobots,redirected:pages.filter(page=>page.redirectChain.length>0||page.url!==page.finalUrl).length,durationMs:input.durationMs??0,truncated:input.truncated??false,partial:input.partial??false}}function createBaseline(scanInput){const scan2=baselineInput(scanInput);const config=defaultConfig(scan2);const pages=(scan2.pages??[]).map(page=>normalizePage(pageInput(page))).sort((left,right)=>left.url.localeCompare(right.url));const sitemapUrls=scan2.sitemap?.urls??[];if(scan2.sitemap&&!scan2.sitemap.url)throw new Error("snapshot sitemap URL must be a string");const sitemap=scan2.sitemap?{url:scan2.sitemap.url,urls:[...sitemapUrls].sort(),sitemapCount:scan2.sitemap.sitemapCount??0,truncated:scan2.sitemap.truncated??false,error:scan2.sitemap.error??null}:null;const siteUrl=scan2.startUrl??config.url;const truncated=scan2.truncated??false;return{schemaVersion:2,engineVersion:ENGINE_VERSION,ruleSetVersion:RULE_SET_VERSION,generatedAt:scan2.generatedAt??new Date().toISOString(),siteUrl,configurationHash:hashConfiguration(config),config,robots:{url:scan2.robots?.url??new URL("/robots.txt",siteUrl).href,status:scan2.robots?.status??null,sha256:scan2.robots?.sha256??null,error:scan2.robots?.error??null,denyAll:scan2.robots?.denyAll??false},sitemap,pages,linkGraph:scan2.linkGraph??createLinkGraph(pages,sitemapUrls),statistics:scan2.statistics??createStatistics(scan2,pages),partial:scan2.partial??false,source:{startUrl:siteUrl,maxPages:config.maxPages,requestDelay:config.delay,includeQuery:config.includeQuery,respectRobots:config.respectRobots,sitemap:typeof config.sitemap==="string"&&!["auto","none"].includes(config.sitemap)?config.sitemap:null},truncated}}function migrateSnapshot(input){const value=baselineInput(input);if(!Array.isArray(value.pages)){throw new Error("snapshot pages must be an array")}if(value.schemaVersion===2){return createBaseline({...value,startUrl:value.siteUrl,options:value.config,pages:value.pages,generatedAt:value.generatedAt,partial:value.partial,statistics:value.statistics,linkGraph:value.linkGraph})}if(value.schemaVersion===1){return createBaseline(value)}throw new Error(`unsupported snapshot schema version: ${String(value.schemaVersion)}`)}function normalizeSnapshotInput(input){if(input.schemaVersion===2)return input;const legacy=input;const firstPage=legacy.pages?.[0];const firstPageUrl=firstPage&&typeof firstPage==="object"?firstPage.url:void 0;const firstUrl=typeof firstPageUrl==="string"?firstPageUrl:legacy.source?.startUrl??"https://invalid.local/";return createBaseline({...legacy,startUrl:legacy.siteUrl??legacy.source?.startUrl??firstUrl,robots:legacy.robots??{url:new URL("/robots.txt",firstUrl).href,status:null,sha256:null,error:null},options:legacy.config??legacy.options??{}})}function audit(snapshotInput,ruleSet={}){const snapshot=normalizeSnapshotInput(snapshotInput);return applyRulePolicy(evaluateCurrentRules(snapshot),snapshot,ruleSet)}function hasDirective2(value,directive){return new RegExp(`(^|[\\s,])${directive}($|[\\s,])`,"i").test(value??"")}function changedIssue(ruleId,url,message,before,after){const candidate=createIssue(ruleId,url,message,{before,after,actual:after});candidate.before=before;candidate.after=after;return candidate}function evaluateRegressionRules(baseline,current){const complete=!current.partial&&!current.truncated;const issues=[];const currentPages=new Map(current.pages.map(page=>[page.url,page]));if(baseline.robots.sha256&¤t.robots.sha256&&baseline.robots.sha256!==current.robots.sha256){issues.push(changedIssue("robots-changed",current.robots.url,"robots.txt content changed",baseline.robots.sha256,current.robots.sha256))}const previousSitemapCount=baseline.sitemap?.urls.length??0;const currentSitemapCount=current.sitemap?.urls.length??0;const sitemapDrop=previousSitemapCount-currentSitemapCount;if(complete&&previousSitemapCount>0&&sitemapDrop>=Math.max(5,Math.ceil(previousSitemapCount*.2))){issues.push(changedIssue("sitemap-url-count-drop",current.sitemap?.url??baseline.sitemap?.url??current.siteUrl,`Sitemap URL count dropped by ${sitemapDrop}`,previousSitemapCount,currentSitemapCount))}for(const before of baseline.pages){const after=currentPages.get(before.url);if(!after){if(complete)issues.push(changedIssue("page-missing",before.url,"Page was not checked",before.status,null));continue}if(after.blockedByRobots&&!before.blockedByRobots){issues.push(changedIssue("robots-blocked",before.url,"Page is now blocked by robots.txt",false,true));continue}if(after.error&&!before.error){issues.push(changedIssue(after.error.includes("redirect loop")?"redirect-loop":"page-unreachable",before.url,`Page request failed: ${after.error}`,before.error,after.error));continue}if(before.status!==null&&before.status<400&&(after.status===null||after.status>=400))issues.push(changedIssue("status-regression",before.url,`HTTP status regressed from ${before.status} to ${after.status??"none"}`,before.status,after.status));const beforeRobots=`${before.robots??""},${before.xRobotsTag??""}`;const afterRobots=`${after.robots??""},${after.xRobotsTag??""}`;if(!hasDirective2(beforeRobots,"noindex")&&hasDirective2(afterRobots,"noindex"))issues.push(changedIssue("new-noindex",before.url,"Page now contains a noindex directive",beforeRobots,afterRobots));if(before.title&&!after.title)issues.push(changedIssue("title-removed",before.url,"Page title was removed",before.title,after.title));else if(before.title&&after.title&&before.title!==after.title)issues.push(changedIssue("title-changed",before.url,"Page title changed",before.title,after.title));if(before.description&&!after.description)issues.push(changedIssue("description-removed",before.url,"Meta description was removed",before.description,after.description));if(before.canonical&&!after.canonical)issues.push(changedIssue("canonical-removed",before.url,"Canonical URL was removed",before.canonical,after.canonical));else if(before.canonical&&after.canonical&&before.canonical!==after.canonical){const candidate=changedIssue("canonical-changed",before.url,"Canonical URL changed",before.canonical,after.canonical);if(new URL(after.canonical).origin!==new URL(before.url).origin)candidate.severity="error";issues.push(candidate)}if(before.h1Count>0&&after.h1Count===0)issues.push(changedIssue("h1-removed",before.url,"All H1 headings were removed",before.h1Count,after.h1Count));if(before.finalUrl&&after.finalUrl&&before.finalUrl!==after.finalUrl){const candidate=changedIssue("redirect-changed",before.url,"Final redirect URL changed",before.finalUrl,after.finalUrl);if(new URL(after.finalUrl).origin!==new URL(before.url).origin)candidate.severity="error";issues.push(candidate)}}return issues}function compareBaselines(baselineInput2,currentInput,ruleSet={}){const baseline=normalizeSnapshotInput(baselineInput2);const current=normalizeSnapshotInput(currentInput);return applyRulePolicy(evaluateRegressionRules(baseline,current),current,ruleSet)}function lifecycle(issue,value){return{...issue,lifecycle:value}}function diff(previousInput,currentInput,ruleSet={}){const previous=normalizeSnapshotInput(previousInput);const current=normalizeSnapshotInput(currentInput);const complete=!current.partial&&!current.truncated;const checkedUrls=new Set(current.pages.map(page=>page.url));const previousIssues=new Map(audit(previous,ruleSet).map(candidate=>[candidate.fingerprint,candidate]));const currentIssues=new Map(audit(current,ruleSet).map(candidate=>[candidate.fingerprint,candidate]));const newIssues=[];const ongoingIssues=[];const unchangedIssues=[];const resolvedIssues=[];for(const[fingerprint,candidate]of currentIssues){const before=previousIssues.get(fingerprint);if(!before)newIssues.push(lifecycle(candidate,"new"));else if(JSON.stringify(before.evidence)===JSON.stringify(candidate.evidence))unchangedIssues.push(lifecycle(candidate,"unchanged"));else ongoingIssues.push(lifecycle({...candidate,before:before.evidence,after:candidate.evidence},"ongoing"))}for(const[fingerprint,candidate]of previousIssues){const evaluated=candidate.scope==="page"?checkedUrls.has(candidate.url):complete;if(evaluated&&!currentIssues.has(fingerprint))resolvedIssues.push(lifecycle(candidate,"resolved"))}const known=new Set(newIssues.map(candidate=>candidate.fingerprint));for(const regression of compareBaselines(previous,current,ruleSet)){if(!known.has(regression.fingerprint))newIssues.push(lifecycle(regression,"new"))}const budgets={...previous.config.regressionBudgets,...current.config.regressionBudgets};const budgetExceeded=Object.entries(budgets).flatMap(([budget,allowed])=>{const actual2=newIssues.filter(candidate=>candidate.severity===budget||candidate.ruleId===budget).length;return actual2>allowed?[{budget,allowed,actual:actual2}]:[]});sortIssues(newIssues);sortIssues(ongoingIssues);sortIssues(unchangedIssues);sortIssues(resolvedIssues);return{complete,newIssues,ongoingIssues,resolvedIssues,unchangedIssues,issues:[...newIssues,...ongoingIssues],budgetExceeded}}var DEFAULT_CONFIG_FILE="seo-audit.config.json";var DEFAULT_SCAN_CONFIG=Object.freeze({schemaVersion:1,url:"",sitemap:"auto",maxPages:100,concurrency:5,delay:100,timeout:1e4,respectRobots:true,includeQuery:false,maxRedirects:10,maxResponseBytes:5*1024*1024,enabledRules:null,severityOverrides:{},suppressions:[],regressionBudgets:{},report:{}});function object(value,field){if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error(`${field} must be an object`)}return value}function integer(value,field,minimum,maximum=Number.MAX_SAFE_INTEGER){if(!Number.isInteger(value)||value<minimum||value>maximum){throw new Error(`${field} must be an integer between ${minimum} and ${maximum}`)}return value}function optionalString(value,field){if(value===void 0)return void 0;if(typeof value!=="string")throw new Error(`${field} must be a string`);return value}function validateConfig(input){const value=object(input,"config");const allowed=new Set(["$schema","schemaVersion","url","sitemap","maxPages","concurrency","delay","timeout","respectRobots","includeQuery","maxRedirects","maxResponseBytes","enabledRules","severityOverrides","suppressions","regressionBudgets","report"]);for(const key of Object.keys(value)){if(!allowed.has(key))throw new Error(`unknown config property: ${key}`)}const result={};if(value.schemaVersion!==void 0&&value.schemaVersion!==1)throw new Error("schemaVersion must be 1");if(value.url!==void 0){const url=optionalString(value.url,"url");if(!/^https?:\/\//i.test(url))throw new Error("url must be an HTTP(S) URL");result.url=url}if(value.sitemap!==void 0){const sitemap=optionalString(value.sitemap,"sitemap");if(!["auto","none"].includes(sitemap)&&!/^https?:\/\//i.test(sitemap)){throw new Error("sitemap must be auto, none, or an HTTP(S) URL")}result.sitemap=sitemap}if(value.maxPages!==void 0)result.maxPages=integer(value.maxPages,"maxPages",1);if(value.concurrency!==void 0)result.concurrency=integer(value.concurrency,"concurrency",1,50);if(value.delay!==void 0)result.delay=integer(value.delay,"delay",0);if(value.timeout!==void 0)result.timeout=integer(value.timeout,"timeout",1);if(value.maxRedirects!==void 0)result.maxRedirects=integer(value.maxRedirects,"maxRedirects",0,50);if(value.maxResponseBytes!==void 0)result.maxResponseBytes=integer(value.maxResponseBytes,"maxResponseBytes",1024);for(const field of["respectRobots","includeQuery"]){if(value[field]!==void 0){if(typeof value[field]!=="boolean")throw new Error(`${field} must be a boolean`);result[field]=value[field]}}if(value.enabledRules!==void 0){if(value.enabledRules!==null&&(!Array.isArray(value.enabledRules)||value.enabledRules.some(rule=>typeof rule!=="string"))){throw new Error("enabledRules must be null or an array of rule IDs")}result.enabledRules=value.enabledRules}if(value.severityOverrides!==void 0){const overrides=object(value.severityOverrides,"severityOverrides");for(const[rule,severity]of Object.entries(overrides)){if(!["error","warning","info"].includes(severity)){throw new Error(`severityOverrides.${rule} must be error, warning, or info`)}}result.severityOverrides=overrides}if(value.suppressions!==void 0){if(!Array.isArray(value.suppressions))throw new Error("suppressions must be an array");result.suppressions=value.suppressions.map((entry,index)=>{const suppression=object(entry,`suppressions[${index}]`);for(const field of["rule","urlPattern","reason"]){if(typeof suppression[field]!=="string"||suppression[field]===""){throw new Error(`suppressions[${index}].${field} must be a non-empty string`)}}if(suppression.expiresAt!==void 0&&!/^\d{4}-\d{2}-\d{2}$/.test(String(suppression.expiresAt))){throw new Error(`suppressions[${index}].expiresAt must use YYYY-MM-DD`)}return suppression})}if(value.regressionBudgets!==void 0){const budgets=object(value.regressionBudgets,"regressionBudgets");result.regressionBudgets=Object.fromEntries(Object.entries(budgets).map(([key,budget])=>[key,integer(budget,`regressionBudgets.${key}`,0)]))}if(value.report!==void 0){const report=object(value.report,"report");const branding={};const agencyName=optionalString(report.agencyName,"report.agencyName");const logo=optionalString(report.logo,"report.logo");const primaryColor=optionalString(report.primaryColor,"report.primaryColor");if(agencyName!==void 0)branding.agencyName=agencyName;if(logo!==void 0)branding.logo=logo;if(primaryColor!==void 0)branding.primaryColor=primaryColor;if(branding.primaryColor&&!/^#[0-9a-f]{6}$/i.test(branding.primaryColor)){throw new Error("report.primaryColor must be a six-digit hex color")}result.report=Object.fromEntries(Object.entries(branding).filter(([,child])=>child!==void 0))}return result}function resolveConfig(cli,file={},baseline={}){const merged={...DEFAULT_SCAN_CONFIG,...baseline,...file,...cli};return{...merged,schemaVersion:1,severityOverrides:{...baseline.severityOverrides??{},...file.severityOverrides??{},...cli.severityOverrides??{}},regressionBudgets:{...baseline.regressionBudgets??{},...file.regressionBudgets??{},...cli.regressionBudgets??{}},report:{...baseline.report??{},...file.report??{},...cli.report??{}},suppressions:cli.suppressions??file.suppressions??baseline.suppressions??[]}}function noop(){}var NOOP_LOGGER=Object.freeze({debug:noop,info:noop,warn:noop,error:noop});import{setTimeout as sleep}from"node:timers/promises";function createRequestGate(intervalMs=0,{now=Date.now,wait=sleep}={}){const interval=Math.max(0,intervalMs);let nextStartAt=0;let queue=Promise.resolve();return function waitForRequestSlot(){if(interval===0)return Promise.resolve();const slot=queue.then(async()=>{const remaining=Math.max(0,nextStartAt-now());if(remaining>0)await wait(remaining);nextStartAt=now()+interval});queue=slot.catch(()=>void 0);return slot}}function createPerOriginRequestGate(intervalMs=0,factory=createRequestGate){const gates=new Map;return url=>{const origin=new URL(url).origin;let gate=gates.get(origin);if(!gate){gate=factory(intervalMs);gates.set(origin,gate)}return gate()}}import{createHash as createHash3}from"node:crypto";import{setTimeout as sleep2}from"node:timers/promises";var RequestFailure=class extends Error{redirectChain;constructor(message,redirectChain=[],options){super(message,options);this.name="RequestFailure";this.redirectChain=redirectChain}};function retryableStatus(status){return status===429||status===500||status===502||status===503||status===504}function retryAfterMs(value,now=Date.now()){if(!value)return null;const seconds=Number(value);if(Number.isFinite(seconds)&&seconds>=0)return Math.min(seconds*1e3,3e4);const date=Date.parse(value);return Number.isNaN(date)?null:Math.min(Math.max(0,date-now),3e4)}function requestSignal(timeout,signal){const timeoutSignal=AbortSignal.timeout(timeout);return signal?AbortSignal.any([signal,timeoutSignal]):timeoutSignal}async function fetchRedirectChain(initialUrl,init,policy2){const chain=[];const visited=new Set([initialUrl]);let url=initialUrl;while(true){policy2.signal?.throwIfAborted();await policy2.gate?.(url);const response=await policy2.fetch(url,{...init,redirect:"manual",signal:requestSignal(policy2.timeout,policy2.signal)});const location=response.headers.get("location");if(response.status<300||response.status>=400||!location){return{response,redirectChain:chain}}const next=new URL(location,url).href;chain.push({url,status:response.status,location:next});await response.body?.cancel();if(visited.has(next))throw new RequestFailure(`redirect loop detected at ${next}`,chain);if(chain.length>policy2.maxRedirects){throw new RequestFailure(`redirect limit of ${policy2.maxRedirects} exceeded`,chain)}visited.add(next);url=next}}async function fetchWithRetry(url,init,policy2){let lastError;for(let attempt=0;attempt<=policy2.retries;attempt+=1){try{const result=await fetchRedirectChain(url,init,policy2);if(!retryableStatus(result.response.status)||attempt===policy2.retries)return result;const serverDelay=retryAfterMs(result.response.headers.get("retry-after"));await result.response.body?.cancel();const jitter=Math.floor((policy2.random??Math.random)()*100);const delayMs=serverDelay??Math.min(250*2**attempt+jitter,3e4);await policy2.onEvent?.({type:"retry",url,attempt:attempt+1,delayMs});await sleep2(delayMs,void 0,{signal:policy2.signal})}catch(error){if(policy2.signal?.aborted)throw policy2.signal.reason??error;lastError=error;if(error instanceof RequestFailure||attempt===policy2.retries)break;const jitter=Math.floor((policy2.random??Math.random)()*100);const delayMs=Math.min(250*2**attempt+jitter,3e4);await policy2.onEvent?.({type:"retry",url,attempt:attempt+1,delayMs});await sleep2(delayMs,void 0,{signal:policy2.signal})}}if(lastError instanceof RequestFailure)throw lastError;throw new RequestFailure(lastError instanceof Error?lastError.message:String(lastError),[],{cause:lastError})}async function readResponseBody(response,maxBytes){if(!response.body)return{text:"",bytes:0,buffer:Buffer.alloc(0)};const reader=response.body.getReader();const chunks=[];let total=0;while(true){const{done,value}=await reader.read();if(done)break;total+=value.byteLength;if(total>maxBytes){await reader.cancel();throw new RequestFailure(`response exceeds ${maxBytes} bytes`)}chunks.push(Buffer.from(value))}const buffer=Buffer.concat(chunks);return{text:buffer.toString("utf8"),bytes:total,buffer}}function patternMatches(pathWithQuery,pattern){if(!pattern)return false;const anchored=pattern.endsWith("$");const source=anchored?pattern.slice(0,-1):pattern;const escaped=source.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replaceAll("*",".*");return new RegExp(`^${escaped}${anchored?"$":""}`).test(pathWithQuery)}function parseRobots(body,userAgent){const groups=[];let current=null;for(const rawLine of body.replace(/^\uFEFF/,"").split(/\r?\n/)){const line=rawLine.replace(/#.*$/,"").trim();const separator=line.indexOf(":");if(!line||separator<0)continue;const field=line.slice(0,separator).trim().toLowerCase();const value=line.slice(separator+1).trim();if(field==="user-agent"){if(!current||current.hasRules){current={agents:[],rules:[],hasRules:false};groups.push(current)}if(value)current.agents.push(value.toLowerCase());continue}if(current&&(field==="allow"||field==="disallow")&&value){current.rules.push({type:field,path:value});current.hasRules=true}}const normalizedAgent=userAgent.toLowerCase();const specific=groups.filter(group=>group.agents.some(agent=>agent!=="*"&&normalizedAgent.includes(agent)));const matching=specific.length>0?specific:groups.filter(group=>group.agents.includes("*"));return matching.flatMap(group=>group.rules)}function isAllowedByRobots(url,robots){if(robots.denyAll)return false;const parsed=new URL(url);const pathWithQuery=`${parsed.pathname}${parsed.search}`;const matches=(robots.rules??[]).filter(rule=>patternMatches(pathWithQuery,rule.path)).sort((left,right)=>right.path.length-left.path.length||(left.type==="allow"?-1:1));return matches.length===0||matches[0]?.type==="allow"}async function fetchRobots(startUrl,options){const robotsUrl=new URL("/robots.txt",startUrl).href;try{const{response}=await fetchWithRetry(robotsUrl,{headers:{accept:"text/plain,*/*;q=0.1","user-agent":options.userAgent}},{fetch:options.fetch,timeout:options.timeout,maxRedirects:options.maxRedirects,retries:options.retries,signal:options.signal,gate:options.requestGate,onEvent:options.onEvent});const{text:body}=await readResponseBody(response,MAX_ROBOTS_BYTES);return{url:robotsUrl,status:response.status,body,sha256:createHash3("sha256").update(body).digest("hex"),rules:response.ok?parseRobots(body,options.userAgent):[],denyAll:response.status===401||response.status===403,error:null}}catch(error){if(options.signal?.aborted)throw error;return{url:robotsUrl,status:null,body:"",sha256:null,rules:[],denyAll:false,error:error instanceof Error?error.message:String(error)}}}var MAX_ROBOTS_BYTES=512*1024;import{gunzipSync}from"node:zlib";var nameStartChar=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";var nameChar=nameStartChar+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";var nameRegexp="["+nameStartChar+"]["+nameChar+"]*";var regexName=new RegExp("^"+nameRegexp+"$");function getAllMatches(string,regex){const matches=[];let match=regex.exec(string);while(match){const allmatches=[];allmatches.startIndex=regex.lastIndex-match[0].length;const len=match.length;for(let index=0;index<len;index++){allmatches.push(match[index])}matches.push(allmatches);match=regex.exec(string)}return matches}var isName=function(string){const match=regexName.exec(string);return!(match===null||typeof match==="undefined")};function isExist(v){return typeof v!=="undefined"}var DANGEROUS_PROPERTY_NAMES=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"];var criticalProperties=["__proto__","constructor","prototype"];var defaultOptions={allowBooleanAttributes:false,unpairedTags:[]};function validate(xmlData,options){options=Object.assign({},defaultOptions,options);const tags=[];let tagFound=false;let reachedRoot=false;if(xmlData[0]==="\uFEFF"){xmlData=xmlData.substr(1)}for(let i=0;i<xmlData.length;i++){if(xmlData[i]==="<"&&xmlData[i+1]==="?"){i+=2;i=readPI(xmlData,i);if(i.err)return i}else if(xmlData[i]==="<"){let tagStartPos=i;i++;if(xmlData[i]==="!"){i=readCommentAndCDATA(xmlData,i);continue}else{let closingTag=false;if(xmlData[i]==="/"){closingTag=true;i++}let tagName="";for(;i<xmlData.length&&xmlData[i]!==">"&&xmlData[i]!==" "&&xmlData[i]!==" "&&xmlData[i]!=="\n"&&xmlData[i]!=="\r";i++){tagName+=xmlData[i]}tagName=tagName.trim();if(tagName[tagName.length-1]==="/"){tagName=tagName.substring(0,tagName.length-1);i--}if(!validateTagName(tagName)){let msg;if(tagName.trim().length===0){msg="Invalid space after '<'."}else{msg="Tag '"+tagName+"' is an invalid name."}return getErrorObject("InvalidTag",msg,getLineNumberForPosition(xmlData,i))}const result=readAttributeStr(xmlData,i);if(result===false){return getErrorObject("InvalidAttr","Attributes for '"+tagName+"' have open quote.",getLineNumberForPosition(xmlData,i))}let attrStr=result.value;i=result.index;if(attrStr[attrStr.length-1]==="/"){const attrStrStart=i-attrStr.length;attrStr=attrStr.substring(0,attrStr.length-1);const isValid=validateAttributeString(attrStr,options);if(isValid===true){tagFound=true}else{return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,attrStrStart+isValid.err.line))}}else if(closingTag){if(!result.tagClosed){return getErrorObject("InvalidTag","Closing tag '"+tagName+"' doesn't have proper closing.",getLineNumberForPosition(xmlData,i))}else if(attrStr.trim().length>0){return getErrorObject("InvalidTag","Closing tag '"+tagName+"' can't have attributes or invalid starting.",getLineNumberForPosition(xmlData,tagStartPos))}else if(tags.length===0){return getErrorObject("InvalidTag","Closing tag '"+tagName+"' has not been opened.",getLineNumberForPosition(xmlData,tagStartPos))}else{const otg=tags.pop();if(tagName!==otg.tagName){let openPos=getLineNumberForPosition(xmlData,otg.tagStartPos);return getErrorObject("InvalidTag","Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",getLineNumberForPosition(xmlData,tagStartPos))}if(tags.length==0){reachedRoot=true}}}else{const isValid=validateAttributeString(attrStr,options);if(isValid!==true){return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,i-attrStr.length+isValid.err.line))}if(reachedRoot===true){return getErrorObject("InvalidXml","Multiple possible root nodes found.",getLineNumberForPosition(xmlData,i))}else if(options.unpairedTags.indexOf(tagName)!==-1){}else{tags.push({tagName,tagStartPos})}tagFound=true}for(i++;i<xmlData.length;i++){if(xmlData[i]==="<"){if(xmlData[i+1]==="!"){i++;i=readCommentAndCDATA(xmlData,i);continue}else if(xmlData[i+1]==="?"){i=readPI(xmlData,++i);if(i.err)return i}else{break}}else if(xmlData[i]==="&"){const afterAmp=validateAmpersand(xmlData,i);if(afterAmp==-1)return getErrorObject("InvalidChar","char '&' is not expected.",getLineNumberForPosition(xmlData,i));i=afterAmp}else{if(reachedRoot===true&&!isWhiteSpace(xmlData[i])){return getErrorObject("InvalidXml","Extra text at the end",getLineNumberForPosition(xmlData,i))}}}if(xmlData[i]==="<"){i--}}}else{if(isWhiteSpace(xmlData[i])){continue}return getErrorObject("InvalidChar","char '"+xmlData[i]+"' is not expected.",getLineNumberForPosition(xmlData,i))}}if(!tagFound){return getErrorObject("InvalidXml","Start tag expected.",1)}else if(tags.length==1){return getErrorObject("InvalidTag","Unclosed tag '"+tags[0].tagName+"'.",getLineNumberForPosition(xmlData,tags[0].tagStartPos))}else if(tags.length>0){return getErrorObject("InvalidXml","Invalid '"+JSON.stringify(tags.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}return true}function isWhiteSpace(char){return char===" "||char===" "||char==="\n"||char==="\r"}function readPI(xmlData,i){const start=i;for(;i<xmlData.length;i++){if(xmlData[i]=="?"||xmlData[i]==" "){const tagname=xmlData.substr(start,i-start);if(i>5&&tagname==="xml"){return getErrorObject("InvalidXml","XML declaration allowed only at the start of the document.",getLineNumberForPosition(xmlData,i))}else if(xmlData[i]=="?"&&xmlData[i+1]==">"){i++;break}else{continue}}}return i}function readCommentAndCDATA(xmlData,i){if(xmlData.length>i+5&&xmlData[i+1]==="-"&&xmlData[i+2]==="-"){for(i+=3;i<xmlData.length;i++){if(xmlData[i]==="-"&&xmlData[i+1]==="-"&&xmlData[i+2]===">"){i+=2;break}}}else if(xmlData.length>i+8&&xmlData[i+1]==="D"&&xmlData[i+2]==="O"&&xmlData[i+3]==="C"&&xmlData[i+4]==="T"&&xmlData[i+5]==="Y"&&xmlData[i+6]==="P"&&xmlData[i+7]==="E"){let angleBracketsCount=1;for(i+=8;i<xmlData.length;i++){if(xmlData[i]==="<"){angleBracketsCount++}else if(xmlData[i]===">"){angleBracketsCount--;if(angleBracketsCount===0){break}}}}else if(xmlData.length>i+9&&xmlData[i+1]==="["&&xmlData[i+2]==="C"&&xmlData[i+3]==="D"&&xmlData[i+4]==="A"&&xmlData[i+5]==="T"&&xmlData[i+6]==="A"&&xmlData[i+7]==="["){for(i+=8;i<xmlData.length;i++){if(xmlData[i]==="]"&&xmlData[i+1]==="]"&&xmlData[i+2]===">"){i+=2;break}}}return i}var doubleQuote='"';var singleQuote="'";function readAttributeStr(xmlData,i){let attrStr="";let startChar="";let tagClosed=false;for(;i<xmlData.length;i++){if(xmlData[i]===doubleQuote||xmlData[i]===singleQuote){if(startChar===""){startChar=xmlData[i]}else if(startChar!==xmlData[i]){}else{startChar=""}}else if(xmlData[i]===">"){if(startChar===""){tagClosed=true;break}}attrStr+=xmlData[i]}if(startChar!==""){return false}return{value:attrStr,index:i,tagClosed}}var validAttrStrRegxp=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function validateAttributeString(attrStr,options){const matches=getAllMatches(attrStr,validAttrStrRegxp);const attrNames={};for(let i=0;i<matches.length;i++){if(matches[i][1].length===0){return getErrorObject("InvalidAttr","Attribute '"+matches[i][2]+"' has no space in starting.",getPositionFromMatch(matches[i]))}else if(matches[i][3]!==void 0&&matches[i][4]===void 0){return getErrorObject("InvalidAttr","Attribute '"+matches[i][2]+"' is without value.",getPositionFromMatch(matches[i]))}else if(matches[i][3]===void 0&&!options.allowBooleanAttributes){return getErrorObject("InvalidAttr","boolean attribute '"+matches[i][2]+"' is not allowed.",getPositionFromMatch(matches[i]))}const attrName=matches[i][2];if(!validateAttrName(attrName)){return getErrorObject("InvalidAttr","Attribute '"+attrName+"' is an invalid name.",getPositionFromMatch(matches[i]))}if(!Object.prototype.hasOwnProperty.call(attrNames,attrName)){attrNames[attrName]=1}else{return getErrorObject("InvalidAttr","Attribute '"+attrName+"' is repeated.",getPositionFromMatch(matches[i]))}}return true}function validateNumberAmpersand(xmlData,i){let re=/\d/;if(xmlData[i]==="x"){i++;re=/[\da-fA-F]/}for(;i<xmlData.length;i++){if(xmlData[i]===";")return i;if(!xmlData[i].match(re))break}return-1}function validateAmpersand(xmlData,i){i++;if(xmlData[i]===";")return-1;if(xmlData[i]==="#"){i++;return validateNumberAmpersand(xmlData,i)}let count=0;for(;i<xmlData.length;i++,count++){if(xmlData[i].match(/\w/)&&count<20)continue;if(xmlData[i]===";")break;return-1}return i}function getErrorObject(code,message,lineNumber){return{err:{code,msg:message,line:lineNumber.line||lineNumber,col:lineNumber.col}}}function validateAttrName(attrName){return isName(attrName)}function validateTagName(tagname){return isName(tagname)}function getLineNumberForPosition(xmlData,index){const lines=xmlData.substring(0,index).split(/\r?\n/);return{line:lines.length,col:lines[lines.length-1].length+1}}function getPositionFromMatch(match){return match.startIndex+match[1].length}var CURRENCY={cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",euro:"\u20AC",dollar:"$",fnof:"\u0192",inr:"\u20B9",af:"\u060B",birr:"\u1265\u122D",peso:"\u20B1",rub:"\u20BD",won:"\u20A9",yuan:"\xA5",cedil:"\xB8"};var XML={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'};var COMMON_HTML={nbsp:"\xA0",copy:"\xA9",reg:"\xAE",trade:"\u2122",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",laquo:"\xAB",raquo:"\xBB",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",bull:"\u2022",para:"\xB6",sect:"\xA7",deg:"\xB0",frac12:"\xBD",frac14:"\xBC",frac34:"\xBE"};var ENTITY_ACTION=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"});var SPECIAL_CHARS=new Set("!?\\\\/[]$%{}^&*()<>|+");function validateEntityName(name){if(name[0]==="#"){throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`)}for(const ch of name){if(SPECIAL_CHARS.has(ch)){throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`)}}return name}function mergeEntityMaps(...maps){const out=Object.create(null);for(const map of maps){if(!map)continue;for(const key of Object.keys(map)){const raw=map[key];if(typeof raw==="string"){out[key]=raw}else if(raw&&typeof raw==="object"&&raw.val!==void 0){const val=raw.val;if(typeof val==="string"){out[key]=val}}}}return out}var LIMIT_TIER_EXTERNAL="external";var LIMIT_TIER_BASE="base";var LIMIT_TIER_ALL="all";function parseLimitTiers(raw){if(!raw||raw===LIMIT_TIER_EXTERNAL)return new Set([LIMIT_TIER_EXTERNAL]);if(raw===LIMIT_TIER_ALL)return new Set([LIMIT_TIER_ALL]);if(raw===LIMIT_TIER_BASE)return new Set([LIMIT_TIER_BASE]);if(Array.isArray(raw))return new Set(raw);return new Set([LIMIT_TIER_EXTERNAL])}var NCR_LEVEL=Object.freeze({allow:0,leave:1,remove:2,throw:3});var XML10_ALLOWED_C0=new Set([9,10,13]);function parseNCRConfig(ncr){if(!ncr){return{xmlVersion:1,onLevel:NCR_LEVEL.allow,nullLevel:NCR_LEVEL.remove}}const xmlVersion=ncr.xmlVersion===1.1?1.1:1;const onLevel=NCR_LEVEL[ncr.onNCR]??NCR_LEVEL.allow;const nullLevel=NCR_LEVEL[ncr.nullNCR]??NCR_LEVEL.remove;const clampedNull=Math.max(nullLevel,NCR_LEVEL.remove);return{xmlVersion,onLevel,nullLevel:clampedNull}}var EntityDecoder=class{constructor(options={}){this._limit=options.limit||{};this._maxTotalExpansions=this._limit.maxTotalExpansions||0;this._maxExpandedLength=this._limit.maxExpandedLength||0;this._postCheck=typeof options.postCheck==="function"?options.postCheck:r=>r;this._limitTiers=parseLimitTiers(this._limit.applyLimitsTo??LIMIT_TIER_EXTERNAL);this._numericAllowed=options.numericAllowed??true;this._baseMap=mergeEntityMaps(XML,options.namedEntities||null);this._externalMap=Object.create(null);this._inputMap=Object.create(null);this._totalExpansions=0;this._expandedLength=0;this._removeSet=new Set(options.remove&&Array.isArray(options.remove)?options.remove:[]);this._leaveSet=new Set(options.leave&&Array.isArray(options.leave)?options.leave:[]);const ncrCfg=parseNCRConfig(options.ncr);this._ncrXmlVersion=ncrCfg.xmlVersion;this._ncrOnLevel=ncrCfg.onLevel;this._ncrNullLevel=ncrCfg.nullLevel;this._onExternalEntity=typeof options.onExternalEntity==="function"?options.onExternalEntity:null;this._onInputEntity=typeof options.onInputEntity==="function"?options.onInputEntity:null}_applyRegistrationHook(hook,name,value,context){if(!hook)return true;const action=hook(name,value);if(action===ENTITY_ACTION.BLOCK)return false;if(action===ENTITY_ACTION.THROW){throw new Error(`[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook`)}return true}setExternalEntities(map){if(map){for(const key of Object.keys(map)){validateEntityName(key)}}if(!this._onExternalEntity){this._externalMap=mergeEntityMaps(map);return}const flat=mergeEntityMaps(map);const filtered=Object.create(null);for(const[name,value]of Object.entries(flat)){if(this._applyRegistrationHook(this._onExternalEntity,name,value,"external")){filtered[name]=value}}this._externalMap=filtered}addExternalEntity(key,value){validateEntityName(key);if(typeof value==="string"&&value.indexOf("&")===-1){if(this._applyRegistrationHook(this._onExternalEntity,key,value,"external")){this._externalMap[key]=value}}}addInputEntities(map){this._totalExpansions=0;this._expandedLength=0;if(!this._onInputEntity){this._inputMap=mergeEntityMaps(map);return}const flat=mergeEntityMaps(map);const filtered=Object.create(null);for(const[name,value]of Object.entries(flat)){if(this._applyRegistrationHook(this._onInputEntity,name,value,"input")){filtered[name]=value}}this._inputMap=filtered}reset(){this._inputMap=Object.create(null);this._totalExpansions=0;this._expandedLength=0;return this}setXmlVersion(version){this._ncrXmlVersion=version===1.1?1.1:1}decode(str){if(typeof str!=="string"||str.length===0)return str;if(str.indexOf("&")===-1)return str;const original=str;const chunks=[];const len=str.length;let last=0;let i=0;const limitExpansions=this._maxTotalExpansions>0;const limitLength=this._maxExpandedLength>0;const checkLimits=limitExpansions||limitLength;while(i<len){if(str.charCodeAt(i)!==38){i++;continue}let j=i+1;while(j<len&&str.charCodeAt(j)!==59&&j-i<=32)j++;if(j>=len||str.charCodeAt(j)!==59){i++;continue}const token=str.slice(i+1,j);if(token.length===0){i++;continue}let replacement;let tier;if(this._removeSet.has(token)){replacement="";if(tier===void 0){tier=LIMIT_TIER_EXTERNAL}}else if(this._leaveSet.has(token)){i++;continue}else if(token.charCodeAt(0)===35){const ncrResult=this._resolveNCR(token);if(ncrResult===void 0){i++;continue}replacement=ncrResult;tier=LIMIT_TIER_BASE}else{const resolved=this._resolveName(token);replacement=resolved?.value;tier=resolved?.tier}if(replacement===void 0){i++;continue}if(i>last)chunks.push(str.slice(last,i));chunks.push(replacement);last=j+1;i=last;if(checkLimits&&this._tierCounts(tier)){if(limitExpansions){this._totalExpansions++;if(this._totalExpansions>this._maxTotalExpansions){throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`)}}if(limitLength){const delta=replacement.length-(token.length+2);if(delta>0){this._expandedLength+=delta;if(this._expandedLength>this._maxExpandedLength){throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}}}if(last<len)chunks.push(str.slice(last));const result=chunks.length===0?str:chunks.join("");return this._postCheck(result,original)}_tierCounts(tier){if(this._limitTiers.has(LIMIT_TIER_ALL))return true;return this._limitTiers.has(tier)}_resolveName(name){if(name in this._inputMap)return{value:this._inputMap[name],tier:LIMIT_TIER_EXTERNAL};if(name in this._externalMap)return{value:this._externalMap[name],tier:LIMIT_TIER_EXTERNAL};if(name in this._baseMap)return{value:this._baseMap[name],tier:LIMIT_TIER_BASE};return void 0}_classifyNCR(cp){if(cp===0)return this._ncrNullLevel;if(cp>=55296&&cp<=57343)return NCR_LEVEL.remove;if(this._ncrXmlVersion===1){if(cp>=1&&cp<=31&&!XML10_ALLOWED_C0.has(cp))return NCR_LEVEL.remove}return-1}_applyNCRAction(action,token,cp){switch(action){case NCR_LEVEL.allow:return String.fromCodePoint(cp);case NCR_LEVEL.remove:return"";case NCR_LEVEL.leave:return void 0;case NCR_LEVEL.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${token}; (U+${cp.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(cp)}}_resolveNCR(token){const second=token.charCodeAt(1);let cp;if(second===120||second===88){cp=parseInt(token.slice(2),16)}else{cp=parseInt(token.slice(1),10)}if(Number.isNaN(cp)||cp<0||cp>1114111)return void 0;const minimum=this._classifyNCR(cp);if(!this._numericAllowed&&minimum<NCR_LEVEL.remove)return void 0;const effective=minimum===-1?this._ncrOnLevel:Math.max(this._ncrOnLevel,minimum);return this._applyNCRAction(effective,token,cp)}};var defaultOnDangerousProperty=name=>{if(DANGEROUS_PROPERTY_NAMES.includes(name)){return"__"+name}return name};var defaultOptions2={preserveOrder:false,attributeNamePrefix:"@_",attributesGroupName:false,textNodeName:"#text",ignoreAttributes:true,removeNSPrefix:false,allowBooleanAttributes:false,parseTagValue:true,parseAttributeValue:false,trimValues:true,cdataPropName:false,numberParseOptions:{hex:true,leadingZeros:true,eNotation:true,unicode:false},tagValueProcessor:function(tagName,val){return val},attributeValueProcessor:function(attrName,val){return val},stopNodes:[],alwaysCreateTextNode:false,isArray:()=>false,commentPropName:false,unpairedTags:[],processEntities:true,htmlEntities:false,entityDecoder:null,ignoreDeclaration:false,ignorePiTags:false,transformTagName:false,transformAttributeName:false,updateTag:function(tagName,jPath,attrs){return tagName},captureMetaData:false,maxNestedTags:100,strictReservedNames:true,jPath:true,onDangerousProperty:defaultOnDangerousProperty};function validatePropertyName(propertyName,optionName){if(typeof propertyName!=="string"){return}const normalized=propertyName.toLowerCase();if(DANGEROUS_PROPERTY_NAMES.some(dangerous=>normalized===dangerous.toLowerCase())){throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`)}if(criticalProperties.some(dangerous=>normalized===dangerous.toLowerCase())){throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`)}}function normalizeProcessEntities(value,htmlEntities){if(typeof value==="boolean"){return{enabled:value,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:Infinity,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}}if(typeof value==="object"&&value!==null){return{enabled:value.enabled!==false,maxEntitySize:Math.max(1,value.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,value.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,value.maxTotalExpansions??Infinity),maxExpandedLength:Math.max(1,value.maxExpandedLength??1e5),maxEntityCount:Math.max(1,value.maxEntityCount??1e3),allowedTags:value.allowedTags??null,tagFilter:value.tagFilter??null,appliesTo:value.appliesTo??"all"}}return normalizeProcessEntities(true)}var buildOptions=function(options){const built=Object.assign({},defaultOptions2,options);const propertyNameOptions=[{value:built.attributeNamePrefix,name:"attributeNamePrefix"},{value:built.attributesGroupName,name:"attributesGroupName"},{value:built.textNodeName,name:"textNodeName"},{value:built.cdataPropName,name:"cdataPropName"},{value:built.commentPropName,name:"commentPropName"}];for(const{value,name}of propertyNameOptions){if(value){validatePropertyName(value,name)}}if(built.onDangerousProperty===null){built.onDangerousProperty=defaultOnDangerousProperty}built.processEntities=normalizeProcessEntities(built.processEntities,built.htmlEntities);built.unpairedTagsSet=new Set(built.unpairedTags);if(built.stopNodes&&Array.isArray(built.stopNodes)){built.stopNodes=built.stopNodes.map(node=>{if(typeof node==="string"&&node.startsWith("*.")){return".."+node.substring(2)}return node})}return built};var METADATA_SYMBOL;if(typeof Symbol!=="function"){METADATA_SYMBOL="@@xmlMetadata"}else{METADATA_SYMBOL=Symbol("XML Node Metadata")}var XmlNode=class{constructor(tagname){this.tagname=tagname;this.child=[];this[":@"]=Object.create(null)}add(key,val){if(key==="__proto__")key="#__proto__";this.child.push({[key]:val})}addChild(node,startIndex){if(node.tagname==="__proto__")node.tagname="#__proto__";if(node[":@"]&&Object.keys(node[":@"]).length>0){this.child.push({[node.tagname]:node.child,[":@"]:node[":@"]})}else{this.child.push({[node.tagname]:node.child})}if(startIndex!==void 0){this.child[this.child.length-1][METADATA_SYMBOL]={startIndex}}}static getMetaDataSymbol(){return METADATA_SYMBOL}};var nameStartChar10=":A-Za-z_\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD";var nameChar10=nameStartChar10+"\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040";var nameStartChar11=":A-Za-z_\xC0-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";var nameChar11=nameStartChar11+"\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040";var buildRegexes=(startChar,char,flags="")=>{const ncStart=startChar.replace(":","");const ncChar=char.replace(":","");const ncNamePat=`[${ncStart}][${ncChar}]*`;return{name:new RegExp(`^[${startChar}][${char}]*$`,flags),ncName:new RegExp(`^${ncNamePat}$`,flags),qName:new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`,flags),nmToken:new RegExp(`^[${char}]+$`,flags),nmTokens:new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`,flags)}};var regexes10=buildRegexes(nameStartChar10,nameChar10);var regexes11=buildRegexes(nameStartChar11,nameChar11,"u");var nameStartCharAscii=":A-Za-z_";var nameCharAscii=nameStartCharAscii+"\\-\\.\\d";var regexesAscii=buildRegexes(nameStartCharAscii,nameCharAscii);var getRegexes=(xmlVersion="1.0",asciiOnly=false)=>{if(asciiOnly)return regexesAscii;return xmlVersion==="1.1"?regexes11:regexes10};var qName=(str,{xmlVersion="1.0",asciiOnly=false}={})=>getRegexes(xmlVersion,asciiOnly).qName.test(str);var DocTypeReader=class{constructor(options,xmlVersion){this.suppressValidationErr=!options;this.options=options;this.xmlVersion=xmlVersion||1}setXmlVersion(xmlVersion=1){this.xmlVersion=xmlVersion}readDocType(xmlData,i){const entities=Object.create(null);let entityCount=0;if(xmlData[i+3]==="O"&&xmlData[i+4]==="C"&&xmlData[i+5]==="T"&&xmlData[i+6]==="Y"&&xmlData[i+7]==="P"&&xmlData[i+8]==="E"){i=i+9;let angleBracketsCount=1;let hasBody=false,comment=false;let exp="";for(;i<xmlData.length;i++){if(xmlData[i]==="<"&&!comment){if(hasBody&&hasSeq(xmlData,"!ENTITY",i)){i+=7;let entityName,val;[entityName,val,i]=this.readEntityExp(xmlData,i+1,this.suppressValidationErr);if(val.indexOf("&")===-1){if(this.options.enabled!==false&&this.options.maxEntityCount!=null&&entityCount>=this.options.maxEntityCount){throw new Error(`Entity count (${entityCount+1}) exceeds maximum allowed (${this.options.maxEntityCount})`)}entities[entityName]=val;entityCount++}}else if(hasBody&&hasSeq(xmlData,"!ELEMENT",i)){i+=8;const{index}=this.readElementExp(xmlData,i+1);i=index}else if(hasBody&&hasSeq(xmlData,"!ATTLIST",i)){i+=8}else if(hasBody&&hasSeq(xmlData,"!NOTATION",i)){i+=9;const{index}=this.readNotationExp(xmlData,i+1,this.suppressValidationErr);i=index}else if(hasSeq(xmlData,"!--",i))comment=true;else throw new Error(`Invalid DOCTYPE`);angleBracketsCount++;exp=""}else if(xmlData[i]===">"){if(comment){if(xmlData[i-1]==="-"&&xmlData[i-2]==="-"){comment=false;angleBracketsCount--}}else{angleBracketsCount--}if(angleBracketsCount===0){break}}else if(xmlData[i]==="["){hasBody=true}else{exp+=xmlData[i]}}if(angleBracketsCount!==0){throw new Error(`Unclosed DOCTYPE`)}}else{throw new Error(`Invalid Tag instead of DOCTYPE`)}return{entities,i}}readEntityExp(xmlData,i){i=skipWhitespace(xmlData,i);const startIndex=i;while(i<xmlData.length&&!/\s/.test(xmlData[i])&&xmlData[i]!=='"'&&xmlData[i]!=="'"){i++}let entityName=xmlData.substring(startIndex,i);validateEntityName2(entityName,{xmlVersion:this.xmlVersion});i=skipWhitespace(xmlData,i);if(!this.suppressValidationErr){if(xmlData.substring(i,i+6).toUpperCase()==="SYSTEM"){throw new Error("External entities are not supported")}else if(xmlData[i]==="%"){throw new Error("Parameter entities are not supported")}}let entityValue="";[i,entityValue]=this.readIdentifierVal(xmlData,i,"entity");if(this.options.enabled!==false&&this.options.maxEntitySize!=null&&entityValue.length>this.options.maxEntitySize){throw new Error(`Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`)}i--;return[entityName,entityValue,i]}readNotationExp(xmlData,i){i=skipWhitespace(xmlData,i);const startIndex=i;while(i<xmlData.length&&!/\s/.test(xmlData[i])){i++}let notationName=xmlData.substring(startIndex,i);!this.suppressValidationErr&&validateEntityName2(notationName,{xmlVersion:this.xmlVersion});i=skipWhitespace(xmlData,i);const identifierType=xmlData.substring(i,i+6).toUpperCase();if(!this.suppressValidationErr&&identifierType!=="SYSTEM"&&identifierType!=="PUBLIC"){throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`)}i+=identifierType.length;i=skipWhitespace(xmlData,i);let publicIdentifier=null;let systemIdentifier=null;if(identifierType==="PUBLIC"){[i,publicIdentifier]=this.readIdentifierVal(xmlData,i,"publicIdentifier");i=skipWhitespace(xmlData,i);if(xmlData[i]==='"'||xmlData[i]==="'"){[i,systemIdentifier]=this.readIdentifierVal(xmlData,i,"systemIdentifier")}}else if(identifierType==="SYSTEM"){[i,systemIdentifier]=this.readIdentifierVal(xmlData,i,"systemIdentifier");if(!this.suppressValidationErr&&!systemIdentifier){throw new Error("Missing mandatory system identifier for SYSTEM notation")}}return{notationName,publicIdentifier,systemIdentifier,index:--i}}readIdentifierVal(xmlData,i,type){let identifierVal="";const startChar=xmlData[i];if(startChar!=='"'&&startChar!=="'"){throw new Error(`Expected quoted string, found "${startChar}"`)}i++;const startIndex=i;while(i<xmlData.length&&xmlData[i]!==startChar){i++}identifierVal=xmlData.substring(startIndex,i);if(xmlData[i]!==startChar){throw new Error(`Unterminated ${type} value`)}i++;return[i,identifierVal]}readElementExp(xmlData,i){i=skipWhitespace(xmlData,i);const startIndex=i;while(i<xmlData.length&&!/\s/.test(xmlData[i])){i++}let elementName=xmlData.substring(startIndex,i);if(!this.suppressValidationErr&&!qName(elementName,{xmlVersion:this.xmlVersion})){throw new Error(`Invalid element name: "${elementName}"`)}i=skipWhitespace(xmlData,i);let contentModel="";if(xmlData[i]==="E"&&hasSeq(xmlData,"MPTY",i))i+=4;else if(xmlData[i]==="A"&&hasSeq(xmlData,"NY",i))i+=2;else if(xmlData[i]==="("){i++;const startIndex2=i;while(i<xmlData.length&&xmlData[i]!==")"){i++}contentModel=xmlData.substring(startIndex2,i);if(xmlData[i]!==")"){throw new Error("Unterminated content model")}}else if(!this.suppressValidationErr){throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`)}return{elementName,contentModel:contentModel.trim(),index:i}}readAttlistExp(xmlData,i){i=skipWhitespace(xmlData,i);let startIndex=i;while(i<xmlData.length&&!/\s/.test(xmlData[i])){i++}let elementName=xmlData.substring(startIndex,i);validateEntityName2(elementName,{xmlVersion:this.xmlVersion});i=skipWhitespace(xmlData,i);startIndex=i;while(i<xmlData.length&&!/\s/.test(xmlData[i])){i++}let attributeName=xmlData.substring(startIndex,i);if(!validateEntityName2(attributeName,{xmlVersion:this.xmlVersion})){throw new Error(`Invalid attribute name: "${attributeName}"`)}i=skipWhitespace(xmlData,i);let attributeType="";if(xmlData.substring(i,i+8).toUpperCase()==="NOTATION"){attributeType="NOTATION";i+=8;i=skipWhitespace(xmlData,i);if(xmlData[i]!=="("){throw new Error(`Expected '(', found "${xmlData[i]}"`)}i++;let allowedNotations=[];while(i<xmlData.length&&xmlData[i]!==")"){const startIndex2=i;while(i<xmlData.length&&xmlData[i]!=="|"&&xmlData[i]!==")"){i++}let notation=xmlData.substring(startIndex2,i);notation=notation.trim();if(!validateEntityName2(notation,{xmlVersion:this.xmlVersion})){throw new Error(`Invalid notation name: "${notation}"`)}allowedNotations.push(notation);if(xmlData[i]==="|"){i++;i=skipWhitespace(xmlData,i)}}if(xmlData[i]!==")"){throw new Error("Unterminated list of notations")}i++;attributeType+=" ("+allowedNotations.join("|")+")"}else{const startIndex2=i;while(i<xmlData.length&&!/\s/.test(xmlData[i])){i++}attributeType+=xmlData.substring(startIndex2,i);const validTypes=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!validTypes.includes(attributeType.toUpperCase())){throw new Error(`Invalid attribute type: "${attributeType}"`)}}i=skipWhitespace(xmlData,i);let defaultValue="";if(xmlData.substring(i,i+8).toUpperCase()==="#REQUIRED"){defaultValue="#REQUIRED";i+=8}else if(xmlData.substring(i,i+7).toUpperCase()==="#IMPLIED"){defaultValue="#IMPLIED";i+=7}else{[i,defaultValue]=this.readIdentifierVal(xmlData,i,"ATTLIST")}return{elementName,attributeName,attributeType,defaultValue,index:i}}};var skipWhitespace=(data,index)=>{while(index<data.length&&/\s/.test(data[index])){index++}return index};function hasSeq(data,seq,i){for(let j=0;j<seq.length;j++){if(seq[j]!==data[i+j+1])return false}return true}function validateEntityName2(name,xmlVersion){if(qName(name,{xmlVersion}))return name;else throw new Error(`Invalid entity name ${name}`)}var SCRIPT_ZEROS=[48,1632,1776,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,65296,120782,120792,120802,120812,120822,66720,68912,69734,69872,69942,70096,70384,70736,70864,71248,71360,71472,71904,72016,72688,72784,73040,73120,73552,92768,92864,93008,123200,123632,124144,125264,130032];var NOT_DIGIT=255;var HIGH_MAP=new Map;var LOW_MAX=65535;var LOW_MIN=1632;var TABLE_OFFSET=LOW_MIN;var TABLE_SIZE=LOW_MAX-LOW_MIN+1;var TABLE=new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT);for(const zero of SCRIPT_ZEROS){for(let d=0;d<10;d++){const cp=zero+d;if(cp<=LOW_MAX){TABLE[cp-TABLE_OFFSET]=d}else{HIGH_MAP.set(cp,d)}}}var CHAR_0=48;var CHAR_9=57;var CHAR_MINUS=45;var MINUS_SET=new Set([8722,65293,65123]);function anynum(str){if(typeof str!=="string")return str;const len=str.length;if(len===0)return str;let firstHit=-1;for(let i=0;i<len;i++){const cc=str.charCodeAt(i);if(cc>=CHAR_0&&cc<=CHAR_9||cc===CHAR_MINUS)continue;if(cc<TABLE_OFFSET){if(MINUS_SET.has(cc)){firstHit=i;break}continue}if(cc>=55296&&cc<=56319){if(i+1<len){const low=str.charCodeAt(i+1);if(low>=56320&&low<=57343){const cp=65536+(cc-55296<<10)+(low-56320);if(HIGH_MAP.has(cp)){firstHit=i;break}}}continue}if(TABLE[cc-TABLE_OFFSET]!==NOT_DIGIT||MINUS_SET.has(cc)){firstHit=i;break}}if(firstHit===-1)return str;const chars=[];if(firstHit>0)chars.push(str.slice(0,firstHit));for(let i=firstHit;i<len;i++){const cc=str.charCodeAt(i);if(cc>=CHAR_0&&cc<=CHAR_9||cc===CHAR_MINUS){chars.push(str[i]);continue}if(cc<TABLE_OFFSET){chars.push(MINUS_SET.has(cc)?"-":str[i]);continue}if(cc>=55296&&cc<=56319){if(i+1<len){const low=str.charCodeAt(i+1);if(low>=56320&&low<=57343){const cp=65536+(cc-55296<<10)+(low-56320);const d2=HIGH_MAP.get(cp);if(d2!==void 0){chars.push(String.fromCharCode(d2+48));i++;continue}}}chars.push(str[i]);continue}if(MINUS_SET.has(cc)){chars.push("-");continue}const d=TABLE[cc-TABLE_OFFSET];chars.push(d!==NOT_DIGIT?String.fromCharCode(d+48):str[i])}return chars.join("")}var anynum_default=anynum;var hexRegex=/^[-+]?0x[a-fA-F0-9]+$/;var binRegex=/^0b[01]+$/;var octRegex=/^0o[0-7]+$/;var numRegex=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;var consider={hex:true,binary:false,octal:false,leadingZeros:true,decimalPoint:".",eNotation:true,infinity:"original",unicode:false};function toNumber(str,options={}){options=Object.assign({},consider,options);if(!str||typeof str!=="string")return str;let trimmedStr=str.trim();if(trimmedStr.length===0)return str;else if(options.skipLike!==void 0&&options.skipLike.test(trimmedStr))return str;else if(trimmedStr==="0")return 0;if(options.unicode){trimmedStr=anynum_default(trimmedStr);if(trimmedStr==="0")return 0}if(options.hex&&hexRegex.test(trimmedStr)){return parse_int(trimmedStr,16)}else if(options.binary&&binRegex.test(trimmedStr)){return parse_int(trimmedStr,2)}else if(options.octal&&octRegex.test(trimmedStr)){return parse_int(trimmedStr,8)}else if(!isFinite(trimmedStr)){return handleInfinity(str,Number(trimmedStr),options)}else if(trimmedStr.includes("e")||trimmedStr.includes("E")){return resolveEnotation(str,trimmedStr,options)}else{const match=numRegex.exec(trimmedStr);if(match){const sign=match[1]||"";const leadingZeros=match[2];let numTrimmedByZeros=trimZeros(match[3]);const decimalAdjacentToLeadingZeros=sign?str[leadingZeros.length+1]===".":str[leadingZeros.length]===".";if(!options.leadingZeros&&(leadingZeros.length>1||leadingZeros.length===1&&!decimalAdjacentToLeadingZeros)){return str}else{const num=Number(trimmedStr);const parsedStr=String(num);if(num===0)return num;if(parsedStr.search(/[eE]/)!==-1){if(options.eNotation)return num;else return str}else if(trimmedStr.indexOf(".")!==-1){if(parsedStr==="0")return num;else if(parsedStr===numTrimmedByZeros)return num;else if(parsedStr===`${sign}${numTrimmedByZeros}`)return num;else return str}let n=leadingZeros?numTrimmedByZeros:trimmedStr;if(leadingZeros){return n===parsedStr||sign+n===parsedStr?num:str}else{return n===parsedStr||n===sign+parsedStr?num:str}}}else{return str}}}var eNotationRegx=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(str,trimmedStr,options){if(!options.eNotation)return str;const notation=trimmedStr.match(eNotationRegx);if(notation){let sign=notation[1]||"";const eChar=notation[3].indexOf("e")===-1?"E":"e";const leadingZeros=notation[2];const eAdjacentToLeadingZeros=sign?str[leadingZeros.length+1]===eChar:str[leadingZeros.length]===eChar;if(leadingZeros.length>1&&eAdjacentToLeadingZeros)return str;else if(leadingZeros.length===1&&(notation[3].startsWith(`.${eChar}`)||notation[3][0]===eChar)){return Number(trimmedStr)}else if(leadingZeros.length>0){if(options.leadingZeros&&!eAdjacentToLeadingZeros){trimmedStr=(notation[1]||"")+notation[3];return Number(trimmedStr)}else return str}else{return Number(trimmedStr)}}else{return str}}function trimZeros(numStr){if(numStr&&numStr.indexOf(".")!==-1){numStr=numStr.replace(/0+$/,"");if(numStr===".")numStr="0";else if(numStr[0]===".")numStr="0"+numStr;else if(numStr[numStr.length-1]===".")numStr=numStr.substring(0,numStr.length-1);return numStr}return numStr}function parse_int(numStr,base){const str=numStr.trim();if(base===2||base===8)numStr=str.substring(2);if(parseInt)return parseInt(numStr,base);else if(Number.parseInt)return Number.parseInt(numStr,base);else if(window&&window.parseInt)return window.parseInt(numStr,base);else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function handleInfinity(str,num,options){const isPositive=num===Infinity;switch(options.infinity.toLowerCase()){case"null":return null;case"infinity":return num;case"string":return isPositive?"Infinity":"-Infinity";case"original":default:return str}}function getIgnoreAttributesFn(ignoreAttributes){if(typeof ignoreAttributes==="function"){return ignoreAttributes}if(Array.isArray(ignoreAttributes)){return attrName=>{for(const pattern of ignoreAttributes){if(typeof pattern==="string"&&attrName===pattern){return true}if(pattern instanceof RegExp&&pattern.test(attrName)){return true}}}}return()=>false}var Expression=class{constructor(pattern,options={},data){this.pattern=pattern;this.separator=options.separator||".";this.segments=this._parse(pattern);this.data=data;this._hasDeepWildcard=this.segments.some(seg=>seg.type==="deep-wildcard");this._hasAttributeCondition=this.segments.some(seg=>seg.attrName!==void 0);this._hasPositionSelector=this.segments.some(seg=>seg.position!==void 0)}_parse(pattern){const segments=[];let i=0;let currentPart="";while(i<pattern.length){if(pattern[i]===this.separator){if(i+1<pattern.length&&pattern[i+1]===this.separator){if(currentPart.trim()){segments.push(this._parseSegment(currentPart.trim()));currentPart=""}segments.push({type:"deep-wildcard"});i+=2}else{if(currentPart.trim()){segments.push(this._parseSegment(currentPart.trim()))}currentPart="";i++}}else{currentPart+=pattern[i];i++}}if(currentPart.trim()){segments.push(this._parseSegment(currentPart.trim()))}return segments}_parseSegment(part){const segment={type:"tag"};let bracketContent=null;let withoutBrackets=part;const bracketMatch=part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(bracketMatch){withoutBrackets=bracketMatch[1]+bracketMatch[3];if(bracketMatch[2]){const content=bracketMatch[2].slice(1,-1);if(content){bracketContent=content}}}let namespace=void 0;let tagAndPosition=withoutBrackets;if(withoutBrackets.includes("::")){const nsIndex=withoutBrackets.indexOf("::");namespace=withoutBrackets.substring(0,nsIndex).trim();tagAndPosition=withoutBrackets.substring(nsIndex+2).trim();if(!namespace){throw new Error(`Invalid namespace in pattern: ${part}`)}}let tag=void 0;let positionMatch=null;if(tagAndPosition.includes(":")){const colonIndex=tagAndPosition.lastIndexOf(":");const tagPart=tagAndPosition.substring(0,colonIndex).trim();const posPart=tagAndPosition.substring(colonIndex+1).trim();const isPositionKeyword=["first","last","odd","even"].includes(posPart)||/^nth\(\d+\)$/.test(posPart);if(isPositionKeyword){tag=tagPart;positionMatch=posPart}else{tag=tagAndPosition}}else{tag=tagAndPosition}if(!tag){throw new Error(`Invalid segment pattern: ${part}`)}segment.tag=tag;if(namespace){segment.namespace=namespace}if(bracketContent){if(bracketContent.includes("=")){const eqIndex=bracketContent.indexOf("=");segment.attrName=bracketContent.substring(0,eqIndex).trim();segment.attrValue=bracketContent.substring(eqIndex+1).trim()}else{segment.attrName=bracketContent.trim()}}if(positionMatch){const nthMatch=positionMatch.match(/^nth\((\d+)\)$/);if(nthMatch){segment.position="nth";segment.positionValue=parseInt(nthMatch[1],10)}else{segment.position=positionMatch}}return segment}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}};var ExpressionSet=class{constructor(){this._byDepthAndTag=new Map;this._wildcardByDepth=new Map;this._deepWildcards=[];this._deepByTerminalTag=new Map;this._patterns=new Set;this._sealed=false}add(expression){if(this._sealed){throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.")}if(this._patterns.has(expression.pattern))return this;this._patterns.add(expression.pattern);if(expression.hasDeepWildcard()){const lastSeg2=expression.segments[expression.segments.length-1];if(lastSeg2&&lastSeg2.type!=="deep-wildcard"&&lastSeg2.tag!=="*"){const tag2=lastSeg2.tag;if(!this._deepByTerminalTag.has(tag2))this._deepByTerminalTag.set(tag2,[]);this._deepByTerminalTag.get(tag2).push(expression)}else{this._deepWildcards.push(expression)}return this}const depth=expression.length;const lastSeg=expression.segments[expression.segments.length-1];const tag=lastSeg?.tag;if(!tag||tag==="*"){if(!this._wildcardByDepth.has(depth))this._wildcardByDepth.set(depth,[]);this._wildcardByDepth.get(depth).push(expression)}else{const key=`${depth}:${tag}`;if(!this._byDepthAndTag.has(key))this._byDepthAndTag.set(key,[]);this._byDepthAndTag.get(key).push(expression)}return this}addAll(expressions){for(const expr of expressions)this.add(expr);return this}has(expression){return this._patterns.has(expression.pattern)}get size(){return this._patterns.size}seal(){this._sealed=true;return this}get isSealed(){return this._sealed}matchesAny(matcher){return this.findMatch(matcher)!==null}findMatch(matcher){const depth=matcher.getDepth();const tag=matcher.getCurrentTag();const exactKey=`${depth}:${tag}`;const exactBucket=this._byDepthAndTag.get(exactKey);if(exactBucket){for(let i=0;i<exactBucket.length;i++){if(matcher.matches(exactBucket[i]))return exactBucket[i]}}const wildcardBucket=this._wildcardByDepth.get(depth);if(wildcardBucket){for(let i=0;i<wildcardBucket.length;i++){if(matcher.matches(wildcardBucket[i]))return wildcardBucket[i]}}const deepBucket=this._deepByTerminalTag.get(tag);if(deepBucket){for(let i=0;i<deepBucket.length;i++){if(matcher.matches(deepBucket[i]))return deepBucket[i]}}for(let i=0;i<this._deepWildcards.length;i++){if(matcher.matches(this._deepWildcards[i]))return this._deepWildcards[i]}return null}};var MatcherView=class{constructor(matcher){this._matcher=matcher}get separator(){return this._matcher.separator}getCurrentTag(){const path=this._matcher.path;return path.length>0?path[path.length-1].tag:void 0}getCurrentNamespace(){const path=this._matcher.path;return path.length>0?path[path.length-1].namespace:void 0}getAttrValue(attrName){const path=this._matcher.path;if(path.length===0)return void 0;return path[path.length-1].values?.[attrName]}hasAttr(attrName){const path=this._matcher.path;if(path.length===0)return false;const current=path[path.length-1];return current.values!==void 0&&attrName in current.values}getAnyParentAttr(attrName){return this._matcher.getAnyParentAttr(attrName)}hasAnyParentAttr(attrName){return this._matcher.hasAnyParentAttr(attrName)}getPosition(){const path=this._matcher.path;if(path.length===0)return-1;return path[path.length-1].position??0}getCounter(){const path=this._matcher.path;if(path.length===0)return-1;return path[path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(separator,includeNamespace=true){return this._matcher.toString(separator,includeNamespace)}toArray(){return this._matcher.path.map(n=>n.tag)}matches(expression){return this._matcher.matches(expression)}matchesAny(exprSet){return exprSet.matchesAny(this._matcher)}};var Matcher=class{constructor(options={}){this.separator=options.separator||".";this.path=[];this.siblingStacks=[];this._pathStringCache=null;this._view=new MatcherView(this);this._keptAttrs=[]}push(tagName,attrValues=null,namespace=null,options=null){this._pathStringCache=null;if(this.path.length>0){this.path[this.path.length-1].values=void 0}const currentLevel=this.path.length;let level=this.siblingStacks[currentLevel];if(!level){level={counts:new Map,total:0};this.siblingStacks[currentLevel]=level}const siblingKey=namespace?`${namespace}:${tagName}`:tagName;const counter=level.counts.get(siblingKey)||0;const position=level.total;level.counts.set(siblingKey,counter+1);level.total++;const node={tag:tagName,position,counter};if(namespace!==null&&namespace!==void 0){node.namespace=namespace}if(attrValues!==null&&attrValues!==void 0){node.values=attrValues}this.path.push(node);const depth=this.path.length;const keep=options!==null?options.keep:null;if(keep!==null&&keep!==void 0&&keep.length>0&&attrValues){for(let i=0;i<keep.length;i++){const name=keep[i];if(attrValues[name]!==void 0){this._keptAttrs.push({depth,name,value:attrValues[name]})}}}}pop(){if(this.path.length===0)return void 0;this._pathStringCache=null;const node=this.path.pop();if(this.siblingStacks.length>this.path.length+1){this.siblingStacks.length=this.path.length+1}const poppedDepth=this.path.length+1;while(this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=poppedDepth){this._keptAttrs.pop()}return node}updateCurrent(attrValues){if(this.path.length>0){const current=this.path[this.path.length-1];if(attrValues!==null&&attrValues!==void 0){current.values=attrValues}}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(attrName){if(this.path.length===0)return void 0;return this.path[this.path.length-1].values?.[attrName]}hasAttr(attrName){if(this.path.length===0)return false;const current=this.path[this.path.length-1];return current.values!==void 0&&attrName in current.values}getAnyParentAttr(attrName){const kept=this._keptAttrs;for(let i=kept.length-1;i>=0;i--){if(kept[i].name===attrName)return kept[i].value}return void 0}hasAnyParentAttr(attrName){const kept=this._keptAttrs;for(let i=kept.length-1;i>=0;i--){if(kept[i].name===attrName)return true}return false}getPosition(){if(this.path.length===0)return-1;return this.path[this.path.length-1].position??0}getCounter(){if(this.path.length===0)return-1;return this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(separator,includeNamespace=true){const sep2=separator||this.separator;const isDefault=sep2===this.separator&&includeNamespace===true;if(isDefault){if(this._pathStringCache!==null){return this._pathStringCache}const result=this.path.map(n=>n.namespace?`${n.namespace}:${n.tag}`:n.tag).join(sep2);this._pathStringCache=result;return result}return this.path.map(n=>includeNamespace&&n.namespace?`${n.namespace}:${n.tag}`:n.tag).join(sep2)}toArray(){return this.path.map(n=>n.tag)}reset(){this._pathStringCache=null;this.path=[];this.siblingStacks=[];this._keptAttrs=[]}matches(expression){const segments=expression.segments;if(segments.length===0){return false}if(expression.hasDeepWildcard()){return this._matchWithDeepWildcard(segments)}return this._matchSimple(segments)}_matchSimple(segments){if(this.path.length!==segments.length){return false}for(let i=0;i<segments.length;i++){if(!this._matchSegment(segments[i],this.path[i],i===this.path.length-1)){return false}}return true}_matchWithDeepWildcard(segments){let pathIdx=this.path.length-1;let segIdx=segments.length-1;while(segIdx>=0&&pathIdx>=0){const segment=segments[segIdx];if(segment.type==="deep-wildcard"){segIdx--;if(segIdx<0){return true}const nextSeg=segments[segIdx];let found=false;for(let i=pathIdx;i>=0;i--){if(this._matchSegment(nextSeg,this.path[i],i===this.path.length-1)){pathIdx=i-1;segIdx--;found=true;break}}if(!found){return false}}else{if(!this._matchSegment(segment,this.path[pathIdx],pathIdx===this.path.length-1)){return false}pathIdx--;segIdx--}}return segIdx<0}_matchSegment(segment,node,isCurrentNode){if(segment.tag!=="*"&&segment.tag!==node.tag){return false}if(segment.namespace!==void 0){if(segment.namespace!=="*"&&segment.namespace!==node.namespace){return false}}if(segment.attrName!==void 0){if(!isCurrentNode){return false}if(!node.values||!(segment.attrName in node.values)){return false}if(segment.attrValue!==void 0){if(String(node.values[segment.attrName])!==String(segment.attrValue)){return false}}}if(segment.position!==void 0){if(!isCurrentNode){return false}const counter=node.counter??0;if(segment.position==="first"&&counter!==0){return false}else if(segment.position==="odd"&&counter%2!==1){return false}else if(segment.position==="even"&&counter%2!==0){return false}else if(segment.position==="nth"&&counter!==segment.positionValue){return false}}return true}matchesAny(exprSet){return exprSet.matchesAny(this)}snapshot(){return{path:this.path.map(node=>({...node})),siblingStacks:this.siblingStacks.map(level=>level?{counts:new Map(level.counts),total:level.total}:level),keptAttrs:this._keptAttrs.map(entry=>({...entry}))}}restore(snapshot){this._pathStringCache=null;this.path=snapshot.path.map(node=>({...node}));this.siblingStacks=snapshot.siblingStacks.map(level=>level?{counts:new Map(level.counts),total:level.total}:level);this._keptAttrs=(snapshot.keptAttrs||[]).map(entry=>({...entry}))}readOnly(){return this._view}};var HTML_PATTERNS=[{id:"html-script-open",description:"<script opening tag",pattern:/<script[\s>/]/i},{id:"html-script-close",description:"</script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI \u2014 can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI \u2014 can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded <script (e.g. <script or <script)",pattern:/(?:�*3[Cc];?|�*60;?|<)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial \u2014 catches common j or j for "j")',pattern:/(?:�*6[Aa];?|�*106;?)\s*(?:�*61;?|a)[\s\S]{0,80}script\s*:/i},{id:"html-style-expression",description:"CSS expression() \u2014 IE-era code execution in style attributes",pattern:/style[\s\S]{0,20}expression\s*\(/i},{id:"html-object-embed",description:"<object or <embed tags that can load active content",pattern:/<(?:object|embed)[\s>/]/i},{id:"html-base-tag",description:"<base href= \u2014 can hijack all relative URLs on a page",pattern:/<base[\s>]/i},{id:"html-meta-refresh",description:'<meta http-equiv="refresh" \u2014 can redirect users',pattern:/<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i},{id:"html-srcdoc",description:"srcdoc= attribute on iframes \u2014 embeds HTML that can run scripts",pattern:/srcdoc\s*=/i},{id:"html-iframe",description:"<iframe tag",pattern:/<iframe[\s>/]/i},{id:"html-form",description:"<form tag \u2014 can be used for phishing / credential harvesting injection",pattern:/<form[\s>/]/i}];var html_default=HTML_PATTERNS;var XML_PATTERNS=[{id:"xml-cdata-injection",description:"CDATA section injection: <![CDATA[ breaks out of text node context",pattern:/<!\[CDATA\[/i},{id:"xml-cdata-close",description:"CDATA close sequence: ]]> can terminate an enclosing CDATA section",pattern:/\]\]>/},{id:"xml-processing-instruction",description:"XML processing instruction: <?xml-stylesheet or <?php etc.",pattern:/<\?(?:xml[\- ]|php|asp)/i},{id:"xml-doctype-injection",description:"DOCTYPE declaration embedded in content \u2014 can define entities",pattern:/<!DOCTYPE(?:[\s[]|$)/i},{id:"xml-entity-system",description:"SYSTEM keyword \u2014 used in external entity declarations (XXE)",pattern:/\bSYSTEM\s+["']/i},{id:"xml-entity-public",description:"PUBLIC keyword \u2014 used in external entity declarations (XXE)",pattern:/\bPUBLIC\s+["']/i},{id:"xml-entity-declaration",description:"<!ENTITY declaration \u2014 defines entities, potential XXE or entity expansion",pattern:/<!ENTITY[\s%]/i},{id:"xml-billion-laughs",description:"Entity reference chaining / billion laughs: repeated &eX; style references",pattern:/(?:&\w{1,20};){3,}/},{id:"xml-namespace-confusion",description:"xmlns: attribute injection \u2014 can redefine namespaces to confuse parsers",pattern:/\bxmlns\s*(?::\w{1,40})?\s*=/i},{id:"xml-comment-injection",description:"<!-- comment injection \u2014 can hide content from some parsers",pattern:/<!--/},{id:"xml-comment-close",description:"--> closes an enclosing XML comment",pattern:/-->/},{id:"xml-pi-close",description:"?> closes an enclosing processing instruction",pattern:/\?>/}];var xml_default=XML_PATTERNS;var SVG_PATTERNS=[{id:"svg-script-element",description:"<script element inside SVG executes JavaScript",pattern:/<script[\s>/]/i},{id:"svg-xlink-href-javascript",description:"xlink:href with javascript: \u2014 classic SVG XSS via <a> or <use>",pattern:/xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-href-javascript",description:"href= with javascript: in SVG context (<a>, <animate>, etc.)",pattern:/href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-foreignobject",description:"<foreignObject embeds HTML inside SVG \u2014 can execute scripts",pattern:/<foreignObject[\s>/]/i},{id:"svg-use-external",description:"<use xlink:href or href pointing to external resource (non-fragment URL)",pattern:/<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i},{id:"svg-animate-href",description:'<animate attributeName="href" \u2014 can dynamically change href to javascript:',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i},{id:"svg-animate-xlinkhref",description:'<animate attributeName="xlink:href"',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i},{id:"svg-set-javascript",description:'<set to="javascript:..." \u2014 sets an attribute to a javascript: URI',pattern:/<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-event-handler",description:"SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",pattern:/\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i},{id:"svg-handler-generic",description:"Generic on* handler catch-all for SVG attributes",pattern:/\bon\w{1,30}\s*=/i},{id:"svg-filter-feimage",description:"<feImage href= \u2014 filter primitive that can load external resources",pattern:/<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i},{id:"svg-image-external",description:"<image xlink:href with http/https or javascript protocol",pattern:/<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i},{id:"svg-style-javascript",description:"style= attribute containing javascript: (e.g. background:url(javascript:...))",pattern:/style\s*=[\s\S]{0,60}javascript\s*:/i}];var svg_default=SVG_PATTERNS;var SQL_PATTERNS=[{id:"sql-block-comment-open",description:"SQL block comment open: /* ... */ \u2014 unusual in legitimate user text",pattern:/\/\*/},{id:"sql-union-select",description:"UNION SELECT \u2014 most common SQL injection aggregation attack",pattern:/\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i},{id:"sql-drop-table",description:"DROP TABLE \u2014 destructive DDL injection",pattern:/\bDROP\s{1,20}TABLE\b/i},{id:"sql-drop-database",description:"DROP DATABASE \u2014 destructive DDL injection",pattern:/\bDROP\s{1,20}DATABASE\b/i},{id:"sql-insert-into",description:"INSERT INTO \u2014 data injection",pattern:/\bINSERT\s{1,20}INTO\b/i},{id:"sql-delete-from",description:"DELETE FROM \u2014 data deletion injection",pattern:/\bDELETE\s{1,20}FROM\b/i},{id:"sql-update-set",description:"UPDATE ... SET \u2014 data modification injection",pattern:/\bUPDATE\b[\s\S]{1,60}\bSET\b/i},{id:"sql-exec-xp",description:"EXEC xp_ \u2014 MSSQL extended stored procedure execution",pattern:/\bEXEC(?:UTE)?\s{1,20}xp_/i},{id:"sql-tautology-string",description:`Classic string tautology: ' OR '1'='1 or " OR "1"="1"`,pattern:/'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i},{id:"sql-tautology-numeric",description:"Numeric tautology: OR 1=1",pattern:/\bOR\s{1,10}1\s*=\s*1\b/i},{id:"sql-always-true-zero",description:"Numeric tautology: OR 0=0",pattern:/\bOR\s{1,10}0\s*=\s*0\b/i},{id:"sql-sleep-benchmark",description:"Time-based blind injection: SLEEP() or BENCHMARK()",pattern:/\b(?:SLEEP|BENCHMARK)\s*\(/i},{id:"sql-waitfor-delay",description:"MSSQL time-based blind injection: WAITFOR DELAY",pattern:/\bWAITFOR\s{1,20}DELAY\b/i},{id:"sql-char-function",description:"CHAR() function \u2014 used to obfuscate injected strings",pattern:/\bCHAR\s*\(\s*\d{1,3}/i},{id:"sql-information-schema",description:"INFORMATION_SCHEMA \u2014 reconnaissance query for table/column enumeration",pattern:/\bINFORMATION_SCHEMA\b/i}];var sql_default=SQL_PATTERNS;var SHELL_PATTERNS=[{id:"shell-path-traversal-unix",description:"Unix path traversal: ../ \u2014 climbing the directory tree",pattern:/\.\.\//},{id:"shell-path-traversal-windows",description:"Windows path traversal: ..\\ \u2014 climbing the directory tree",pattern:/\.\.\\/},{id:"shell-path-traversal-encoded",description:"URL-encoded path traversal: %2e%2e or %2f variants",pattern:/%2e%2e|%2f\.\.|\.\.%2f/i},{id:"shell-null-byte",description:"Null byte injection: \\x00 or %00 \u2014 truncates strings in C-backed functions",pattern:/\x00|%00/},{id:"shell-semicolon",description:"Semicolon command separator: cmd1; cmd2",pattern:/;/},{id:"shell-pipe",description:"Pipe operator: cmd1 | cmd2",pattern:/\|/},{id:"shell-and-operator",description:"AND operator: cmd1 && cmd2",pattern:/&&/},{id:"shell-or-operator",description:"OR operator: cmd1 || cmd2",pattern:/\|\|/},{id:"shell-backtick",description:"Backtick command substitution: `cmd`",pattern:/`/},{id:"shell-dollar-paren",description:"Dollar-paren command substitution: $(cmd)",pattern:/\$\(/},{id:"shell-dollar-brace",description:"Dollar-brace variable expansion: ${var} \u2014 can be abused for injection",pattern:/\$\{/},{id:"shell-redirect-out",description:"Output redirection: cmd > file or cmd >> file",pattern:/>{1,2}/},{id:"shell-redirect-in",description:"Input redirection: cmd < file",pattern:/</},{id:"shell-newline-injection",description:"Newline injection: \\n or \\r \u2014 can inject new shell commands",pattern:/[\n\r]/},{id:"shell-glob-star",description:"Glob expansion: * or ? \u2014 can expand to unintended files",pattern:/[/\\][*?]/},{id:"shell-absolute-root",description:"Absolute root path injection: string starting with / or \\ (Windows UNC)",pattern:/^(?:\/|\\\\)/},{id:"shell-windows-drive",description:"Windows drive letter path injection: C:\\ or D:/",pattern:/^[a-zA-Z]:[/\\]/},{id:"shell-curl-wget",description:"curl/wget with URL or flags \u2014 can exfiltrate data or download payloads",pattern:/\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i}];var shell_default=SHELL_PATTERNS;var REDOS_PATTERNS=[{id:"redos-nested-quantifier-plus",description:"Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",pattern:/\([^)]*\+[^)]*\)[+*]/},{id:"redos-nested-quantifier-star",description:"Nested * quantifier: (a*)* or (a*)+ \u2014 catastrophic backtracking",pattern:/\([^)]*\*[^)]*\)[*+]/},{id:"redos-nested-groups",description:"Doubly nested quantified groups: ((a+)+) \u2014 guaranteed catastrophic",pattern:/\(\([^)]{0,40}\)[+*]\)[+*]/},{id:"redos-alternation-overlap",description:"Overlapping alternation under quantifier: (a|a)+ \u2014 ambiguous NFA paths",pattern:/\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/},{id:"redos-star-plus-concat",description:"(x*x)+ pattern \u2014 triggers super-linear backtracking",pattern:/\([^)]{0,10}\*[^)]{0,10}\)[+*]/},{id:"redos-dot-star-greedy",description:"(.*){n,} or (.+){n,} \u2014 repeated greedy dot quantifiers",pattern:/\(\.[*+]\)\{?\d/},{id:"redos-large-repetition",description:"Very large fixed or range repetition count {1000,} or {1000,n} \u2014 denial of service via backtracking",pattern:/\{\d{4,}(?:,\d*)?\}/},{id:"redos-catastrophic-alternation",description:"Long alternation with many similar branches \u2014 polynomial backtracking risk",pattern:/\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/}];var redos_default=REDOS_PATTERNS;var sep=`["'\\s]*:`;var NOSQL_PATTERNS=[{id:"nosql-where-operator",description:"$where \u2014 executes arbitrary JavaScript server-side in MongoDB",pattern:new RegExp(`\\$where${sep}`,"i")},{id:"nosql-ne-operator",description:'$ne \u2014 "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${sep}`,"i")},{id:"nosql-gt-operator",description:'$gt \u2014 "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${sep}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte \u2014 "less than" bypass variants',pattern:new RegExp(`\\$lte?${sep}`,"i")},{id:"nosql-regex-operator",description:"$regex \u2014 can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${sep}`,"i")},{id:"nosql-or-operator",description:"$or \u2014 logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${sep}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and \u2014 logical AND operator injection",pattern:new RegExp(`\\$and${sep}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor \u2014 logical NOR operator injection",pattern:new RegExp(`\\$nor${sep}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists \u2014 can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${sep}`,"i")},{id:"nosql-in-operator",description:"$in \u2014 matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${sep}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr \u2014 allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${sep}`,"i")},{id:"nosql-function-operator",description:"$function \u2014 executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${sep}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator \u2014 custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${sep}`,"i")},{id:"nosql-proto-pollution",description:"__proto__ \u2014 prototype pollution via object key injection",pattern:/__proto__/},{id:"nosql-constructor-prototype",description:"constructor.prototype \u2014 alternative prototype pollution vector (dot notation or JSON key)",pattern:/constructor[\s"':.,{\[]*prototype/i},{id:"nosql-proto-bracket",description:'["__proto__"] \u2014 bracket-notation prototype pollution',pattern:/\[["']__proto__["']\]/}];var nosql_default=NOSQL_PATTERNS;var LOG_PATTERNS=[{id:"log-crlf-injection",description:"CRLF injection: literal \\r or \\n embeds fake log lines",pattern:/[\r\n]/},{id:"log-url-encoded-crlf",description:"URL-encoded CRLF: %0d, %0a, %0D, %0A \u2014 decoded by some log parsers",pattern:/%0[dDaA]/},{id:"log-unicode-newline",description:"Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",pattern:/[\u2028\u2029]/},{id:"log-log4shell-jndi",description:"Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",pattern:/\$\{jndi\s*:/i},{id:"log-log4shell-obfuscated",description:"Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",pattern:/\$\{::-/},{id:"log-log4j-lookup",description:"Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} \u2014 data exfiltration",pattern:/\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i},{id:"log-ssti-double-brace",description:"SSTI double-brace: {{expression}} \u2014 Jinja2, Twig, Handlebars, etc.",pattern:/\{\{[\s\S]{0,80}\}\}/},{id:"log-ssti-hash-brace",description:"SSTI hash-brace: #{expression} \u2014 Thymeleaf, Velocity, Ruby ERB",pattern:/#\{[\s\S]{0,80}\}/},{id:"log-ssti-dollar-brace",description:"SSTI/EL injection: ${expression with operators or method calls} \u2014 JSP EL, Freemarker, SpEL",pattern:/\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i},{id:"log-ssti-percent-tag",description:"SSTI ERB/ASP tag: <%= expression %> \u2014 Ruby ERB, ASP",pattern:/<%=[\s\S]{0,80}%>/},{id:"log-null-byte",description:"Null byte: \\x00 or %00 \u2014 can truncate log entries in C-backed loggers",pattern:/\x00|%00/},{id:"log-ansi-escape",description:"ANSI escape sequence: ESC[ \u2014 can manipulate terminal output when logs are tailed",pattern:/\x1b\[/}];var log_default=LOG_PATTERNS;var SQL_STRICT_EXTRA=[{id:"sql-line-comment",description:"SQL line comment: -- followed by whitespace or end of string",pattern:/--(?:\s|$)/},{id:"sql-stacked-query",description:"Stacked queries: semicolon immediately followed by a SQL keyword",pattern:/;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i},{id:"sql-hex-encoding",description:"Hex-encoded string injection: 0x41414141 style (MySQL)",pattern:/\b0x[0-9a-f]{4,}/i}];var SQL_STRICT_PATTERNS=[...sql_default,...SQL_STRICT_EXTRA];var sql_strict_default=SQL_STRICT_PATTERNS;html_default.label="HTML";xml_default.label="XML";svg_default.label="SVG";sql_default.label="SQL";sql_strict_default.label="SQL-STRICT";shell_default.label="SHELL";redos_default.label="REDOS";nosql_default.label="NOSQL";log_default.label="LOG";var VALID_CONTEXTS=Object.freeze({HTML:html_default,XML:xml_default,SVG:svg_default,SQL:sql_default,"SQL-STRICT":sql_strict_default,SHELL:shell_default,REDOS:redos_default,NOSQL:nosql_default,LOG:log_default});function assertString(value){if(typeof value!=="string"){throw new TypeError(`is-unsafe: first argument must be a string, got ${typeof value}`)}}function assertContext(context){if(context instanceof RegExp)return;if(Array.isArray(context)){if(context.length===0){throw new TypeError("is-unsafe: context must not be an empty array")}if(Array.isArray(context[0])){for(const list of context){if(!Array.isArray(list)||list.length===0){throw new TypeError("is-unsafe: each context in the array must be a non-empty pattern array (PatternList)")}}}return}throw new TypeError(`is-unsafe: second argument must be a PatternList (e.g. HTML), an array of PatternLists (e.g. [HTML, XML]), or a RegExp. Got: ${typeof context}`)}function normalise(context){if(context instanceof RegExp)return{lists:null,regex:context};if(Array.isArray(context[0]))return{lists:context,regex:null};return{lists:[context],regex:null}}function matchList(value,list){const label=list.label??"CUSTOM";for(const rule of list){if(rule.pattern.test(value)){return{context:label,id:rule.id,description:rule.description,pattern:rule.pattern}}}return null}function isUnsafe(value,context){assertString(value);assertContext(context);const{lists,regex}=normalise(context);if(regex)return regex.test(value);for(const list of lists){if(matchList(value,list)!==null)return true}return false}function extractRawAttributes(prefixedAttrs,options){if(!prefixedAttrs)return{};const attrs=options.attributesGroupName?prefixedAttrs[options.attributesGroupName]:prefixedAttrs;if(!attrs)return{};const rawAttrs={};for(const key in attrs){if(key.startsWith(options.attributeNamePrefix)){const rawName=key.substring(options.attributeNamePrefix.length);rawAttrs[rawName]=attrs[key]}else{rawAttrs[key]=attrs[key]}}return rawAttrs}function extractNamespace(rawTagName){if(!rawTagName||typeof rawTagName!=="string")return void 0;const colonIndex=rawTagName.indexOf(":");if(colonIndex!==-1&&colonIndex>0){const ns=rawTagName.substring(0,colonIndex);if(ns!=="xmlns"){return ns}}return void 0}var OrderedObjParser=class{constructor(options,externalEntities){this.options=options;this.currentNode=null;this.tagsNodeStack=[];this.parseXml=parseXml;this.parseTextData=parseTextData;this.resolveNameSpace=resolveNameSpace;this.buildAttributesMap=buildAttributesMap;this.isItStopNode=isItStopNode;this.replaceEntitiesValue=replaceEntitiesValue;this.readStopNodeData=readStopNodeData;this.saveTextToParentTag=saveTextToParentTag;this.addChild=addChild;this.ignoreAttributesFn=getIgnoreAttributesFn(this.options.ignoreAttributes);this.entityExpansionCount=0;this.currentExpandedLength=0;this.doctypefound=false;let namedEntities={...XML};if(this.options.entityDecoder){this.entityDecoder=this.options.entityDecoder}else{if(typeof this.options.htmlEntities==="object")namedEntities=this.options.htmlEntities;else if(this.options.htmlEntities===true)namedEntities={...COMMON_HTML,...CURRENCY};this.entityDecoder=new EntityDecoder({namedEntities:{...namedEntities,...externalEntities},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo},onInputEntity:(name,value)=>isUnsafe(value,[html_default,xml_default])?ENTITY_ACTION.BLOCK:ENTITY_ACTION.ALLOW})}this.matcher=new Matcher;this.readonlyMatcher=this.matcher.readOnly();this.isCurrentNodeStopNode=false;this.stopNodeExpressionsSet=new ExpressionSet;const stopNodesOpts=this.options.stopNodes;if(stopNodesOpts&&stopNodesOpts.length>0){for(let i=0;i<stopNodesOpts.length;i++){const stopNodeExp=stopNodesOpts[i];if(typeof stopNodeExp==="string"){this.stopNodeExpressionsSet.add(new Expression(stopNodeExp))}else if(stopNodeExp instanceof Expression){this.stopNodeExpressionsSet.add(stopNodeExp)}}this.stopNodeExpressionsSet.seal()}}};function parseTextData(val,tagName,jPath,dontTrim,hasAttributes,isLeafNode,escapeEntities){const options=this.options;if(val!==void 0){if(options.trimValues&&!dontTrim){val=val.trim()}if(val.length>0){if(!escapeEntities)val=this.replaceEntitiesValue(val,tagName,jPath);const jPathOrMatcher=options.jPath?jPath.toString():jPath;const newval=options.tagValueProcessor(tagName,val,jPathOrMatcher,hasAttributes,isLeafNode);if(newval===null||newval===void 0){return val}else if(typeof newval!==typeof val||newval!==val){return newval}else if(options.trimValues){return parseValue(val,options.parseTagValue,options.numberParseOptions)}else{const trimmedVal=val.trim();if(trimmedVal===val){return parseValue(val,options.parseTagValue,options.numberParseOptions)}else{return val}}}}}function resolveNameSpace(tagname){if(this.options.removeNSPrefix){const tags=tagname.split(":");const prefix=tagname.charAt(0)==="/"?"/":"";if(tags[0]==="xmlns"){return""}if(tags.length===2){tagname=prefix+tags[1]}}return tagname}var attrsRegx=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function buildAttributesMap(attrStr,jPath,tagName,force=false){const options=this.options;if(force===true||options.ignoreAttributes!==true&&typeof attrStr==="string"){const matches=getAllMatches(attrStr,attrsRegx);const len=matches.length;const attrs={};const processedVals=new Array(len);let hasRawAttrs=false;const rawAttrsForMatcher={};for(let i=0;i<len;i++){const attrName=this.resolveNameSpace(matches[i][1]);const oldVal=matches[i][4];if(attrName.length&&oldVal!==void 0){let val=oldVal;if(options.trimValues)val=val.trim();val=this.replaceEntitiesValue(val,tagName,this.readonlyMatcher);processedVals[i]=val;rawAttrsForMatcher[attrName]=val;hasRawAttrs=true}}if(hasRawAttrs&&typeof jPath==="object"&&jPath.updateCurrent){jPath.updateCurrent(rawAttrsForMatcher)}const jPathStr=options.jPath?jPath.toString():this.readonlyMatcher;let hasAttrs=false;for(let i=0;i<len;i++){const attrName=this.resolveNameSpace(matches[i][1]);if(this.ignoreAttributesFn(attrName,jPathStr))continue;let aName=options.attributeNamePrefix+attrName;if(attrName.length){if(options.transformAttributeName){aName=options.transformAttributeName(aName)}aName=sanitizeName(aName,options);if(matches[i][4]!==void 0){const oldVal=processedVals[i];const newVal=options.attributeValueProcessor(attrName,oldVal,jPathStr);if(newVal===null||newVal===void 0){attrs[aName]=oldVal}else if(typeof newVal!==typeof oldVal||newVal!==oldVal){attrs[aName]=newVal}else{attrs[aName]=parseValue(oldVal,options.parseAttributeValue,options.numberParseOptions)}hasAttrs=true}else if(options.allowBooleanAttributes){attrs[aName]=true;hasAttrs=true}}}if(!hasAttrs)return;if(options.attributesGroupName&&!options.preserveOrder){const attrCollection={};attrCollection[options.attributesGroupName]=attrs;return attrCollection}return attrs}}var parseXml=function(xmlData){xmlData=xmlData.replace(/\r\n?/g,"\n");const xmlObj=new XmlNode("!xml");let currentNode=xmlObj;let textData="";this.matcher.reset();this.entityDecoder.reset();this.entityExpansionCount=0;this.currentExpandedLength=0;this.doctypefound=false;const options=this.options;const docTypeReader=new DocTypeReader(options.processEntities);const xmlLen=xmlData.length;for(let i=0;i<xmlLen;i++){const ch=xmlData[i];if(ch==="<"){const c1=xmlData.charCodeAt(i+1);if(c1===47){const closeIndex=findClosingIndex(xmlData,">",i,"Closing Tag is not closed.");let tagName=xmlData.substring(i+2,closeIndex).trim();if(options.removeNSPrefix){const colonIndex=tagName.indexOf(":");if(colonIndex!==-1){tagName=tagName.substr(colonIndex+1)}}tagName=transformTagName(options.transformTagName,tagName,"",options).tagName;if(currentNode){textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher)}const lastTagName=this.matcher.getCurrentTag();if(tagName&&options.unpairedTagsSet.has(tagName)){throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`)}if(lastTagName&&options.unpairedTagsSet.has(lastTagName)){this.matcher.pop();this.tagsNodeStack.pop()}this.matcher.pop();this.isCurrentNodeStopNode=false;currentNode=this.tagsNodeStack.pop();textData="";i=closeIndex}else if(c1===63){let tagData=readTagExp(xmlData,i,false,"?>");if(!tagData)throw new Error("Pi Tag is not closed.");textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher);const attsMap=this.buildAttributesMap(tagData.tagExp,this.matcher,tagData.tagName,true);if(attsMap){const ver=attsMap[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(ver)||1);docTypeReader.setXmlVersion(Number(ver)||1)}if(options.ignoreDeclaration&&tagData.tagName==="?xml"||options.ignorePiTags){}else{const childNode=new XmlNode(tagData.tagName);childNode.add(options.textNodeName,"");if(tagData.tagName!==tagData.tagExp&&tagData.attrExpPresent&&options.ignoreAttributes!==true){childNode[":@"]=attsMap}this.addChild(currentNode,childNode,this.readonlyMatcher,i)}i=tagData.closeIndex+1}else if(c1===33&&xmlData.charCodeAt(i+2)===45&&xmlData.charCodeAt(i+3)===45){const endIndex=findClosingIndex(xmlData,"-->",i+4,"Comment is not closed.");if(options.commentPropName){const comment=xmlData.substring(i+4,endIndex-2);textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher);currentNode.add(options.commentPropName,[{[options.textNodeName]:comment}])}i=endIndex}else if(c1===33&&xmlData.charCodeAt(i+2)===68){if(this.doctypefound)throw new Error("Multiple DOCTYPE declarations found.");this.doctypefound=true;const result=docTypeReader.readDocType(xmlData,i);this.entityDecoder.addInputEntities(result.entities);i=result.i}else if(c1===33&&xmlData.charCodeAt(i+2)===91){const closeIndex=findClosingIndex(xmlData,"]]>",i,"CDATA is not closed.")-2;const tagExp=xmlData.substring(i+9,closeIndex);textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher);let val=this.parseTextData(tagExp,currentNode.tagname,this.readonlyMatcher,true,false,true,true);if(val==void 0)val="";if(options.cdataPropName){currentNode.add(options.cdataPropName,[{[options.textNodeName]:tagExp}])}else{currentNode.add(options.textNodeName,val)}i=closeIndex+2}else{let result=readTagExp(xmlData,i,options.removeNSPrefix);if(!result){const context=xmlData.substring(Math.max(0,i-50),Math.min(xmlLen,i+50));throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`)}let tagName=result.tagName;const rawTagName=result.rawTagName;let tagExp=result.tagExp;let attrExpPresent=result.attrExpPresent;let closeIndex=result.closeIndex;({tagName,tagExp}=transformTagName(options.transformTagName,tagName,tagExp,options));if(options.strictReservedNames&&(tagName===options.commentPropName||tagName===options.cdataPropName||tagName===options.textNodeName||tagName===options.attributesGroupName)){throw new Error(`Invalid tag name: ${tagName}`)}if(currentNode&&textData){if(currentNode.tagname!=="!xml"){textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher,false)}}const lastTag=currentNode;if(lastTag&&options.unpairedTagsSet.has(lastTag.tagname)){currentNode=this.tagsNodeStack.pop();this.matcher.pop()}let isSelfClosing=false;if(tagExp.length>0&&tagExp.lastIndexOf("/")===tagExp.length-1){isSelfClosing=true;if(tagName[tagName.length-1]==="/"){tagName=tagName.substr(0,tagName.length-1);tagExp=tagName}else{tagExp=tagExp.substr(0,tagExp.length-1)}attrExpPresent=tagName!==tagExp}let prefixedAttrs=null;let rawAttrs={};let namespace=void 0;namespace=extractNamespace(rawTagName);if(tagName!==xmlObj.tagname){this.matcher.push(tagName,{},namespace)}if(tagName!==tagExp&&attrExpPresent){prefixedAttrs=this.buildAttributesMap(tagExp,this.matcher,tagName);if(prefixedAttrs){rawAttrs=extractRawAttributes(prefixedAttrs,options)}}if(tagName!==xmlObj.tagname){this.isCurrentNodeStopNode=this.isItStopNode()}const startIndex=i;if(this.isCurrentNodeStopNode){let tagContent="";if(isSelfClosing){i=result.closeIndex}else if(options.unpairedTagsSet.has(tagName)){i=result.closeIndex}else{const result2=this.readStopNodeData(xmlData,rawTagName,closeIndex+1);if(!result2)throw new Error(`Unexpected end of ${rawTagName}`);i=result2.i;tagContent=result2.tagContent}const childNode=new XmlNode(tagName);if(prefixedAttrs){childNode[":@"]=prefixedAttrs}childNode.add(options.textNodeName,tagContent);this.matcher.pop();this.isCurrentNodeStopNode=false;this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex)}else{if(isSelfClosing){({tagName,tagExp}=transformTagName(options.transformTagName,tagName,tagExp,options));const childNode=new XmlNode(tagName);if(prefixedAttrs){childNode[":@"]=prefixedAttrs}this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex);this.matcher.pop();this.isCurrentNodeStopNode=false}else if(options.unpairedTagsSet.has(tagName)){const childNode=new XmlNode(tagName);if(prefixedAttrs){childNode[":@"]=prefixedAttrs}this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex);this.matcher.pop();this.isCurrentNodeStopNode=false;i=result.closeIndex;continue}else{const childNode=new XmlNode(tagName);if(this.tagsNodeStack.length>options.maxNestedTags){throw new Error("Maximum nested tags exceeded")}this.tagsNodeStack.push(currentNode);if(prefixedAttrs){childNode[":@"]=prefixedAttrs}this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex);currentNode=childNode}textData="";i=closeIndex}}}else{textData+=xmlData[i]}}return xmlObj.child};function addChild(currentNode,childNode,matcher,startIndex){if(!this.options.captureMetaData)startIndex=void 0;const jPathOrMatcher=this.options.jPath?matcher.toString():matcher;const result=this.options.updateTag(childNode.tagname,jPathOrMatcher,childNode[":@"]);if(result===false){}else if(typeof result==="string"){childNode.tagname=result;currentNode.addChild(childNode,startIndex)}else{currentNode.addChild(childNode,startIndex)}}function replaceEntitiesValue(val,tagName,jPath){const entityConfig=this.options.processEntities;if(!entityConfig||!entityConfig.enabled){return val}if(entityConfig.allowedTags){const jPathOrMatcher=this.options.jPath?jPath.toString():jPath;const allowed=Array.isArray(entityConfig.allowedTags)?entityConfig.allowedTags.includes(tagName):entityConfig.allowedTags(tagName,jPathOrMatcher);if(!allowed){return val}}if(entityConfig.tagFilter){const jPathOrMatcher=this.options.jPath?jPath.toString():jPath;if(!entityConfig.tagFilter(tagName,jPathOrMatcher)){return val}}return this.entityDecoder.decode(val)}function saveTextToParentTag(textData,parentNode,matcher,isLeafNode){if(textData){if(isLeafNode===void 0)isLeafNode=parentNode.child.length===0;textData=this.parseTextData(textData,parentNode.tagname,matcher,false,parentNode[":@"]?Object.keys(parentNode[":@"]).length!==0:false,isLeafNode);if(textData!==void 0&&textData!=="")parentNode.add(this.options.textNodeName,textData);textData=""}return textData}function isItStopNode(){if(this.stopNodeExpressionsSet.size===0)return false;return this.matcher.matchesAny(this.stopNodeExpressionsSet)}function tagExpWithClosingIndex(xmlData,i,closingChar=">"){let attrBoundary=0;const len=xmlData.length;const closeCode0=closingChar.charCodeAt(0);const closeCode1=closingChar.length>1?closingChar.charCodeAt(1):-1;let result="";let segmentStart=i;for(let index=i;index<len;index++){const code=xmlData.charCodeAt(index);if(attrBoundary){if(code===attrBoundary)attrBoundary=0}else if(code===34||code===39){attrBoundary=code}else if(code===closeCode0){if(closeCode1!==-1){if(xmlData.charCodeAt(index+1)===closeCode1){result+=xmlData.substring(segmentStart,index);return{data:result,index}}}else{result+=xmlData.substring(segmentStart,index);return{data:result,index}}}else if(code===9&&!attrBoundary){result+=xmlData.substring(segmentStart,index)+" ";segmentStart=index+1}}}function findClosingIndex(xmlData,str,i,errMsg){const closingIndex=xmlData.indexOf(str,i);if(closingIndex===-1){throw new Error(errMsg)}else{return closingIndex+str.length-1}}function findClosingChar(xmlData,char,i,errMsg){const closingIndex=xmlData.indexOf(char,i);if(closingIndex===-1)throw new Error(errMsg);return closingIndex}function readTagExp(xmlData,i,removeNSPrefix,closingChar=">"){const result=tagExpWithClosingIndex(xmlData,i+1,closingChar);if(!result)return;let tagExp=result.data;const closeIndex=result.index;const separatorIndex=tagExp.search(/\s/);let tagName=tagExp;let attrExpPresent=true;if(separatorIndex!==-1){tagName=tagExp.substring(0,separatorIndex);tagExp=tagExp.substring(separatorIndex+1).trimStart()}const rawTagName=tagName;if(removeNSPrefix){const colonIndex=tagName.indexOf(":");if(colonIndex!==-1){tagName=tagName.substr(colonIndex+1);attrExpPresent=tagName!==result.data.substr(colonIndex+1)}}return{tagName,tagExp,closeIndex,attrExpPresent,rawTagName}}function readStopNodeData(xmlData,tagName,i){const startIndex=i;let openTagCount=1;const xmllen=xmlData.length;for(;i<xmllen;i++){if(xmlData[i]==="<"){const c1=xmlData.charCodeAt(i+1);if(c1===47){const closeIndex=findClosingChar(xmlData,">",i,`${tagName} is not closed`);let closeTagName=xmlData.substring(i+2,closeIndex).trim();if(closeTagName===tagName){openTagCount--;if(openTagCount===0){return{tagContent:xmlData.substring(startIndex,i),i:closeIndex}}}i=closeIndex}else if(c1===63){const closeIndex=findClosingIndex(xmlData,"?>",i+1,"StopNode is not closed.");i=closeIndex}else if(c1===33&&xmlData.charCodeAt(i+2)===45&&xmlData.charCodeAt(i+3)===45){const closeIndex=findClosingIndex(xmlData,"-->",i+3,"StopNode is not closed.");i=closeIndex}else if(c1===33&&xmlData.charCodeAt(i+2)===91){const closeIndex=findClosingIndex(xmlData,"]]>",i,"StopNode is not closed.")-2;i=closeIndex}else{const tagData=readTagExp(xmlData,i,false);if(tagData){const openTagName=tagData&&tagData.tagName;if(openTagName===tagName&&tagData.tagExp[tagData.tagExp.length-1]!=="/"){openTagCount++}i=tagData.closeIndex}}}}}function parseValue(val,shouldParse,options){if(shouldParse&&typeof val==="string"){const newval=val.trim();if(newval==="true")return true;else if(newval==="false")return false;else return toNumber(val,options)}else{if(isExist(val)){return val}else{return""}}}function transformTagName(fn,tagName,tagExp,options){if(fn){const newTagName=fn(tagName);if(tagExp===tagName){tagExp=newTagName}tagName=newTagName}tagName=sanitizeName(tagName,options);return{tagName,tagExp}}function sanitizeName(name,options){if(criticalProperties.includes(name)){throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`)}else if(DANGEROUS_PROPERTY_NAMES.includes(name)){return options.onDangerousProperty(name)}return name}var METADATA_SYMBOL2=XmlNode.getMetaDataSymbol();function stripAttributePrefix(attrs,prefix){if(!attrs||typeof attrs!=="object")return{};if(!prefix)return attrs;const rawAttrs={};for(const key in attrs){if(key.startsWith(prefix)){const rawName=key.substring(prefix.length);rawAttrs[rawName]=attrs[key]}else{rawAttrs[key]=attrs[key]}}return rawAttrs}function prettify(node,options,matcher,readonlyMatcher){return compress(node,options,matcher,readonlyMatcher)}function compress(arr,options,matcher,readonlyMatcher){let text;const compressedObj={};for(let i=0;i<arr.length;i++){const tagObj=arr[i];const property=propName(tagObj);if(property!==void 0&&property!==options.textNodeName){const rawAttrs=stripAttributePrefix(tagObj[":@"]||{},options.attributeNamePrefix);matcher.push(property,rawAttrs)}if(property===options.textNodeName){if(text===void 0)text=tagObj[property];else text+=""+tagObj[property]}else if(property===void 0){continue}else if(tagObj[property]){let val=compress(tagObj[property],options,matcher,readonlyMatcher);const isLeaf=isLeafTag(val,options);if(Object.keys(val).length===0&&options.alwaysCreateTextNode){val[options.textNodeName]=""}if(tagObj[":@"]){assignAttributes(val,tagObj[":@"],readonlyMatcher,options)}else if(Object.keys(val).length===1&&val[options.textNodeName]!==void 0&&!options.alwaysCreateTextNode){val=val[options.textNodeName]}else if(Object.keys(val).length===0){if(options.alwaysCreateTextNode)val[options.textNodeName]="";else val=""}if(tagObj[METADATA_SYMBOL2]!==void 0&&typeof val==="object"&&val!==null){val[METADATA_SYMBOL2]=tagObj[METADATA_SYMBOL2]}if(compressedObj[property]!==void 0&&Object.prototype.hasOwnProperty.call(compressedObj,property)){if(!Array.isArray(compressedObj[property])){compressedObj[property]=[compressedObj[property]]}compressedObj[property].push(val)}else{const jPathOrMatcher=options.jPath?readonlyMatcher.toString():readonlyMatcher;if(options.isArray(property,jPathOrMatcher,isLeaf)){compressedObj[property]=[val]}else{compressedObj[property]=val}}if(property!==void 0&&property!==options.textNodeName){matcher.pop()}}}if(typeof text==="string"){if(text.length>0)compressedObj[options.textNodeName]=text}else if(text!==void 0)compressedObj[options.textNodeName]=text;return compressedObj}function propName(obj){const keys=Object.keys(obj);for(let i=0;i<keys.length;i++){const key=keys[i];if(key!==":@")return key}}function assignAttributes(obj,attrMap,readonlyMatcher,options){if(attrMap){const keys=Object.keys(attrMap);const len=keys.length;for(let i=0;i<len;i++){const atrrName=keys[i];const rawAttrName=atrrName.startsWith(options.attributeNamePrefix)?atrrName.substring(options.attributeNamePrefix.length):atrrName;const jPathOrMatcher=options.jPath?readonlyMatcher.toString()+"."+rawAttrName:readonlyMatcher;if(options.isArray(atrrName,jPathOrMatcher,true,true)){obj[atrrName]=[attrMap[atrrName]]}else{obj[atrrName]=attrMap[atrrName]}}}}function isLeafTag(obj,options){const{textNodeName}=options;const propCount=Object.keys(obj).length;if(propCount===0){return true}if(propCount===1&&(obj[textNodeName]||typeof obj[textNodeName]==="boolean"||obj[textNodeName]===0)){return true}return false}var XMLParser=class{constructor(options){this.externalEntities={};this.options=buildOptions(options)}parse(xmlData,validationOption){if(typeof xmlData!=="string"&&xmlData.toString){xmlData=xmlData.toString()}else if(typeof xmlData!=="string"){throw new Error("XML data is accepted in String or Bytes[] form.")}if(validationOption){if(validationOption===true)validationOption={};const result=validate(xmlData,validationOption);if(result!==true){throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)}}const orderedObjParser=new OrderedObjParser(this.options,this.externalEntities);const orderedResult=orderedObjParser.parseXml(xmlData);if(this.options.preserveOrder||orderedResult===void 0)return orderedResult;else return prettify(orderedResult,this.options,orderedObjParser.matcher,orderedObjParser.readonlyMatcher)}addEntity(key,value){if(value.indexOf("&")!==-1){throw new Error("Entity value can't have '&'")}else if(key.indexOf("&")!==-1||key.indexOf(";")!==-1){throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'")}else if(value==="&"){throw new Error("An entity with value '&' is not permitted")}else{this.externalEntities[key]=value}}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}};var XMLValidator={validate};var SKIPPED_EXTENSIONS=/\.(?:avif|bmp|css|csv|docx?|eot|gif|gz|ico|jpe?g|js|json|map|mp3|mp4|mov|ogg|otf|pdf|png|pptx?|rar|rss|svg|tar|tiff?|ttf|txt|wav|webm|webp|woff2?|xlsx?|xml|zip)$/i;function normalizeUrl(input,base,{includeQuery=false}={}){let url;try{url=base?new URL(input,base):new URL(input)}catch{return null}if(url.protocol!=="http:"&&url.protocol!=="https:"){return null}url.hash="";if(!includeQuery){url.search=""}if(url.pathname.length>1&&url.pathname.endsWith("/")){url.pathname=url.pathname.replace(/\/+$/,"")}return url.href}function isSameOrigin(url,origin){try{return new URL(url).origin===origin}catch{return false}}function isCrawlableUrl(url){try{const parsed=new URL(url);return!SKIPPED_EXTENSIONS.test(parsed.pathname)}catch{return false}}var MAX_SITEMAP_BYTES=10*1024*1024;var MAX_SITEMAPS=100;var DEFAULT_SITEMAP_LIMIT=5e4;var parser=new XMLParser({ignoreAttributes:false,removeNSPrefix:true,trimValues:true});function record(value){return value&&typeof value==="object"&&!Array.isArray(value)?value:null}function locations(value){const entries=value===void 0?[]:Array.isArray(value)?value:[value];return entries.flatMap(entry=>{const location=record(entry)?.loc;return typeof location==="string"?[location]:[]})}function decodeSitemap(buffer,url,contentType){const gzip=url.toLowerCase().endsWith(".gz")||contentType.includes("gzip")||buffer[0]===31&&buffer[1]===139;const decoded=gzip?gunzipSync(buffer):buffer;if(decoded.byteLength>MAX_SITEMAP_BYTES)throw new Error(`sitemap exceeds ${MAX_SITEMAP_BYTES} bytes after decompression: ${url}`);return decoded.toString("utf8").replace(/^\uFEFF/,"")}function parseSitemap(xml,url){const validation=XMLValidator.validate(xml);if(validation!==true)throw new Error(`invalid sitemap XML at ${url}: ${validation.err.msg}`);const data=record(parser.parse(xml));const sitemapIndex=record(data?.sitemapindex);if(sitemapIndex){return{kind:"index",locations:locations(sitemapIndex.sitemap)}}const urlSet=record(data?.urlset);if(urlSet){return{kind:"urlset",locations:locations(urlSet.url)}}throw new Error(`XML is not a sitemap urlset or sitemapindex: ${url}`)}function policy(options){return{fetch:options.fetch??globalThis.fetch,timeout:options.timeout,maxRedirects:options.maxRedirects??10,retries:options.retries??2,signal:options.signal,gate:options.requestGate?async url=>options.requestGate?.(url):void 0,onEvent:options.onEvent}}async function fetchSitemap(url,options){const{response}=await fetchWithRetry(url,{headers:{accept:"application/xml,text/xml,application/gzip,text/plain;q=0.9,*/*;q=0.1","user-agent":options.userAgent}},policy(options));if(!response.ok){await response.body?.cancel();throw new Error(`sitemap returned HTTP ${response.status}: ${url}`)}const{buffer}=await readResponseBody(response,MAX_SITEMAP_BYTES);return decodeSitemap(buffer,url,response.headers.get("content-type")?.toLowerCase()??"")}async function isSitemapResponse(url,options){try{const xml=await fetchSitemap(url,options);parseSitemap(xml,url);return true}catch{return false}}async function discoverSitemapUrl(inputUrl,options){const startUrl=normalizeUrl(inputUrl,void 0);if(!startUrl)throw new Error(`invalid start URL: ${inputUrl}`);const origin=new URL(startUrl).origin;const robotsUrl=new URL("/robots.txt",origin).href;try{if(options.robotsBody!==void 0){for(const match of options.robotsBody.matchAll(/^sitemap:\s*(\S+)\s*$/gim)){const location=match[1];if(!location)continue;const candidate=normalizeUrl(location,robotsUrl,{includeQuery:true});if(candidate&&isSameOrigin(candidate,origin))return candidate}}else{const{response}=await fetchWithRetry(robotsUrl,{headers:{accept:"text/plain,*/*;q=0.1","user-agent":options.userAgent}},policy({...options,siteOrigin:origin}));if(response.ok){const{text}=await readResponseBody(response,512*1024);for(const match of text.matchAll(/^sitemap:\s*(\S+)\s*$/gim)){const location=match[1];if(!location)continue;const candidate=normalizeUrl(location,robotsUrl,{includeQuery:true});if(candidate&&isSameOrigin(candidate,origin))return candidate}}else await response.body?.cancel()}}catch{}for(const path of["/sitemap.xml","/sitemap.xml.gz","/sitemap_index.xml"]){const candidate=new URL(path,origin).href;if(await isSitemapResponse(candidate,{...options,siteOrigin:origin}))return candidate}return null}async function loadSitemapUrls(inputUrl,options){const sitemapUrl=normalizeUrl(inputUrl,void 0,{includeQuery:true});if(!sitemapUrl)throw new Error(`invalid sitemap URL: ${inputUrl}`);const sitemapOrigin=new URL(sitemapUrl).origin;const sitemapQueue=[sitemapUrl];const visitedSitemaps=new Set;const pageUrls=[];const pageSet=new Set;const limit=options.maxUrls??DEFAULT_SITEMAP_LIMIT;let truncated=false;while(sitemapQueue.length>0&&visitedSitemaps.size<MAX_SITEMAPS&&pageUrls.length<limit){const currentUrl=sitemapQueue.shift();if(visitedSitemaps.has(currentUrl))continue;visitedSitemaps.add(currentUrl);const parsed=parseSitemap(await fetchSitemap(currentUrl,options),currentUrl);if(parsed.kind==="index"){for(const location of parsed.locations){const child=normalizeUrl(location,currentUrl,{includeQuery:true});if(child&&isSameOrigin(child,sitemapOrigin)&&!visitedSitemaps.has(child)&&!sitemapQueue.includes(child))sitemapQueue.push(child)}sitemapQueue.sort();continue}for(const location of parsed.locations){const pageUrl=normalizeUrl(location,currentUrl,{includeQuery:options.includeQuery??false});if(!pageUrl||pageSet.has(pageUrl)||!isSameOrigin(pageUrl,options.siteOrigin)||!isCrawlableUrl(pageUrl))continue;pageSet.add(pageUrl);pageUrls.push(pageUrl);if(pageUrls.length>=limit){truncated=true;break}}}if(sitemapQueue.length>0||visitedSitemaps.size>=MAX_SITEMAPS)truncated=true;return{url:sitemapUrl,urls:pageUrls.sort(),sitemapCount:visitedSitemaps.size,truncated,error:null}}async function emit(options,event){await options.onEvent?.(event)}async function planScan(configInput,options={}){const config=resolveConfig(configInput);const startUrl=normalizeUrl(config.url,void 0,{includeQuery:config.includeQuery});if(!startUrl)throw new Error(`invalid start URL: ${config.url}`);const origin=new URL(startUrl).origin;const fetch=options.fetch??globalThis.fetch;const requestGate=createPerOriginRequestGate(config.delay);const logger=options.logger??NOOP_LOGGER;await emit(options,{type:"plan-start",url:startUrl});const robots=await fetchRobots(startUrl,{userAgent:DEFAULT_USER_AGENT,timeout:config.timeout,maxRedirects:config.maxRedirects,retries:2,fetch,signal:options.signal,requestGate,onEvent:options.onEvent,logger});await emit(options,{type:"robots",robots});let sitemapUrl=null;if(config.sitemap==="auto"){sitemapUrl=await discoverSitemapUrl(startUrl,{timeout:config.timeout,maxRedirects:config.maxRedirects,userAgent:DEFAULT_USER_AGENT,fetch,signal:options.signal,requestGate,onEvent:options.onEvent,robotsBody:robots.body})}else if(config.sitemap!=="none"){sitemapUrl=config.sitemap}let sitemap=null;if(sitemapUrl){try{sitemap=await loadSitemapUrls(sitemapUrl,{siteOrigin:origin,includeQuery:config.includeQuery,maxUrls:5e4,timeout:config.timeout,maxRedirects:config.maxRedirects,retries:2,userAgent:DEFAULT_USER_AGENT,fetch,signal:options.signal,requestGate,onEvent:options.onEvent})}catch(error){sitemap={url:sitemapUrl,urls:[],sitemapCount:0,truncated:false,error:error instanceof Error?error.message:String(error)};logger.warn(`Could not load sitemap ${sitemapUrl}: ${sitemap.error}`)}}const candidateUrls=sitemap?[...new Set([startUrl,...sitemap.urls])].sort((left,right)=>left===startUrl?-1:right===startUrl?1:left.localeCompare(right)):[startUrl];const candidateCount=sitemap?candidateUrls.length:null;await emit(options,{type:"sitemap",sitemap,candidateCount});return{planVersion:1,config,startUrl,origin,userAgent:DEFAULT_USER_AGENT,robots,sitemap,candidateUrls,candidateCount,mode:sitemap?"sitemap":"links"}}import{createHash as createHash4}from"node:crypto";var UNDEFINED_CODE_POINTS=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]);var REPLACEMENT_CHARACTER="\uFFFD";var CODE_POINTS;(function(CODE_POINTS2){CODE_POINTS2[CODE_POINTS2["EOF"]=-1]="EOF";CODE_POINTS2[CODE_POINTS2["NULL"]=0]="NULL";CODE_POINTS2[CODE_POINTS2["TABULATION"]=9]="TABULATION";CODE_POINTS2[CODE_POINTS2["CARRIAGE_RETURN"]=13]="CARRIAGE_RETURN";CODE_POINTS2[CODE_POINTS2["LINE_FEED"]=10]="LINE_FEED";CODE_POINTS2[CODE_POINTS2["FORM_FEED"]=12]="FORM_FEED";CODE_POINTS2[CODE_POINTS2["SPACE"]=32]="SPACE";CODE_POINTS2[CODE_POINTS2["EXCLAMATION_MARK"]=33]="EXCLAMATION_MARK";CODE_POINTS2[CODE_POINTS2["QUOTATION_MARK"]=34]="QUOTATION_MARK";CODE_POINTS2[CODE_POINTS2["AMPERSAND"]=38]="AMPERSAND";CODE_POINTS2[CODE_POINTS2["APOSTROPHE"]=39]="APOSTROPHE";CODE_POINTS2[CODE_POINTS2["HYPHEN_MINUS"]=45]="HYPHEN_MINUS";CODE_POINTS2[CODE_POINTS2["SOLIDUS"]=47]="SOLIDUS";CODE_POINTS2[CODE_POINTS2["DIGIT_0"]=48]="DIGIT_0";CODE_POINTS2[CODE_POINTS2["DIGIT_9"]=57]="DIGIT_9";CODE_POINTS2[CODE_POINTS2["SEMICOLON"]=59]="SEMICOLON";CODE_POINTS2[CODE_POINTS2["LESS_THAN_SIGN"]=60]="LESS_THAN_SIGN";CODE_POINTS2[CODE_POINTS2["EQUALS_SIGN"]=61]="EQUALS_SIGN";CODE_POINTS2[CODE_POINTS2["GREATER_THAN_SIGN"]=62]="GREATER_THAN_SIGN";CODE_POINTS2[CODE_POINTS2["QUESTION_MARK"]=63]="QUESTION_MARK";CODE_POINTS2[CODE_POINTS2["LATIN_CAPITAL_A"]=65]="LATIN_CAPITAL_A";CODE_POINTS2[CODE_POINTS2["LATIN_CAPITAL_Z"]=90]="LATIN_CAPITAL_Z";CODE_POINTS2[CODE_POINTS2["RIGHT_SQUARE_BRACKET"]=93]="RIGHT_SQUARE_BRACKET";CODE_POINTS2[CODE_POINTS2["GRAVE_ACCENT"]=96]="GRAVE_ACCENT";CODE_POINTS2[CODE_POINTS2["LATIN_SMALL_A"]=97]="LATIN_SMALL_A";CODE_POINTS2[CODE_POINTS2["LATIN_SMALL_Z"]=122]="LATIN_SMALL_Z"})(CODE_POINTS||(CODE_POINTS={}));var SEQUENCES={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function isSurrogate(cp){return cp>=55296&&cp<=57343}function isSurrogatePair(cp){return cp>=56320&&cp<=57343}function getSurrogatePairCodePoint(cp1,cp2){return(cp1-55296)*1024+9216+cp2}function isControlCodePoint(cp){return cp!==32&&cp!==10&&cp!==13&&cp!==9&&cp!==12&&cp>=1&&cp<=31||cp>=127&&cp<=159}function isUndefinedCodePoint(cp){return cp>=64976&&cp<=65007||UNDEFINED_CODE_POINTS.has(cp)}var ERR;(function(ERR2){ERR2["controlCharacterInInputStream"]="control-character-in-input-stream";ERR2["noncharacterInInputStream"]="noncharacter-in-input-stream";ERR2["surrogateInInputStream"]="surrogate-in-input-stream";ERR2["nonVoidHtmlElementStartTagWithTrailingSolidus"]="non-void-html-element-start-tag-with-trailing-solidus";ERR2["endTagWithAttributes"]="end-tag-with-attributes";ERR2["endTagWithTrailingSolidus"]="end-tag-with-trailing-solidus";ERR2["unexpectedSolidusInTag"]="unexpected-solidus-in-tag";ERR2["unexpectedNullCharacter"]="unexpected-null-character";ERR2["unexpectedQuestionMarkInsteadOfTagName"]="unexpected-question-mark-instead-of-tag-name";ERR2["invalidFirstCharacterOfTagName"]="invalid-first-character-of-tag-name";ERR2["unexpectedEqualsSignBeforeAttributeName"]="unexpected-equals-sign-before-attribute-name";ERR2["missingEndTagName"]="missing-end-tag-name";ERR2["unexpectedCharacterInAttributeName"]="unexpected-character-in-attribute-name";ERR2["unknownNamedCharacterReference"]="unknown-named-character-reference";ERR2["missingSemicolonAfterCharacterReference"]="missing-semicolon-after-character-reference";ERR2["unexpectedCharacterAfterDoctypeSystemIdentifier"]="unexpected-character-after-doctype-system-identifier";ERR2["unexpectedCharacterInUnquotedAttributeValue"]="unexpected-character-in-unquoted-attribute-value";ERR2["eofBeforeTagName"]="eof-before-tag-name";ERR2["eofInTag"]="eof-in-tag";ERR2["missingAttributeValue"]="missing-attribute-value";ERR2["missingWhitespaceBetweenAttributes"]="missing-whitespace-between-attributes";ERR2["missingWhitespaceAfterDoctypePublicKeyword"]="missing-whitespace-after-doctype-public-keyword";ERR2["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"]="missing-whitespace-between-doctype-public-and-system-identifiers";ERR2["missingWhitespaceAfterDoctypeSystemKeyword"]="missing-whitespace-after-doctype-system-keyword";ERR2["missingQuoteBeforeDoctypePublicIdentifier"]="missing-quote-before-doctype-public-identifier";ERR2["missingQuoteBeforeDoctypeSystemIdentifier"]="missing-quote-before-doctype-system-identifier";ERR2["missingDoctypePublicIdentifier"]="missing-doctype-public-identifier";ERR2["missingDoctypeSystemIdentifier"]="missing-doctype-system-identifier";ERR2["abruptDoctypePublicIdentifier"]="abrupt-doctype-public-identifier";ERR2["abruptDoctypeSystemIdentifier"]="abrupt-doctype-system-identifier";ERR2["cdataInHtmlContent"]="cdata-in-html-content";ERR2["incorrectlyOpenedComment"]="incorrectly-opened-comment";ERR2["eofInScriptHtmlCommentLikeText"]="eof-in-script-html-comment-like-text";ERR2["eofInDoctype"]="eof-in-doctype";ERR2["nestedComment"]="nested-comment";ERR2["abruptClosingOfEmptyComment"]="abrupt-closing-of-empty-comment";ERR2["eofInComment"]="eof-in-comment";ERR2["incorrectlyClosedComment"]="incorrectly-closed-comment";ERR2["eofInCdata"]="eof-in-cdata";ERR2["absenceOfDigitsInNumericCharacterReference"]="absence-of-digits-in-numeric-character-reference";ERR2["nullCharacterReference"]="null-character-reference";ERR2["surrogateCharacterReference"]="surrogate-character-reference";ERR2["characterReferenceOutsideUnicodeRange"]="character-reference-outside-unicode-range";ERR2["controlCharacterReference"]="control-character-reference";ERR2["noncharacterCharacterReference"]="noncharacter-character-reference";ERR2["missingWhitespaceBeforeDoctypeName"]="missing-whitespace-before-doctype-name";ERR2["missingDoctypeName"]="missing-doctype-name";ERR2["invalidCharacterSequenceAfterDoctypeName"]="invalid-character-sequence-after-doctype-name";ERR2["duplicateAttribute"]="duplicate-attribute";ERR2["nonConformingDoctype"]="non-conforming-doctype";ERR2["missingDoctype"]="missing-doctype";ERR2["misplacedDoctype"]="misplaced-doctype";ERR2["endTagWithoutMatchingOpenElement"]="end-tag-without-matching-open-element";ERR2["closingOfElementWithOpenChildElements"]="closing-of-element-with-open-child-elements";ERR2["disallowedContentInNoscriptInHead"]="disallowed-content-in-noscript-in-head";ERR2["openElementsLeftAfterEof"]="open-elements-left-after-eof";ERR2["abandonedHeadElementChild"]="abandoned-head-element-child";ERR2["misplacedStartTagForHeadElement"]="misplaced-start-tag-for-head-element";ERR2["nestedNoscriptInHead"]="nested-noscript-in-head";ERR2["eofInElementThatCanContainOnlyText"]="eof-in-element-that-can-contain-only-text"})(ERR||(ERR={}));var DEFAULT_BUFFER_WATERLINE=1<<16;var Preprocessor=class{constructor(handler){this.handler=handler;this.html="";this.pos=-1;this.lastGapPos=-2;this.gapStack=[];this.skipNextNewLine=false;this.lastChunkWritten=false;this.endOfChunkHit=false;this.bufferWaterline=DEFAULT_BUFFER_WATERLINE;this.isEol=false;this.lineStartPos=0;this.droppedBufferSize=0;this.line=1;this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+Number(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(code,cpOffset){const{line,col,offset}=this;const startCol=col+cpOffset;const startOffset=offset+cpOffset;return{code,startLine:line,endLine:line,startCol,endCol:startCol,startOffset,endOffset:startOffset}}_err(code){if(this.handler.onParseError&&this.lastErrOffset!==this.offset){this.lastErrOffset=this.offset;this.handler.onParseError(this.getError(code,0))}}_addGap(){this.gapStack.push(this.lastGapPos);this.lastGapPos=this.pos}_processSurrogate(cp){if(this.pos!==this.html.length-1){const nextCp=this.html.charCodeAt(this.pos+1);if(isSurrogatePair(nextCp)){this.pos++;this._addGap();return getSurrogatePairCodePoint(cp,nextCp)}}else if(!this.lastChunkWritten){this.endOfChunkHit=true;return CODE_POINTS.EOF}this._err(ERR.surrogateInInputStream);return cp}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){if(this.willDropParsedChunk()){this.html=this.html.substring(this.pos);this.lineStartPos-=this.pos;this.droppedBufferSize+=this.pos;this.pos=0;this.lastGapPos=-2;this.gapStack.length=0}}write(chunk,isLastChunk){if(this.html.length>0){this.html+=chunk}else{this.html=chunk}this.endOfChunkHit=false;this.lastChunkWritten=isLastChunk}insertHtmlAtCurrentPos(chunk){this.html=this.html.substring(0,this.pos+1)+chunk+this.html.substring(this.pos+1);this.endOfChunkHit=false}startsWith(pattern,caseSensitive){if(this.pos+pattern.length>this.html.length){this.endOfChunkHit=!this.lastChunkWritten;return false}if(caseSensitive){return this.html.startsWith(pattern,this.pos)}for(let i=0;i<pattern.length;i++){const cp=this.html.charCodeAt(this.pos+i)|32;if(cp!==pattern.charCodeAt(i)){return false}}return true}peek(offset){const pos=this.pos+offset;if(pos>=this.html.length){this.endOfChunkHit=!this.lastChunkWritten;return CODE_POINTS.EOF}const code=this.html.charCodeAt(pos);return code===CODE_POINTS.CARRIAGE_RETURN?CODE_POINTS.LINE_FEED:code}advance(){this.pos++;if(this.isEol){this.isEol=false;this.line++;this.lineStartPos=this.pos}if(this.pos>=this.html.length){this.endOfChunkHit=!this.lastChunkWritten;return CODE_POINTS.EOF}let cp=this.html.charCodeAt(this.pos);if(cp===CODE_POINTS.CARRIAGE_RETURN){this.isEol=true;this.skipNextNewLine=true;return CODE_POINTS.LINE_FEED}if(cp===CODE_POINTS.LINE_FEED){this.isEol=true;if(this.skipNextNewLine){this.line--;this.skipNextNewLine=false;this._addGap();return this.advance()}}this.skipNextNewLine=false;if(isSurrogate(cp)){cp=this._processSurrogate(cp)}const isCommonValidRange=this.handler.onParseError===null||cp>31&&cp<127||cp===CODE_POINTS.LINE_FEED||cp===CODE_POINTS.CARRIAGE_RETURN||cp>159&&cp<64976;if(!isCommonValidRange){this._checkForProblematicCharacters(cp)}return cp}_checkForProblematicCharacters(cp){if(isControlCodePoint(cp)){this._err(ERR.controlCharacterInInputStream)}else if(isUndefinedCodePoint(cp)){this._err(ERR.noncharacterInInputStream)}}retreat(count){this.pos-=count;while(this.pos<this.lastGapPos){this.lastGapPos=this.gapStack.pop();this.pos--}this.isEol=false}};var TokenType;(function(TokenType2){TokenType2[TokenType2["CHARACTER"]=0]="CHARACTER";TokenType2[TokenType2["NULL_CHARACTER"]=1]="NULL_CHARACTER";TokenType2[TokenType2["WHITESPACE_CHARACTER"]=2]="WHITESPACE_CHARACTER";TokenType2[TokenType2["START_TAG"]=3]="START_TAG";TokenType2[TokenType2["END_TAG"]=4]="END_TAG";TokenType2[TokenType2["COMMENT"]=5]="COMMENT";TokenType2[TokenType2["DOCTYPE"]=6]="DOCTYPE";TokenType2[TokenType2["EOF"]=7]="EOF";TokenType2[TokenType2["HIBERNATION"]=8]="HIBERNATION"})(TokenType||(TokenType={}));function getTokenAttr(token,attrName){for(let i=token.attrs.length-1;i>=0;i--){if(token.attrs[i].name===attrName){return token.attrs[i].value}}return null}var decodeMap=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function replaceCodePoint(codePoint){if(codePoint>=55296&&codePoint<=57343||codePoint>1114111){return 65533}return decodeMap.get(codePoint)??codePoint}function decodeBase64(input){const binary=atob(input);const evenLength=binary.length&~1;const out=new Uint16Array(evenLength/2);for(let index=0,outIndex=0;index<evenLength;index+=2){const lo=binary.charCodeAt(index);const hi=binary.charCodeAt(index+1);out[outIndex++]=lo|hi<<8}return out}var htmlDecodeTree=decodeBase64("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0E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E_LENGTH"]=49152]="VALUE_LENGTH";BinTrieFlags2[BinTrieFlags2["FLAG13"]=8192]="FLAG13";BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"]=8064]="BRANCH_LENGTH";BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"]=127]="JUMP_TABLE"})(BinTrieFlags||(BinTrieFlags={}));var CharCodes;(function(CharCodes2){CharCodes2[CharCodes2["NUM"]=35]="NUM";CharCodes2[CharCodes2["SEMI"]=59]="SEMI";CharCodes2[CharCodes2["EQUALS"]=61]="EQUALS";CharCodes2[CharCodes2["ZERO"]=48]="ZERO";CharCodes2[CharCodes2["NINE"]=57]="NINE";CharCodes2[CharCodes2["LOWER_A"]=97]="LOWER_A";CharCodes2[CharCodes2["LOWER_F"]=102]="LOWER_F";CharCodes2[CharCodes2["LOWER_X"]=120]="LOWER_X";CharCodes2[CharCodes2["LOWER_Z"]=122]="LOWER_Z";CharCodes2[CharCodes2["UPPER_A"]=65]="UPPER_A";CharCodes2[CharCodes2["UPPER_F"]=70]="UPPER_F";CharCodes2[CharCodes2["UPPER_Z"]=90]="UPPER_Z"})(CharCodes||(CharCodes={}));var TO_LOWER_BIT=32;function isNumber(code){return code>=CharCodes.ZERO&&code<=CharCodes.NINE}function isHexadecimalCharacter(code){return code>=CharCodes.UPPER_A&&code<=CharCodes.UPPER_F||code>=CharCodes.LOWER_A&&code<=CharCodes.LOWER_F}function isAsciiAlphaNumeric(code){return code>=CharCodes.UPPER_A&&code<=CharCodes.UPPER_Z||code>=CharCodes.LOWER_A&&code<=CharCodes.LOWER_Z||isNumber(code)}function isEntityInAttributeInvalidEnd(code){return code===CharCodes.EQUALS||isAsciiAlphaNumeric(code)}var EntityDecoderState;(function(EntityDecoderState2){EntityDecoderState2[EntityDecoderState2["EntityStart"]=0]="EntityStart";EntityDecoderState2[EntityDecoderState2["NumericStart"]=1]="NumericStart";EntityDecoderState2[EntityDecoderState2["NumericDecimal"]=2]="NumericDecimal";EntityDecoderState2[EntityDecoderState2["NumericHex"]=3]="NumericHex";EntityDecoderState2[EntityDecoderState2["NamedEntity"]=4]="NamedEntity"})(EntityDecoderState||(EntityDecoderState={}));var DecodingMode;(function(DecodingMode2){DecodingMode2[DecodingMode2["Legacy"]=0]="Legacy";DecodingMode2[DecodingMode2["Strict"]=1]="Strict";DecodingMode2[DecodingMode2["Attribute"]=2]="Attribute"})(DecodingMode||(DecodingMode={}));var EntityDecoder2=class{decodeTree;emitCodePoint;errors;constructor(decodeTree,emitCodePoint,errors){this.decodeTree=decodeTree;this.emitCodePoint=emitCodePoint;this.errors=errors}state=EntityDecoderState.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=DecodingMode.Strict;runConsumed=0;startEntity(decodeMode){this.decodeMode=decodeMode;this.state=EntityDecoderState.EntityStart;this.result=0;this.treeIndex=0;this.excess=1;this.consumed=1;this.runConsumed=0}write(input,offset){switch(this.state){case EntityDecoderState.EntityStart:{if(input.charCodeAt(offset)===CharCodes.NUM){this.state=EntityDecoderState.NumericStart;this.consumed+=1;return this.stateNumericStart(input,offset+1)}this.state=EntityDecoderState.NamedEntity;return this.stateNamedEntity(input,offset)}case EntityDecoderState.NumericStart:{return this.stateNumericStart(input,offset)}case EntityDecoderState.NumericDecimal:{return this.stateNumericDecimal(input,offset)}case EntityDecoderState.NumericHex:{return this.stateNumericHex(input,offset)}case EntityDecoderState.NamedEntity:{return this.stateNamedEntity(input,offset)}}}stateNumericStart(input,offset){if(offset>=input.length){return-1}if((input.charCodeAt(offset)|TO_LOWER_BIT)===CharCodes.LOWER_X){this.state=EntityDecoderState.NumericHex;this.consumed+=1;return this.stateNumericHex(input,offset+1)}this.state=EntityDecoderState.NumericDecimal;return this.stateNumericDecimal(input,offset)}stateNumericHex(input,offset){while(offset<input.length){const char=input.charCodeAt(offset);if(isNumber(char)||isHexadecimalCharacter(char)){const digit=char<=CharCodes.NINE?char-CharCodes.ZERO:(char|TO_LOWER_BIT)-CharCodes.LOWER_A+10;this.result=this.result*16+digit;this.consumed++;offset++}else{return this.emitNumericEntity(char,3)}}return-1}stateNumericDecimal(input,offset){while(offset<input.length){const char=input.charCodeAt(offset);if(isNumber(char)){this.result=this.result*10+(char-CharCodes.ZERO);this.consumed++;offset++}else{return this.emitNumericEntity(char,2)}}return-1}emitNumericEntity(lastCp,expectedLength){if(this.consumed<=expectedLength){this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);return 0}if(lastCp===CharCodes.SEMI){this.consumed+=1}else if(this.decodeMode===DecodingMode.Strict){return 0}this.emitCodePoint(replaceCodePoint(this.result),this.consumed);if(this.errors){if(lastCp!==CharCodes.SEMI){this.errors.missingSemicolonAfterCharacterReference()}this.errors.validateNumericCharacterReference(this.result)}return this.consumed}stateNamedEntity(input,offset){const{decodeTree}=this;let current=decodeTree[this.treeIndex];let valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14;while(offset<input.length){if(valueLength===0&&(current&BinTrieFlags.FLAG13)!==0){const runLength=(current&BinTrieFlags.BRANCH_LENGTH)>>7;if(this.runConsumed===0){const firstChar=current&BinTrieFlags.JUMP_TABLE;if(input.charCodeAt(offset)!==firstChar){return this.result===0?0:this.emitNotTerminatedNamedEntity()}offset++;this.excess++;this.runConsumed++}while(this.runConsumed<runLength){if(offset>=input.length){return-1}const charIndexInPacked=this.runConsumed-1;const packedWord=decodeTree[this.treeIndex+1+(charIndexInPacked>>1)];const expectedChar=charIndexInPacked%2===0?packedWord&255:packedWord>>8&255;if(input.charCodeAt(offset)!==expectedChar){this.runConsumed=0;return this.result===0?0:this.emitNotTerminatedNamedEntity()}offset++;this.excess++;this.runConsumed++}this.runConsumed=0;this.treeIndex+=1+(runLength>>1);current=decodeTree[this.treeIndex];valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14}if(offset>=input.length)break;const char=input.charCodeAt(offset);if(char===CharCodes.SEMI&&valueLength!==0&&(current&BinTrieFlags.FLAG13)!==0){return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess)}this.treeIndex=determineBranch(decodeTree,current,this.treeIndex+Math.max(1,valueLength),char);if(this.treeIndex<0){return this.result===0||this.decodeMode===DecodingMode.Attribute&&(valueLength===0||isEntityInAttributeInvalidEnd(char))?0:this.emitNotTerminatedNamedEntity()}current=decodeTree[this.treeIndex];valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14;if(valueLength!==0){if(char===CharCodes.SEMI){return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess)}if(this.decodeMode!==DecodingMode.Strict&&(current&BinTrieFlags.FLAG13)===0){this.result=this.treeIndex;this.consumed+=this.excess;this.excess=0}}offset++;this.excess++}return-1}emitNotTerminatedNamedEntity(){const{result,decodeTree}=this;const valueLength=(decodeTree[result]&BinTrieFlags.VALUE_LENGTH)>>14;this.emitNamedEntityData(result,valueLength,this.consumed);this.errors?.missingSemicolonAfterCharacterReference();return this.consumed}emitNamedEntityData(result,valueLength,consumed){const{decodeTree}=this;this.emitCodePoint(valueLength===1?decodeTree[result]&~(BinTrieFlags.VALUE_LENGTH|BinTrieFlags.FLAG13):decodeTree[result+1],consumed);if(valueLength===3){this.emitCodePoint(decodeTree[result+2],consumed)}return consumed}end(){switch(this.state){case EntityDecoderState.NamedEntity:{return this.result!==0&&(this.decodeMode!==DecodingMode.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0}case EntityDecoderState.NumericDecimal:{return this.emitNumericEntity(0,2)}case EntityDecoderState.NumericHex:{return this.emitNumericEntity(0,3)}case EntityDecoderState.NumericStart:{this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);return 0}case EntityDecoderState.EntityStart:{return 0}}}};function determineBranch(decodeTree,current,nodeIndex,char){const branchCount=(current&BinTrieFlags.BRANCH_LENGTH)>>7;const jumpOffset=current&BinTrieFlags.JUMP_TABLE;if(branchCount===0){return jumpOffset!==0&&char===jumpOffset?nodeIndex:-1}if(jumpOffset){const value=char-jumpOffset;return value<0||value>=branchCount?-1:decodeTree[nodeIndex+value]-1}const packedKeySlots=branchCount+1>>1;let lo=0;let hi=branchCount-1;while(lo<=hi){const mid=lo+hi>>>1;const slot=mid>>1;const packed=decodeTree[nodeIndex+slot];const midKey=packed>>(mid&1)*8&255;if(midKey<char){lo=mid+1}else if(midKey>char){hi=mid-1}else{return decodeTree[nodeIndex+packedKeySlots+mid]}}return-1}var NS;(function(NS2){NS2["HTML"]="http://www.w3.org/1999/xhtml";NS2["MATHML"]="http://www.w3.org/1998/Math/MathML";NS2["SVG"]="http://www.w3.org/2000/svg";NS2["XLINK"]="http://www.w3.org/1999/xlink";NS2["XML"]="http://www.w3.org/XML/1998/namespace";NS2["XMLNS"]="http://www.w3.org/2000/xmlns/"})(NS||(NS={}));var ATTRS;(function(ATTRS2){ATTRS2["TYPE"]="type";ATTRS2["ACTION"]="action";ATTRS2["ENCODING"]="encoding";ATTRS2["PROMPT"]="prompt";ATTRS2["NAME"]="name";ATTRS2["COLOR"]="color";ATTRS2["FACE"]="face";ATTRS2["SIZE"]="size"})(ATTRS||(ATTRS={}));var DOCUMENT_MODE;(function(DOCUMENT_MODE2){DOCUMENT_MODE2["NO_QUIRKS"]="no-quirks";DOCUMENT_MODE2["QUIRKS"]="quirks";DOCUMENT_MODE2["LIMITED_QUIRKS"]="limited-quirks"})(DOCUMENT_MODE||(DOCUMENT_MODE={}));var TAG_NAMES;(function(TAG_NAMES2){TAG_NAMES2["A"]="a";TAG_NAMES2["ADDRESS"]="address";TAG_NAMES2["ANNOTATION_XML"]="annotation-xml";TAG_NAMES2["APPLET"]="applet";TAG_NAMES2["AREA"]="area";TAG_NAMES2["ARTICLE"]="article";TAG_NAMES2["ASIDE"]="aside";TAG_NAMES2["B"]="b";TAG_NAMES2["BASE"]="base";TAG_NAMES2["BASEFONT"]="basefont";TAG_NAMES2["BGSOUND"]="bgsound";TAG_NAMES2["BIG"]="big";TAG_NAMES2["BLOCKQUOTE"]="blockquote";TAG_NAMES2["BODY"]="body";TAG_NAMES2["BR"]="br";TAG_NAMES2["BUTTON"]="button";TAG_NAMES2["CAPTION"]="caption";TAG_NAMES2["CENTER"]="center";TAG_NAMES2["CODE"]="code";TAG_NAMES2["COL"]="col";TAG_NAMES2["COLGROUP"]="colgroup";TAG_NAMES2["DD"]="dd";TAG_NAMES2["DESC"]="desc";TAG_NAMES2["DETAILS"]="details";TAG_NAMES2["DIALOG"]="dialog";TAG_NAMES2["DIR"]="dir";TAG_NAMES2["DIV"]="div";TAG_NAMES2["DL"]="dl";TAG_NAMES2["DT"]="dt";TAG_NAMES2["EM"]="em";TAG_NAMES2["EMBED"]="embed";TAG_NAMES2["FIELDSET"]="fieldset";TAG_NAMES2["FIGCAPTION"]="figcaption";TAG_NAMES2["FIGURE"]="figure";TAG_NAMES2["FONT"]="font";TAG_NAMES2["FOOTER"]="footer";TAG_NAMES2["FOREIGN_OBJECT"]="foreignObject";TAG_NAMES2["FORM"]="form";TAG_NAMES2["FRAME"]="frame";TAG_NAMES2["FRAMESET"]="frameset";TAG_NAMES2["H1"]="h1";TAG_NAMES2["H2"]="h2";TAG_NAMES2["H3"]="h3";TAG_NAMES2["H4"]="h4";TAG_NAMES2["H5"]="h5";TAG_NAMES2["H6"]="h6";TAG_NAMES2["HEAD"]="head";TAG_NAMES2["HEADER"]="header";TAG_NAMES2["HGROUP"]="hgroup";TAG_NAMES2["HR"]="hr";TAG_NAMES2["HTML"]="html";TAG_NAMES2["I"]="i";TAG_NAMES2["IMG"]="img";TAG_NAMES2["IMAGE"]="image";TAG_NAMES2["INPUT"]="input";TAG_NAMES2["IFRAME"]="iframe";TAG_NAMES2["KEYGEN"]="keygen";TAG_NAMES2["LABEL"]="label";TAG_NAMES2["LI"]="li";TAG_NAMES2["LINK"]="link";TAG_NAMES2["LISTING"]="listing";TAG_NAMES2["MAIN"]="main";TAG_NAMES2["MALIGNMARK"]="malignmark";TAG_NAMES2["MARQUEE"]="marquee";TAG_NAMES2["MATH"]="math";TAG_NAMES2["MENU"]="menu";TAG_NAMES2["META"]="meta";TAG_NAMES2["MGLYPH"]="mglyph";TAG_NAMES2["MI"]="mi";TAG_NAMES2["MO"]="mo";TAG_NAMES2["MN"]="mn";TAG_NAMES2["MS"]="ms";TAG_NAMES2["MTEXT"]="mtext";TAG_NAMES2["NAV"]="nav";TAG_NAMES2["NOBR"]="nobr";TAG_NAMES2["NOFRAMES"]="noframes";TAG_NAMES2["NOEMBED"]="noembed";TAG_NAMES2["NOSCRIPT"]="noscript";TAG_NAMES2["OBJECT"]="object";TAG_NAMES2["OL"]="ol";TAG_NAMES2["OPTGROUP"]="optgroup";TAG_NAMES2["OPTION"]="option";TAG_NAMES2["P"]="p";TAG_NAMES2["PARAM"]="param";TAG_NAMES2["PLAINTEXT"]="plaintext";TAG_NAMES2["PRE"]="pre";TAG_NAMES2["RB"]="rb";TAG_NAMES2["RP"]="rp";TAG_NAMES2["RT"]="rt";TAG_NAMES2["RTC"]="rtc";TAG_NAMES2["RUBY"]="ruby";TAG_NAMES2["S"]="s";TAG_NAMES2["SCRIPT"]="script";TAG_NAMES2["SEARCH"]="search";TAG_NAMES2["SECTION"]="section";TAG_NAMES2["SELECT"]="select";TAG_NAMES2["SOURCE"]="source";TAG_NAMES2["SMALL"]="small";TAG_NAMES2["SPAN"]="span";TAG_NAMES2["STRIKE"]="strike";TAG_NAMES2["STRONG"]="strong";TAG_NAMES2["STYLE"]="style";TAG_NAMES2["SUB"]="sub";TAG_NAMES2["SUMMARY"]="summary";TAG_NAMES2["SUP"]="sup";TAG_NAMES2["TABLE"]="table";TAG_NAMES2["TBODY"]="tbody";TAG_NAMES2["TEMPLATE"]="template";TAG_NAMES2["TEXTAREA"]="textarea";TAG_NAMES2["TFOOT"]="tfoot";TAG_NAMES2["TD"]="td";TAG_NAMES2["TH"]="th";TAG_NAMES2["THEAD"]="thead";TAG_NAMES2["TITLE"]="title";TAG_NAMES2["TR"]="tr";TAG_NAMES2["TRACK"]="track";TAG_NAMES2["TT"]="tt";TAG_NAMES2["U"]="u";TAG_NAMES2["UL"]="ul";TAG_NAMES2["SVG"]="svg";TAG_NAMES2["VAR"]="var";TAG_NAMES2["WBR"]="wbr";TAG_NAMES2["XMP"]="xmp"})(TAG_NAMES||(TAG_NAMES={}));var TAG_ID;(function(TAG_ID2){TAG_ID2[TAG_ID2["UNKNOWN"]=0]="UNKNOWN";TAG_ID2[TAG_ID2["A"]=1]="A";TAG_ID2[TAG_ID2["ADDRESS"]=2]="ADDRESS";TAG_ID2[TAG_ID2["ANNOTATION_XML"]=3]="ANNOTATION_XML";TAG_ID2[TAG_ID2["APPLET"]=4]="APPLET";TAG_ID2[TAG_ID2["AREA"]=5]="AREA";TAG_ID2[TAG_ID2["ARTICLE"]=6]="ARTICLE";TAG_ID2[TAG_ID2["ASIDE"]=7]="ASIDE";TAG_ID2[TAG_ID2["B"]=8]="B";TAG_ID2[TAG_ID2["BASE"]=9]="BASE";TAG_ID2[TAG_ID2["BASEFONT"]=10]="BASEFONT";TAG_ID2[TAG_ID2["BGSOUND"]=11]="BGSOUND";TAG_ID2[TAG_ID2["BIG"]=12]="BIG";TAG_ID2[TAG_ID2["BLOCKQUOTE"]=13]="BLOCKQUOTE";TAG_ID2[TAG_ID2["BODY"]=14]="BODY";TAG_ID2[TAG_ID2["BR"]=15]="BR";TAG_ID2[TAG_ID2["BUTTON"]=16]="BUTTON";TAG_ID2[TAG_ID2["CAPTION"]=17]="CAPTION";TAG_ID2[TAG_ID2["CENTER"]=18]="CENTER";TAG_ID2[TAG_ID2["CODE"]=19]="CODE";TAG_ID2[TAG_ID2["COL"]=20]="COL";TAG_ID2[TAG_ID2["COLGROUP"]=21]="COLGROUP";TAG_ID2[TAG_ID2["DD"]=22]="DD";TAG_ID2[TAG_ID2["DESC"]=23]="DESC";TAG_ID2[TAG_ID2["DETAILS"]=24]="DETAILS";TAG_ID2[TAG_ID2["DIALOG"]=25]="DIALOG";TAG_ID2[TAG_ID2["DIR"]=26]="DIR";TAG_ID2[TAG_ID2["DIV"]=27]="DIV";TAG_ID2[TAG_ID2["DL"]=28]="DL";TAG_ID2[TAG_ID2["DT"]=29]="DT";TAG_ID2[TAG_ID2["EM"]=30]="EM";TAG_ID2[TAG_ID2["EMBED"]=31]="EMBED";TAG_ID2[TAG_ID2["FIELDSET"]=32]="FIELDSET";TAG_ID2[TAG_ID2["FIGCAPTION"]=33]="FIGCAPTION";TAG_ID2[TAG_ID2["FIGURE"]=34]="FIGURE";TAG_ID2[TAG_ID2["FONT"]=35]="FONT";TAG_ID2[TAG_ID2["FOOTER"]=36]="FOOTER";TAG_ID2[TAG_ID2["FOREIGN_OBJECT"]=37]="FOREIGN_OBJECT";TAG_ID2[TAG_ID2["FORM"]=38]="FORM";TAG_ID2[TAG_ID2["FRAME"]=39]="FRAME";TAG_ID2[TAG_ID2["FRAMESET"]=40]="FRAMESET";TAG_ID2[TAG_ID2["H1"]=41]="H1";TAG_ID2[TAG_ID2["H2"]=42]="H2";TAG_ID2[TAG_ID2["H3"]=43]="H3";TAG_ID2[TAG_ID2["H4"]=44]="H4";TAG_ID2[TAG_ID2["H5"]=45]="H5";TAG_ID2[TAG_ID2["H6"]=46]="H6";TAG_ID2[TAG_ID2["HEAD"]=47]="HEAD";TAG_ID2[TAG_ID2["HEADER"]=48]="HEADER";TAG_ID2[TAG_ID2["HGROUP"]=49]="HGROUP";TAG_ID2[TAG_ID2["HR"]=50]="HR";TAG_ID2[TAG_ID2["HTML"]=51]="HTML";TAG_ID2[TAG_ID2["I"]=52]="I";TAG_ID2[TAG_ID2["IMG"]=53]="IMG";TAG_ID2[TAG_ID2["IMAGE"]=54]="IMAGE";TAG_ID2[TAG_ID2["INPUT"]=55]="INPUT";TAG_ID2[TAG_ID2["IFRAME"]=56]="IFRAME";TAG_ID2[TAG_ID2["KEYGEN"]=57]="KEYGEN";TAG_ID2[TAG_ID2["LABEL"]=58]="LABEL";TAG_ID2[TAG_ID2["LI"]=59]="LI";TAG_ID2[TAG_ID2["LINK"]=60]="LINK";TAG_ID2[TAG_ID2["LISTING"]=61]="LISTING";TAG_ID2[TAG_ID2["MAIN"]=62]="MAIN";TAG_ID2[TAG_ID2["MALIGNMARK"]=63]="MALIGNMARK";TAG_ID2[TAG_ID2["MARQUEE"]=64]="MARQUEE";TAG_ID2[TAG_ID2["MATH"]=65]="MATH";TAG_ID2[TAG_ID2["MENU"]=66]="MENU";TAG_ID2[TAG_ID2["META"]=67]="META";TAG_ID2[TAG_ID2["MGLYPH"]=68]="MGLYPH";TAG_ID2[TAG_ID2["MI"]=69]="MI";TAG_ID2[TAG_ID2["MO"]=70]="MO";TAG_ID2[TAG_ID2["MN"]=71]="MN";TAG_ID2[TAG_ID2["MS"]=72]="MS";TAG_ID2[TAG_ID2["MTEXT"]=73]="MTEXT";TAG_ID2[TAG_ID2["NAV"]=74]="NAV";TAG_ID2[TAG_ID2["NOBR"]=75]="NOBR";TAG_ID2[TAG_ID2["NOFRAMES"]=76]="NOFRAMES";TAG_ID2[TAG_ID2["NOEMBED"]=77]="NOEMBED";TAG_ID2[TAG_ID2["NOSCRIPT"]=78]="NOSCRIPT";TAG_ID2[TAG_ID2["OBJECT"]=79]="OBJECT";TAG_ID2[TAG_ID2["OL"]=80]="OL";TAG_ID2[TAG_ID2["OPTGROUP"]=81]="OPTGROUP";TAG_ID2[TAG_ID2["OPTION"]=82]="OPTION";TAG_ID2[TAG_ID2["P"]=83]="P";TAG_ID2[TAG_ID2["PARAM"]=84]="PARAM";TAG_ID2[TAG_ID2["PLAINTEXT"]=85]="PLAINTEXT";TAG_ID2[TAG_ID2["PRE"]=86]="PRE";TAG_ID2[TAG_ID2["RB"]=87]="RB";TAG_ID2[TAG_ID2["RP"]=88]="RP";TAG_ID2[TAG_ID2["RT"]=89]="RT";TAG_ID2[TAG_ID2["RTC"]=90]="RTC";TAG_ID2[TAG_ID2["RUBY"]=91]="RUBY";TAG_ID2[TAG_ID2["S"]=92]="S";TAG_ID2[TAG_ID2["SCRIPT"]=93]="SCRIPT";TAG_ID2[TAG_ID2["SEARCH"]=94]="SEARCH";TAG_ID2[TAG_ID2["SECTION"]=95]="SECTION";TAG_ID2[TAG_ID2["SELECT"]=96]="SELECT";TAG_ID2[TAG_ID2["SOURCE"]=97]="SOURCE";TAG_ID2[TAG_ID2["SMALL"]=98]="SMALL";TAG_ID2[TAG_ID2["SPAN"]=99]="SPAN";TAG_ID2[TAG_ID2["STRIKE"]=100]="STRIKE";TAG_ID2[TAG_ID2["STRONG"]=101]="STRONG";TAG_ID2[TAG_ID2["STYLE"]=102]="STYLE";TAG_ID2[TAG_ID2["SUB"]=103]="SUB";TAG_ID2[TAG_ID2["SUMMARY"]=104]="SUMMARY";TAG_ID2[TAG_ID2["SUP"]=105]="SUP";TAG_ID2[TAG_ID2["TABLE"]=106]="TABLE";TAG_ID2[TAG_ID2["TBODY"]=107]="TBODY";TAG_ID2[TAG_ID2["TEMPLATE"]=108]="TEMPLATE";TAG_ID2[TAG_ID2["TEXTAREA"]=109]="TEXTAREA";TAG_ID2[TAG_ID2["TFOOT"]=110]="TFOOT";TAG_ID2[TAG_ID2["TD"]=111]="TD";TAG_ID2[TAG_ID2["TH"]=112]="TH";TAG_ID2[TAG_ID2["THEAD"]=113]="THEAD";TAG_ID2[TAG_ID2["TITLE"]=114]="TITLE";TAG_ID2[TAG_ID2["TR"]=115]="TR";TAG_ID2[TAG_ID2["TRACK"]=116]="TRACK";TAG_ID2[TAG_ID2["TT"]=117]="TT";TAG_ID2[TAG_ID2["U"]=118]="U";TAG_ID2[TAG_ID2["UL"]=119]="UL";TAG_ID2[TAG_ID2["SVG"]=120]="SVG";TAG_ID2[TAG_ID2["VAR"]=121]="VAR";TAG_ID2[TAG_ID2["WBR"]=122]="WBR";TAG_ID2[TAG_ID2["XMP"]=123]="XMP"})(TAG_ID||(TAG_ID={}));var TAG_NAME_TO_ID=new Map([[TAG_NAMES.A,TAG_ID.A],[TAG_NAMES.ADDRESS,TAG_ID.ADDRESS],[TAG_NAMES.ANNOTATION_XML,TAG_ID.ANNOTATION_XML],[TAG_NAMES.APPLET,TAG_ID.APPLET],[TAG_NAMES.AREA,TAG_ID.AREA],[TAG_NAMES.ARTICLE,TAG_ID.ARTICLE],[TAG_NAMES.ASIDE,TAG_ID.ASIDE],[TAG_NAMES.B,TAG_ID.B],[TAG_NAMES.BASE,TAG_ID.BASE],[TAG_NAMES.BASEFONT,TAG_ID.BASEFONT],[TAG_NAMES.BGSOUND,TAG_ID.BGSOUND],[TAG_NAMES.BIG,TAG_ID.BIG],[TAG_NAMES.BLOCKQUOTE,TAG_ID.BLOCKQUOTE],[TAG_NAMES.BODY,TAG_ID.BODY],[TAG_NAMES.BR,TAG_ID.BR],[TAG_NAMES.BUTTON,TAG_ID.BUTTON],[TAG_NAMES.CAPTION,TAG_ID.CAPTION],[TAG_NAMES.CENTER,TAG_ID.CENTER],[TAG_NAMES.CODE,TAG_ID.CODE],[TAG_NAMES.COL,TAG_ID.COL],[TAG_NAMES.COLGROUP,TAG_ID.COLGROUP],[TAG_NAMES.DD,TAG_ID.DD],[TAG_NAMES.DESC,TAG_ID.DESC],[TAG_NAMES.DETAILS,TAG_ID.DETAILS],[TAG_NAMES.DIALOG,TAG_ID.DIALOG],[TAG_NAMES.DIR,TAG_ID.DIR],[TAG_NAMES.DIV,TAG_ID.DIV],[TAG_NAMES.DL,TAG_ID.DL],[TAG_NAMES.DT,TAG_ID.DT],[TAG_NAMES.EM,TAG_ID.EM],[TAG_NAMES.EMBED,TAG_ID.EMBED],[TAG_NAMES.FIELDSET,TAG_ID.FIELDSET],[TAG_NAMES.FIGCAPTION,TAG_ID.FIGCAPTION],[TAG_NAMES.FIGURE,TAG_ID.FIGURE],[TAG_NAMES.FONT,TAG_ID.FONT],[TAG_NAMES.FOOTER,TAG_ID.FOOTER],[TAG_NAMES.FOREIGN_OBJECT,TAG_ID.FOREIGN_OBJECT],[TAG_NAMES.FORM,TAG_ID.FORM],[TAG_NAMES.FRAME,TAG_ID.FRAME],[TAG_NAMES.FRAMESET,TAG_ID.FRAMESET],[TAG_NAMES.H1,TAG_ID.H1],[TAG_NAMES.H2,TAG_ID.H2],[TAG_NAMES.H3,TAG_ID.H3],[TAG_NAMES.H4,TAG_ID.H4],[TAG_NAMES.H5,TAG_ID.H5],[TAG_NAMES.H6,TAG_ID.H6],[TAG_NAMES.HEAD,TAG_ID.HEAD],[TAG_NAMES.HEADER,TAG_ID.HEADER],[TAG_NAMES.HGROUP,TAG_ID.HGROUP],[TAG_NAMES.HR,TAG_ID.HR],[TAG_NAMES.HTML,TAG_ID.HTML],[TAG_NAMES.I,TAG_ID.I],[TAG_NAMES.IMG,TAG_ID.IMG],[TAG_NAMES.IMAGE,TAG_ID.IMAGE],[TAG_NAMES.INPUT,TAG_ID.INPUT],[TAG_NAMES.IFRAME,TAG_ID.IFRAME],[TAG_NAMES.KEYGEN,TAG_ID.KEYGEN],[TAG_NAMES.LABEL,TAG_ID.LABEL],[TAG_NAMES.LI,TAG_ID.LI],[TAG_NAMES.LINK,TAG_ID.LINK],[TAG_NAMES.LISTING,TAG_ID.LISTING],[TAG_NAMES.MAIN,TAG_ID.MAIN],[TAG_NAMES.MALIGNMARK,TAG_ID.MALIGNMARK],[TAG_NAMES.MARQUEE,TAG_ID.MARQUEE],[TAG_NAMES.MATH,TAG_ID.MATH],[TAG_NAMES.MENU,TAG_ID.MENU],[TAG_NAMES.META,TAG_ID.META],[TAG_NAMES.MGLYPH,TAG_ID.MGLYPH],[TAG_NAMES.MI,TAG_ID.MI],[TAG_NAMES.MO,TAG_ID.MO],[TAG_NAMES.MN,TAG_ID.MN],[TAG_NAMES.MS,TAG_ID.MS],[TAG_NAMES.MTEXT,TAG_ID.MTEXT],[TAG_NAMES.NAV,TAG_ID.NAV],[TAG_NAMES.NOBR,TAG_ID.NOBR],[TAG_NAMES.NOFRAMES,TAG_ID.NOFRAMES],[TAG_NAMES.NOEMBED,TAG_ID.NOEMBED],[TAG_NAMES.NOSCRIPT,TAG_ID.NOSCRIPT],[TAG_NAMES.OBJECT,TAG_ID.OBJECT],[TAG_NAMES.OL,TAG_ID.OL],[TAG_NAMES.OPTGROUP,TAG_ID.OPTGROUP],[TAG_NAMES.OPTION,TAG_ID.OPTION],[TAG_NAMES.P,TAG_ID.P],[TAG_NAMES.PARAM,TAG_ID.PARAM],[TAG_NAMES.PLAINTEXT,TAG_ID.PLAINTEXT],[TAG_NAMES.PRE,TAG_ID.PRE],[TAG_NAMES.RB,TAG_ID.RB],[TAG_NAMES.RP,TAG_ID.RP],[TAG_NAMES.RT,TAG_ID.RT],[TAG_NAMES.RTC,TAG_ID.RTC],[TAG_NAMES.RUBY,TAG_ID.RUBY],[TAG_NAMES.S,TAG_ID.S],[TAG_NAMES.SCRIPT,TAG_ID.SCRIPT],[TAG_NAMES.SEARCH,TAG_ID.SEARCH],[TAG_NAMES.SECTION,TAG_ID.SECTION],[TAG_NAMES.SELECT,TAG_ID.SELECT],[TAG_NAMES.SOURCE,TAG_ID.SOURCE],[TAG_NAMES.SMALL,TAG_ID.SMALL],[TAG_NAMES.SPAN,TAG_ID.SPAN],[TAG_NAMES.STRIKE,TAG_ID.STRIKE],[TAG_NAMES.STRONG,TAG_ID.STRONG],[TAG_NAMES.STYLE,TAG_ID.STYLE],[TAG_NAMES.SUB,TAG_ID.SUB],[TAG_NAMES.SUMMARY,TAG_ID.SUMMARY],[TAG_NAMES.SUP,TAG_ID.SUP],[TAG_NAMES.TABLE,TAG_ID.TABLE],[TAG_NAMES.TBODY,TAG_ID.TBODY],[TAG_NAMES.TEMPLATE,TAG_ID.TEMPLATE],[TAG_NAMES.TEXTAREA,TAG_ID.TEXTAREA],[TAG_NAMES.TFOOT,TAG_ID.TFOOT],[TAG_NAMES.TD,TAG_ID.TD],[TAG_NAMES.TH,TAG_ID.TH],[TAG_NAMES.THEAD,TAG_ID.THEAD],[TAG_NAMES.TITLE,TAG_ID.TITLE],[TAG_NAMES.TR,TAG_ID.TR],[TAG_NAMES.TRACK,TAG_ID.TRACK],[TAG_NAMES.TT,TAG_ID.TT],[TAG_NAMES.U,TAG_ID.U],[TAG_NAMES.UL,TAG_ID.UL],[TAG_NAMES.SVG,TAG_ID.SVG],[TAG_NAMES.VAR,TAG_ID.VAR],[TAG_NAMES.WBR,TAG_ID.WBR],[TAG_NAMES.XMP,TAG_ID.XMP]]);function getTagID(tagName){var _a;return(_a=TAG_NAME_TO_ID.get(tagName))!==null&&_a!==void 0?_a:TAG_ID.UNKNOWN}var $=TAG_ID;var SPECIAL_ELEMENTS={[NS.HTML]:new Set([$.ADDRESS,$.APPLET,$.AREA,$.ARTICLE,$.ASIDE,$.BASE,$.BASEFONT,$.BGSOUND,$.BLOCKQUOTE,$.BODY,$.BR,$.BUTTON,$.CAPTION,$.CENTER,$.COL,$.COLGROUP,$.DD,$.DETAILS,$.DIR,$.DIV,$.DL,$.DT,$.EMBED,$.FIELDSET,$.FIGCAPTION,$.FIGURE,$.FOOTER,$.FORM,$.FRAME,$.FRAMESET,$.H1,$.H2,$.H3,$.H4,$.H5,$.H6,$.HEAD,$.HEADER,$.HGROUP,$.HR,$.HTML,$.IFRAME,$.IMG,$.INPUT,$.LI,$.LINK,$.LISTING,$.MAIN,$.MARQUEE,$.MENU,$.META,$.NAV,$.NOEMBED,$.NOFRAMES,$.NOSCRIPT,$.OBJECT,$.OL,$.P,$.PARAM,$.PLAINTEXT,$.PRE,$.SCRIPT,$.SECTION,$.SELECT,$.SOURCE,$.STYLE,$.SUMMARY,$.TABLE,$.TBODY,$.TD,$.TEMPLATE,$.TEXTAREA,$.TFOOT,$.TH,$.THEAD,$.TITLE,$.TR,$.TRACK,$.UL,$.WBR,$.XMP]),[NS.MATHML]:new Set([$.MI,$.MO,$.MN,$.MS,$.MTEXT,$.ANNOTATION_XML]),[NS.SVG]:new Set([$.TITLE,$.FOREIGN_OBJECT,$.DESC]),[NS.XLINK]:new Set,[NS.XML]:new Set,[NS.XMLNS]:new Set};var NUMBERED_HEADERS=new Set([$.H1,$.H2,$.H3,$.H4,$.H5,$.H6]);var UNESCAPED_TEXT=new Set([TAG_NAMES.STYLE,TAG_NAMES.SCRIPT,TAG_NAMES.XMP,TAG_NAMES.IFRAME,TAG_NAMES.NOEMBED,TAG_NAMES.NOFRAMES,TAG_NAMES.PLAINTEXT]);var State;(function(State2){State2[State2["DATA"]=0]="DATA";State2[State2["RCDATA"]=1]="RCDATA";State2[State2["RAWTEXT"]=2]="RAWTEXT";State2[State2["SCRIPT_DATA"]=3]="SCRIPT_DATA";State2[State2["PLAINTEXT"]=4]="PLAINTEXT";State2[State2["TAG_OPEN"]=5]="TAG_OPEN";State2[State2["END_TAG_OPEN"]=6]="END_TAG_OPEN";State2[State2["TAG_NAME"]=7]="TAG_NAME";State2[State2["RCDATA_LESS_THAN_SIGN"]=8]="RCDATA_LESS_THAN_SIGN";State2[State2["RCDATA_END_TAG_OPEN"]=9]="RCDATA_END_TAG_OPEN";State2[State2["RCDATA_END_TAG_NAME"]=10]="RCDATA_END_TAG_NAME";State2[State2["RAWTEXT_LESS_THAN_SIGN"]=11]="RAWTEXT_LESS_THAN_SIGN";State2[State2["RAWTEXT_END_TAG_OPEN"]=12]="RAWTEXT_END_TAG_OPEN";State2[State2["RAWTEXT_END_TAG_NAME"]=13]="RAWTEXT_END_TAG_NAME";State2[State2["SCRIPT_DATA_LESS_THAN_SIGN"]=14]="SCRIPT_DATA_LESS_THAN_SIGN";State2[State2["SCRIPT_DATA_END_TAG_OPEN"]=15]="SCRIPT_DATA_END_TAG_OPEN";State2[State2["SCRIPT_DATA_END_TAG_NAME"]=16]="SCRIPT_DATA_END_TAG_NAME";State2[State2["SCRIPT_DATA_ESCAPE_START"]=17]="SCRIPT_DATA_ESCAPE_START";State2[State2["SCRIPT_DATA_ESCAPE_START_DASH"]=18]="SCRIPT_DATA_ESCAPE_START_DASH";State2[State2["SCRIPT_DATA_ESCAPED"]=19]="SCRIPT_DATA_ESCAPED";State2[State2["SCRIPT_DATA_ESCAPED_DASH"]=20]="SCRIPT_DATA_ESCAPED_DASH";State2[State2["SCRIPT_DATA_ESCAPED_DASH_DASH"]=21]="SCRIPT_DATA_ESCAPED_DASH_DASH";State2[State2["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"]=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";State2[State2["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"]=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN";State2[State2["SCRIPT_DATA_ESCAPED_END_TAG_NAME"]=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME";State2[State2["SCRIPT_DATA_DOUBLE_ESCAPE_START"]=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START";State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED"]=26]="SCRIPT_DATA_DOUBLE_ESCAPED";State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"]=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH";State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"]=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"]=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";State2[State2["SCRIPT_DATA_DOUBLE_ESCAPE_END"]=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END";State2[State2["BEFORE_ATTRIBUTE_NAME"]=31]="BEFORE_ATTRIBUTE_NAME";State2[State2["ATTRIBUTE_NAME"]=32]="ATTRIBUTE_NAME";State2[State2["AFTER_ATTRIBUTE_NAME"]=33]="AFTER_ATTRIBUTE_NAME";State2[State2["BEFORE_ATTRIBUTE_VALUE"]=34]="BEFORE_ATTRIBUTE_VALUE";State2[State2["ATTRIBUTE_VALUE_DOUBLE_QUOTED"]=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED";State2[State2["ATTRIBUTE_VALUE_SINGLE_QUOTED"]=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED";State2[State2["ATTRIBUTE_VALUE_UNQUOTED"]=37]="ATTRIBUTE_VALUE_UNQUOTED";State2[State2["AFTER_ATTRIBUTE_VALUE_QUOTED"]=38]="AFTER_ATTRIBUTE_VALUE_QUOTED";State2[State2["SELF_CLOSING_START_TAG"]=39]="SELF_CLOSING_START_TAG";State2[State2["BOGUS_COMMENT"]=40]="BOGUS_COMMENT";State2[State2["MARKUP_DECLARATION_OPEN"]=41]="MARKUP_DECLARATION_OPEN";State2[State2["COMMENT_START"]=42]="COMMENT_START";State2[State2["COMMENT_START_DASH"]=43]="COMMENT_START_DASH";State2[State2["COMMENT"]=44]="COMMENT";State2[State2["COMMENT_LESS_THAN_SIGN"]=45]="COMMENT_LESS_THAN_SIGN";State2[State2["COMMENT_LESS_THAN_SIGN_BANG"]=46]="COMMENT_LESS_THAN_SIGN_BANG";State2[State2["COMMENT_LESS_THAN_SIGN_BANG_DASH"]=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH";State2[State2["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"]=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";State2[State2["COMMENT_END_DASH"]=49]="COMMENT_END_DASH";State2[State2["COMMENT_END"]=50]="COMMENT_END";State2[State2["COMMENT_END_BANG"]=51]="COMMENT_END_BANG";State2[State2["DOCTYPE"]=52]="DOCTYPE";State2[State2["BEFORE_DOCTYPE_NAME"]=53]="BEFORE_DOCTYPE_NAME";State2[State2["DOCTYPE_NAME"]=54]="DOCTYPE_NAME";State2[State2["AFTER_DOCTYPE_NAME"]=55]="AFTER_DOCTYPE_NAME";State2[State2["AFTER_DOCTYPE_PUBLIC_KEYWORD"]=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD";State2[State2["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"]=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";State2[State2["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"]=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";State2[State2["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"]=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";State2[State2["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"]=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER";State2[State2["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"]=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";State2[State2["AFTER_DOCTYPE_SYSTEM_KEYWORD"]=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD";State2[State2["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"]=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";State2[State2["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"]=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";State2[State2["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"]=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";State2[State2["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"]=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER";State2[State2["BOGUS_DOCTYPE"]=67]="BOGUS_DOCTYPE";State2[State2["CDATA_SECTION"]=68]="CDATA_SECTION";State2[State2["CDATA_SECTION_BRACKET"]=69]="CDATA_SECTION_BRACKET";State2[State2["CDATA_SECTION_END"]=70]="CDATA_SECTION_END";State2[State2["CHARACTER_REFERENCE"]=71]="CHARACTER_REFERENCE";State2[State2["AMBIGUOUS_AMPERSAND"]=72]="AMBIGUOUS_AMPERSAND"})(State||(State={}));var TokenizerMode={DATA:State.DATA,RCDATA:State.RCDATA,RAWTEXT:State.RAWTEXT,SCRIPT_DATA:State.SCRIPT_DATA,PLAINTEXT:State.PLAINTEXT,CDATA_SECTION:State.CDATA_SECTION};function isAsciiDigit(cp){return cp>=CODE_POINTS.DIGIT_0&&cp<=CODE_POINTS.DIGIT_9}function isAsciiUpper(cp){return cp>=CODE_POINTS.LATIN_CAPITAL_A&&cp<=CODE_POINTS.LATIN_CAPITAL_Z}function isAsciiLower(cp){return cp>=CODE_POINTS.LATIN_SMALL_A&&cp<=CODE_POINTS.LATIN_SMALL_Z}function isAsciiLetter(cp){return isAsciiLower(cp)||isAsciiUpper(cp)}function isAsciiAlphaNumeric2(cp){return isAsciiLetter(cp)||isAsciiDigit(cp)}function toAsciiLower(cp){return cp+32}function isWhitespace(cp){return cp===CODE_POINTS.SPACE||cp===CODE_POINTS.LINE_FEED||cp===CODE_POINTS.TABULATION||cp===CODE_POINTS.FORM_FEED}function isScriptDataDoubleEscapeSequenceEnd(cp){return isWhitespace(cp)||cp===CODE_POINTS.SOLIDUS||cp===CODE_POINTS.GREATER_THAN_SIGN}function getErrorForNumericCharacterReference(code){if(code===CODE_POINTS.NULL){return ERR.nullCharacterReference}else if(code>1114111){return ERR.characterReferenceOutsideUnicodeRange}else if(isSurrogate(code)){return ERR.surrogateCharacterReference}else if(isUndefinedCodePoint(code)){return ERR.noncharacterCharacterReference}else if(isControlCodePoint(code)||code===CODE_POINTS.CARRIAGE_RETURN){return ERR.controlCharacterReference}return null}var Tokenizer=class{constructor(options,handler){this.options=options;this.handler=handler;this.paused=false;this.inLoop=false;this.inForeignNode=false;this.lastStartTagName="";this.active=false;this.state=State.DATA;this.returnState=State.DATA;this.entityStartPos=0;this.consumedAfterSnapshot=-1;this.currentCharacterToken=null;this.currentToken=null;this.currentAttr={name:"",value:""};this.preprocessor=new Preprocessor(handler);this.currentLocation=this.getCurrentLocation(-1);this.entityDecoder=new EntityDecoder2(htmlDecodeTree,(cp,consumed)=>{this.preprocessor.pos=this.entityStartPos+consumed-1;this._flushCodePointConsumedAsCharacterReference(cp)},handler.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(ERR.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:consumed=>{this._err(ERR.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+consumed)},validateNumericCharacterReference:code=>{const error=getErrorForNumericCharacterReference(code);if(error)this._err(error,1)}}:void 0)}_err(code,cpOffset=0){var _a,_b;(_b=(_a=this.handler).onParseError)===null||_b===void 0?void 0:_b.call(_a,this.preprocessor.getError(code,cpOffset))}getCurrentLocation(offset){if(!this.options.sourceCodeLocationInfo){return null}return{startLine:this.preprocessor.line,startCol:this.preprocessor.col-offset,startOffset:this.preprocessor.offset-offset,endLine:-1,endCol:-1,endOffset:-1}}_runParsingLoop(){if(this.inLoop)return;this.inLoop=true;while(this.active&&!this.paused){this.consumedAfterSnapshot=0;const cp=this._consume();if(!this._ensureHibernation()){this._callState(cp)}}this.inLoop=false}pause(){this.paused=true}resume(writeCallback){if(!this.paused){throw new Error("Parser was already resumed")}this.paused=false;if(this.inLoop)return;this._runParsingLoop();if(!this.paused){writeCallback===null||writeCallback===void 0?void 0:writeCallback()}}write(chunk,isLastChunk,writeCallback){this.active=true;this.preprocessor.write(chunk,isLastChunk);this._runParsingLoop();if(!this.paused){writeCallback===null||writeCallback===void 0?void 0:writeCallback()}}insertHtmlAtCurrentPos(chunk){this.active=true;this.preprocessor.insertHtmlAtCurrentPos(chunk);this._runParsingLoop()}_ensureHibernation(){if(this.preprocessor.endOfChunkHit){this.preprocessor.retreat(this.consumedAfterSnapshot);this.consumedAfterSnapshot=0;this.active=false;return true}return false}_consume(){this.consumedAfterSnapshot++;return this.preprocessor.advance()}_advanceBy(count){this.consumedAfterSnapshot+=count;for(let i=0;i<count;i++){this.preprocessor.advance()}}_consumeSequenceIfMatch(pattern,caseSensitive){if(this.preprocessor.startsWith(pattern,caseSensitive)){this._advanceBy(pattern.length-1);return true}return false}_createStartTagToken(){this.currentToken={type:TokenType.START_TAG,tagName:"",tagID:TAG_ID.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:TokenType.END_TAG,tagName:"",tagID:TAG_ID.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(offset){this.currentToken={type:TokenType.COMMENT,data:"",location:this.getCurrentLocation(offset)}}_createDoctypeToken(initialName){this.currentToken={type:TokenType.DOCTYPE,name:initialName,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(type,chars){this.currentCharacterToken={type,chars,location:this.currentLocation}}_createAttr(attrNameFirstCh){this.currentAttr={name:attrNameFirstCh,value:""};this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var _a;var _b;const token=this.currentToken;if(getTokenAttr(token,this.currentAttr.name)===null){token.attrs.push(this.currentAttr);if(token.location&&this.currentLocation){const attrLocations=(_a=(_b=token.location).attrs)!==null&&_a!==void 0?_a:_b.attrs=Object.create(null);attrLocations[this.currentAttr.name]=this.currentLocation;this._leaveAttrValue()}}else{this._err(ERR.duplicateAttribute)}}_leaveAttrValue(){if(this.currentLocation){this.currentLocation.endLine=this.preprocessor.line;this.currentLocation.endCol=this.preprocessor.col;this.currentLocation.endOffset=this.preprocessor.offset}}prepareToken(ct){this._emitCurrentCharacterToken(ct.location);this.currentToken=null;if(ct.location){ct.location.endLine=this.preprocessor.line;ct.location.endCol=this.preprocessor.col+1;ct.location.endOffset=this.preprocessor.offset+1}this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const ct=this.currentToken;this.prepareToken(ct);ct.tagID=getTagID(ct.tagName);if(ct.type===TokenType.START_TAG){this.lastStartTagName=ct.tagName;this.handler.onStartTag(ct)}else{if(ct.attrs.length>0){this._err(ERR.endTagWithAttributes)}if(ct.selfClosing){this._err(ERR.endTagWithTrailingSolidus)}this.handler.onEndTag(ct)}this.preprocessor.dropParsedChunk()}emitCurrentComment(ct){this.prepareToken(ct);this.handler.onComment(ct);this.preprocessor.dropParsedChunk()}emitCurrentDoctype(ct){this.prepareToken(ct);this.handler.onDoctype(ct);this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(nextLocation){if(this.currentCharacterToken){if(nextLocation&&this.currentCharacterToken.location){this.currentCharacterToken.location.endLine=nextLocation.startLine;this.currentCharacterToken.location.endCol=nextLocation.startCol;this.currentCharacterToken.location.endOffset=nextLocation.startOffset}switch(this.currentCharacterToken.type){case TokenType.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case TokenType.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case TokenType.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const location=this.getCurrentLocation(0);if(location){location.endLine=location.startLine;location.endCol=location.startCol;location.endOffset=location.startOffset}this._emitCurrentCharacterToken(location);this.handler.onEof({type:TokenType.EOF,location});this.active=false}_appendCharToCurrentCharacterToken(type,ch){if(this.currentCharacterToken){if(this.currentCharacterToken.type===type){this.currentCharacterToken.chars+=ch;return}else{this.currentLocation=this.getCurrentLocation(0);this._emitCurrentCharacterToken(this.currentLocation);this.preprocessor.dropParsedChunk()}}this._createCharacterToken(type,ch)}_emitCodePoint(cp){const type=isWhitespace(cp)?TokenType.WHITESPACE_CHARACTER:cp===CODE_POINTS.NULL?TokenType.NULL_CHARACTER:TokenType.CHARACTER;this._appendCharToCurrentCharacterToken(type,cp<65536?String.fromCharCode(cp):String.fromCodePoint(cp))}_emitChars(ch){this._appendCharToCurrentCharacterToken(TokenType.CHARACTER,ch)}_startCharacterReference(){this.returnState=this.state;this.state=State.CHARACTER_REFERENCE;this.entityStartPos=this.preprocessor.pos;this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?DecodingMode.Attribute:DecodingMode.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===State.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===State.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===State.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(cp){if(this._isCharacterReferenceInAttribute()){this.currentAttr.value+=String.fromCodePoint(cp)}else{this._emitCodePoint(cp)}}_callState(cp){switch(this.state){case State.DATA:{this._stateData(cp);break}case State.RCDATA:{this._stateRcdata(cp);break}case State.RAWTEXT:{this._stateRawtext(cp);break}case State.SCRIPT_DATA:{this._stateScriptData(cp);break}case State.PLAINTEXT:{this._statePlaintext(cp);break}case State.TAG_OPEN:{this._stateTagOpen(cp);break}case State.END_TAG_OPEN:{this._stateEndTagOpen(cp);break}case State.TAG_NAME:{this._stateTagName(cp);break}case State.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(cp);break}case State.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(cp);break}case State.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(cp);break}case State.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(cp);break}case State.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(cp);break}case State.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(cp);break}case State.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(cp);break}case State.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(cp);break}case State.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(cp);break}case State.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(cp);break}case State.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(cp);break}case State.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(cp);break}case State.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(cp);break}case State.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(cp);break}case State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(cp);break}case State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(cp);break}case State.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(cp);break}case State.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(cp);break}case State.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(cp);break}case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(cp);break}case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(cp);break}case State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(cp);break}case State.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(cp);break}case State.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(cp);break}case State.ATTRIBUTE_NAME:{this._stateAttributeName(cp);break}case State.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(cp);break}case State.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(cp);break}case State.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(cp);break}case State.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(cp);break}case State.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(cp);break}case State.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(cp);break}case State.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(cp);break}case State.BOGUS_COMMENT:{this._stateBogusComment(cp);break}case State.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(cp);break}case State.COMMENT_START:{this._stateCommentStart(cp);break}case State.COMMENT_START_DASH:{this._stateCommentStartDash(cp);break}case State.COMMENT:{this._stateComment(cp);break}case State.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(cp);break}case State.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(cp);break}case State.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(cp);break}case State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(cp);break}case State.COMMENT_END_DASH:{this._stateCommentEndDash(cp);break}case State.COMMENT_END:{this._stateCommentEnd(cp);break}case State.COMMENT_END_BANG:{this._stateCommentEndBang(cp);break}case State.DOCTYPE:{this._stateDoctype(cp);break}case State.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(cp);break}case State.DOCTYPE_NAME:{this._stateDoctypeName(cp);break}case State.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(cp);break}case State.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(cp);break}case State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(cp);break}case State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(cp);break}case State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(cp);break}case State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(cp);break}case State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(cp);break}case State.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(cp);break}case State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(cp);break}case State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(cp);break}case State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(cp);break}case State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(cp);break}case State.BOGUS_DOCTYPE:{this._stateBogusDoctype(cp);break}case State.CDATA_SECTION:{this._stateCdataSection(cp);break}case State.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(cp);break}case State.CDATA_SECTION_END:{this._stateCdataSectionEnd(cp);break}case State.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case State.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(cp);break}default:{throw new Error("Unknown state")}}}_stateData(cp){switch(cp){case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.TAG_OPEN;break}case CODE_POINTS.AMPERSAND:{this._startCharacterReference();break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitCodePoint(cp);break}case CODE_POINTS.EOF:{this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateRcdata(cp){switch(cp){case CODE_POINTS.AMPERSAND:{this._startCharacterReference();break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.RCDATA_LESS_THAN_SIGN;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateRawtext(cp){switch(cp){case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.RAWTEXT_LESS_THAN_SIGN;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateScriptData(cp){switch(cp){case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_LESS_THAN_SIGN;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_statePlaintext(cp){switch(cp){case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateTagOpen(cp){if(isAsciiLetter(cp)){this._createStartTagToken();this.state=State.TAG_NAME;this._stateTagName(cp)}else switch(cp){case CODE_POINTS.EXCLAMATION_MARK:{this.state=State.MARKUP_DECLARATION_OPEN;break}case CODE_POINTS.SOLIDUS:{this.state=State.END_TAG_OPEN;break}case CODE_POINTS.QUESTION_MARK:{this._err(ERR.unexpectedQuestionMarkInsteadOfTagName);this._createCommentToken(1);this.state=State.BOGUS_COMMENT;this._stateBogusComment(cp);break}case CODE_POINTS.EOF:{this._err(ERR.eofBeforeTagName);this._emitChars("<");this._emitEOFToken();break}default:{this._err(ERR.invalidFirstCharacterOfTagName);this._emitChars("<");this.state=State.DATA;this._stateData(cp)}}}_stateEndTagOpen(cp){if(isAsciiLetter(cp)){this._createEndTagToken();this.state=State.TAG_NAME;this._stateTagName(cp)}else switch(cp){case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingEndTagName);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofBeforeTagName);this._emitChars("</");this._emitEOFToken();break}default:{this._err(ERR.invalidFirstCharacterOfTagName);this._createCommentToken(2);this.state=State.BOGUS_COMMENT;this._stateBogusComment(cp)}}}_stateTagName(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this.state=State.BEFORE_ATTRIBUTE_NAME;break}case CODE_POINTS.SOLIDUS:{this.state=State.SELF_CLOSING_START_TAG;break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentTagToken();break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.tagName+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{token.tagName+=String.fromCodePoint(isAsciiUpper(cp)?toAsciiLower(cp):cp)}}}_stateRcdataLessThanSign(cp){if(cp===CODE_POINTS.SOLIDUS){this.state=State.RCDATA_END_TAG_OPEN}else{this._emitChars("<");this.state=State.RCDATA;this._stateRcdata(cp)}}_stateRcdataEndTagOpen(cp){if(isAsciiLetter(cp)){this.state=State.RCDATA_END_TAG_NAME;this._stateRcdataEndTagName(cp)}else{this._emitChars("</");this.state=State.RCDATA;this._stateRcdata(cp)}}handleSpecialEndTag(_cp){if(!this.preprocessor.startsWith(this.lastStartTagName,false)){return!this._ensureHibernation()}this._createEndTagToken();const token=this.currentToken;token.tagName=this.lastStartTagName;const cp=this.preprocessor.peek(this.lastStartTagName.length);switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this._advanceBy(this.lastStartTagName.length);this.state=State.BEFORE_ATTRIBUTE_NAME;return false}case CODE_POINTS.SOLIDUS:{this._advanceBy(this.lastStartTagName.length);this.state=State.SELF_CLOSING_START_TAG;return false}case CODE_POINTS.GREATER_THAN_SIGN:{this._advanceBy(this.lastStartTagName.length);this.emitCurrentTagToken();this.state=State.DATA;return false}default:{return!this._ensureHibernation()}}}_stateRcdataEndTagName(cp){if(this.handleSpecialEndTag(cp)){this._emitChars("</");this.state=State.RCDATA;this._stateRcdata(cp)}}_stateRawtextLessThanSign(cp){if(cp===CODE_POINTS.SOLIDUS){this.state=State.RAWTEXT_END_TAG_OPEN}else{this._emitChars("<");this.state=State.RAWTEXT;this._stateRawtext(cp)}}_stateRawtextEndTagOpen(cp){if(isAsciiLetter(cp)){this.state=State.RAWTEXT_END_TAG_NAME;this._stateRawtextEndTagName(cp)}else{this._emitChars("</");this.state=State.RAWTEXT;this._stateRawtext(cp)}}_stateRawtextEndTagName(cp){if(this.handleSpecialEndTag(cp)){this._emitChars("</");this.state=State.RAWTEXT;this._stateRawtext(cp)}}_stateScriptDataLessThanSign(cp){switch(cp){case CODE_POINTS.SOLIDUS:{this.state=State.SCRIPT_DATA_END_TAG_OPEN;break}case CODE_POINTS.EXCLAMATION_MARK:{this.state=State.SCRIPT_DATA_ESCAPE_START;this._emitChars("<!");break}default:{this._emitChars("<");this.state=State.SCRIPT_DATA;this._stateScriptData(cp)}}}_stateScriptDataEndTagOpen(cp){if(isAsciiLetter(cp)){this.state=State.SCRIPT_DATA_END_TAG_NAME;this._stateScriptDataEndTagName(cp)}else{this._emitChars("</");this.state=State.SCRIPT_DATA;this._stateScriptData(cp)}}_stateScriptDataEndTagName(cp){if(this.handleSpecialEndTag(cp)){this._emitChars("</");this.state=State.SCRIPT_DATA;this._stateScriptData(cp)}}_stateScriptDataEscapeStart(cp){if(cp===CODE_POINTS.HYPHEN_MINUS){this.state=State.SCRIPT_DATA_ESCAPE_START_DASH;this._emitChars("-")}else{this.state=State.SCRIPT_DATA;this._stateScriptData(cp)}}_stateScriptDataEscapeStartDash(cp){if(cp===CODE_POINTS.HYPHEN_MINUS){this.state=State.SCRIPT_DATA_ESCAPED_DASH_DASH;this._emitChars("-")}else{this.state=State.SCRIPT_DATA;this._stateScriptData(cp)}}_stateScriptDataEscaped(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.SCRIPT_DATA_ESCAPED_DASH;this._emitChars("-");break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._err(ERR.eofInScriptHtmlCommentLikeText);this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateScriptDataEscapedDash(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.SCRIPT_DATA_ESCAPED_DASH_DASH;this._emitChars("-");break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.state=State.SCRIPT_DATA_ESCAPED;this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._err(ERR.eofInScriptHtmlCommentLikeText);this._emitEOFToken();break}default:{this.state=State.SCRIPT_DATA_ESCAPED;this._emitCodePoint(cp)}}}_stateScriptDataEscapedDashDash(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this._emitChars("-");break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.SCRIPT_DATA;this._emitChars(">");break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.state=State.SCRIPT_DATA_ESCAPED;this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._err(ERR.eofInScriptHtmlCommentLikeText);this._emitEOFToken();break}default:{this.state=State.SCRIPT_DATA_ESCAPED;this._emitCodePoint(cp)}}}_stateScriptDataEscapedLessThanSign(cp){if(cp===CODE_POINTS.SOLIDUS){this.state=State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN}else if(isAsciiLetter(cp)){this._emitChars("<");this.state=State.SCRIPT_DATA_DOUBLE_ESCAPE_START;this._stateScriptDataDoubleEscapeStart(cp)}else{this._emitChars("<");this.state=State.SCRIPT_DATA_ESCAPED;this._stateScriptDataEscaped(cp)}}_stateScriptDataEscapedEndTagOpen(cp){if(isAsciiLetter(cp)){this.state=State.SCRIPT_DATA_ESCAPED_END_TAG_NAME;this._stateScriptDataEscapedEndTagName(cp)}else{this._emitChars("</");this.state=State.SCRIPT_DATA_ESCAPED;this._stateScriptDataEscaped(cp)}}_stateScriptDataEscapedEndTagName(cp){if(this.handleSpecialEndTag(cp)){this._emitChars("</");this.state=State.SCRIPT_DATA_ESCAPED;this._stateScriptDataEscaped(cp)}}_stateScriptDataDoubleEscapeStart(cp){if(this.preprocessor.startsWith(SEQUENCES.SCRIPT,false)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))){this._emitCodePoint(cp);for(let i=0;i<SEQUENCES.SCRIPT.length;i++){this._emitCodePoint(this._consume())}this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED}else if(!this._ensureHibernation()){this.state=State.SCRIPT_DATA_ESCAPED;this._stateScriptDataEscaped(cp)}}_stateScriptDataDoubleEscaped(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH;this._emitChars("-");break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;this._emitChars("<");break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._err(ERR.eofInScriptHtmlCommentLikeText);this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateScriptDataDoubleEscapedDash(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH;this._emitChars("-");break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;this._emitChars("<");break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED;this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._err(ERR.eofInScriptHtmlCommentLikeText);this._emitEOFToken();break}default:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED;this._emitCodePoint(cp)}}}_stateScriptDataDoubleEscapedDashDash(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this._emitChars("-");break}case CODE_POINTS.LESS_THAN_SIGN:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;this._emitChars("<");break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.SCRIPT_DATA;this._emitChars(">");break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED;this._emitChars(REPLACEMENT_CHARACTER);break}case CODE_POINTS.EOF:{this._err(ERR.eofInScriptHtmlCommentLikeText);this._emitEOFToken();break}default:{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED;this._emitCodePoint(cp)}}}_stateScriptDataDoubleEscapedLessThanSign(cp){if(cp===CODE_POINTS.SOLIDUS){this.state=State.SCRIPT_DATA_DOUBLE_ESCAPE_END;this._emitChars("/")}else{this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED;this._stateScriptDataDoubleEscaped(cp)}}_stateScriptDataDoubleEscapeEnd(cp){if(this.preprocessor.startsWith(SEQUENCES.SCRIPT,false)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))){this._emitCodePoint(cp);for(let i=0;i<SEQUENCES.SCRIPT.length;i++){this._emitCodePoint(this._consume())}this.state=State.SCRIPT_DATA_ESCAPED}else if(!this._ensureHibernation()){this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED;this._stateScriptDataDoubleEscaped(cp)}}_stateBeforeAttributeName(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.SOLIDUS:case CODE_POINTS.GREATER_THAN_SIGN:case CODE_POINTS.EOF:{this.state=State.AFTER_ATTRIBUTE_NAME;this._stateAfterAttributeName(cp);break}case CODE_POINTS.EQUALS_SIGN:{this._err(ERR.unexpectedEqualsSignBeforeAttributeName);this._createAttr("=");this.state=State.ATTRIBUTE_NAME;break}default:{this._createAttr("");this.state=State.ATTRIBUTE_NAME;this._stateAttributeName(cp)}}}_stateAttributeName(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:case CODE_POINTS.SOLIDUS:case CODE_POINTS.GREATER_THAN_SIGN:case CODE_POINTS.EOF:{this._leaveAttrName();this.state=State.AFTER_ATTRIBUTE_NAME;this._stateAfterAttributeName(cp);break}case CODE_POINTS.EQUALS_SIGN:{this._leaveAttrName();this.state=State.BEFORE_ATTRIBUTE_VALUE;break}case CODE_POINTS.QUOTATION_MARK:case CODE_POINTS.APOSTROPHE:case CODE_POINTS.LESS_THAN_SIGN:{this._err(ERR.unexpectedCharacterInAttributeName);this.currentAttr.name+=String.fromCodePoint(cp);break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.currentAttr.name+=REPLACEMENT_CHARACTER;break}default:{this.currentAttr.name+=String.fromCodePoint(isAsciiUpper(cp)?toAsciiLower(cp):cp)}}}_stateAfterAttributeName(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.SOLIDUS:{this.state=State.SELF_CLOSING_START_TAG;break}case CODE_POINTS.EQUALS_SIGN:{this.state=State.BEFORE_ATTRIBUTE_VALUE;break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentTagToken();break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{this._createAttr("");this.state=State.ATTRIBUTE_NAME;this._stateAttributeName(cp)}}}_stateBeforeAttributeValue(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.QUOTATION_MARK:{this.state=State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{this.state=State.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingAttributeValue);this.state=State.DATA;this.emitCurrentTagToken();break}default:{this.state=State.ATTRIBUTE_VALUE_UNQUOTED;this._stateAttributeValueUnquoted(cp)}}}_stateAttributeValueDoubleQuoted(cp){switch(cp){case CODE_POINTS.QUOTATION_MARK:{this.state=State.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case CODE_POINTS.AMPERSAND:{this._startCharacterReference();break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.currentAttr.value+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{this.currentAttr.value+=String.fromCodePoint(cp)}}}_stateAttributeValueSingleQuoted(cp){switch(cp){case CODE_POINTS.APOSTROPHE:{this.state=State.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case CODE_POINTS.AMPERSAND:{this._startCharacterReference();break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.currentAttr.value+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{this.currentAttr.value+=String.fromCodePoint(cp)}}}_stateAttributeValueUnquoted(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this._leaveAttrValue();this.state=State.BEFORE_ATTRIBUTE_NAME;break}case CODE_POINTS.AMPERSAND:{this._startCharacterReference();break}case CODE_POINTS.GREATER_THAN_SIGN:{this._leaveAttrValue();this.state=State.DATA;this.emitCurrentTagToken();break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this.currentAttr.value+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.QUOTATION_MARK:case CODE_POINTS.APOSTROPHE:case CODE_POINTS.LESS_THAN_SIGN:case CODE_POINTS.EQUALS_SIGN:case CODE_POINTS.GRAVE_ACCENT:{this._err(ERR.unexpectedCharacterInUnquotedAttributeValue);this.currentAttr.value+=String.fromCodePoint(cp);break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{this.currentAttr.value+=String.fromCodePoint(cp)}}}_stateAfterAttributeValueQuoted(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this._leaveAttrValue();this.state=State.BEFORE_ATTRIBUTE_NAME;break}case CODE_POINTS.SOLIDUS:{this._leaveAttrValue();this.state=State.SELF_CLOSING_START_TAG;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._leaveAttrValue();this.state=State.DATA;this.emitCurrentTagToken();break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{this._err(ERR.missingWhitespaceBetweenAttributes);this.state=State.BEFORE_ATTRIBUTE_NAME;this._stateBeforeAttributeName(cp)}}}_stateSelfClosingStartTag(cp){switch(cp){case CODE_POINTS.GREATER_THAN_SIGN:{const token=this.currentToken;token.selfClosing=true;this.state=State.DATA;this.emitCurrentTagToken();break}case CODE_POINTS.EOF:{this._err(ERR.eofInTag);this._emitEOFToken();break}default:{this._err(ERR.unexpectedSolidusInTag);this.state=State.BEFORE_ATTRIBUTE_NAME;this._stateBeforeAttributeName(cp)}}}_stateBogusComment(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentComment(token);break}case CODE_POINTS.EOF:{this.emitCurrentComment(token);this._emitEOFToken();break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.data+=REPLACEMENT_CHARACTER;break}default:{token.data+=String.fromCodePoint(cp)}}}_stateMarkupDeclarationOpen(cp){if(this._consumeSequenceIfMatch(SEQUENCES.DASH_DASH,true)){this._createCommentToken(SEQUENCES.DASH_DASH.length+1);this.state=State.COMMENT_START}else if(this._consumeSequenceIfMatch(SEQUENCES.DOCTYPE,false)){this.currentLocation=this.getCurrentLocation(SEQUENCES.DOCTYPE.length+1);this.state=State.DOCTYPE}else if(this._consumeSequenceIfMatch(SEQUENCES.CDATA_START,true)){if(this.inForeignNode){this.state=State.CDATA_SECTION}else{this._err(ERR.cdataInHtmlContent);this._createCommentToken(SEQUENCES.CDATA_START.length+1);this.currentToken.data="[CDATA[";this.state=State.BOGUS_COMMENT}}else if(!this._ensureHibernation()){this._err(ERR.incorrectlyOpenedComment);this._createCommentToken(2);this.state=State.BOGUS_COMMENT;this._stateBogusComment(cp)}}_stateCommentStart(cp){switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.COMMENT_START_DASH;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.abruptClosingOfEmptyComment);this.state=State.DATA;const token=this.currentToken;this.emitCurrentComment(token);break}default:{this.state=State.COMMENT;this._stateComment(cp)}}}_stateCommentStartDash(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.COMMENT_END;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.abruptClosingOfEmptyComment);this.state=State.DATA;this.emitCurrentComment(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInComment);this.emitCurrentComment(token);this._emitEOFToken();break}default:{token.data+="-";this.state=State.COMMENT;this._stateComment(cp)}}}_stateComment(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.COMMENT_END_DASH;break}case CODE_POINTS.LESS_THAN_SIGN:{token.data+="<";this.state=State.COMMENT_LESS_THAN_SIGN;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.data+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.EOF:{this._err(ERR.eofInComment);this.emitCurrentComment(token);this._emitEOFToken();break}default:{token.data+=String.fromCodePoint(cp)}}}_stateCommentLessThanSign(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.EXCLAMATION_MARK:{token.data+="!";this.state=State.COMMENT_LESS_THAN_SIGN_BANG;break}case CODE_POINTS.LESS_THAN_SIGN:{token.data+="<";break}default:{this.state=State.COMMENT;this._stateComment(cp)}}}_stateCommentLessThanSignBang(cp){if(cp===CODE_POINTS.HYPHEN_MINUS){this.state=State.COMMENT_LESS_THAN_SIGN_BANG_DASH}else{this.state=State.COMMENT;this._stateComment(cp)}}_stateCommentLessThanSignBangDash(cp){if(cp===CODE_POINTS.HYPHEN_MINUS){this.state=State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH}else{this.state=State.COMMENT_END_DASH;this._stateCommentEndDash(cp)}}_stateCommentLessThanSignBangDashDash(cp){if(cp!==CODE_POINTS.GREATER_THAN_SIGN&&cp!==CODE_POINTS.EOF){this._err(ERR.nestedComment)}this.state=State.COMMENT_END;this._stateCommentEnd(cp)}_stateCommentEndDash(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.HYPHEN_MINUS:{this.state=State.COMMENT_END;break}case CODE_POINTS.EOF:{this._err(ERR.eofInComment);this.emitCurrentComment(token);this._emitEOFToken();break}default:{token.data+="-";this.state=State.COMMENT;this._stateComment(cp)}}}_stateCommentEnd(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentComment(token);break}case CODE_POINTS.EXCLAMATION_MARK:{this.state=State.COMMENT_END_BANG;break}case CODE_POINTS.HYPHEN_MINUS:{token.data+="-";break}case CODE_POINTS.EOF:{this._err(ERR.eofInComment);this.emitCurrentComment(token);this._emitEOFToken();break}default:{token.data+="--";this.state=State.COMMENT;this._stateComment(cp)}}}_stateCommentEndBang(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.HYPHEN_MINUS:{token.data+="--!";this.state=State.COMMENT_END_DASH;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.incorrectlyClosedComment);this.state=State.DATA;this.emitCurrentComment(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInComment);this.emitCurrentComment(token);this._emitEOFToken();break}default:{token.data+="--!";this.state=State.COMMENT;this._stateComment(cp)}}}_stateDoctype(cp){switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this.state=State.BEFORE_DOCTYPE_NAME;break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.BEFORE_DOCTYPE_NAME;this._stateBeforeDoctypeName(cp);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);this._createDoctypeToken(null);const token=this.currentToken;token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingWhitespaceBeforeDoctypeName);this.state=State.BEFORE_DOCTYPE_NAME;this._stateBeforeDoctypeName(cp)}}}_stateBeforeDoctypeName(cp){if(isAsciiUpper(cp)){this._createDoctypeToken(String.fromCharCode(toAsciiLower(cp)));this.state=State.DOCTYPE_NAME}else switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);this._createDoctypeToken(REPLACEMENT_CHARACTER);this.state=State.DOCTYPE_NAME;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingDoctypeName);this._createDoctypeToken(null);const token=this.currentToken;token.forceQuirks=true;this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);this._createDoctypeToken(null);const token=this.currentToken;token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._createDoctypeToken(String.fromCodePoint(cp));this.state=State.DOCTYPE_NAME}}}_stateDoctypeName(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this.state=State.AFTER_DOCTYPE_NAME;break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.name+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{token.name+=String.fromCodePoint(isAsciiUpper(cp)?toAsciiLower(cp):cp)}}}_stateAfterDoctypeName(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{if(this._consumeSequenceIfMatch(SEQUENCES.PUBLIC,false)){this.state=State.AFTER_DOCTYPE_PUBLIC_KEYWORD}else if(this._consumeSequenceIfMatch(SEQUENCES.SYSTEM,false)){this.state=State.AFTER_DOCTYPE_SYSTEM_KEYWORD}else if(!this._ensureHibernation()){this._err(ERR.invalidCharacterSequenceAfterDoctypeName);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}}_stateAfterDoctypePublicKeyword(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this.state=State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case CODE_POINTS.QUOTATION_MARK:{this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);token.publicId="";this.state=State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);token.publicId="";this.state=State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingDoctypePublicIdentifier);token.forceQuirks=true;this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateBeforeDoctypePublicIdentifier(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.QUOTATION_MARK:{token.publicId="";this.state=State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{token.publicId="";this.state=State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingDoctypePublicIdentifier);token.forceQuirks=true;this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateDoctypePublicIdentifierDoubleQuoted(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.QUOTATION_MARK:{this.state=State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.publicId+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.abruptDoctypePublicIdentifier);token.forceQuirks=true;this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{token.publicId+=String.fromCodePoint(cp)}}}_stateDoctypePublicIdentifierSingleQuoted(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.APOSTROPHE:{this.state=State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.publicId+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.abruptDoctypePublicIdentifier);token.forceQuirks=true;this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{token.publicId+=String.fromCodePoint(cp)}}}_stateAfterDoctypePublicIdentifier(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this.state=State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.QUOTATION_MARK:{this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateBetweenDoctypePublicAndSystemIdentifiers(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.GREATER_THAN_SIGN:{this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.QUOTATION_MARK:{token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateAfterDoctypeSystemKeyword(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{this.state=State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case CODE_POINTS.QUOTATION_MARK:{this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingDoctypeSystemIdentifier);token.forceQuirks=true;this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateBeforeDoctypeSystemIdentifier(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.QUOTATION_MARK:{token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case CODE_POINTS.APOSTROPHE:{token.systemId="";this.state=State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.missingDoctypeSystemIdentifier);token.forceQuirks=true;this.state=State.DATA;this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);token.forceQuirks=true;this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateDoctypeSystemIdentifierDoubleQuoted(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.QUOTATION_MARK:{this.state=State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.systemId+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.abruptDoctypeSystemIdentifier);token.forceQuirks=true;this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{token.systemId+=String.fromCodePoint(cp)}}}_stateDoctypeSystemIdentifierSingleQuoted(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.APOSTROPHE:{this.state=State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);token.systemId+=REPLACEMENT_CHARACTER;break}case CODE_POINTS.GREATER_THAN_SIGN:{this._err(ERR.abruptDoctypeSystemIdentifier);token.forceQuirks=true;this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{token.systemId+=String.fromCodePoint(cp)}}}_stateAfterDoctypeSystemIdentifier(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:{break}case CODE_POINTS.GREATER_THAN_SIGN:{this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype);token.forceQuirks=true;this.emitCurrentDoctype(token);this._emitEOFToken();break}default:{this._err(ERR.unexpectedCharacterAfterDoctypeSystemIdentifier);this.state=State.BOGUS_DOCTYPE;this._stateBogusDoctype(cp)}}}_stateBogusDoctype(cp){const token=this.currentToken;switch(cp){case CODE_POINTS.GREATER_THAN_SIGN:{this.emitCurrentDoctype(token);this.state=State.DATA;break}case CODE_POINTS.NULL:{this._err(ERR.unexpectedNullCharacter);break}case CODE_POINTS.EOF:{this.emitCurrentDoctype(token);this._emitEOFToken();break}default:}}_stateCdataSection(cp){switch(cp){case CODE_POINTS.RIGHT_SQUARE_BRACKET:{this.state=State.CDATA_SECTION_BRACKET;break}case CODE_POINTS.EOF:{this._err(ERR.eofInCdata);this._emitEOFToken();break}default:{this._emitCodePoint(cp)}}}_stateCdataSectionBracket(cp){if(cp===CODE_POINTS.RIGHT_SQUARE_BRACKET){this.state=State.CDATA_SECTION_END}else{this._emitChars("]");this.state=State.CDATA_SECTION;this._stateCdataSection(cp)}}_stateCdataSectionEnd(cp){switch(cp){case CODE_POINTS.GREATER_THAN_SIGN:{this.state=State.DATA;break}case CODE_POINTS.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:{this._emitChars("]]");this.state=State.CDATA_SECTION;this._stateCdataSection(cp)}}}_stateCharacterReference(){let length=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(length<0){if(this.preprocessor.lastChunkWritten){length=this.entityDecoder.end()}else{this.active=false;this.preprocessor.pos=this.preprocessor.html.length-1;this.consumedAfterSnapshot=0;this.preprocessor.endOfChunkHit=true;return}}if(length===0){this.preprocessor.pos=this.entityStartPos;this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);this.state=!this._isCharacterReferenceInAttribute()&&isAsciiAlphaNumeric2(this.preprocessor.peek(1))?State.AMBIGUOUS_AMPERSAND:this.returnState}else{this.state=this.returnState}}_stateAmbiguousAmpersand(cp){if(isAsciiAlphaNumeric2(cp)){this._flushCodePointConsumedAsCharacterReference(cp)}else{if(cp===CODE_POINTS.SEMICOLON){this._err(ERR.unknownNamedCharacterReference)}this.state=this.returnState;this._callState(cp)}}};var IMPLICIT_END_TAG_REQUIRED=new Set([TAG_ID.DD,TAG_ID.DT,TAG_ID.LI,TAG_ID.OPTGROUP,TAG_ID.OPTION,TAG_ID.P,TAG_ID.RB,TAG_ID.RP,TAG_ID.RT,TAG_ID.RTC]);var IMPLICIT_END_TAG_REQUIRED_THOROUGHLY=new Set([...IMPLICIT_END_TAG_REQUIRED,TAG_ID.CAPTION,TAG_ID.COLGROUP,TAG_ID.TBODY,TAG_ID.TD,TAG_ID.TFOOT,TAG_ID.TH,TAG_ID.THEAD,TAG_ID.TR]);var SCOPING_ELEMENTS_HTML=new Set([TAG_ID.APPLET,TAG_ID.CAPTION,TAG_ID.HTML,TAG_ID.MARQUEE,TAG_ID.OBJECT,TAG_ID.TABLE,TAG_ID.TD,TAG_ID.TEMPLATE,TAG_ID.TH]);var SCOPING_ELEMENTS_HTML_LIST=new Set([...SCOPING_ELEMENTS_HTML,TAG_ID.OL,TAG_ID.UL]);var SCOPING_ELEMENTS_HTML_BUTTON=new Set([...SCOPING_ELEMENTS_HTML,TAG_ID.BUTTON]);var SCOPING_ELEMENTS_MATHML=new Set([TAG_ID.ANNOTATION_XML,TAG_ID.MI,TAG_ID.MN,TAG_ID.MO,TAG_ID.MS,TAG_ID.MTEXT]);var SCOPING_ELEMENTS_SVG=new Set([TAG_ID.DESC,TAG_ID.FOREIGN_OBJECT,TAG_ID.TITLE]);var TABLE_ROW_CONTEXT=new Set([TAG_ID.TR,TAG_ID.TEMPLATE,TAG_ID.HTML]);var TABLE_BODY_CONTEXT=new Set([TAG_ID.TBODY,TAG_ID.TFOOT,TAG_ID.THEAD,TAG_ID.TEMPLATE,TAG_ID.HTML]);var TABLE_CONTEXT=new Set([TAG_ID.TABLE,TAG_ID.TEMPLATE,TAG_ID.HTML]);var TABLE_CELLS=new Set([TAG_ID.TD,TAG_ID.TH]);var OpenElementStack=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(document,treeAdapter,handler){this.treeAdapter=treeAdapter;this.handler=handler;this.items=[];this.tagIDs=[];this.stackTop=-1;this.tmplCount=0;this.currentTagId=TAG_ID.UNKNOWN;this.current=document}_indexOf(element){return this.items.lastIndexOf(element,this.stackTop)}_isInTemplate(){return this.currentTagId===TAG_ID.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===NS.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop];this.currentTagId=this.tagIDs[this.stackTop]}push(element,tagID){this.stackTop++;this.items[this.stackTop]=element;this.current=element;this.tagIDs[this.stackTop]=tagID;this.currentTagId=tagID;if(this._isInTemplate()){this.tmplCount++}this.handler.onItemPush(element,tagID,true)}pop(){const popped=this.current;if(this.tmplCount>0&&this._isInTemplate()){this.tmplCount--}this.stackTop--;this._updateCurrentElement();this.handler.onItemPop(popped,true)}replace(oldElement,newElement){const idx=this._indexOf(oldElement);this.items[idx]=newElement;if(idx===this.stackTop){this.current=newElement}}insertAfter(referenceElement,newElement,newElementID){const insertionIdx=this._indexOf(referenceElement)+1;this.items.splice(insertionIdx,0,newElement);this.tagIDs.splice(insertionIdx,0,newElementID);this.stackTop++;if(insertionIdx===this.stackTop){this._updateCurrentElement()}if(this.current&&this.currentTagId!==void 0){this.handler.onItemPush(this.current,this.currentTagId,insertionIdx===this.stackTop)}}popUntilTagNamePopped(tagName){let targetIdx=this.stackTop+1;do{targetIdx=this.tagIDs.lastIndexOf(tagName,targetIdx-1)}while(targetIdx>0&&this.treeAdapter.getNamespaceURI(this.items[targetIdx])!==NS.HTML);this.shortenToLength(Math.max(targetIdx,0))}shortenToLength(idx){while(this.stackTop>=idx){const popped=this.current;if(this.tmplCount>0&&this._isInTemplate()){this.tmplCount-=1}this.stackTop--;this._updateCurrentElement();this.handler.onItemPop(popped,this.stackTop<idx)}}popUntilElementPopped(element){const idx=this._indexOf(element);this.shortenToLength(Math.max(idx,0))}popUntilPopped(tagNames,targetNS){const idx=this._indexOfTagNames(tagNames,targetNS);this.shortenToLength(Math.max(idx,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(NUMBERED_HEADERS,NS.HTML)}popUntilTableCellPopped(){this.popUntilPopped(TABLE_CELLS,NS.HTML)}popAllUpToHtmlElement(){this.tmplCount=0;this.shortenToLength(1)}_indexOfTagNames(tagNames,namespace){for(let i=this.stackTop;i>=0;i--){if(tagNames.has(this.tagIDs[i])&&this.treeAdapter.getNamespaceURI(this.items[i])===namespace){return i}}return-1}clearBackTo(tagNames,targetNS){const idx=this._indexOfTagNames(tagNames,targetNS);this.shortenToLength(idx+1)}clearBackToTableContext(){this.clearBackTo(TABLE_CONTEXT,NS.HTML)}clearBackToTableBodyContext(){this.clearBackTo(TABLE_BODY_CONTEXT,NS.HTML)}clearBackToTableRowContext(){this.clearBackTo(TABLE_ROW_CONTEXT,NS.HTML)}remove(element){const idx=this._indexOf(element);if(idx>=0){if(idx===this.stackTop){this.pop()}else{this.items.splice(idx,1);this.tagIDs.splice(idx,1);this.stackTop--;this._updateCurrentElement();this.handler.onItemPop(element,false)}}}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===TAG_ID.BODY?this.items[1]:null}contains(element){return this._indexOf(element)>-1}getCommonAncestor(element){const elementIdx=this._indexOf(element)-1;return elementIdx>=0?this.items[elementIdx]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===TAG_ID.HTML}hasInDynamicScope(tagName,htmlScope){for(let i=this.stackTop;i>=0;i--){const tn=this.tagIDs[i];switch(this.treeAdapter.getNamespaceURI(this.items[i])){case NS.HTML:{if(tn===tagName)return true;if(htmlScope.has(tn))return false;break}case NS.SVG:{if(SCOPING_ELEMENTS_SVG.has(tn))return false;break}case NS.MATHML:{if(SCOPING_ELEMENTS_MATHML.has(tn))return false;break}}}return true}hasInScope(tagName){return this.hasInDynamicScope(tagName,SCOPING_ELEMENTS_HTML)}hasInListItemScope(tagName){return this.hasInDynamicScope(tagName,SCOPING_ELEMENTS_HTML_LIST)}hasInButtonScope(tagName){return this.hasInDynamicScope(tagName,SCOPING_ELEMENTS_HTML_BUTTON)}hasNumberedHeaderInScope(){for(let i=this.stackTop;i>=0;i--){const tn=this.tagIDs[i];switch(this.treeAdapter.getNamespaceURI(this.items[i])){case NS.HTML:{if(NUMBERED_HEADERS.has(tn))return true;if(SCOPING_ELEMENTS_HTML.has(tn))return false;break}case NS.SVG:{if(SCOPING_ELEMENTS_SVG.has(tn))return false;break}case NS.MATHML:{if(SCOPING_ELEMENTS_MATHML.has(tn))return false;break}}}return true}hasInTableScope(tagName){for(let i=this.stackTop;i>=0;i--){if(this.treeAdapter.getNamespaceURI(this.items[i])!==NS.HTML){continue}switch(this.tagIDs[i]){case tagName:{return true}case TAG_ID.TABLE:case TAG_ID.HTML:{return false}}}return true}hasTableBodyContextInTableScope(){for(let i=this.stackTop;i>=0;i--){if(this.treeAdapter.getNamespaceURI(this.items[i])!==NS.HTML){continue}switch(this.tagIDs[i]){case TAG_ID.TBODY:case TAG_ID.THEAD:case TAG_ID.TFOOT:{return true}case TAG_ID.TABLE:case TAG_ID.HTML:{return false}}}return true}hasInSelectScope(tagName){for(let i=this.stackTop;i>=0;i--){if(this.treeAdapter.getNamespaceURI(this.items[i])!==NS.HTML){continue}switch(this.tagIDs[i]){case tagName:{return true}case TAG_ID.OPTION:case TAG_ID.OPTGROUP:{break}default:{return false}}}return true}generateImpliedEndTags(){while(this.currentTagId!==void 0&&IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId)){this.pop()}}generateImpliedEndTagsThoroughly(){while(this.currentTagId!==void 0&&IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)){this.pop()}}generateImpliedEndTagsWithExclusion(exclusionId){while(this.currentTagId!==void 0&&this.currentTagId!==exclusionId&&IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)){this.pop()}}};var NOAH_ARK_CAPACITY=3;var EntryType;(function(EntryType2){EntryType2[EntryType2["Marker"]=0]="Marker";EntryType2[EntryType2["Element"]=1]="Element"})(EntryType||(EntryType={}));var MARKER={type:EntryType.Marker};var FormattingElementList=class{constructor(treeAdapter){this.treeAdapter=treeAdapter;this.entries=[];this.bookmark=null}_getNoahArkConditionCandidates(newElement,neAttrs){const candidates=[];const neAttrsLength=neAttrs.length;const neTagName=this.treeAdapter.getTagName(newElement);const neNamespaceURI=this.treeAdapter.getNamespaceURI(newElement);for(let i=0;i<this.entries.length;i++){const entry=this.entries[i];if(entry.type===EntryType.Marker){break}const{element}=entry;if(this.treeAdapter.getTagName(element)===neTagName&&this.treeAdapter.getNamespaceURI(element)===neNamespaceURI){const elementAttrs=this.treeAdapter.getAttrList(element);if(elementAttrs.length===neAttrsLength){candidates.push({idx:i,attrs:elementAttrs})}}}return candidates}_ensureNoahArkCondition(newElement){if(this.entries.length<NOAH_ARK_CAPACITY)return;const neAttrs=this.treeAdapter.getAttrList(newElement);const candidates=this._getNoahArkConditionCandidates(newElement,neAttrs);if(candidates.length<NOAH_ARK_CAPACITY)return;const neAttrsMap=new Map(neAttrs.map(neAttr=>[neAttr.name,neAttr.value]));let validCandidates=0;for(let i=0;i<candidates.length;i++){const candidate=candidates[i];if(candidate.attrs.every(cAttr=>neAttrsMap.get(cAttr.name)===cAttr.value)){validCandidates+=1;if(validCandidates>=NOAH_ARK_CAPACITY){this.entries.splice(candidate.idx,1)}}}}insertMarker(){this.entries.unshift(MARKER)}pushElement(element,token){this._ensureNoahArkCondition(element);this.entries.unshift({type:EntryType.Element,element,token})}insertElementAfterBookmark(element,token){const bookmarkIdx=this.entries.indexOf(this.bookmark);this.entries.splice(bookmarkIdx,0,{type:EntryType.Element,element,token})}removeEntry(entry){const entryIndex=this.entries.indexOf(entry);if(entryIndex!==-1){this.entries.splice(entryIndex,1)}}clearToLastMarker(){const markerIdx=this.entries.indexOf(MARKER);if(markerIdx===-1){this.entries.length=0}else{this.entries.splice(0,markerIdx+1)}}getElementEntryInScopeWithTagName(tagName){const entry=this.entries.find(entry2=>entry2.type===EntryType.Marker||this.treeAdapter.getTagName(entry2.element)===tagName);return entry&&entry.type===EntryType.Element?entry:null}getElementEntry(element){return this.entries.find(entry=>entry.type===EntryType.Element&&entry.element===element)}};var defaultTreeAdapter={createDocument(){return{nodeName:"#document",mode:DOCUMENT_MODE.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(tagName,namespaceURI,attrs){return{nodeName:tagName,tagName,attrs,namespaceURI,childNodes:[],parentNode:null}},createCommentNode(data){return{nodeName:"#comment",data,parentNode:null}},createTextNode(value){return{nodeName:"#text",value,parentNode:null}},appendChild(parentNode,newNode){parentNode.childNodes.push(newNode);newNode.parentNode=parentNode},insertBefore(parentNode,newNode,referenceNode){const insertionIdx=parentNode.childNodes.indexOf(referenceNode);parentNode.childNodes.splice(insertionIdx,0,newNode);newNode.parentNode=parentNode},setTemplateContent(templateElement,contentElement){templateElement.content=contentElement},getTemplateContent(templateElement){return templateElement.content},setDocumentType(document,name,publicId,systemId){const doctypeNode=document.childNodes.find(node=>node.nodeName==="#documentType");if(doctypeNode){doctypeNode.name=name;doctypeNode.publicId=publicId;doctypeNode.systemId=systemId}else{const node={nodeName:"#documentType",name,publicId,systemId,parentNode:null};defaultTreeAdapter.appendChild(document,node)}},setDocumentMode(document,mode){document.mode=mode},getDocumentMode(document){return document.mode},detachNode(node){if(node.parentNode){const idx=node.parentNode.childNodes.indexOf(node);node.parentNode.childNodes.splice(idx,1);node.parentNode=null}},insertText(parentNode,text){if(parentNode.childNodes.length>0){const prevNode=parentNode.childNodes[parentNode.childNodes.length-1];if(defaultTreeAdapter.isTextNode(prevNode)){prevNode.value+=text;return}}defaultTreeAdapter.appendChild(parentNode,defaultTreeAdapter.createTextNode(text))},insertTextBefore(parentNode,text,referenceNode){const prevNode=parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode)-1];if(prevNode&&defaultTreeAdapter.isTextNode(prevNode)){prevNode.value+=text}else{defaultTreeAdapter.insertBefore(parentNode,defaultTreeAdapter.createTextNode(text),referenceNode)}},adoptAttributes(recipient,attrs){const recipientAttrsMap=new Set(recipient.attrs.map(attr=>attr.name));for(let j=0;j<attrs.length;j++){if(!recipientAttrsMap.has(attrs[j].name)){recipient.attrs.push(attrs[j])}}},getFirstChild(node){return node.childNodes[0]},getChildNodes(node){return node.childNodes},getParentNode(node){return node.parentNode},getAttrList(element){return element.attrs},getTagName(element){return element.tagName},getNamespaceURI(element){return element.namespaceURI},getTextNodeContent(textNode){return textNode.value},getCommentNodeContent(commentNode){return commentNode.data},getDocumentTypeNodeName(doctypeNode){return doctypeNode.name},getDocumentTypeNodePublicId(doctypeNode){return doctypeNode.publicId},getDocumentTypeNodeSystemId(doctypeNode){return doctypeNode.systemId},isTextNode(node){return node.nodeName==="#text"},isCommentNode(node){return node.nodeName==="#comment"},isDocumentTypeNode(node){return node.nodeName==="#documentType"},isElementNode(node){return Object.prototype.hasOwnProperty.call(node,"tagName")},setNodeSourceCodeLocation(node,location){node.sourceCodeLocation=location},getNodeSourceCodeLocation(node){return node.sourceCodeLocation},updateNodeSourceCodeLocation(node,endLocation){node.sourceCodeLocation={...node.sourceCodeLocation,...endLocation}}};var VALID_DOCTYPE_NAME="html";var VALID_SYSTEM_ID="about:legacy-compat";var QUIRKS_MODE_SYSTEM_ID="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd";var QUIRKS_MODE_PUBLIC_ID_PREFIXES=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"];var QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES=[...QUIRKS_MODE_PUBLIC_ID_PREFIXES,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];var QUIRKS_MODE_PUBLIC_IDS=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]);var LIMITED_QUIRKS_PUBLIC_ID_PREFIXES=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"];var LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES=[...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function hasPrefix(publicId,prefixes){return prefixes.some(prefix=>publicId.startsWith(prefix))}function isConforming(token){return token.name===VALID_DOCTYPE_NAME&&token.publicId===null&&(token.systemId===null||token.systemId===VALID_SYSTEM_ID)}function getDocumentMode(token){if(token.name!==VALID_DOCTYPE_NAME){return DOCUMENT_MODE.QUIRKS}const{systemId}=token;if(systemId&&systemId.toLowerCase()===QUIRKS_MODE_SYSTEM_ID){return DOCUMENT_MODE.QUIRKS}let{publicId}=token;if(publicId!==null){publicId=publicId.toLowerCase();if(QUIRKS_MODE_PUBLIC_IDS.has(publicId)){return DOCUMENT_MODE.QUIRKS}let prefixes=systemId===null?QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES:QUIRKS_MODE_PUBLIC_ID_PREFIXES;if(hasPrefix(publicId,prefixes)){return DOCUMENT_MODE.QUIRKS}prefixes=systemId===null?LIMITED_QUIRKS_PUBLIC_ID_PREFIXES:LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;if(hasPrefix(publicId,prefixes)){return DOCUMENT_MODE.LIMITED_QUIRKS}}return DOCUMENT_MODE.NO_QUIRKS}var MIME_TYPES={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"};var DEFINITION_URL_ATTR="definitionurl";var ADJUSTED_DEFINITION_URL_ATTR="definitionURL";var SVG_ATTRS_ADJUSTMENT_MAP=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(attr=>[attr.toLowerCase(),attr]));var XML_ATTRS_ADJUSTMENT_MAP=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:NS.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:NS.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:NS.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:NS.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:NS.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:NS.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:NS.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:NS.XML}],["xml:space",{prefix:"xml",name:"space",namespace:NS.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:NS.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:NS.XMLNS}]]);var SVG_TAG_NAMES_ADJUSTMENT_MAP=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(tn=>[tn.toLowerCase(),tn]));var EXITS_FOREIGN_CONTENT=new Set([TAG_ID.B,TAG_ID.BIG,TAG_ID.BLOCKQUOTE,TAG_ID.BODY,TAG_ID.BR,TAG_ID.CENTER,TAG_ID.CODE,TAG_ID.DD,TAG_ID.DIV,TAG_ID.DL,TAG_ID.DT,TAG_ID.EM,TAG_ID.EMBED,TAG_ID.H1,TAG_ID.H2,TAG_ID.H3,TAG_ID.H4,TAG_ID.H5,TAG_ID.H6,TAG_ID.HEAD,TAG_ID.HR,TAG_ID.I,TAG_ID.IMG,TAG_ID.LI,TAG_ID.LISTING,TAG_ID.MENU,TAG_ID.META,TAG_ID.NOBR,TAG_ID.OL,TAG_ID.P,TAG_ID.PRE,TAG_ID.RUBY,TAG_ID.S,TAG_ID.SMALL,TAG_ID.SPAN,TAG_ID.STRONG,TAG_ID.STRIKE,TAG_ID.SUB,TAG_ID.SUP,TAG_ID.TABLE,TAG_ID.TT,TAG_ID.U,TAG_ID.UL,TAG_ID.VAR]);function causesExit(startTagToken){const tn=startTagToken.tagID;const isFontWithAttrs=tn===TAG_ID.FONT&&startTagToken.attrs.some(({name})=>name===ATTRS.COLOR||name===ATTRS.SIZE||name===ATTRS.FACE);return isFontWithAttrs||EXITS_FOREIGN_CONTENT.has(tn)}function adjustTokenMathMLAttrs(token){for(let i=0;i<token.attrs.length;i++){if(token.attrs[i].name===DEFINITION_URL_ATTR){token.attrs[i].name=ADJUSTED_DEFINITION_URL_ATTR;break}}}function adjustTokenSVGAttrs(token){for(let i=0;i<token.attrs.length;i++){const adjustedAttrName=SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);if(adjustedAttrName!=null){token.attrs[i].name=adjustedAttrName}}}function adjustTokenXMLAttrs(token){for(let i=0;i<token.attrs.length;i++){const adjustedAttrEntry=XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);if(adjustedAttrEntry){token.attrs[i].prefix=adjustedAttrEntry.prefix;token.attrs[i].name=adjustedAttrEntry.name;token.attrs[i].namespace=adjustedAttrEntry.namespace}}}function adjustTokenSVGTagName(token){const adjustedTagName=SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);if(adjustedTagName!=null){token.tagName=adjustedTagName;token.tagID=getTagID(token.tagName)}}function isMathMLTextIntegrationPoint(tn,ns){return ns===NS.MATHML&&(tn===TAG_ID.MI||tn===TAG_ID.MO||tn===TAG_ID.MN||tn===TAG_ID.MS||tn===TAG_ID.MTEXT)}function isHtmlIntegrationPoint(tn,ns,attrs){if(ns===NS.MATHML&&tn===TAG_ID.ANNOTATION_XML){for(let i=0;i<attrs.length;i++){if(attrs[i].name===ATTRS.ENCODING){const value=attrs[i].value.toLowerCase();return value===MIME_TYPES.TEXT_HTML||value===MIME_TYPES.APPLICATION_XML}}}return ns===NS.SVG&&(tn===TAG_ID.FOREIGN_OBJECT||tn===TAG_ID.DESC||tn===TAG_ID.TITLE)}function isIntegrationPoint(tn,ns,attrs,foreignNS){return(!foreignNS||foreignNS===NS.HTML)&&isHtmlIntegrationPoint(tn,ns,attrs)||(!foreignNS||foreignNS===NS.MATHML)&&isMathMLTextIntegrationPoint(tn,ns)}var HIDDEN_INPUT_TYPE="hidden";var AA_OUTER_LOOP_ITER=8;var AA_INNER_LOOP_ITER=3;var InsertionMode;(function(InsertionMode2){InsertionMode2[InsertionMode2["INITIAL"]=0]="INITIAL";InsertionMode2[InsertionMode2["BEFORE_HTML"]=1]="BEFORE_HTML";InsertionMode2[InsertionMode2["BEFORE_HEAD"]=2]="BEFORE_HEAD";InsertionMode2[InsertionMode2["IN_HEAD"]=3]="IN_HEAD";InsertionMode2[InsertionMode2["IN_HEAD_NO_SCRIPT"]=4]="IN_HEAD_NO_SCRIPT";InsertionMode2[InsertionMode2["AFTER_HEAD"]=5]="AFTER_HEAD";InsertionMode2[InsertionMode2["IN_BODY"]=6]="IN_BODY";InsertionMode2[InsertionMode2["TEXT"]=7]="TEXT";InsertionMode2[InsertionMode2["IN_TABLE"]=8]="IN_TABLE";InsertionMode2[InsertionMode2["IN_TABLE_TEXT"]=9]="IN_TABLE_TEXT";InsertionMode2[InsertionMode2["IN_CAPTION"]=10]="IN_CAPTION";InsertionMode2[InsertionMode2["IN_COLUMN_GROUP"]=11]="IN_COLUMN_GROUP";InsertionMode2[InsertionMode2["IN_TABLE_BODY"]=12]="IN_TABLE_BODY";InsertionMode2[InsertionMode2["IN_ROW"]=13]="IN_ROW";InsertionMode2[InsertionMode2["IN_CELL"]=14]="IN_CELL";InsertionMode2[InsertionMode2["IN_SELECT"]=15]="IN_SELECT";InsertionMode2[InsertionMode2["IN_SELECT_IN_TABLE"]=16]="IN_SELECT_IN_TABLE";InsertionMode2[InsertionMode2["IN_TEMPLATE"]=17]="IN_TEMPLATE";InsertionMode2[InsertionMode2["AFTER_BODY"]=18]="AFTER_BODY";InsertionMode2[InsertionMode2["IN_FRAMESET"]=19]="IN_FRAMESET";InsertionMode2[InsertionMode2["AFTER_FRAMESET"]=20]="AFTER_FRAMESET";InsertionMode2[InsertionMode2["AFTER_AFTER_BODY"]=21]="AFTER_AFTER_BODY";InsertionMode2[InsertionMode2["AFTER_AFTER_FRAMESET"]=22]="AFTER_AFTER_FRAMESET"})(InsertionMode||(InsertionMode={}));var BASE_LOC={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1};var TABLE_STRUCTURE_TAGS=new Set([TAG_ID.TABLE,TAG_ID.TBODY,TAG_ID.TFOOT,TAG_ID.THEAD,TAG_ID.TR]);var defaultParserOptions={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:defaultTreeAdapter,onParseError:null};var Parser=class{constructor(options,document,fragmentContext=null,scriptHandler=null){this.fragmentContext=fragmentContext;this.scriptHandler=scriptHandler;this.currentToken=null;this.stopped=false;this.insertionMode=InsertionMode.INITIAL;this.originalInsertionMode=InsertionMode.INITIAL;this.headElement=null;this.formElement=null;this.currentNotInHTML=false;this.tmplInsertionModeStack=[];this.pendingCharacterTokens=[];this.hasNonWhitespacePendingCharacterToken=false;this.framesetOk=true;this.skipNextNewLine=false;this.fosterParentingEnabled=false;this.options={...defaultParserOptions,...options};this.treeAdapter=this.options.treeAdapter;this.onParseError=this.options.onParseError;if(this.onParseError){this.options.sourceCodeLocationInfo=true}this.document=document!==null&&document!==void 0?document:this.treeAdapter.createDocument();this.tokenizer=new Tokenizer(this.options,this);this.activeFormattingElements=new FormattingElementList(this.treeAdapter);this.fragmentContextID=fragmentContext?getTagID(this.treeAdapter.getTagName(fragmentContext)):TAG_ID.UNKNOWN;this._setContextModes(fragmentContext!==null&&fragmentContext!==void 0?fragmentContext:this.document,this.fragmentContextID);this.openElements=new OpenElementStack(this.document,this.treeAdapter,this)}static parse(html,options){const parser2=new this(options);parser2.tokenizer.write(html,true);return parser2.document}static getFragmentParser(fragmentContext,options){const opts={...defaultParserOptions,...options};fragmentContext!==null&&fragmentContext!==void 0?fragmentContext:fragmentContext=opts.treeAdapter.createElement(TAG_NAMES.TEMPLATE,NS.HTML,[]);const documentMock=opts.treeAdapter.createElement("documentmock",NS.HTML,[]);const parser2=new this(opts,documentMock,fragmentContext);if(parser2.fragmentContextID===TAG_ID.TEMPLATE){parser2.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE)}parser2._initTokenizerForFragmentParsing();parser2._insertFakeRootElement();parser2._resetInsertionMode();parser2._findFormInFragmentContext();return parser2}getFragment(){const rootElement=this.treeAdapter.getFirstChild(this.document);const fragment=this.treeAdapter.createDocumentFragment();this._adoptNodes(rootElement,fragment);return fragment}_err(token,code,beforeToken){var _a;if(!this.onParseError)return;const loc=(_a=token.location)!==null&&_a!==void 0?_a:BASE_LOC;const err={code,startLine:loc.startLine,startCol:loc.startCol,startOffset:loc.startOffset,endLine:beforeToken?loc.startLine:loc.endLine,endCol:beforeToken?loc.startCol:loc.endCol,endOffset:beforeToken?loc.startOffset:loc.endOffset};this.onParseError(err)}onItemPush(node,tid,isTop){var _a,_b;(_b=(_a=this.treeAdapter).onItemPush)===null||_b===void 0?void 0:_b.call(_a,node);if(isTop&&this.openElements.stackTop>0)this._setContextModes(node,tid)}onItemPop(node,isTop){var _a,_b;if(this.options.sourceCodeLocationInfo){this._setEndLocation(node,this.currentToken)}(_b=(_a=this.treeAdapter).onItemPop)===null||_b===void 0?void 0:_b.call(_a,node,this.openElements.current);if(isTop){let current;let currentTagId;if(this.openElements.stackTop===0&&this.fragmentContext){current=this.fragmentContext;currentTagId=this.fragmentContextID}else{({current,currentTagId}=this.openElements)}this._setContextModes(current,currentTagId)}}_setContextModes(current,tid){const isHTML=current===this.document||current&&this.treeAdapter.getNamespaceURI(current)===NS.HTML;this.currentNotInHTML=!isHTML;this.tokenizer.inForeignNode=!isHTML&¤t!==void 0&&tid!==void 0&&!this._isIntegrationPoint(tid,current)}_switchToTextParsing(currentToken,nextTokenizerState){this._insertElement(currentToken,NS.HTML);this.tokenizer.state=nextTokenizerState;this.originalInsertionMode=this.insertionMode;this.insertionMode=InsertionMode.TEXT}switchToPlaintextParsing(){this.insertionMode=InsertionMode.TEXT;this.originalInsertionMode=InsertionMode.IN_BODY;this.tokenizer.state=TokenizerMode.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let node=this.fragmentContext;while(node){if(this.treeAdapter.getTagName(node)===TAG_NAMES.FORM){this.formElement=node;break}node=this.treeAdapter.getParentNode(node)}}_initTokenizerForFragmentParsing(){if(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==NS.HTML){return}switch(this.fragmentContextID){case TAG_ID.TITLE:case TAG_ID.TEXTAREA:{this.tokenizer.state=TokenizerMode.RCDATA;break}case TAG_ID.STYLE:case TAG_ID.XMP:case TAG_ID.IFRAME:case TAG_ID.NOEMBED:case TAG_ID.NOFRAMES:case TAG_ID.NOSCRIPT:{this.tokenizer.state=TokenizerMode.RAWTEXT;break}case TAG_ID.SCRIPT:{this.tokenizer.state=TokenizerMode.SCRIPT_DATA;break}case TAG_ID.PLAINTEXT:{this.tokenizer.state=TokenizerMode.PLAINTEXT;break}default:}}_setDocumentType(token){const name=token.name||"";const publicId=token.publicId||"";const systemId=token.systemId||"";this.treeAdapter.setDocumentType(this.document,name,publicId,systemId);if(token.location){const documentChildren=this.treeAdapter.getChildNodes(this.document);const docTypeNode=documentChildren.find(node=>this.treeAdapter.isDocumentTypeNode(node));if(docTypeNode){this.treeAdapter.setNodeSourceCodeLocation(docTypeNode,token.location)}}}_attachElementToTree(element,location){if(this.options.sourceCodeLocationInfo){const loc=location&&{...location,startTag:location};this.treeAdapter.setNodeSourceCodeLocation(element,loc)}if(this._shouldFosterParentOnInsertion()){this._fosterParentElement(element)}else{const parent=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(parent!==null&&parent!==void 0?parent:this.document,element)}}_appendElement(token,namespaceURI){const element=this.treeAdapter.createElement(token.tagName,namespaceURI,token.attrs);this._attachElementToTree(element,token.location)}_insertElement(token,namespaceURI){const element=this.treeAdapter.createElement(token.tagName,namespaceURI,token.attrs);this._attachElementToTree(element,token.location);this.openElements.push(element,token.tagID)}_insertFakeElement(tagName,tagID){const element=this.treeAdapter.createElement(tagName,NS.HTML,[]);this._attachElementToTree(element,null);this.openElements.push(element,tagID)}_insertTemplate(token){const tmpl=this.treeAdapter.createElement(token.tagName,NS.HTML,token.attrs);const content=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(tmpl,content);this._attachElementToTree(tmpl,token.location);this.openElements.push(tmpl,token.tagID);if(this.options.sourceCodeLocationInfo)this.treeAdapter.setNodeSourceCodeLocation(content,null)}_insertFakeRootElement(){const element=this.treeAdapter.createElement(TAG_NAMES.HTML,NS.HTML,[]);if(this.options.sourceCodeLocationInfo)this.treeAdapter.setNodeSourceCodeLocation(element,null);this.treeAdapter.appendChild(this.openElements.current,element);this.openElements.push(element,TAG_ID.HTML)}_appendCommentNode(token,parent){const commentNode=this.treeAdapter.createCommentNode(token.data);this.treeAdapter.appendChild(parent,commentNode);if(this.options.sourceCodeLocationInfo){this.treeAdapter.setNodeSourceCodeLocation(commentNode,token.location)}}_insertCharacters(token){let parent;let beforeElement;if(this._shouldFosterParentOnInsertion()){({parent,beforeElement}=this._findFosterParentingLocation());if(beforeElement){this.treeAdapter.insertTextBefore(parent,token.chars,beforeElement)}else{this.treeAdapter.insertText(parent,token.chars)}}else{parent=this.openElements.currentTmplContentOrNode;this.treeAdapter.insertText(parent,token.chars)}if(!token.location)return;const siblings=this.treeAdapter.getChildNodes(parent);const textNodeIdx=beforeElement?siblings.lastIndexOf(beforeElement):siblings.length;const textNode=siblings[textNodeIdx-1];const tnLoc=this.treeAdapter.getNodeSourceCodeLocation(textNode);if(tnLoc){const{endLine,endCol,endOffset}=token.location;this.treeAdapter.updateNodeSourceCodeLocation(textNode,{endLine,endCol,endOffset})}else if(this.options.sourceCodeLocationInfo){this.treeAdapter.setNodeSourceCodeLocation(textNode,token.location)}}_adoptNodes(donor,recipient){for(let child=this.treeAdapter.getFirstChild(donor);child;child=this.treeAdapter.getFirstChild(donor)){this.treeAdapter.detachNode(child);this.treeAdapter.appendChild(recipient,child)}}_setEndLocation(element,closingToken){if(this.treeAdapter.getNodeSourceCodeLocation(element)&&closingToken.location){const ctLoc=closingToken.location;const tn=this.treeAdapter.getTagName(element);const endLoc=closingToken.type===TokenType.END_TAG&&tn===closingToken.tagName?{endTag:{...ctLoc},endLine:ctLoc.endLine,endCol:ctLoc.endCol,endOffset:ctLoc.endOffset}:{endLine:ctLoc.startLine,endCol:ctLoc.startCol,endOffset:ctLoc.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(element,endLoc)}}shouldProcessStartTagTokenInForeignContent(token){if(!this.currentNotInHTML)return false;let current;let currentTagId;if(this.openElements.stackTop===0&&this.fragmentContext){current=this.fragmentContext;currentTagId=this.fragmentContextID}else{({current,currentTagId}=this.openElements)}if(token.tagID===TAG_ID.SVG&&this.treeAdapter.getTagName(current)===TAG_NAMES.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(current)===NS.MATHML){return false}return this.tokenizer.inForeignNode||(token.tagID===TAG_ID.MGLYPH||token.tagID===TAG_ID.MALIGNMARK)&¤tTagId!==void 0&&!this._isIntegrationPoint(currentTagId,current,NS.HTML)}_processToken(token){switch(token.type){case TokenType.CHARACTER:{this.onCharacter(token);break}case TokenType.NULL_CHARACTER:{this.onNullCharacter(token);break}case TokenType.COMMENT:{this.onComment(token);break}case TokenType.DOCTYPE:{this.onDoctype(token);break}case TokenType.START_TAG:{this._processStartTag(token);break}case TokenType.END_TAG:{this.onEndTag(token);break}case TokenType.EOF:{this.onEof(token);break}case TokenType.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(token);break}}}_isIntegrationPoint(tid,element,foreignNS){const ns=this.treeAdapter.getNamespaceURI(element);const attrs=this.treeAdapter.getAttrList(element);return isIntegrationPoint(tid,ns,attrs,foreignNS)}_reconstructActiveFormattingElements(){const listLength=this.activeFormattingElements.entries.length;if(listLength){const endIndex=this.activeFormattingElements.entries.findIndex(entry=>entry.type===EntryType.Marker||this.openElements.contains(entry.element));const unopenIdx=endIndex===-1?listLength-1:endIndex-1;for(let i=unopenIdx;i>=0;i--){const entry=this.activeFormattingElements.entries[i];this._insertElement(entry.token,this.treeAdapter.getNamespaceURI(entry.element));entry.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags();this.openElements.popUntilTableCellPopped();this.activeFormattingElements.clearToLastMarker();this.insertionMode=InsertionMode.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.P);this.openElements.popUntilTagNamePopped(TAG_ID.P)}_resetInsertionMode(){for(let i=this.openElements.stackTop;i>=0;i--){switch(i===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[i]){case TAG_ID.TR:{this.insertionMode=InsertionMode.IN_ROW;return}case TAG_ID.TBODY:case TAG_ID.THEAD:case TAG_ID.TFOOT:{this.insertionMode=InsertionMode.IN_TABLE_BODY;return}case TAG_ID.CAPTION:{this.insertionMode=InsertionMode.IN_CAPTION;return}case TAG_ID.COLGROUP:{this.insertionMode=InsertionMode.IN_COLUMN_GROUP;return}case TAG_ID.TABLE:{this.insertionMode=InsertionMode.IN_TABLE;return}case TAG_ID.BODY:{this.insertionMode=InsertionMode.IN_BODY;return}case TAG_ID.FRAMESET:{this.insertionMode=InsertionMode.IN_FRAMESET;return}case TAG_ID.SELECT:{this._resetInsertionModeForSelect(i);return}case TAG_ID.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case TAG_ID.HTML:{this.insertionMode=this.headElement?InsertionMode.AFTER_HEAD:InsertionMode.BEFORE_HEAD;return}case TAG_ID.TD:case TAG_ID.TH:{if(i>0){this.insertionMode=InsertionMode.IN_CELL;return}break}case TAG_ID.HEAD:{if(i>0){this.insertionMode=InsertionMode.IN_HEAD;return}break}}}this.insertionMode=InsertionMode.IN_BODY}_resetInsertionModeForSelect(selectIdx){if(selectIdx>0){for(let i=selectIdx-1;i>0;i--){const tn=this.openElements.tagIDs[i];if(tn===TAG_ID.TEMPLATE){break}else if(tn===TAG_ID.TABLE){this.insertionMode=InsertionMode.IN_SELECT_IN_TABLE;return}}}this.insertionMode=InsertionMode.IN_SELECT}_isElementCausesFosterParenting(tn){return TABLE_STRUCTURE_TAGS.has(tn)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let i=this.openElements.stackTop;i>=0;i--){const openElement=this.openElements.items[i];switch(this.openElements.tagIDs[i]){case TAG_ID.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(openElement)===NS.HTML){return{parent:this.treeAdapter.getTemplateContent(openElement),beforeElement:null}}break}case TAG_ID.TABLE:{const parent=this.treeAdapter.getParentNode(openElement);if(parent){return{parent,beforeElement:openElement}}return{parent:this.openElements.items[i-1],beforeElement:null}}default:}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(element){const location=this._findFosterParentingLocation();if(location.beforeElement){this.treeAdapter.insertBefore(location.parent,element,location.beforeElement)}else{this.treeAdapter.appendChild(location.parent,element)}}_isSpecialElement(element,id){const ns=this.treeAdapter.getNamespaceURI(element);return SPECIAL_ELEMENTS[ns].has(id)}onCharacter(token){this.skipNextNewLine=false;if(this.tokenizer.inForeignNode){characterInForeignContent(this,token);return}switch(this.insertionMode){case InsertionMode.INITIAL:{tokenInInitialMode(this,token);break}case InsertionMode.BEFORE_HTML:{tokenBeforeHtml(this,token);break}case InsertionMode.BEFORE_HEAD:{tokenBeforeHead(this,token);break}case InsertionMode.IN_HEAD:{tokenInHead(this,token);break}case InsertionMode.IN_HEAD_NO_SCRIPT:{tokenInHeadNoScript(this,token);break}case InsertionMode.AFTER_HEAD:{tokenAfterHead(this,token);break}case InsertionMode.IN_BODY:case InsertionMode.IN_CAPTION:case InsertionMode.IN_CELL:case InsertionMode.IN_TEMPLATE:{characterInBody(this,token);break}case InsertionMode.TEXT:case InsertionMode.IN_SELECT:case InsertionMode.IN_SELECT_IN_TABLE:{this._insertCharacters(token);break}case InsertionMode.IN_TABLE:case InsertionMode.IN_TABLE_BODY:case InsertionMode.IN_ROW:{characterInTable(this,token);break}case InsertionMode.IN_TABLE_TEXT:{characterInTableText(this,token);break}case InsertionMode.IN_COLUMN_GROUP:{tokenInColumnGroup(this,token);break}case InsertionMode.AFTER_BODY:{tokenAfterBody(this,token);break}case InsertionMode.AFTER_AFTER_BODY:{tokenAfterAfterBody(this,token);break}default:}}onNullCharacter(token){this.skipNextNewLine=false;if(this.tokenizer.inForeignNode){nullCharacterInForeignContent(this,token);return}switch(this.insertionMode){case InsertionMode.INITIAL:{tokenInInitialMode(this,token);break}case InsertionMode.BEFORE_HTML:{tokenBeforeHtml(this,token);break}case InsertionMode.BEFORE_HEAD:{tokenBeforeHead(this,token);break}case InsertionMode.IN_HEAD:{tokenInHead(this,token);break}case InsertionMode.IN_HEAD_NO_SCRIPT:{tokenInHeadNoScript(this,token);break}case InsertionMode.AFTER_HEAD:{tokenAfterHead(this,token);break}case InsertionMode.TEXT:{this._insertCharacters(token);break}case InsertionMode.IN_TABLE:case InsertionMode.IN_TABLE_BODY:case InsertionMode.IN_ROW:{characterInTable(this,token);break}case InsertionMode.IN_COLUMN_GROUP:{tokenInColumnGroup(this,token);break}case InsertionMode.AFTER_BODY:{tokenAfterBody(this,token);break}case InsertionMode.AFTER_AFTER_BODY:{tokenAfterAfterBody(this,token);break}default:}}onComment(token){this.skipNextNewLine=false;if(this.currentNotInHTML){appendComment(this,token);return}switch(this.insertionMode){case InsertionMode.INITIAL:case InsertionMode.BEFORE_HTML:case InsertionMode.BEFORE_HEAD:case InsertionMode.IN_HEAD:case InsertionMode.IN_HEAD_NO_SCRIPT:case InsertionMode.AFTER_HEAD:case InsertionMode.IN_BODY:case InsertionMode.IN_TABLE:case InsertionMode.IN_CAPTION:case InsertionMode.IN_COLUMN_GROUP:case InsertionMode.IN_TABLE_BODY:case InsertionMode.IN_ROW:case InsertionMode.IN_CELL:case InsertionMode.IN_SELECT:case InsertionMode.IN_SELECT_IN_TABLE:case InsertionMode.IN_TEMPLATE:case InsertionMode.IN_FRAMESET:case InsertionMode.AFTER_FRAMESET:{appendComment(this,token);break}case InsertionMode.IN_TABLE_TEXT:{tokenInTableText(this,token);break}case InsertionMode.AFTER_BODY:{appendCommentToRootHtmlElement(this,token);break}case InsertionMode.AFTER_AFTER_BODY:case InsertionMode.AFTER_AFTER_FRAMESET:{appendCommentToDocument(this,token);break}default:}}onDoctype(token){this.skipNextNewLine=false;switch(this.insertionMode){case InsertionMode.INITIAL:{doctypeInInitialMode(this,token);break}case InsertionMode.BEFORE_HEAD:case InsertionMode.IN_HEAD:case InsertionMode.IN_HEAD_NO_SCRIPT:case InsertionMode.AFTER_HEAD:{this._err(token,ERR.misplacedDoctype);break}case InsertionMode.IN_TABLE_TEXT:{tokenInTableText(this,token);break}default:}}onStartTag(token){this.skipNextNewLine=false;this.currentToken=token;this._processStartTag(token);if(token.selfClosing&&!token.ackSelfClosing){this._err(token,ERR.nonVoidHtmlElementStartTagWithTrailingSolidus)}}_processStartTag(token){if(this.shouldProcessStartTagTokenInForeignContent(token)){startTagInForeignContent(this,token)}else{this._startTagOutsideForeignContent(token)}}_startTagOutsideForeignContent(token){switch(this.insertionMode){case InsertionMode.INITIAL:{tokenInInitialMode(this,token);break}case InsertionMode.BEFORE_HTML:{startTagBeforeHtml(this,token);break}case InsertionMode.BEFORE_HEAD:{startTagBeforeHead(this,token);break}case InsertionMode.IN_HEAD:{startTagInHead(this,token);break}case InsertionMode.IN_HEAD_NO_SCRIPT:{startTagInHeadNoScript(this,token);break}case InsertionMode.AFTER_HEAD:{startTagAfterHead(this,token);break}case InsertionMode.IN_BODY:{startTagInBody(this,token);break}case InsertionMode.IN_TABLE:{startTagInTable(this,token);break}case InsertionMode.IN_TABLE_TEXT:{tokenInTableText(this,token);break}case InsertionMode.IN_CAPTION:{startTagInCaption(this,token);break}case InsertionMode.IN_COLUMN_GROUP:{startTagInColumnGroup(this,token);break}case InsertionMode.IN_TABLE_BODY:{startTagInTableBody(this,token);break}case InsertionMode.IN_ROW:{startTagInRow(this,token);break}case InsertionMode.IN_CELL:{startTagInCell(this,token);break}case InsertionMode.IN_SELECT:{startTagInSelect(this,token);break}case InsertionMode.IN_SELECT_IN_TABLE:{startTagInSelectInTable(this,token);break}case InsertionMode.IN_TEMPLATE:{startTagInTemplate(this,token);break}case InsertionMode.AFTER_BODY:{startTagAfterBody(this,token);break}case InsertionMode.IN_FRAMESET:{startTagInFrameset(this,token);break}case InsertionMode.AFTER_FRAMESET:{startTagAfterFrameset(this,token);break}case InsertionMode.AFTER_AFTER_BODY:{startTagAfterAfterBody(this,token);break}case InsertionMode.AFTER_AFTER_FRAMESET:{startTagAfterAfterFrameset(this,token);break}default:}}onEndTag(token){this.skipNextNewLine=false;this.currentToken=token;if(this.currentNotInHTML){endTagInForeignContent(this,token)}else{this._endTagOutsideForeignContent(token)}}_endTagOutsideForeignContent(token){switch(this.insertionMode){case InsertionMode.INITIAL:{tokenInInitialMode(this,token);break}case InsertionMode.BEFORE_HTML:{endTagBeforeHtml(this,token);break}case InsertionMode.BEFORE_HEAD:{endTagBeforeHead(this,token);break}case InsertionMode.IN_HEAD:{endTagInHead(this,token);break}case InsertionMode.IN_HEAD_NO_SCRIPT:{endTagInHeadNoScript(this,token);break}case InsertionMode.AFTER_HEAD:{endTagAfterHead(this,token);break}case InsertionMode.IN_BODY:{endTagInBody(this,token);break}case InsertionMode.TEXT:{endTagInText(this,token);break}case InsertionMode.IN_TABLE:{endTagInTable(this,token);break}case InsertionMode.IN_TABLE_TEXT:{tokenInTableText(this,token);break}case InsertionMode.IN_CAPTION:{endTagInCaption(this,token);break}case InsertionMode.IN_COLUMN_GROUP:{endTagInColumnGroup(this,token);break}case InsertionMode.IN_TABLE_BODY:{endTagInTableBody(this,token);break}case InsertionMode.IN_ROW:{endTagInRow(this,token);break}case InsertionMode.IN_CELL:{endTagInCell(this,token);break}case InsertionMode.IN_SELECT:{endTagInSelect(this,token);break}case InsertionMode.IN_SELECT_IN_TABLE:{endTagInSelectInTable(this,token);break}case InsertionMode.IN_TEMPLATE:{endTagInTemplate(this,token);break}case InsertionMode.AFTER_BODY:{endTagAfterBody(this,token);break}case InsertionMode.IN_FRAMESET:{endTagInFrameset(this,token);break}case InsertionMode.AFTER_FRAMESET:{endTagAfterFrameset(this,token);break}case InsertionMode.AFTER_AFTER_BODY:{tokenAfterAfterBody(this,token);break}default:}}onEof(token){switch(this.insertionMode){case InsertionMode.INITIAL:{tokenInInitialMode(this,token);break}case InsertionMode.BEFORE_HTML:{tokenBeforeHtml(this,token);break}case InsertionMode.BEFORE_HEAD:{tokenBeforeHead(this,token);break}case InsertionMode.IN_HEAD:{tokenInHead(this,token);break}case InsertionMode.IN_HEAD_NO_SCRIPT:{tokenInHeadNoScript(this,token);break}case InsertionMode.AFTER_HEAD:{tokenAfterHead(this,token);break}case InsertionMode.IN_BODY:case InsertionMode.IN_TABLE:case InsertionMode.IN_CAPTION:case InsertionMode.IN_COLUMN_GROUP:case InsertionMode.IN_TABLE_BODY:case InsertionMode.IN_ROW:case InsertionMode.IN_CELL:case InsertionMode.IN_SELECT:case InsertionMode.IN_SELECT_IN_TABLE:{eofInBody(this,token);break}case InsertionMode.TEXT:{eofInText(this,token);break}case InsertionMode.IN_TABLE_TEXT:{tokenInTableText(this,token);break}case InsertionMode.IN_TEMPLATE:{eofInTemplate(this,token);break}case InsertionMode.AFTER_BODY:case InsertionMode.IN_FRAMESET:case InsertionMode.AFTER_FRAMESET:case InsertionMode.AFTER_AFTER_BODY:case InsertionMode.AFTER_AFTER_FRAMESET:{stopParsing(this,token);break}default:}}onWhitespaceCharacter(token){if(this.skipNextNewLine){this.skipNextNewLine=false;if(token.chars.charCodeAt(0)===CODE_POINTS.LINE_FEED){if(token.chars.length===1){return}token.chars=token.chars.substr(1)}}if(this.tokenizer.inForeignNode){this._insertCharacters(token);return}switch(this.insertionMode){case InsertionMode.IN_HEAD:case InsertionMode.IN_HEAD_NO_SCRIPT:case InsertionMode.AFTER_HEAD:case InsertionMode.TEXT:case InsertionMode.IN_COLUMN_GROUP:case InsertionMode.IN_SELECT:case InsertionMode.IN_SELECT_IN_TABLE:case InsertionMode.IN_FRAMESET:case InsertionMode.AFTER_FRAMESET:{this._insertCharacters(token);break}case InsertionMode.IN_BODY:case InsertionMode.IN_CAPTION:case InsertionMode.IN_CELL:case InsertionMode.IN_TEMPLATE:case InsertionMode.AFTER_BODY:case InsertionMode.AFTER_AFTER_BODY:case InsertionMode.AFTER_AFTER_FRAMESET:{whitespaceCharacterInBody(this,token);break}case InsertionMode.IN_TABLE:case InsertionMode.IN_TABLE_BODY:case InsertionMode.IN_ROW:{characterInTable(this,token);break}case InsertionMode.IN_TABLE_TEXT:{whitespaceCharacterInTableText(this,token);break}default:}}};function aaObtainFormattingElementEntry(p,token){let formattingElementEntry=p.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName);if(formattingElementEntry){if(!p.openElements.contains(formattingElementEntry.element)){p.activeFormattingElements.removeEntry(formattingElementEntry);formattingElementEntry=null}else if(!p.openElements.hasInScope(token.tagID)){formattingElementEntry=null}}else{genericEndTagInBody(p,token)}return formattingElementEntry}function aaObtainFurthestBlock(p,formattingElementEntry){let furthestBlock=null;let idx=p.openElements.stackTop;for(;idx>=0;idx--){const element=p.openElements.items[idx];if(element===formattingElementEntry.element){break}if(p._isSpecialElement(element,p.openElements.tagIDs[idx])){furthestBlock=element}}if(!furthestBlock){p.openElements.shortenToLength(Math.max(idx,0));p.activeFormattingElements.removeEntry(formattingElementEntry)}return furthestBlock}function aaInnerLoop(p,furthestBlock,formattingElement){let lastElement=furthestBlock;let nextElement=p.openElements.getCommonAncestor(furthestBlock);for(let i=0,element=nextElement;element!==formattingElement;i++,element=nextElement){nextElement=p.openElements.getCommonAncestor(element);const elementEntry=p.activeFormattingElements.getElementEntry(element);const counterOverflow=elementEntry&&i>=AA_INNER_LOOP_ITER;const shouldRemoveFromOpenElements=!elementEntry||counterOverflow;if(shouldRemoveFromOpenElements){if(counterOverflow){p.activeFormattingElements.removeEntry(elementEntry)}p.openElements.remove(element)}else{element=aaRecreateElementFromEntry(p,elementEntry);if(lastElement===furthestBlock){p.activeFormattingElements.bookmark=elementEntry}p.treeAdapter.detachNode(lastElement);p.treeAdapter.appendChild(element,lastElement);lastElement=element}}return lastElement}function aaRecreateElementFromEntry(p,elementEntry){const ns=p.treeAdapter.getNamespaceURI(elementEntry.element);const newElement=p.treeAdapter.createElement(elementEntry.token.tagName,ns,elementEntry.token.attrs);p.openElements.replace(elementEntry.element,newElement);elementEntry.element=newElement;return newElement}function aaInsertLastNodeInCommonAncestor(p,commonAncestor,lastElement){const tn=p.treeAdapter.getTagName(commonAncestor);const tid=getTagID(tn);if(p._isElementCausesFosterParenting(tid)){p._fosterParentElement(lastElement)}else{const ns=p.treeAdapter.getNamespaceURI(commonAncestor);if(tid===TAG_ID.TEMPLATE&&ns===NS.HTML){commonAncestor=p.treeAdapter.getTemplateContent(commonAncestor)}p.treeAdapter.appendChild(commonAncestor,lastElement)}}function aaReplaceFormattingElement(p,furthestBlock,formattingElementEntry){const ns=p.treeAdapter.getNamespaceURI(formattingElementEntry.element);const{token}=formattingElementEntry;const newElement=p.treeAdapter.createElement(token.tagName,ns,token.attrs);p._adoptNodes(furthestBlock,newElement);p.treeAdapter.appendChild(furthestBlock,newElement);p.activeFormattingElements.insertElementAfterBookmark(newElement,token);p.activeFormattingElements.removeEntry(formattingElementEntry);p.openElements.remove(formattingElementEntry.element);p.openElements.insertAfter(furthestBlock,newElement,token.tagID)}function callAdoptionAgency(p,token){for(let i=0;i<AA_OUTER_LOOP_ITER;i++){const formattingElementEntry=aaObtainFormattingElementEntry(p,token);if(!formattingElementEntry){break}const furthestBlock=aaObtainFurthestBlock(p,formattingElementEntry);if(!furthestBlock){break}p.activeFormattingElements.bookmark=formattingElementEntry;const lastElement=aaInnerLoop(p,furthestBlock,formattingElementEntry.element);const commonAncestor=p.openElements.getCommonAncestor(formattingElementEntry.element);p.treeAdapter.detachNode(lastElement);if(commonAncestor)aaInsertLastNodeInCommonAncestor(p,commonAncestor,lastElement);aaReplaceFormattingElement(p,furthestBlock,formattingElementEntry)}}function appendComment(p,token){p._appendCommentNode(token,p.openElements.currentTmplContentOrNode)}function appendCommentToRootHtmlElement(p,token){p._appendCommentNode(token,p.openElements.items[0])}function appendCommentToDocument(p,token){p._appendCommentNode(token,p.document)}function stopParsing(p,token){p.stopped=true;if(token.location){const target=p.fragmentContext?0:2;for(let i=p.openElements.stackTop;i>=target;i--){p._setEndLocation(p.openElements.items[i],token)}if(!p.fragmentContext&&p.openElements.stackTop>=0){const htmlElement=p.openElements.items[0];const htmlLocation=p.treeAdapter.getNodeSourceCodeLocation(htmlElement);if(htmlLocation&&!htmlLocation.endTag){p._setEndLocation(htmlElement,token);if(p.openElements.stackTop>=1){const bodyElement=p.openElements.items[1];const bodyLocation=p.treeAdapter.getNodeSourceCodeLocation(bodyElement);if(bodyLocation&&!bodyLocation.endTag){p._setEndLocation(bodyElement,token)}}}}}}function doctypeInInitialMode(p,token){p._setDocumentType(token);const mode=token.forceQuirks?DOCUMENT_MODE.QUIRKS:getDocumentMode(token);if(!isConforming(token)){p._err(token,ERR.nonConformingDoctype)}p.treeAdapter.setDocumentMode(p.document,mode);p.insertionMode=InsertionMode.BEFORE_HTML}function tokenInInitialMode(p,token){p._err(token,ERR.missingDoctype,true);p.treeAdapter.setDocumentMode(p.document,DOCUMENT_MODE.QUIRKS);p.insertionMode=InsertionMode.BEFORE_HTML;p._processToken(token)}function startTagBeforeHtml(p,token){if(token.tagID===TAG_ID.HTML){p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.BEFORE_HEAD}else{tokenBeforeHtml(p,token)}}function endTagBeforeHtml(p,token){const tn=token.tagID;if(tn===TAG_ID.HTML||tn===TAG_ID.HEAD||tn===TAG_ID.BODY||tn===TAG_ID.BR){tokenBeforeHtml(p,token)}}function tokenBeforeHtml(p,token){p._insertFakeRootElement();p.insertionMode=InsertionMode.BEFORE_HEAD;p._processToken(token)}function startTagBeforeHead(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.HEAD:{p._insertElement(token,NS.HTML);p.headElement=p.openElements.current;p.insertionMode=InsertionMode.IN_HEAD;break}default:{tokenBeforeHead(p,token)}}}function endTagBeforeHead(p,token){const tn=token.tagID;if(tn===TAG_ID.HEAD||tn===TAG_ID.BODY||tn===TAG_ID.HTML||tn===TAG_ID.BR){tokenBeforeHead(p,token)}else{p._err(token,ERR.endTagWithoutMatchingOpenElement)}}function tokenBeforeHead(p,token){p._insertFakeElement(TAG_NAMES.HEAD,TAG_ID.HEAD);p.headElement=p.openElements.current;p.insertionMode=InsertionMode.IN_HEAD;p._processToken(token)}function startTagInHead(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.BASE:case TAG_ID.BASEFONT:case TAG_ID.BGSOUND:case TAG_ID.LINK:case TAG_ID.META:{p._appendElement(token,NS.HTML);token.ackSelfClosing=true;break}case TAG_ID.TITLE:{p._switchToTextParsing(token,TokenizerMode.RCDATA);break}case TAG_ID.NOSCRIPT:{if(p.options.scriptingEnabled){p._switchToTextParsing(token,TokenizerMode.RAWTEXT)}else{p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_HEAD_NO_SCRIPT}break}case TAG_ID.NOFRAMES:case TAG_ID.STYLE:{p._switchToTextParsing(token,TokenizerMode.RAWTEXT);break}case TAG_ID.SCRIPT:{p._switchToTextParsing(token,TokenizerMode.SCRIPT_DATA);break}case TAG_ID.TEMPLATE:{p._insertTemplate(token);p.activeFormattingElements.insertMarker();p.framesetOk=false;p.insertionMode=InsertionMode.IN_TEMPLATE;p.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);break}case TAG_ID.HEAD:{p._err(token,ERR.misplacedStartTagForHeadElement);break}default:{tokenInHead(p,token)}}}function endTagInHead(p,token){switch(token.tagID){case TAG_ID.HEAD:{p.openElements.pop();p.insertionMode=InsertionMode.AFTER_HEAD;break}case TAG_ID.BODY:case TAG_ID.BR:case TAG_ID.HTML:{tokenInHead(p,token);break}case TAG_ID.TEMPLATE:{templateEndTagInHead(p,token);break}default:{p._err(token,ERR.endTagWithoutMatchingOpenElement)}}}function templateEndTagInHead(p,token){if(p.openElements.tmplCount>0){p.openElements.generateImpliedEndTagsThoroughly();if(p.openElements.currentTagId!==TAG_ID.TEMPLATE){p._err(token,ERR.closingOfElementWithOpenChildElements)}p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);p.activeFormattingElements.clearToLastMarker();p.tmplInsertionModeStack.shift();p._resetInsertionMode()}else{p._err(token,ERR.endTagWithoutMatchingOpenElement)}}function tokenInHead(p,token){p.openElements.pop();p.insertionMode=InsertionMode.AFTER_HEAD;p._processToken(token)}function startTagInHeadNoScript(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.BASEFONT:case TAG_ID.BGSOUND:case TAG_ID.HEAD:case TAG_ID.LINK:case TAG_ID.META:case TAG_ID.NOFRAMES:case TAG_ID.STYLE:{startTagInHead(p,token);break}case TAG_ID.NOSCRIPT:{p._err(token,ERR.nestedNoscriptInHead);break}default:{tokenInHeadNoScript(p,token)}}}function endTagInHeadNoScript(p,token){switch(token.tagID){case TAG_ID.NOSCRIPT:{p.openElements.pop();p.insertionMode=InsertionMode.IN_HEAD;break}case TAG_ID.BR:{tokenInHeadNoScript(p,token);break}default:{p._err(token,ERR.endTagWithoutMatchingOpenElement)}}}function tokenInHeadNoScript(p,token){const errCode=token.type===TokenType.EOF?ERR.openElementsLeftAfterEof:ERR.disallowedContentInNoscriptInHead;p._err(token,errCode);p.openElements.pop();p.insertionMode=InsertionMode.IN_HEAD;p._processToken(token)}function startTagAfterHead(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.BODY:{p._insertElement(token,NS.HTML);p.framesetOk=false;p.insertionMode=InsertionMode.IN_BODY;break}case TAG_ID.FRAMESET:{p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_FRAMESET;break}case TAG_ID.BASE:case TAG_ID.BASEFONT:case TAG_ID.BGSOUND:case TAG_ID.LINK:case TAG_ID.META:case TAG_ID.NOFRAMES:case TAG_ID.SCRIPT:case TAG_ID.STYLE:case TAG_ID.TEMPLATE:case TAG_ID.TITLE:{p._err(token,ERR.abandonedHeadElementChild);p.openElements.push(p.headElement,TAG_ID.HEAD);startTagInHead(p,token);p.openElements.remove(p.headElement);break}case TAG_ID.HEAD:{p._err(token,ERR.misplacedStartTagForHeadElement);break}default:{tokenAfterHead(p,token)}}}function endTagAfterHead(p,token){switch(token.tagID){case TAG_ID.BODY:case TAG_ID.HTML:case TAG_ID.BR:{tokenAfterHead(p,token);break}case TAG_ID.TEMPLATE:{templateEndTagInHead(p,token);break}default:{p._err(token,ERR.endTagWithoutMatchingOpenElement)}}}function tokenAfterHead(p,token){p._insertFakeElement(TAG_NAMES.BODY,TAG_ID.BODY);p.insertionMode=InsertionMode.IN_BODY;modeInBody(p,token)}function modeInBody(p,token){switch(token.type){case TokenType.CHARACTER:{characterInBody(p,token);break}case TokenType.WHITESPACE_CHARACTER:{whitespaceCharacterInBody(p,token);break}case TokenType.COMMENT:{appendComment(p,token);break}case TokenType.START_TAG:{startTagInBody(p,token);break}case TokenType.END_TAG:{endTagInBody(p,token);break}case TokenType.EOF:{eofInBody(p,token);break}default:}}function whitespaceCharacterInBody(p,token){p._reconstructActiveFormattingElements();p._insertCharacters(token)}function characterInBody(p,token){p._reconstructActiveFormattingElements();p._insertCharacters(token);p.framesetOk=false}function htmlStartTagInBody(p,token){if(p.openElements.tmplCount===0){p.treeAdapter.adoptAttributes(p.openElements.items[0],token.attrs)}}function bodyStartTagInBody(p,token){const bodyElement=p.openElements.tryPeekProperlyNestedBodyElement();if(bodyElement&&p.openElements.tmplCount===0){p.framesetOk=false;p.treeAdapter.adoptAttributes(bodyElement,token.attrs)}}function framesetStartTagInBody(p,token){const bodyElement=p.openElements.tryPeekProperlyNestedBodyElement();if(p.framesetOk&&bodyElement){p.treeAdapter.detachNode(bodyElement);p.openElements.popAllUpToHtmlElement();p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_FRAMESET}}function addressStartTagInBody(p,token){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._insertElement(token,NS.HTML)}function numberedHeaderStartTagInBody(p,token){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}if(p.openElements.currentTagId!==void 0&&NUMBERED_HEADERS.has(p.openElements.currentTagId)){p.openElements.pop()}p._insertElement(token,NS.HTML)}function preStartTagInBody(p,token){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._insertElement(token,NS.HTML);p.skipNextNewLine=true;p.framesetOk=false}function formStartTagInBody(p,token){const inTemplate=p.openElements.tmplCount>0;if(!p.formElement||inTemplate){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._insertElement(token,NS.HTML);if(!inTemplate){p.formElement=p.openElements.current}}}function listItemStartTagInBody(p,token){p.framesetOk=false;const tn=token.tagID;for(let i=p.openElements.stackTop;i>=0;i--){const elementId=p.openElements.tagIDs[i];if(tn===TAG_ID.LI&&elementId===TAG_ID.LI||(tn===TAG_ID.DD||tn===TAG_ID.DT)&&(elementId===TAG_ID.DD||elementId===TAG_ID.DT)){p.openElements.generateImpliedEndTagsWithExclusion(elementId);p.openElements.popUntilTagNamePopped(elementId);break}if(elementId!==TAG_ID.ADDRESS&&elementId!==TAG_ID.DIV&&elementId!==TAG_ID.P&&p._isSpecialElement(p.openElements.items[i],elementId)){break}}if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._insertElement(token,NS.HTML)}function plaintextStartTagInBody(p,token){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._insertElement(token,NS.HTML);p.tokenizer.state=TokenizerMode.PLAINTEXT}function buttonStartTagInBody(p,token){if(p.openElements.hasInScope(TAG_ID.BUTTON)){p.openElements.generateImpliedEndTags();p.openElements.popUntilTagNamePopped(TAG_ID.BUTTON)}p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML);p.framesetOk=false}function aStartTagInBody(p,token){const activeElementEntry=p.activeFormattingElements.getElementEntryInScopeWithTagName(TAG_NAMES.A);if(activeElementEntry){callAdoptionAgency(p,token);p.openElements.remove(activeElementEntry.element);p.activeFormattingElements.removeEntry(activeElementEntry)}p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML);p.activeFormattingElements.pushElement(p.openElements.current,token)}function bStartTagInBody(p,token){p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML);p.activeFormattingElements.pushElement(p.openElements.current,token)}function nobrStartTagInBody(p,token){p._reconstructActiveFormattingElements();if(p.openElements.hasInScope(TAG_ID.NOBR)){callAdoptionAgency(p,token);p._reconstructActiveFormattingElements()}p._insertElement(token,NS.HTML);p.activeFormattingElements.pushElement(p.openElements.current,token)}function appletStartTagInBody(p,token){p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML);p.activeFormattingElements.insertMarker();p.framesetOk=false}function tableStartTagInBody(p,token){if(p.treeAdapter.getDocumentMode(p.document)!==DOCUMENT_MODE.QUIRKS&&p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._insertElement(token,NS.HTML);p.framesetOk=false;p.insertionMode=InsertionMode.IN_TABLE}function areaStartTagInBody(p,token){p._reconstructActiveFormattingElements();p._appendElement(token,NS.HTML);p.framesetOk=false;token.ackSelfClosing=true}function isHiddenInput(token){const inputType=getTokenAttr(token,ATTRS.TYPE);return inputType!=null&&inputType.toLowerCase()===HIDDEN_INPUT_TYPE}function inputStartTagInBody(p,token){p._reconstructActiveFormattingElements();p._appendElement(token,NS.HTML);if(!isHiddenInput(token)){p.framesetOk=false}token.ackSelfClosing=true}function paramStartTagInBody(p,token){p._appendElement(token,NS.HTML);token.ackSelfClosing=true}function hrStartTagInBody(p,token){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._appendElement(token,NS.HTML);p.framesetOk=false;token.ackSelfClosing=true}function imageStartTagInBody(p,token){token.tagName=TAG_NAMES.IMG;token.tagID=TAG_ID.IMG;areaStartTagInBody(p,token)}function textareaStartTagInBody(p,token){p._insertElement(token,NS.HTML);p.skipNextNewLine=true;p.tokenizer.state=TokenizerMode.RCDATA;p.originalInsertionMode=p.insertionMode;p.framesetOk=false;p.insertionMode=InsertionMode.TEXT}function xmpStartTagInBody(p,token){if(p.openElements.hasInButtonScope(TAG_ID.P)){p._closePElement()}p._reconstructActiveFormattingElements();p.framesetOk=false;p._switchToTextParsing(token,TokenizerMode.RAWTEXT)}function iframeStartTagInBody(p,token){p.framesetOk=false;p._switchToTextParsing(token,TokenizerMode.RAWTEXT)}function rawTextStartTagInBody(p,token){p._switchToTextParsing(token,TokenizerMode.RAWTEXT)}function selectStartTagInBody(p,token){p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML);p.framesetOk=false;p.insertionMode=p.insertionMode===InsertionMode.IN_TABLE||p.insertionMode===InsertionMode.IN_CAPTION||p.insertionMode===InsertionMode.IN_TABLE_BODY||p.insertionMode===InsertionMode.IN_ROW||p.insertionMode===InsertionMode.IN_CELL?InsertionMode.IN_SELECT_IN_TABLE:InsertionMode.IN_SELECT}function optgroupStartTagInBody(p,token){if(p.openElements.currentTagId===TAG_ID.OPTION){p.openElements.pop()}p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML)}function rbStartTagInBody(p,token){if(p.openElements.hasInScope(TAG_ID.RUBY)){p.openElements.generateImpliedEndTags()}p._insertElement(token,NS.HTML)}function rtStartTagInBody(p,token){if(p.openElements.hasInScope(TAG_ID.RUBY)){p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.RTC)}p._insertElement(token,NS.HTML)}function mathStartTagInBody(p,token){p._reconstructActiveFormattingElements();adjustTokenMathMLAttrs(token);adjustTokenXMLAttrs(token);if(token.selfClosing){p._appendElement(token,NS.MATHML)}else{p._insertElement(token,NS.MATHML)}token.ackSelfClosing=true}function svgStartTagInBody(p,token){p._reconstructActiveFormattingElements();adjustTokenSVGAttrs(token);adjustTokenXMLAttrs(token);if(token.selfClosing){p._appendElement(token,NS.SVG)}else{p._insertElement(token,NS.SVG)}token.ackSelfClosing=true}function genericStartTagInBody(p,token){p._reconstructActiveFormattingElements();p._insertElement(token,NS.HTML)}function startTagInBody(p,token){switch(token.tagID){case TAG_ID.I:case TAG_ID.S:case TAG_ID.B:case TAG_ID.U:case TAG_ID.EM:case TAG_ID.TT:case TAG_ID.BIG:case TAG_ID.CODE:case TAG_ID.FONT:case TAG_ID.SMALL:case TAG_ID.STRIKE:case TAG_ID.STRONG:{bStartTagInBody(p,token);break}case TAG_ID.A:{aStartTagInBody(p,token);break}case TAG_ID.H1:case TAG_ID.H2:case TAG_ID.H3:case TAG_ID.H4:case TAG_ID.H5:case TAG_ID.H6:{numberedHeaderStartTagInBody(p,token);break}case TAG_ID.P:case TAG_ID.DL:case TAG_ID.OL:case TAG_ID.UL:case TAG_ID.DIV:case TAG_ID.DIR:case TAG_ID.NAV:case TAG_ID.MAIN:case TAG_ID.MENU:case TAG_ID.ASIDE:case TAG_ID.CENTER:case TAG_ID.FIGURE:case TAG_ID.FOOTER:case TAG_ID.HEADER:case TAG_ID.HGROUP:case TAG_ID.DIALOG:case TAG_ID.DETAILS:case TAG_ID.ADDRESS:case TAG_ID.ARTICLE:case TAG_ID.SEARCH:case TAG_ID.SECTION:case TAG_ID.SUMMARY:case TAG_ID.FIELDSET:case TAG_ID.BLOCKQUOTE:case TAG_ID.FIGCAPTION:{addressStartTagInBody(p,token);break}case TAG_ID.LI:case TAG_ID.DD:case TAG_ID.DT:{listItemStartTagInBody(p,token);break}case TAG_ID.BR:case TAG_ID.IMG:case TAG_ID.WBR:case TAG_ID.AREA:case TAG_ID.EMBED:case TAG_ID.KEYGEN:{areaStartTagInBody(p,token);break}case TAG_ID.HR:{hrStartTagInBody(p,token);break}case TAG_ID.RB:case TAG_ID.RTC:{rbStartTagInBody(p,token);break}case TAG_ID.RT:case TAG_ID.RP:{rtStartTagInBody(p,token);break}case TAG_ID.PRE:case TAG_ID.LISTING:{preStartTagInBody(p,token);break}case TAG_ID.XMP:{xmpStartTagInBody(p,token);break}case TAG_ID.SVG:{svgStartTagInBody(p,token);break}case TAG_ID.HTML:{htmlStartTagInBody(p,token);break}case TAG_ID.BASE:case TAG_ID.LINK:case TAG_ID.META:case TAG_ID.STYLE:case TAG_ID.TITLE:case TAG_ID.SCRIPT:case TAG_ID.BGSOUND:case TAG_ID.BASEFONT:case TAG_ID.TEMPLATE:{startTagInHead(p,token);break}case TAG_ID.BODY:{bodyStartTagInBody(p,token);break}case TAG_ID.FORM:{formStartTagInBody(p,token);break}case TAG_ID.NOBR:{nobrStartTagInBody(p,token);break}case TAG_ID.MATH:{mathStartTagInBody(p,token);break}case TAG_ID.TABLE:{tableStartTagInBody(p,token);break}case TAG_ID.INPUT:{inputStartTagInBody(p,token);break}case TAG_ID.PARAM:case TAG_ID.TRACK:case TAG_ID.SOURCE:{paramStartTagInBody(p,token);break}case TAG_ID.IMAGE:{imageStartTagInBody(p,token);break}case TAG_ID.BUTTON:{buttonStartTagInBody(p,token);break}case TAG_ID.APPLET:case TAG_ID.OBJECT:case TAG_ID.MARQUEE:{appletStartTagInBody(p,token);break}case TAG_ID.IFRAME:{iframeStartTagInBody(p,token);break}case TAG_ID.SELECT:{selectStartTagInBody(p,token);break}case TAG_ID.OPTION:case TAG_ID.OPTGROUP:{optgroupStartTagInBody(p,token);break}case TAG_ID.NOEMBED:case TAG_ID.NOFRAMES:{rawTextStartTagInBody(p,token);break}case TAG_ID.FRAMESET:{framesetStartTagInBody(p,token);break}case TAG_ID.TEXTAREA:{textareaStartTagInBody(p,token);break}case TAG_ID.NOSCRIPT:{if(p.options.scriptingEnabled){rawTextStartTagInBody(p,token)}else{genericStartTagInBody(p,token)}break}case TAG_ID.PLAINTEXT:{plaintextStartTagInBody(p,token);break}case TAG_ID.COL:case TAG_ID.TH:case TAG_ID.TD:case TAG_ID.TR:case TAG_ID.HEAD:case TAG_ID.FRAME:case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:case TAG_ID.CAPTION:case TAG_ID.COLGROUP:{break}default:{genericStartTagInBody(p,token)}}}function bodyEndTagInBody(p,token){if(p.openElements.hasInScope(TAG_ID.BODY)){p.insertionMode=InsertionMode.AFTER_BODY;if(p.options.sourceCodeLocationInfo){const bodyElement=p.openElements.tryPeekProperlyNestedBodyElement();if(bodyElement){p._setEndLocation(bodyElement,token)}}}}function htmlEndTagInBody(p,token){if(p.openElements.hasInScope(TAG_ID.BODY)){p.insertionMode=InsertionMode.AFTER_BODY;endTagAfterBody(p,token)}}function addressEndTagInBody(p,token){const tn=token.tagID;if(p.openElements.hasInScope(tn)){p.openElements.generateImpliedEndTags();p.openElements.popUntilTagNamePopped(tn)}}function formEndTagInBody(p){const inTemplate=p.openElements.tmplCount>0;const{formElement}=p;if(!inTemplate){p.formElement=null}if((formElement||inTemplate)&&p.openElements.hasInScope(TAG_ID.FORM)){p.openElements.generateImpliedEndTags();if(inTemplate){p.openElements.popUntilTagNamePopped(TAG_ID.FORM)}else if(formElement){p.openElements.remove(formElement)}}}function pEndTagInBody(p){if(!p.openElements.hasInButtonScope(TAG_ID.P)){p._insertFakeElement(TAG_NAMES.P,TAG_ID.P)}p._closePElement()}function liEndTagInBody(p){if(p.openElements.hasInListItemScope(TAG_ID.LI)){p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.LI);p.openElements.popUntilTagNamePopped(TAG_ID.LI)}}function ddEndTagInBody(p,token){const tn=token.tagID;if(p.openElements.hasInScope(tn)){p.openElements.generateImpliedEndTagsWithExclusion(tn);p.openElements.popUntilTagNamePopped(tn)}}function numberedHeaderEndTagInBody(p){if(p.openElements.hasNumberedHeaderInScope()){p.openElements.generateImpliedEndTags();p.openElements.popUntilNumberedHeaderPopped()}}function appletEndTagInBody(p,token){const tn=token.tagID;if(p.openElements.hasInScope(tn)){p.openElements.generateImpliedEndTags();p.openElements.popUntilTagNamePopped(tn);p.activeFormattingElements.clearToLastMarker()}}function brEndTagInBody(p){p._reconstructActiveFormattingElements();p._insertFakeElement(TAG_NAMES.BR,TAG_ID.BR);p.openElements.pop();p.framesetOk=false}function genericEndTagInBody(p,token){const tn=token.tagName;const tid=token.tagID;for(let i=p.openElements.stackTop;i>0;i--){const element=p.openElements.items[i];const elementId=p.openElements.tagIDs[i];if(tid===elementId&&(tid!==TAG_ID.UNKNOWN||p.treeAdapter.getTagName(element)===tn)){p.openElements.generateImpliedEndTagsWithExclusion(tid);if(p.openElements.stackTop>=i)p.openElements.shortenToLength(i);break}if(p._isSpecialElement(element,elementId)){break}}}function endTagInBody(p,token){switch(token.tagID){case TAG_ID.A:case TAG_ID.B:case TAG_ID.I:case TAG_ID.S:case TAG_ID.U:case TAG_ID.EM:case TAG_ID.TT:case TAG_ID.BIG:case TAG_ID.CODE:case TAG_ID.FONT:case TAG_ID.NOBR:case TAG_ID.SMALL:case TAG_ID.STRIKE:case TAG_ID.STRONG:{callAdoptionAgency(p,token);break}case TAG_ID.P:{pEndTagInBody(p);break}case TAG_ID.DL:case TAG_ID.UL:case TAG_ID.OL:case TAG_ID.DIR:case TAG_ID.DIV:case TAG_ID.NAV:case TAG_ID.PRE:case TAG_ID.MAIN:case TAG_ID.MENU:case TAG_ID.ASIDE:case TAG_ID.BUTTON:case TAG_ID.CENTER:case TAG_ID.FIGURE:case TAG_ID.FOOTER:case TAG_ID.HEADER:case TAG_ID.HGROUP:case TAG_ID.DIALOG:case TAG_ID.ADDRESS:case TAG_ID.ARTICLE:case TAG_ID.DETAILS:case TAG_ID.SEARCH:case TAG_ID.SECTION:case TAG_ID.SUMMARY:case TAG_ID.LISTING:case TAG_ID.FIELDSET:case TAG_ID.BLOCKQUOTE:case TAG_ID.FIGCAPTION:{addressEndTagInBody(p,token);break}case TAG_ID.LI:{liEndTagInBody(p);break}case TAG_ID.DD:case TAG_ID.DT:{ddEndTagInBody(p,token);break}case TAG_ID.H1:case TAG_ID.H2:case TAG_ID.H3:case TAG_ID.H4:case TAG_ID.H5:case TAG_ID.H6:{numberedHeaderEndTagInBody(p);break}case TAG_ID.BR:{brEndTagInBody(p);break}case TAG_ID.BODY:{bodyEndTagInBody(p,token);break}case TAG_ID.HTML:{htmlEndTagInBody(p,token);break}case TAG_ID.FORM:{formEndTagInBody(p);break}case TAG_ID.APPLET:case TAG_ID.OBJECT:case TAG_ID.MARQUEE:{appletEndTagInBody(p,token);break}case TAG_ID.TEMPLATE:{templateEndTagInHead(p,token);break}default:{genericEndTagInBody(p,token)}}}function eofInBody(p,token){if(p.tmplInsertionModeStack.length>0){eofInTemplate(p,token)}else{stopParsing(p,token)}}function endTagInText(p,token){var _a;if(token.tagID===TAG_ID.SCRIPT){(_a=p.scriptHandler)===null||_a===void 0?void 0:_a.call(p,p.openElements.current)}p.openElements.pop();p.insertionMode=p.originalInsertionMode}function eofInText(p,token){p._err(token,ERR.eofInElementThatCanContainOnlyText);p.openElements.pop();p.insertionMode=p.originalInsertionMode;p.onEof(token)}function characterInTable(p,token){if(p.openElements.currentTagId!==void 0&&TABLE_STRUCTURE_TAGS.has(p.openElements.currentTagId)){p.pendingCharacterTokens.length=0;p.hasNonWhitespacePendingCharacterToken=false;p.originalInsertionMode=p.insertionMode;p.insertionMode=InsertionMode.IN_TABLE_TEXT;switch(token.type){case TokenType.CHARACTER:{characterInTableText(p,token);break}case TokenType.WHITESPACE_CHARACTER:{whitespaceCharacterInTableText(p,token);break}}}else{tokenInTable(p,token)}}function captionStartTagInTable(p,token){p.openElements.clearBackToTableContext();p.activeFormattingElements.insertMarker();p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_CAPTION}function colgroupStartTagInTable(p,token){p.openElements.clearBackToTableContext();p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_COLUMN_GROUP}function colStartTagInTable(p,token){p.openElements.clearBackToTableContext();p._insertFakeElement(TAG_NAMES.COLGROUP,TAG_ID.COLGROUP);p.insertionMode=InsertionMode.IN_COLUMN_GROUP;startTagInColumnGroup(p,token)}function tbodyStartTagInTable(p,token){p.openElements.clearBackToTableContext();p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_TABLE_BODY}function tdStartTagInTable(p,token){p.openElements.clearBackToTableContext();p._insertFakeElement(TAG_NAMES.TBODY,TAG_ID.TBODY);p.insertionMode=InsertionMode.IN_TABLE_BODY;startTagInTableBody(p,token)}function tableStartTagInTable(p,token){if(p.openElements.hasInTableScope(TAG_ID.TABLE)){p.openElements.popUntilTagNamePopped(TAG_ID.TABLE);p._resetInsertionMode();p._processStartTag(token)}}function inputStartTagInTable(p,token){if(isHiddenInput(token)){p._appendElement(token,NS.HTML)}else{tokenInTable(p,token)}token.ackSelfClosing=true}function formStartTagInTable(p,token){if(!p.formElement&&p.openElements.tmplCount===0){p._insertElement(token,NS.HTML);p.formElement=p.openElements.current;p.openElements.pop()}}function startTagInTable(p,token){switch(token.tagID){case TAG_ID.TD:case TAG_ID.TH:case TAG_ID.TR:{tdStartTagInTable(p,token);break}case TAG_ID.STYLE:case TAG_ID.SCRIPT:case TAG_ID.TEMPLATE:{startTagInHead(p,token);break}case TAG_ID.COL:{colStartTagInTable(p,token);break}case TAG_ID.FORM:{formStartTagInTable(p,token);break}case TAG_ID.TABLE:{tableStartTagInTable(p,token);break}case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:{tbodyStartTagInTable(p,token);break}case TAG_ID.INPUT:{inputStartTagInTable(p,token);break}case TAG_ID.CAPTION:{captionStartTagInTable(p,token);break}case TAG_ID.COLGROUP:{colgroupStartTagInTable(p,token);break}default:{tokenInTable(p,token)}}}function endTagInTable(p,token){switch(token.tagID){case TAG_ID.TABLE:{if(p.openElements.hasInTableScope(TAG_ID.TABLE)){p.openElements.popUntilTagNamePopped(TAG_ID.TABLE);p._resetInsertionMode()}break}case TAG_ID.TEMPLATE:{templateEndTagInHead(p,token);break}case TAG_ID.BODY:case TAG_ID.CAPTION:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.HTML:case TAG_ID.TBODY:case TAG_ID.TD:case TAG_ID.TFOOT:case TAG_ID.TH:case TAG_ID.THEAD:case TAG_ID.TR:{break}default:{tokenInTable(p,token)}}}function tokenInTable(p,token){const savedFosterParentingState=p.fosterParentingEnabled;p.fosterParentingEnabled=true;modeInBody(p,token);p.fosterParentingEnabled=savedFosterParentingState}function whitespaceCharacterInTableText(p,token){p.pendingCharacterTokens.push(token)}function characterInTableText(p,token){p.pendingCharacterTokens.push(token);p.hasNonWhitespacePendingCharacterToken=true}function tokenInTableText(p,token){let i=0;if(p.hasNonWhitespacePendingCharacterToken){for(;i<p.pendingCharacterTokens.length;i++){tokenInTable(p,p.pendingCharacterTokens[i])}}else{for(;i<p.pendingCharacterTokens.length;i++){p._insertCharacters(p.pendingCharacterTokens[i])}}p.insertionMode=p.originalInsertionMode;p._processToken(token)}var TABLE_VOID_ELEMENTS=new Set([TAG_ID.CAPTION,TAG_ID.COL,TAG_ID.COLGROUP,TAG_ID.TBODY,TAG_ID.TD,TAG_ID.TFOOT,TAG_ID.TH,TAG_ID.THEAD,TAG_ID.TR]);function startTagInCaption(p,token){const tn=token.tagID;if(TABLE_VOID_ELEMENTS.has(tn)){if(p.openElements.hasInTableScope(TAG_ID.CAPTION)){p.openElements.generateImpliedEndTags();p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);p.activeFormattingElements.clearToLastMarker();p.insertionMode=InsertionMode.IN_TABLE;startTagInTable(p,token)}}else{startTagInBody(p,token)}}function endTagInCaption(p,token){const tn=token.tagID;switch(tn){case TAG_ID.CAPTION:case TAG_ID.TABLE:{if(p.openElements.hasInTableScope(TAG_ID.CAPTION)){p.openElements.generateImpliedEndTags();p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);p.activeFormattingElements.clearToLastMarker();p.insertionMode=InsertionMode.IN_TABLE;if(tn===TAG_ID.TABLE){endTagInTable(p,token)}}break}case TAG_ID.BODY:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.HTML:case TAG_ID.TBODY:case TAG_ID.TD:case TAG_ID.TFOOT:case TAG_ID.TH:case TAG_ID.THEAD:case TAG_ID.TR:{break}default:{endTagInBody(p,token)}}}function startTagInColumnGroup(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.COL:{p._appendElement(token,NS.HTML);token.ackSelfClosing=true;break}case TAG_ID.TEMPLATE:{startTagInHead(p,token);break}default:{tokenInColumnGroup(p,token)}}}function endTagInColumnGroup(p,token){switch(token.tagID){case TAG_ID.COLGROUP:{if(p.openElements.currentTagId===TAG_ID.COLGROUP){p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE}break}case TAG_ID.TEMPLATE:{templateEndTagInHead(p,token);break}case TAG_ID.COL:{break}default:{tokenInColumnGroup(p,token)}}}function tokenInColumnGroup(p,token){if(p.openElements.currentTagId===TAG_ID.COLGROUP){p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE;p._processToken(token)}}function startTagInTableBody(p,token){switch(token.tagID){case TAG_ID.TR:{p.openElements.clearBackToTableBodyContext();p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_ROW;break}case TAG_ID.TH:case TAG_ID.TD:{p.openElements.clearBackToTableBodyContext();p._insertFakeElement(TAG_NAMES.TR,TAG_ID.TR);p.insertionMode=InsertionMode.IN_ROW;startTagInRow(p,token);break}case TAG_ID.CAPTION:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:{if(p.openElements.hasTableBodyContextInTableScope()){p.openElements.clearBackToTableBodyContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE;startTagInTable(p,token)}break}default:{startTagInTable(p,token)}}}function endTagInTableBody(p,token){const tn=token.tagID;switch(token.tagID){case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:{if(p.openElements.hasInTableScope(tn)){p.openElements.clearBackToTableBodyContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE}break}case TAG_ID.TABLE:{if(p.openElements.hasTableBodyContextInTableScope()){p.openElements.clearBackToTableBodyContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE;endTagInTable(p,token)}break}case TAG_ID.BODY:case TAG_ID.CAPTION:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.HTML:case TAG_ID.TD:case TAG_ID.TH:case TAG_ID.TR:{break}default:{endTagInTable(p,token)}}}function startTagInRow(p,token){switch(token.tagID){case TAG_ID.TH:case TAG_ID.TD:{p.openElements.clearBackToTableRowContext();p._insertElement(token,NS.HTML);p.insertionMode=InsertionMode.IN_CELL;p.activeFormattingElements.insertMarker();break}case TAG_ID.CAPTION:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:case TAG_ID.TR:{if(p.openElements.hasInTableScope(TAG_ID.TR)){p.openElements.clearBackToTableRowContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE_BODY;startTagInTableBody(p,token)}break}default:{startTagInTable(p,token)}}}function endTagInRow(p,token){switch(token.tagID){case TAG_ID.TR:{if(p.openElements.hasInTableScope(TAG_ID.TR)){p.openElements.clearBackToTableRowContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE_BODY}break}case TAG_ID.TABLE:{if(p.openElements.hasInTableScope(TAG_ID.TR)){p.openElements.clearBackToTableRowContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE_BODY;endTagInTableBody(p,token)}break}case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:{if(p.openElements.hasInTableScope(token.tagID)||p.openElements.hasInTableScope(TAG_ID.TR)){p.openElements.clearBackToTableRowContext();p.openElements.pop();p.insertionMode=InsertionMode.IN_TABLE_BODY;endTagInTableBody(p,token)}break}case TAG_ID.BODY:case TAG_ID.CAPTION:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.HTML:case TAG_ID.TD:case TAG_ID.TH:{break}default:{endTagInTable(p,token)}}}function startTagInCell(p,token){const tn=token.tagID;if(TABLE_VOID_ELEMENTS.has(tn)){if(p.openElements.hasInTableScope(TAG_ID.TD)||p.openElements.hasInTableScope(TAG_ID.TH)){p._closeTableCell();startTagInRow(p,token)}}else{startTagInBody(p,token)}}function endTagInCell(p,token){const tn=token.tagID;switch(tn){case TAG_ID.TD:case TAG_ID.TH:{if(p.openElements.hasInTableScope(tn)){p.openElements.generateImpliedEndTags();p.openElements.popUntilTagNamePopped(tn);p.activeFormattingElements.clearToLastMarker();p.insertionMode=InsertionMode.IN_ROW}break}case TAG_ID.TABLE:case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:case TAG_ID.TR:{if(p.openElements.hasInTableScope(tn)){p._closeTableCell();endTagInRow(p,token)}break}case TAG_ID.BODY:case TAG_ID.CAPTION:case TAG_ID.COL:case TAG_ID.COLGROUP:case TAG_ID.HTML:{break}default:{endTagInBody(p,token)}}}function startTagInSelect(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.OPTION:{if(p.openElements.currentTagId===TAG_ID.OPTION){p.openElements.pop()}p._insertElement(token,NS.HTML);break}case TAG_ID.OPTGROUP:{if(p.openElements.currentTagId===TAG_ID.OPTION){p.openElements.pop()}if(p.openElements.currentTagId===TAG_ID.OPTGROUP){p.openElements.pop()}p._insertElement(token,NS.HTML);break}case TAG_ID.HR:{if(p.openElements.currentTagId===TAG_ID.OPTION){p.openElements.pop()}if(p.openElements.currentTagId===TAG_ID.OPTGROUP){p.openElements.pop()}p._appendElement(token,NS.HTML);token.ackSelfClosing=true;break}case TAG_ID.INPUT:case TAG_ID.KEYGEN:case TAG_ID.TEXTAREA:case TAG_ID.SELECT:{if(p.openElements.hasInSelectScope(TAG_ID.SELECT)){p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);p._resetInsertionMode();if(token.tagID!==TAG_ID.SELECT){p._processStartTag(token)}}break}case TAG_ID.SCRIPT:case TAG_ID.TEMPLATE:{startTagInHead(p,token);break}default:}}function endTagInSelect(p,token){switch(token.tagID){case TAG_ID.OPTGROUP:{if(p.openElements.stackTop>0&&p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.tagIDs[p.openElements.stackTop-1]===TAG_ID.OPTGROUP){p.openElements.pop()}if(p.openElements.currentTagId===TAG_ID.OPTGROUP){p.openElements.pop()}break}case TAG_ID.OPTION:{if(p.openElements.currentTagId===TAG_ID.OPTION){p.openElements.pop()}break}case TAG_ID.SELECT:{if(p.openElements.hasInSelectScope(TAG_ID.SELECT)){p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);p._resetInsertionMode()}break}case TAG_ID.TEMPLATE:{templateEndTagInHead(p,token);break}default:}}function startTagInSelectInTable(p,token){const tn=token.tagID;if(tn===TAG_ID.CAPTION||tn===TAG_ID.TABLE||tn===TAG_ID.TBODY||tn===TAG_ID.TFOOT||tn===TAG_ID.THEAD||tn===TAG_ID.TR||tn===TAG_ID.TD||tn===TAG_ID.TH){p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);p._resetInsertionMode();p._processStartTag(token)}else{startTagInSelect(p,token)}}function endTagInSelectInTable(p,token){const tn=token.tagID;if(tn===TAG_ID.CAPTION||tn===TAG_ID.TABLE||tn===TAG_ID.TBODY||tn===TAG_ID.TFOOT||tn===TAG_ID.THEAD||tn===TAG_ID.TR||tn===TAG_ID.TD||tn===TAG_ID.TH){if(p.openElements.hasInTableScope(tn)){p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);p._resetInsertionMode();p.onEndTag(token)}}else{endTagInSelect(p,token)}}function startTagInTemplate(p,token){switch(token.tagID){case TAG_ID.BASE:case TAG_ID.BASEFONT:case TAG_ID.BGSOUND:case TAG_ID.LINK:case TAG_ID.META:case TAG_ID.NOFRAMES:case TAG_ID.SCRIPT:case TAG_ID.STYLE:case TAG_ID.TEMPLATE:case TAG_ID.TITLE:{startTagInHead(p,token);break}case TAG_ID.CAPTION:case TAG_ID.COLGROUP:case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:{p.tmplInsertionModeStack[0]=InsertionMode.IN_TABLE;p.insertionMode=InsertionMode.IN_TABLE;startTagInTable(p,token);break}case TAG_ID.COL:{p.tmplInsertionModeStack[0]=InsertionMode.IN_COLUMN_GROUP;p.insertionMode=InsertionMode.IN_COLUMN_GROUP;startTagInColumnGroup(p,token);break}case TAG_ID.TR:{p.tmplInsertionModeStack[0]=InsertionMode.IN_TABLE_BODY;p.insertionMode=InsertionMode.IN_TABLE_BODY;startTagInTableBody(p,token);break}case TAG_ID.TD:case TAG_ID.TH:{p.tmplInsertionModeStack[0]=InsertionMode.IN_ROW;p.insertionMode=InsertionMode.IN_ROW;startTagInRow(p,token);break}default:{p.tmplInsertionModeStack[0]=InsertionMode.IN_BODY;p.insertionMode=InsertionMode.IN_BODY;startTagInBody(p,token)}}}function endTagInTemplate(p,token){if(token.tagID===TAG_ID.TEMPLATE){templateEndTagInHead(p,token)}}function eofInTemplate(p,token){if(p.openElements.tmplCount>0){p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);p.activeFormattingElements.clearToLastMarker();p.tmplInsertionModeStack.shift();p._resetInsertionMode();p.onEof(token)}else{stopParsing(p,token)}}function startTagAfterBody(p,token){if(token.tagID===TAG_ID.HTML){startTagInBody(p,token)}else{tokenAfterBody(p,token)}}function endTagAfterBody(p,token){var _a;if(token.tagID===TAG_ID.HTML){if(!p.fragmentContext){p.insertionMode=InsertionMode.AFTER_AFTER_BODY}if(p.options.sourceCodeLocationInfo&&p.openElements.tagIDs[0]===TAG_ID.HTML){p._setEndLocation(p.openElements.items[0],token);const bodyElement=p.openElements.items[1];if(bodyElement&&!((_a=p.treeAdapter.getNodeSourceCodeLocation(bodyElement))===null||_a===void 0?void 0:_a.endTag)){p._setEndLocation(bodyElement,token)}}}else{tokenAfterBody(p,token)}}function tokenAfterBody(p,token){p.insertionMode=InsertionMode.IN_BODY;modeInBody(p,token)}function startTagInFrameset(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.FRAMESET:{p._insertElement(token,NS.HTML);break}case TAG_ID.FRAME:{p._appendElement(token,NS.HTML);token.ackSelfClosing=true;break}case TAG_ID.NOFRAMES:{startTagInHead(p,token);break}default:}}function endTagInFrameset(p,token){if(token.tagID===TAG_ID.FRAMESET&&!p.openElements.isRootHtmlElementCurrent()){p.openElements.pop();if(!p.fragmentContext&&p.openElements.currentTagId!==TAG_ID.FRAMESET){p.insertionMode=InsertionMode.AFTER_FRAMESET}}}function startTagAfterFrameset(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.NOFRAMES:{startTagInHead(p,token);break}default:}}function endTagAfterFrameset(p,token){if(token.tagID===TAG_ID.HTML){p.insertionMode=InsertionMode.AFTER_AFTER_FRAMESET}}function startTagAfterAfterBody(p,token){if(token.tagID===TAG_ID.HTML){startTagInBody(p,token)}else{tokenAfterAfterBody(p,token)}}function tokenAfterAfterBody(p,token){p.insertionMode=InsertionMode.IN_BODY;modeInBody(p,token)}function startTagAfterAfterFrameset(p,token){switch(token.tagID){case TAG_ID.HTML:{startTagInBody(p,token);break}case TAG_ID.NOFRAMES:{startTagInHead(p,token);break}default:}}function nullCharacterInForeignContent(p,token){token.chars=REPLACEMENT_CHARACTER;p._insertCharacters(token)}function characterInForeignContent(p,token){p._insertCharacters(token);p.framesetOk=false}function popUntilHtmlOrIntegrationPoint(p){while(p.treeAdapter.getNamespaceURI(p.openElements.current)!==NS.HTML&&p.openElements.currentTagId!==void 0&&!p._isIntegrationPoint(p.openElements.currentTagId,p.openElements.current)){p.openElements.pop()}}function startTagInForeignContent(p,token){if(causesExit(token)){popUntilHtmlOrIntegrationPoint(p);p._startTagOutsideForeignContent(token)}else{const current=p._getAdjustedCurrentElement();const currentNs=p.treeAdapter.getNamespaceURI(current);if(currentNs===NS.MATHML){adjustTokenMathMLAttrs(token)}else if(currentNs===NS.SVG){adjustTokenSVGTagName(token);adjustTokenSVGAttrs(token)}adjustTokenXMLAttrs(token);if(token.selfClosing){p._appendElement(token,currentNs)}else{p._insertElement(token,currentNs)}token.ackSelfClosing=true}}function endTagInForeignContent(p,token){if(token.tagID===TAG_ID.P||token.tagID===TAG_ID.BR){popUntilHtmlOrIntegrationPoint(p);p._endTagOutsideForeignContent(token);return}for(let i=p.openElements.stackTop;i>0;i--){const element=p.openElements.items[i];if(p.treeAdapter.getNamespaceURI(element)===NS.HTML){p._endTagOutsideForeignContent(token);break}const tagName=p.treeAdapter.getTagName(element);if(tagName.toLowerCase()===token.tagName){token.tagName=tagName;p.openElements.shortenToLength(i);break}}}var VOID_ELEMENTS=new Set([TAG_NAMES.AREA,TAG_NAMES.BASE,TAG_NAMES.BASEFONT,TAG_NAMES.BGSOUND,TAG_NAMES.BR,TAG_NAMES.COL,TAG_NAMES.EMBED,TAG_NAMES.FRAME,TAG_NAMES.HR,TAG_NAMES.IMG,TAG_NAMES.INPUT,TAG_NAMES.KEYGEN,TAG_NAMES.LINK,TAG_NAMES.META,TAG_NAMES.PARAM,TAG_NAMES.SOURCE,TAG_NAMES.TRACK,TAG_NAMES.WBR]);function parse(html,options){return Parser.parse(html,options)}function getAttribute(node,name){return node.attrs?.find(item=>item.name.toLowerCase()===name.toLowerCase())?.value??null}function getText(node){if(node.nodeName==="#text")return node.value??"";return(node.childNodes??[]).map(getText).join("")}function cleanText(value){const cleaned=value?.replace(/\s+/g," ").trim();return cleaned||null}function extractSeoData(html){const document=parse(html);const result={title:null,description:null,canonical:null,robots:null,lang:null,h1Count:0,openGraph:{title:null,description:null,image:null},twitter:{card:null,title:null,description:null,image:null},hreflang:[],jsonLd:[],images:[],links:[],wordCount:0,visibleText:""};const textParts=[];function visit(node,hidden=false){const tagName=node.tagName?.toLowerCase();const excludesText=hidden||tagName==="script"||tagName==="style"||tagName==="noscript"||tagName==="template";if(node.nodeName==="#text"&&!excludesText){const text=cleanText(node.value);if(text)textParts.push(text)}if(tagName==="html"&&result.lang===null)result.lang=cleanText(getAttribute(node,"lang"));if(tagName==="title"&&result.title===null)result.title=cleanText(getText(node));if(tagName==="h1")result.h1Count+=1;if(tagName==="meta"){const name=getAttribute(node,"name")?.toLowerCase();const property=getAttribute(node,"property")?.toLowerCase();const content=cleanText(getAttribute(node,"content"));if(name==="description"&&result.description===null)result.description=content;else if(name==="robots"&&result.robots===null)result.robots=content;else if(property==="og:title"&&result.openGraph.title===null)result.openGraph.title=content;else if(property==="og:description"&&result.openGraph.description===null)result.openGraph.description=content;else if(property==="og:image"&&result.openGraph.image===null)result.openGraph.image=content;else if(name==="twitter:card"&&result.twitter.card===null)result.twitter.card=content;else if(name==="twitter:title"&&result.twitter.title===null)result.twitter.title=content;else if(name==="twitter:description"&&result.twitter.description===null)result.twitter.description=content;else if(name==="twitter:image"&&result.twitter.image===null)result.twitter.image=content}if(tagName==="link"){const rel=getAttribute(node,"rel")?.toLowerCase().split(/\s+/).filter(Boolean)??[];if(rel.includes("canonical")&&result.canonical===null)result.canonical=cleanText(getAttribute(node,"href"));if(rel.includes("alternate")){const lang=cleanText(getAttribute(node,"hreflang"));const url=cleanText(getAttribute(node,"href"));if(lang&&url)result.hreflang.push({lang,url})}}if(tagName==="a"){const href=getAttribute(node,"href");if(href)result.links.push(href)}if(tagName==="img"){result.images.push({src:cleanText(getAttribute(node,"src")),alt:getAttribute(node,"alt")})}if(tagName==="script"&&getAttribute(node,"type")?.toLowerCase()==="application/ld+json"){const source=getText(node).trim();if(source){try{result.jsonLd.push({valid:true,value:JSON.parse(source)})}catch(error){result.jsonLd.push({valid:false,error:error instanceof Error?error.message:String(error)})}}}for(const child of node.childNodes??[])visit(child,excludesText)}visit(document);result.visibleText=textParts.join(" ");result.wordCount=result.visibleText?result.visibleText.split(/\s+/u).length:0;return result}function emptyPage(url,depth){return{url,finalUrl:null,status:null,contentType:null,blockedByRobots:false,error:null,title:null,description:null,canonical:null,canonicalRaw:null,robots:null,xRobotsTag:null,lang:null,h1Count:0,openGraph:{title:null,description:null,image:null},twitter:{card:null,title:null,description:null,image:null},hreflang:[],jsonLd:[],images:[],links:[],internalLinks:[],externalLinks:[],wordCount:0,contentHash:null,depth,redirectChain:[],responseBytes:0}}async function emit2(options,event){await options.onEvent?.(event)}async function fetchPage(requestUrl,depth,siteOrigin,options,robots){const page=emptyPage(requestUrl,depth);if(options.respectRobots&&!isAllowedByRobots(requestUrl,robots)){page.blockedByRobots=true;return page}try{const{response,redirectChain}=await fetchWithRetry(requestUrl,{headers:{accept:"text/html,application/xhtml+xml;q=0.9,*/*;q=0.1","user-agent":options.userAgent}},{...options,gate:options.requestGate,onEvent:options.onEvent});const contentType=response.headers.get("content-type")??"";const isHtml=contentType.includes("text/html")||contentType.includes("application/xhtml+xml");const finalUrl=normalizeUrl(response.url,void 0,{includeQuery:options.includeQuery});page.finalUrl=finalUrl;page.status=response.status;page.contentType=contentType||null;page.xRobotsTag=response.headers.get("x-robots-tag");page.redirectChain=redirectChain;if(!isHtml){await response.body?.cancel();return page}const{text:body,bytes}=await readResponseBody(response,options.maxResponseBytes);const seo=extractSeoData(body);const baseUrl=finalUrl??requestUrl;const canonical=seo.canonical?normalizeUrl(seo.canonical,baseUrl,{includeQuery:true}):null;const links=[...new Set(seo.links.map(link=>normalizeUrl(link,baseUrl,{includeQuery:options.includeQuery})).filter(link=>Boolean(link)))].sort();const hreflang=seo.hreflang.map(item=>({lang:item.lang,url:normalizeUrl(item.url,baseUrl,{includeQuery:true})}));Object.assign(page,{...seo,visibleText:void 0,canonical,canonicalRaw:seo.canonical,links,internalLinks:links.filter(link=>isSameOrigin(link,siteOrigin)),externalLinks:links.filter(link=>!isSameOrigin(link,siteOrigin)),hreflang,contentHash:seo.visibleText?createHash4("sha256").update(seo.visibleText.toLowerCase()).digest("hex"):null,responseBytes:bytes});return page}catch(error){if(options.signal?.aborted)throw error;page.error=error instanceof Error?error.message:String(error);if(error instanceof RequestFailure)page.redirectChain=error.redirectChain;return page}}function withDefaults(raw={}){const requestDelay=raw.requestDelay??raw.delay??100;const providedGate=raw.requestGate;return{...raw,maxPages:raw.maxPages??100,concurrency:Math.max(1,raw.concurrency??5),timeout:raw.timeout??1e4,includeQuery:raw.includeQuery??false,respectRobots:raw.respectRobots??true,sitemap:raw.sitemap??null,sitemapData:raw.sitemapData??null,userAgent:raw.userAgent??DEFAULT_USER_AGENT,requestDelay,requestGate:providedGate?async url=>providedGate(url):createPerOriginRequestGate(requestDelay),maxRedirects:raw.maxRedirects??10,maxResponseBytes:raw.maxResponseBytes??5*1024*1024,retries:raw.retries??2,fetch:raw.fetch??globalThis.fetch,logger:raw.logger??NOOP_LOGGER}}async function runPool(concurrency,next){const output=[];const workers=Array.from({length:concurrency},async()=>{while(true){const value=await next();if(value===null)return;output.push(value)}});await Promise.all(workers);return output}async function crawlSite(inputUrl,rawOptions={}){const startedAt=Date.now();const options=withDefaults(rawOptions);const startUrl=normalizeUrl(inputUrl,void 0,{includeQuery:options.includeQuery});if(!startUrl)throw new Error(`invalid start URL: ${inputUrl}`);const origin=new URL(startUrl).origin;await emit2(options,{type:"scan-start",url:startUrl,total:options.maxPages});const robots=rawOptions.robots??await fetchRobots(startUrl,options);let sitemap=options.sitemapData;if(!sitemap&&options.sitemap){try{sitemap=await loadSitemapUrls(options.sitemap,{...options,maxUrls:rawOptions.sitemapMaxUrls??5e4,siteOrigin:origin})}catch(error){sitemap={url:options.sitemap,urls:[],sitemapCount:0,truncated:false,error:error instanceof Error?error.message:String(error)};options.logger.warn(`Could not load sitemap ${options.sitemap}: ${sitemap.error}`)}}const seeds=[...new Set([startUrl,...sitemap?.urls??[]])];let frontier=seeds.slice(0,options.maxPages).map(url=>({url,depth:0}));const scheduled=new Set(frontier.map(item=>item.url));const cached=new Map((rawOptions.cachedPages??[]).map(page=>[page.url,page]));const pages=new Map;const maxQueueSize=Math.max(options.maxPages*10,options.maxPages);let hasMore=false;while(frontier.length>0&&pages.size<options.maxPages&&!options.signal?.aborted){frontier.sort((left,right)=>left.url.localeCompare(right.url));const remaining=options.maxPages-pages.size;const current=frontier.slice(0,remaining);if(frontier.length>current.length)hasMore=true;let cursor=0;const completed=await runPool(options.concurrency,async()=>{if(options.signal?.aborted||cursor>=current.length)return null;const item=current[cursor++];if(!item)return null;let page=cached.get(item.url);if(!page){try{page=await fetchPage(item.url,item.depth,origin,options,robots)}catch(error){if(options.signal?.aborted)return null;throw error}}pages.set(item.url,page);if(!cached.has(item.url)){await rawOptions.onBatch?.([page]);await options.storage?.saveCheckpoint?.(startUrl,page);await emit2(options,{type:"checkpoint",page,completed:pages.size,total:options.maxPages})}rawOptions.onProgress?.(pages.size,options.maxPages);await emit2(options,{type:"page",completed:pages.size,total:options.maxPages,page});await emit2(options,{type:"progress",completed:pages.size,total:options.maxPages,page});return{item,page}});const next=new Map;for(const{item,page}of completed.sort((left,right)=>left.item.url.localeCompare(right.item.url))){const discoveredLinks=page.internalLinks?.length?page.internalLinks:(page.links??[]).filter(link=>isSameOrigin(link,origin));for(const link of[...discoveredLinks].sort()){if(scheduled.size>=maxQueueSize||scheduled.has(link)||!isCrawlableUrl(link))continue;scheduled.add(link);next.set(link,{url:link,depth:item.depth+1})}}frontier=[...next.values()]}const sortedPages=[...pages.values()].sort((left,right)=>left.url.localeCompare(right.url));const partial=Boolean(options.signal?.aborted);const truncated=partial||hasMore||frontier.length>0||(sitemap?sitemap.urls.length>sortedPages.length:false)||(sitemap?.truncated??false);const result={startUrl,pages:sortedPages,robots,sitemap,truncated,partial,durationMs:Date.now()-startedAt,options};result.snapshot=createBaseline(result);if(!partial)await options.storage?.removeCheckpoint?.(startUrl);if(partial)await emit2(options,{type:"cancelled",completed:sortedPages.length,total:options.maxPages,partial:true});else await emit2(options,{type:"complete",completed:sortedPages.length,total:options.maxPages});return result}function isPlan(input){return"planVersion"in input}function checkpointIdentity(plan){return{schemaVersion:2,pageSchemaVersion:1,siteUrl:plan.startUrl,sitemapUrl:plan.sitemap?.url??null,includeQuery:plan.config.includeQuery,respectRobots:plan.config.respectRobots,timeout:plan.config.timeout,maxRedirects:plan.config.maxRedirects,maxResponseBytes:plan.config.maxResponseBytes,userAgent:plan.userAgent}}function reusableCheckpointPage(page){return!page.error&&(page.status===null||page.status<500)}async function scan(input,options={}){let plannedRobots=null;let plannedSitemap=null;let plan;try{plan=isPlan(input)?input:await planScan(input,{...options,async onEvent(event){if(event.type==="robots")plannedRobots=event.robots;if(event.type==="sitemap")plannedSitemap=event.sitemap;await options.onEvent?.(event)}})}catch(error){if(isPlan(input)||!options.signal?.aborted)throw error;const config2=resolveConfig(input);const startUrl=normalizeUrl(config2.url,void 0,{includeQuery:config2.includeQuery});if(!startUrl)throw new Error(`invalid start URL: ${config2.url}`,{cause:error});const robots=plannedRobots??{url:new URL("/robots.txt",startUrl).href,status:null,sha256:null,error:"Scan cancelled before robots.txt planning completed",denyAll:false};const snapshot=createBaseline({startUrl,pages:[],robots,sitemap:plannedSitemap,options:config2,partial:true,truncated:true});await options.checkpointStore?.flush?.();await options.onEvent?.({type:"cancelled",completed:0,total:config2.maxPages,partial:true});return{snapshot,startUrl,pages:[],robots,sitemap:plannedSitemap,truncated:true,partial:true,durationMs:0,options:config2}}if(plan.planVersion!==1)throw new Error(`unsupported scan plan version: ${String(plan.planVersion)}`);const limit=options.limit??plan.config.maxPages;if(!Number.isInteger(limit)||limit<=0)throw new Error("scan limit must be a positive integer");const config={...plan.config,maxPages:limit};const requestGate=createPerOriginRequestGate(config.delay);const identity=checkpointIdentity(plan);const checkpoint=options.checkpointStore&&options.resume!==false?await options.checkpointStore.load(identity):null;const cachedPages=[...options.cachedPages??[],...checkpoint?.pages.filter(reusableCheckpointPage)??[]];const uniqueCachedPages=[...new Map(cachedPages.map(page=>[page.url,page])).values()];if(uniqueCachedPages.length>0){await options.onEvent?.({type:"resume",completed:uniqueCachedPages.length,total:limit})}const result=await crawlSite(plan.startUrl,{...options,maxPages:limit,concurrency:config.concurrency,requestDelay:config.delay,timeout:config.timeout,respectRobots:config.respectRobots,includeQuery:config.includeQuery,maxRedirects:config.maxRedirects,maxResponseBytes:config.maxResponseBytes,enabledRules:config.enabledRules,severityOverrides:config.severityOverrides,suppressions:config.suppressions,regressionBudgets:config.regressionBudgets,report:config.report,requestGate,robots:plan.robots,sitemap:plan.sitemap?.url??null,sitemapData:plan.sitemap,userAgent:plan.userAgent,cachedPages:uniqueCachedPages,async onBatch(pages){for(const page of pages)await options.checkpointStore?.append(identity,page);await options.onBatch?.(pages)}});await options.checkpointStore?.flush?.();if(!result.partial&&!options.retainCheckpoint){await options.checkpointStore?.clear(identity)}return result}function segmentToken(segment){if(/^\d+$/.test(segment))return":id";if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(segment))return":uuid";if(/^\d{4}-\d{2}-\d{2}$/.test(segment))return":date";if(/^[0-9a-f]{16,}$/i.test(segment))return":hash";return null}function parseIssueUrls(issues){return issues.flatMap(issue=>{try{const url=new URL(issue.url);return[{issue,url,segments:url.pathname.split("/").filter(Boolean)}]}catch{return[]}})}function dynamicSegments(pages){const siblings=new Map;for(const page of pages){for(let index=1;index<page.segments.length;index+=1){if(segmentToken(page.segments[index]))continue;const prefix=page.segments.slice(0,index).join("/");const key=`${page.url.origin}|${page.segments.length}|${index}|${prefix}`;const values=siblings.get(key)??new Set;values.add(page.segments[index]);siblings.set(key,values)}}return new Set([...siblings].filter(([,values])=>values.size>=2).map(([key])=>key))}function templateFor(page,dynamic){const segments=page.segments.map((segment,index)=>{const token=segmentToken(segment);if(token)return token;const prefix=page.segments.slice(0,index).join("/");const key=`${page.url.origin}|${page.segments.length}|${index}|${prefix}`;return index>0&&dynamic.has(key)?":slug":segment});return`/${segments.join("/")}${page.url.pathname.endsWith("/")&&segments.length>0?"/":""}`}function groupIssuesByTemplate(issues){const pages=parseIssueUrls(issues);const dynamic=dynamicSegments(pages);const grouped=new Map;for(const page of pages){const template=templateFor(page,dynamic);const key=`${page.url.origin}${template}`;const group=grouped.get(key)??{origin:page.url.origin,template,issues:[],urls:new Set};group.issues.push(page.issue);group.urls.add(page.issue.url);grouped.set(key,group)}return[...grouped.values()].map(group=>{const severities={error:0,warning:0,info:0};const rules={};const owners={};for(const issue of group.issues){severities[issue.severity]+=1;rules[issue.ruleId]=(rules[issue.ruleId]??0)+1;owners[issue.owner]=(owners[issue.owner]??0)+1}const urls=[...group.urls].sort();return{origin:group.origin,template:group.template,issueCount:group.issues.length,affectedPages:urls.length,severities,rules,owners,urls,representativeUrls:urls.slice(0,3)}}).sort((left,right)=>right.issueCount-left.issueCount||left.template.localeCompare(right.template)||left.origin.localeCompare(right.origin))}function englishRuleLabel(ruleId){const text=ruleId.replaceAll("-"," ");return text.charAt(0).toUpperCase()+text.slice(1)}var UK_RULE_LABELS={"page-unreachable":"\u041D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430","http-error":"HTTP-\u043F\u043E\u043C\u0438\u043B\u043A\u0430",noindex:"Noindex","x-robots-noindex":"Noindex \u0443 X-Robots-Tag","robots-blocked":"\u0417\u0430\u0431\u043B\u043E\u043A\u043E\u0432\u0430\u043D\u043E robots.txt","missing-canonical":"\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 canonical","invalid-canonical":"\u041D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 canonical","cross-domain-canonical":"Canonical \u043D\u0430 \u0456\u043D\u0448\u043E\u043C\u0443 \u0434\u043E\u043C\u0435\u043D\u0456","canonical-target-error":"\u041F\u043E\u043C\u0438\u043B\u043A\u0430 \u0446\u0456\u043B\u0456 canonical","redirect-loop":"\u0426\u0438\u043A\u043B \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u044C","long-redirect-chain":"\u0414\u043E\u0432\u0433\u0438\u0439 \u043B\u0430\u043D\u0446\u044E\u0436\u043E\u043A \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u044C","sitemap-unavailable":"Sitemap \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0438\u0439","noindex-in-sitemap":"Noindex \u0443 sitemap","redirect-in-sitemap":"\u041F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043D\u044F \u0443 sitemap","missing-title":"\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 title","duplicate-title":"\u0414\u0443\u0431\u043B\u044C\u043E\u0432\u0430\u043D\u0438\u0439 title","title-length":"\u0414\u043E\u0432\u0436\u0438\u043D\u0430 title","missing-description":"\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 description","duplicate-description":"\u0414\u0443\u0431\u043B\u044C\u043E\u0432\u0430\u043D\u0438\u0439 description","description-length":"\u0414\u043E\u0432\u0436\u0438\u043D\u0430 description","missing-h1":"\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439 H1","broken-internal-link":"\u041D\u0435\u0440\u043E\u0431\u043E\u0447\u0435 \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0454 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F","orphan-sitemap-page":"\u0406\u0437\u043E\u043B\u044C\u043E\u0432\u0430\u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430 sitemap","crawlable-not-in-sitemap":"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u044F \u0443 sitemap","invalid-hreflang":"\u041D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 hreflang","malformed-json-ld":"\u041D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 JSON-LD","http-on-https-site":"HTTP URL \u043D\u0430 HTTPS-\u0441\u0430\u0439\u0442\u0456","invalid-language":"\u041D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0435 \u043E\u0433\u043E\u043B\u043E\u0448\u0435\u043D\u043D\u044F \u043C\u043E\u0432\u0438","duplicate-content":"\u0414\u0443\u0431\u043B\u044C\u043E\u0432\u0430\u043D\u0438\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442","multiple-h1":"\u041A\u0456\u043B\u044C\u043A\u0430 H1","missing-open-graph":"\u041D\u0435\u043F\u043E\u0432\u043D\u0456 Open Graph metadata","missing-twitter-metadata":"\u041D\u0435\u043F\u043E\u0432\u043D\u0456 Twitter metadata","image-missing-alt":"\u0417\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F \u0431\u0435\u0437 alt","low-word-count":"\u041C\u0430\u043B\u043E \u0442\u0435\u043A\u0441\u0442\u0443","robots-changed":"robots.txt \u0437\u043C\u0456\u043D\u0435\u043D\u043E","page-missing":"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u043D\u0435 \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u0435\u043D\u043E","status-regression":"\u0420\u0435\u0433\u0440\u0435\u0441\u0456\u044F HTTP-\u0441\u0442\u0430\u0442\u0443\u0441\u0443","new-noindex":"\u041D\u043E\u0432\u0438\u0439 noindex","title-removed":"Title \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E","title-changed":"Title \u0437\u043C\u0456\u043D\u0435\u043D\u043E","description-removed":"Description \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E","canonical-removed":"Canonical \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E","canonical-changed":"Canonical \u0437\u043C\u0456\u043D\u0435\u043D\u043E","h1-removed":"H1 \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E","redirect-changed":"\u041F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043D\u044F \u0437\u043C\u0456\u043D\u0435\u043D\u043E","sitemap-url-count-drop":"\u0417\u043C\u0435\u043D\u0448\u0435\u043D\u043D\u044F URL \u0443 sitemap"};var UK_REMEDIATIONS={"page-unreachable":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0430\u0431\u043E \u043F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F \u043D\u0430 \u043D\u0435\u0457.","http-error":"\u041F\u043E\u0432\u0435\u0440\u043D\u0456\u0442\u044C \u0443\u0441\u043F\u0456\u0448\u043D\u0443 \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u044C \u0430\u0431\u043E \u0441\u0432\u0456\u0434\u043E\u043C\u0435 \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043D\u044F.",noindex:"\u041F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C noindex, \u044F\u043A\u0449\u043E \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0430\u0454 \u0437\u2019\u044F\u0432\u043B\u044F\u0442\u0438\u0441\u044F \u0432 \u043F\u043E\u0448\u0443\u043A\u0443.","x-robots-noindex":"\u041F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C noindex \u0456\u0437 X-Robots-Tag, \u044F\u043A\u0449\u043E \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0430\u0454 \u0456\u043D\u0434\u0435\u043A\u0441\u0443\u0432\u0430\u0442\u0438\u0441\u044F.","robots-blocked":"\u0414\u043E\u0437\u0432\u043E\u043B\u044C\u0442\u0435 URL \u0443 robots.txt, \u044F\u043A\u0449\u043E \u0439\u043E\u0433\u043E \u043F\u043E\u0442\u0440\u0456\u0431\u043D\u043E \u0441\u043A\u0430\u043D\u0443\u0432\u0430\u0442\u0438.","missing-canonical":"\u0412\u043A\u0430\u0436\u0456\u0442\u044C \u0431\u0430\u0436\u0430\u043D\u0438\u0439 canonical URL, \u044F\u043A\u0449\u043E \u043C\u043E\u0436\u043B\u0438\u0432\u0456 \u0434\u0443\u0431\u043B\u0456\u043A\u0430\u0442\u0438 \u0430\u0434\u0440\u0435\u0441\u0438.","invalid-canonical":"\u0412\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u0430\u0439\u0442\u0435 \u0430\u0431\u0441\u043E\u043B\u044E\u0442\u043D\u0438\u0439 \u0430\u0431\u043E \u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 \u0432\u0456\u0434\u043D\u043E\u0441\u043D\u0438\u0439 HTTP(S) canonical URL.","cross-domain-canonical":"\u041F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435 \u0437\u043E\u0432\u043D\u0456\u0448\u043D\u0456\u0439 canonical \u0430\u0431\u043E \u0432\u043A\u0430\u0436\u0456\u0442\u044C \u043F\u043E\u0442\u0440\u0456\u0431\u043D\u0438\u0439 URL \u0446\u044C\u043E\u0433\u043E \u0441\u0430\u0439\u0442\u0443.","canonical-target-error":"\u0421\u043F\u0440\u044F\u043C\u0443\u0439\u0442\u0435 canonical \u043D\u0430 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0438\u0439 URL, \u0434\u043E\u0437\u0432\u043E\u043B\u0435\u043D\u0438\u0439 \u0434\u043B\u044F \u0456\u043D\u0434\u0435\u043A\u0441\u0430\u0446\u0456\u0457.","redirect-loop":"\u041F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C \u0446\u0438\u043A\u043B\u0456\u0447\u043D\u0438\u0439 \u043C\u0430\u0440\u0448\u0440\u0443\u0442 \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u044C.","long-redirect-chain":"\u041F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u044F\u0439\u0442\u0435 \u043E\u0434\u0440\u0430\u0437\u0443 \u043D\u0430 \u043A\u0456\u043D\u0446\u0435\u0432\u0443 \u0430\u0434\u0440\u0435\u0441\u0443.","sitemap-unavailable":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 \u0456 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0438\u0439 XML sitemap.","noindex-in-sitemap":"\u041F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C URL \u0456\u0437 sitemap \u0430\u0431\u043E \u0434\u043E\u0437\u0432\u043E\u043B\u044C\u0442\u0435 \u0439\u043E\u0433\u043E \u0456\u043D\u0434\u0435\u043A\u0441\u0430\u0446\u0456\u044E.","redirect-in-sitemap":"\u0417\u0430\u043C\u0456\u043D\u0456\u0442\u044C URL \u0443 sitemap \u043D\u0430 \u0439\u043E\u0433\u043E \u043A\u0456\u043D\u0446\u0435\u0432\u0443 canonical-\u0430\u0434\u0440\u0435\u0441\u0443.","missing-title":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u0443\u043D\u0456\u043A\u0430\u043B\u044C\u043D\u0438\u0439 \u043E\u043F\u0438\u0441\u043E\u0432\u0438\u0439 HTML title.","duplicate-title":"\u041D\u0430\u043F\u0438\u0448\u0456\u0442\u044C title, \u044F\u043A\u0438\u0439 \u0443\u043D\u0456\u043A\u0430\u043B\u044C\u043D\u043E \u043E\u043F\u0438\u0441\u0443\u0454 \u0446\u044E \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443.","title-length":"\u0417\u0440\u043E\u0431\u0456\u0442\u044C title \u0441\u0442\u0438\u0441\u043B\u0438\u043C \u0456 \u0437\u043C\u0456\u0441\u0442\u043E\u0432\u043D\u0438\u043C, \u0437\u0430\u0437\u0432\u0438\u0447\u0430\u0439 10\u201360 \u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432.","missing-description":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u043A\u043E\u0440\u0438\u0441\u043D\u0438\u0439 meta description.","duplicate-description":"\u041D\u0430\u043F\u0438\u0448\u0456\u0442\u044C \u0443\u043D\u0456\u043A\u0430\u043B\u044C\u043D\u0438\u0439 meta description \u0434\u043B\u044F \u0446\u0456\u0454\u0457 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438.","description-length":"\u0417\u0440\u043E\u0431\u0456\u0442\u044C description \u043A\u043E\u0440\u0438\u0441\u043D\u0438\u043C \u0456 \u0437\u0430\u0437\u0432\u0438\u0447\u0430\u0439 \u0434\u043E\u0432\u0436\u0438\u043D\u043E\u044E 50\u2013160 \u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432.","missing-h1":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u043E\u0434\u0438\u043D \u0437\u0440\u043E\u0437\u0443\u043C\u0456\u043B\u0438\u0439 \u043E\u0441\u043D\u043E\u0432\u043D\u0438\u0439 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A.","broken-internal-link":"\u041E\u043D\u043E\u0432\u0456\u0442\u044C \u0430\u0431\u043E \u043F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0454 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F \u0447\u0438 \u0432\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u0439\u043E\u0433\u043E \u0446\u0456\u043B\u044C.","orphan-sitemap-page":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u0437\u043C\u0456\u0441\u0442\u043E\u0432\u043D\u0456 \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0456 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F \u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0456\u0437 sitemap.","crawlable-not-in-sitemap":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0434\u043E sitemap \u0430\u0431\u043E \u0441\u0432\u0456\u0434\u043E\u043C\u043E \u0432\u0438\u043A\u043B\u044E\u0447\u0456\u0442\u044C \u0457\u0457.","invalid-hreflang":"\u0412\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u0430\u0439\u0442\u0435 \u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0456 \u043C\u043E\u0432\u043D\u0456 \u0442\u0435\u0433\u0438 \u0442\u0430 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0456 HTTP(S) alternate URL.","malformed-json-ld":"\u0412\u0438\u043F\u0440\u0430\u0432\u0442\u0435 JSON-\u0441\u0438\u043D\u0442\u0430\u043A\u0441\u0438\u0441 \u0443 \u0431\u043B\u043E\u0446\u0456 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u043E\u0432\u0430\u043D\u0438\u0445 \u0434\u0430\u043D\u0438\u0445.","http-on-https-site":"\u0412\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0439\u0442\u0435 HTTPS \u0434\u043B\u044F \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0456\u0445 URL \u0456 metadata.","invalid-language":"\u0412\u043A\u0430\u0436\u0456\u0442\u044C \u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 \u043C\u043E\u0432\u043D\u0438\u0439 \u0442\u0435\u0433 BCP 47 \u0432 \u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456 html.","duplicate-content":"\u041E\u0431\u2019\u0454\u0434\u043D\u0430\u0439\u0442\u0435 \u0434\u0443\u0431\u043B\u044C\u043E\u0432\u0430\u043D\u0456 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u0430\u0431\u043E \u0437\u0440\u043E\u0431\u0456\u0442\u044C \u0457\u0445\u043D\u0456\u0439 \u043E\u0441\u043D\u043E\u0432\u043D\u0438\u0439 \u043A\u043E\u043D\u0442\u0435\u043D\u0442 \u0432\u0456\u0434\u043C\u0456\u043D\u043D\u0438\u043C.","multiple-h1":"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0442\u0435, \u0447\u0438 \u043E\u0434\u0438\u043D \u043E\u0441\u043D\u043E\u0432\u043D\u0438\u0439 H1 \u043D\u0435 \u0437\u0440\u043E\u0431\u0438\u0442\u044C \u0456\u0454\u0440\u0430\u0440\u0445\u0456\u044E \u0437\u0440\u043E\u0437\u0443\u043C\u0456\u043B\u0456\u0448\u043E\u044E.","missing-open-graph":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 Open Graph title, description \u0442\u0430 image \u0434\u043B\u044F \u043F\u043E\u0448\u0438\u0440\u0435\u043D\u043D\u044F \u0432 \u0441\u043E\u0446\u043C\u0435\u0440\u0435\u0436\u0430\u0445.","missing-twitter-metadata":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 Twitter card metadata, \u044F\u043A\u0449\u043E \u0432\u0430\u0436\u043B\u0438\u0432\u0456 \u0441\u043E\u0446\u0456\u0430\u043B\u044C\u043D\u0456 \u043F\u0440\u0435\u0432\u2019\u044E.","image-missing-alt":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u0437\u043C\u0456\u0441\u0442\u043E\u0432\u043D\u0438\u0439 alt \u0430\u0431\u043E \u043F\u043E\u0440\u043E\u0436\u043D\u0456\u0439 alt \u0434\u043B\u044F \u0434\u0435\u043A\u043E\u0440\u0430\u0442\u0438\u0432\u043D\u0438\u0445 \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u044C.","low-word-count":"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0442\u0435, \u0447\u0438 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u0434\u043E\u0441\u0442\u0430\u0442\u043D\u044C\u043E \u043A\u043E\u0440\u0438\u0441\u043D\u043E\u0433\u043E \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E \u043A\u043E\u043D\u0442\u0435\u043D\u0442\u0443.","robots-changed":"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0442\u0435 \u0437\u043C\u0456\u043D\u0443 robots.txt \u0456 \u043F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435, \u0449\u043E \u0434\u043E\u0441\u0442\u0443\u043F \u0434\u043B\u044F \u0441\u043A\u0430\u043D\u0443\u0432\u0430\u043D\u043D\u044F \u0437\u043C\u0456\u043D\u0435\u043D\u043E \u0441\u0432\u0456\u0434\u043E\u043C\u043E.","page-missing":"\u0414\u043E\u0434\u0430\u0439\u0442\u0435 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0434\u043E \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0438 \u0430\u0431\u043E \u043F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435, \u0449\u043E \u0457\u0457 \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E \u0441\u0432\u0456\u0434\u043E\u043C\u043E.","status-regression":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u043F\u043E\u043F\u0435\u0440\u0435\u0434\u043D\u044E \u0443\u0441\u043F\u0456\u0448\u043D\u0443 HTTP-\u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u044C.","new-noindex":"\u041F\u0440\u0438\u0431\u0435\u0440\u0456\u0442\u044C \u043D\u043E\u0432\u0438\u0439 noindex, \u044F\u043A\u0449\u043E \u0439\u043E\u0433\u043E \u043D\u0435 \u0434\u043E\u0434\u0430\u043D\u043E \u043D\u0430\u0432\u043C\u0438\u0441\u043D\u043E.","title-removed":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u0437\u043C\u0456\u0441\u0442\u043E\u0432\u043D\u0438\u0439 title.","title-changed":"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0442\u0435 \u0442\u0430 \u043F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435 \u0437\u043C\u0456\u043D\u0435\u043D\u0438\u0439 title.","description-removed":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u043A\u043E\u0440\u0438\u0441\u043D\u0438\u0439 meta description.","canonical-removed":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C canonical.","canonical-changed":"\u041F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435, \u0449\u043E \u043D\u043E\u0432\u0430 \u0446\u0456\u043B\u044C canonical \u0441\u0432\u0456\u0434\u043E\u043C\u0430 \u0439 \u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0430.","h1-removed":"\u0412\u0456\u0434\u043D\u043E\u0432\u0456\u0442\u044C \u0437\u0440\u043E\u0437\u0443\u043C\u0456\u043B\u0438\u0439 \u043E\u0441\u043D\u043E\u0432\u043D\u0438\u0439 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A.","redirect-changed":"\u041F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435, \u0449\u043E \u043D\u043E\u0432\u0430 \u0446\u0456\u043B\u044C \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043D\u044F \u0441\u0432\u0456\u0434\u043E\u043C\u0430.","sitemap-url-count-drop":"\u0414\u043E\u0441\u043B\u0456\u0434\u0456\u0442\u044C \u0432\u0442\u0440\u0430\u0442\u0443 URL \u0443 sitemap \u0456 \u043F\u043E\u0432\u0435\u0440\u043D\u0456\u0442\u044C \u043F\u0440\u043E\u043F\u0443\u0449\u0435\u043D\u0456 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u0434\u043B\u044F \u0456\u043D\u0434\u0435\u043A\u0441\u0430\u0446\u0456\u0457."};function actual(issue){return issue.evidence?.actual??issue.after}function ukrainianMessage(issue,ruleId){const value=actual(issue);switch(ruleId){case"page-unreachable":case"redirect-loop":return`\u0417\u0430\u043F\u0438\u0442 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0432\u0441\u044F \u043F\u043E\u043C\u0438\u043B\u043A\u043E\u044E: ${String(value??"\u043D\u0435\u0432\u0456\u0434\u043E\u043C\u0430 \u043F\u043E\u043C\u0438\u043B\u043A\u0430")}`;case"http-error":return`\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043F\u043E\u0432\u0435\u0440\u043D\u0443\u043B\u0430 HTTP ${String(value??"\u043D\u0435\u0432\u0456\u0434\u043E\u043C\u043E")}`;case"noindex":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u0434\u0438\u0440\u0435\u043A\u0442\u0438\u0432\u0443 noindex \u0443 meta";case"x-robots-noindex":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0456\u0441\u0442\u0438\u0442\u044C noindex \u0443 X-Robots-Tag";case"robots-blocked":return issue.before===false?"\u0422\u0435\u043F\u0435\u0440 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0437\u0430\u0431\u043B\u043E\u043A\u043E\u0432\u0430\u043D\u043E \u0447\u0435\u0440\u0435\u0437 robots.txt":"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0437\u0430\u0431\u043B\u043E\u043A\u043E\u0432\u0430\u043D\u043E \u0447\u0435\u0440\u0435\u0437 robots.txt";case"missing-canonical":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043D\u0435 \u043C\u0456\u0441\u0442\u0438\u0442\u044C canonical URL";case"invalid-canonical":return"Canonical URL \u043D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439";case"cross-domain-canonical":return"Canonical \u0432\u043A\u0430\u0437\u0443\u0454 \u043D\u0430 \u0456\u043D\u0448\u0438\u0439 \u0434\u043E\u043C\u0435\u043D";case"canonical-target-error":return"\u0426\u0456\u043B\u044C canonical \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430";case"long-redirect-chain":return`\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0454 ${String(value??0)} \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u044C`;case"sitemap-unavailable":return"\u041D\u0435 \u0432\u0434\u0430\u043B\u043E\u0441\u044F \u0437\u0430\u0432\u0430\u043D\u0442\u0430\u0436\u0438\u0442\u0438 \u043D\u0430\u043B\u0430\u0448\u0442\u043E\u0432\u0430\u043D\u0438\u0439 sitemap";case"noindex-in-sitemap":return"URL \u0456\u0437 sitemap \u043F\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 noindex";case"redirect-in-sitemap":return"URL \u0456\u0437 sitemap \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u044F\u0454\u0442\u044C\u0441\u044F";case"missing-title":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043D\u0435 \u043C\u0430\u0454 title";case"duplicate-title":return"\u041A\u0456\u043B\u044C\u043A\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043E\u043A \u043C\u0430\u044E\u0442\u044C \u043E\u0434\u043D\u0430\u043A\u043E\u0432\u0438\u0439 title";case"title-length":return`\u0414\u043E\u0432\u0436\u0438\u043D\u0430 title \u2014 ${String(value??0)} \u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432`;case"missing-description":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043D\u0435 \u043C\u0430\u0454 meta description";case"duplicate-description":return"\u041A\u0456\u043B\u044C\u043A\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043E\u043A \u043C\u0430\u044E\u0442\u044C \u043E\u0434\u043D\u0430\u043A\u043E\u0432\u0438\u0439 meta description";case"description-length":return`\u0414\u043E\u0432\u0436\u0438\u043D\u0430 description \u2014 ${String(value??0)} \u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432`;case"missing-h1":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043D\u0435 \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430 H1";case"multiple-h1":return`\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0456\u0441\u0442\u0438\u0442\u044C H1 \u0443 \u043A\u0456\u043B\u044C\u043A\u043E\u0441\u0442\u0456: ${String(value??0)}`;case"broken-internal-link":return"\u0412\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0454 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F \u0432\u0435\u0434\u0435 \u043D\u0430 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0443 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443";case"orphan-sitemap-page":return"\u041D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u0456\u0437 sitemap \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u043E \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0456\u0445 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u044C";case"crawlable-not-in-sitemap":return"\u0414\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0434\u043B\u044F \u0441\u043A\u0430\u043D\u0443\u0432\u0430\u043D\u043D\u044F \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u044F \u0443 sitemap";case"invalid-hreflang":return"\u041E\u0433\u043E\u043B\u043E\u0448\u0435\u043D\u043D\u044F hreflang \u043D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0435";case"malformed-json-ld":return"\u0411\u043B\u043E\u043A JSON-LD \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u043D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0438\u0439 JSON";case"http-on-https-site":return"HTTPS-\u0441\u0430\u0439\u0442 \u043F\u043E\u0441\u0438\u043B\u0430\u0454\u0442\u044C\u0441\u044F \u043D\u0430 \u0432\u043D\u0443\u0442\u0440\u0456\u0448\u043D\u0456\u0439 HTTP URL";case"invalid-language":return"\u041E\u0433\u043E\u043B\u043E\u0448\u0435\u043D\u043D\u044F \u043C\u043E\u0432\u0438 HTML \u043D\u0435\u043A\u043E\u0440\u0435\u043A\u0442\u043D\u0435";case"duplicate-content":return"\u041E\u0441\u043D\u043E\u0432\u043D\u0438\u0439 \u0442\u0435\u043A\u0441\u0442 \u0454 \u0442\u043E\u0447\u043D\u0438\u043C \u0434\u0443\u0431\u043B\u0435\u043C \u0456\u043D\u0448\u043E\u0457 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438";case"missing-open-graph":return"Open Graph metadata \u043D\u0435\u043F\u043E\u0432\u043D\u0456";case"missing-twitter-metadata":return"Twitter card metadata \u043D\u0435\u043F\u043E\u0432\u043D\u0456";case"image-missing-alt":return`${Array.isArray(value)?value.length:String(value??0)} \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u044C \u043D\u0435 \u043C\u0430\u044E\u0442\u044C \u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430 alt`;case"low-word-count":return`\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u043F\u0440\u0438\u0431\u043B\u0438\u0437\u043D\u043E ${String(value??0)} \u0432\u0438\u0434\u0438\u043C\u0438\u0445 \u0441\u043B\u0456\u0432`;case"robots-changed":return"\u0412\u043C\u0456\u0441\u0442 robots.txt \u0437\u043C\u0456\u043D\u0438\u0432\u0441\u044F";case"page-missing":return"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0443 \u043D\u0435 \u0431\u0443\u043B\u043E \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u0435\u043D\u043E";case"status-regression":return`HTTP-\u0441\u0442\u0430\u0442\u0443\u0441 \u043F\u043E\u0433\u0456\u0440\u0448\u0438\u0432\u0441\u044F \u0437 ${String(issue.before??"\u043D\u0435\u0432\u0456\u0434\u043E\u043C\u043E")} \u0434\u043E ${String(issue.after??"\u0432\u0456\u0434\u0441\u0443\u0442\u043D\u0456\u0439")}`;case"new-noindex":return"\u0422\u0435\u043F\u0435\u0440 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430 \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u0434\u0438\u0440\u0435\u043A\u0442\u0438\u0432\u0443 noindex";case"title-removed":return"Title \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E";case"title-changed":return"Title \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u0437\u043C\u0456\u043D\u0435\u043D\u043E";case"description-removed":return"Meta description \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E";case"canonical-removed":return"Canonical URL \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E";case"canonical-changed":return"Canonical URL \u0437\u043C\u0456\u043D\u0435\u043D\u043E";case"h1-removed":return"\u0423\u0441\u0456 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0438 H1 \u0432\u0438\u0434\u0430\u043B\u0435\u043D\u043E";case"redirect-changed":return"\u041A\u0456\u043D\u0446\u0435\u0432\u0438\u0439 URL \u043F\u0435\u0440\u0435\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u043D\u044F \u0437\u043C\u0456\u043D\u0435\u043D\u043E";case"sitemap-url-count-drop":return`\u041A\u0456\u043B\u044C\u043A\u0456\u0441\u0442\u044C URL \u0443 sitemap \u0437\u043C\u0435\u043D\u0448\u0438\u043B\u0430\u0441\u044F \u043D\u0430 ${String((Number(issue.before)||0)-(Number(issue.after)||0))}`;default:return issue.message??"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0442\u0435 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0443 \u0442\u0430 \u043F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435 \u043E\u0447\u0456\u043A\u0443\u0432\u0430\u043D\u0443 \u043F\u043E\u0432\u0435\u0434\u0456\u043D\u043A\u0443."}}function localizeIssue(issue,ruleId){const englishRemediation=issue.remediation??"Review the finding and confirm the intended behavior.";return{en:{rule:englishRuleLabel(ruleId),message:issue.message??"",remediation:englishRemediation},uk:{rule:UK_RULE_LABELS[ruleId]??englishRuleLabel(ruleId),message:ukrainianMessage(issue,ruleId),remediation:UK_REMEDIATIONS[ruleId]??"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0442\u0435 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0443 \u0442\u0430 \u043F\u0456\u0434\u0442\u0432\u0435\u0440\u0434\u044C\u0442\u0435 \u043E\u0447\u0456\u043A\u0443\u0432\u0430\u043D\u0443 \u043F\u043E\u0432\u0435\u0434\u0456\u043D\u043A\u0443."}}}var REPORT_COPY={en:{language:"Language",titles:{partial:"Partial SEO scan report",check:"SEO regression report",scan:"SEO baseline audit"},generated:"Generated",engine:"Engine",rules:"Rules",issueLifecycle:"Issue lifecycle",partialTitle:"Partial results.",partialMessage:"This report contains the pages saved so far. Run the same scan command again to resume without requesting them twice.",incompleteTitle:"Incomplete comparison.",incompleteMessage:"Regressions found on checked pages are shown, but unchecked pages are not marked missing or resolved.",previewTitle:"Preview deployment comparison.",production:"Production",preview:"Preview",cards:{pages:"Pages checked",error:"Errors",warning:"Warnings",info:"Info",affected:"Affected pages"},analytics:{title:"Issue statistics",hint:"Select a chart item to filter the issue table.",severity:"By severity",topRules:"Most frequent checks",owners:"By owner",lifecycle:"By lifecycle",templates:"Affected page templates",total:"Total issues",noData:"No issues to chart.",filterBy:"Filter by"},history:{title:"Local scan history",hint:"Issue trends from snapshots stored on this device.",chartLabel:"Issue trend across runs.",runs:"Runs",pages:"Latest pages",newIssues:"New issues",resolvedIssues:"Resolved issues",sitemapUrls:"Sitemap URLs",maxDepth:"Maximum crawl depth"},tabs:{current:"Current / all",new:"New",ongoing:"Ongoing",resolved:"Resolved",unchanged:"Unchanged"},filters:{search:"URL or text",searchPlaceholder:"URL, check, or message",severity:"Severity",rule:"Check",template:"Page template",owner:"Owner",rows:"Rows"},all:{severity:"All severities",rule:"All checks",template:"All templates",owner:"All owners"},severities:{error:"Error",warning:"Warning",info:"Info"},owners:{seo:"SEO",content:"Content",developer:"Developer"},rows:{100:"100 per page",250:"250 per page",500:"500 per page"},guide:{error:"Errors",errorText:"need attention first.",warning:"Warnings",warningText:"are important improvements.",info:"Info",infoText:"is useful context.",score:"No opaque SEO score is used."},exportCsv:"Export CSV",previous:"Previous",next:"Next",table:{severity:"Severity",lifecycle:"Lifecycle",ruleOwner:"Check / owner",page:"Page",finding:"What was found",change:"Change",before:"Before",evidence:"Evidence / after",remediation:"Remediation",fingerprint:"Fingerprint"},empty:{cleanTitle:"No SEO issues found",cleanMessage:"The scanned pages passed all current checks.",filteredTitle:"No matching issues",filteredMessage:"Try a different lifecycle tab or clear the selected filters.",clear:"Clear filters"},lifecycle:{current:"Current",new:"New",ongoing:"Ongoing",resolved:"Resolved",unchanged:"Unchanged"},notPresent:"Not present",page:"Page",of:"of",issue:"issue",issues:"issues",docs:"docs",footer:"Generated locally. No report data was uploaded."},uk:{language:"\u041C\u043E\u0432\u0430",titles:{partial:"\u0417\u0432\u0456\u0442 \u0447\u0430\u0441\u0442\u043A\u043E\u0432\u043E\u0433\u043E SEO-\u0441\u043A\u0430\u043D\u0443\u0432\u0430\u043D\u043D\u044F",check:"\u0417\u0432\u0456\u0442 \u043F\u0440\u043E SEO-\u0440\u0435\u0433\u0440\u0435\u0441\u0456\u0457",scan:"\u0411\u0430\u0437\u043E\u0432\u0438\u0439 SEO-\u0430\u0443\u0434\u0438\u0442"},generated:"\u0421\u0442\u0432\u043E\u0440\u0435\u043D\u043E",engine:"\u0420\u0443\u0448\u0456\u0439",rules:"\u041F\u0440\u0430\u0432\u0438\u043B\u0430",issueLifecycle:"\u0421\u0442\u0430\u043D\u0438 \u043F\u0440\u043E\u0431\u043B\u0435\u043C",partialTitle:"\u0427\u0430\u0441\u0442\u043A\u043E\u0432\u0456 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0438.",partialMessage:"\u0417\u0432\u0456\u0442 \u043C\u0456\u0441\u0442\u0438\u0442\u044C \u0443\u0436\u0435 \u0437\u0431\u0435\u0440\u0435\u0436\u0435\u043D\u0456 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438. \u0417\u0430\u043F\u0443\u0441\u0442\u0456\u0442\u044C \u0442\u0443 \u0441\u0430\u043C\u0443 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u0449\u0435 \u0440\u0430\u0437, \u0449\u043E\u0431 \u043F\u0440\u043E\u0434\u043E\u0432\u0436\u0438\u0442\u0438 \u0431\u0435\u0437 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u0438\u0445 \u0437\u0430\u043F\u0438\u0442\u0456\u0432.",incompleteTitle:"\u041D\u0435\u043F\u043E\u0432\u043D\u0435 \u043F\u043E\u0440\u0456\u0432\u043D\u044F\u043D\u043D\u044F.",incompleteMessage:"\u041F\u043E\u043A\u0430\u0437\u0430\u043D\u043E \u0440\u0435\u0433\u0440\u0435\u0441\u0456\u0457 \u043D\u0430 \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u0435\u043D\u0438\u0445 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0430\u0445, \u0430\u043B\u0435 \u043D\u0435\u043F\u0435\u0440\u0435\u0432\u0456\u0440\u0435\u043D\u0456 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u043D\u0435 \u043F\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u043E \u044F\u043A \u0432\u0456\u0434\u0441\u0443\u0442\u043D\u0456 \u0447\u0438 \u0432\u0438\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0456.",previewTitle:"\u041F\u043E\u0440\u0456\u0432\u043D\u044F\u043D\u043D\u044F production \u0456 preview.",production:"Production",preview:"Preview",cards:{pages:"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0435\u043D\u043E \u0441\u0442\u043E\u0440\u0456\u043D\u043E\u043A",error:"\u041F\u043E\u043C\u0438\u043B\u043A\u0438",warning:"\u041F\u043E\u043F\u0435\u0440\u0435\u0434\u0436\u0435\u043D\u043D\u044F",info:"\u0406\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0456\u044F",affected:"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u0437 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0430\u043C\u0438"},analytics:{title:"\u0421\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u043F\u0440\u043E\u0431\u043B\u0435\u043C",hint:"\u041E\u0431\u0435\u0440\u0456\u0442\u044C \u0435\u043B\u0435\u043C\u0435\u043D\u0442 \u0433\u0440\u0430\u0444\u0456\u043A\u0430, \u0449\u043E\u0431 \u0432\u0456\u0434\u0444\u0456\u043B\u044C\u0442\u0440\u0443\u0432\u0430\u0442\u0438 \u0442\u0430\u0431\u043B\u0438\u0446\u044E \u043F\u0440\u043E\u0431\u043B\u0435\u043C.",severity:"\u0417\u0430 \u0432\u0430\u0436\u043B\u0438\u0432\u0456\u0441\u0442\u044E",topRules:"\u041D\u0430\u0439\u0447\u0430\u0441\u0442\u0456\u0448\u0456 \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0438",owners:"\u0417\u0430 \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u043B\u044C\u043D\u0438\u043C\u0438",lifecycle:"\u0417\u0430 \u0441\u0442\u0430\u043D\u043E\u043C",templates:"\u0428\u0430\u0431\u043B\u043E\u043D\u0438 \u0441\u0442\u043E\u0440\u0456\u043D\u043E\u043A \u0456\u0437 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0430\u043C\u0438",total:"\u0423\u0441\u044C\u043E\u0433\u043E \u043F\u0440\u043E\u0431\u043B\u0435\u043C",noData:"\u041D\u0435\u043C\u0430\u0454 \u043F\u0440\u043E\u0431\u043B\u0435\u043C \u0434\u043B\u044F \u0432\u0456\u0434\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F.",filterBy:"\u0424\u0456\u043B\u044C\u0442\u0440\u0443\u0432\u0430\u0442\u0438 \u0437\u0430"},history:{title:"\u041B\u043E\u043A\u0430\u043B\u044C\u043D\u0430 \u0456\u0441\u0442\u043E\u0440\u0456\u044F \u0441\u043A\u0430\u043D\u0443\u0432\u0430\u043D\u044C",hint:"\u0414\u0438\u043D\u0430\u043C\u0456\u043A\u0430 \u043F\u0440\u043E\u0431\u043B\u0435\u043C \u0437\u0456 snapshot-\u0444\u0430\u0439\u043B\u0456\u0432, \u0437\u0431\u0435\u0440\u0435\u0436\u0435\u043D\u0438\u0445 \u043D\u0430 \u0446\u044C\u043E\u043C\u0443 \u043F\u0440\u0438\u0441\u0442\u0440\u043E\u0457.",chartLabel:"\u0414\u0438\u043D\u0430\u043C\u0456\u043A\u0430 \u043F\u0440\u043E\u0431\u043B\u0435\u043C \u0437\u0430 \u0437\u0430\u043F\u0443\u0441\u043A\u0430\u043C\u0438.",runs:"\u0417\u0430\u043F\u0443\u0441\u043A\u0438",pages:"\u0421\u0442\u043E\u0440\u0456\u043D\u043E\u043A \u0432\u043E\u0441\u0442\u0430\u043D\u043D\u0454",newIssues:"\u041D\u043E\u0432\u0456 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0438",resolvedIssues:"\u0412\u0438\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0456 \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0438",sitemapUrls:"URL \u0443 sitemap",maxDepth:"\u041C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u0430 \u0433\u043B\u0438\u0431\u0438\u043D\u0430"},tabs:{current:"\u041F\u043E\u0442\u043E\u0447\u043D\u0456 / \u0443\u0441\u0456",new:"\u041D\u043E\u0432\u0456",ongoing:"\u0422\u0440\u0438\u0432\u0430\u044E\u0442\u044C",resolved:"\u0412\u0438\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0456",unchanged:"\u0411\u0435\u0437 \u0437\u043C\u0456\u043D"},filters:{search:"URL \u0430\u0431\u043E \u0442\u0435\u043A\u0441\u0442",searchPlaceholder:"URL, \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0430 \u0430\u0431\u043E \u043F\u043E\u0432\u0456\u0434\u043E\u043C\u043B\u0435\u043D\u043D\u044F",severity:"\u0412\u0430\u0436\u043B\u0438\u0432\u0456\u0441\u0442\u044C",rule:"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0430",template:"\u0428\u0430\u0431\u043B\u043E\u043D \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438",owner:"\u0412\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u043B\u044C\u043D\u0438\u0439",rows:"\u0420\u044F\u0434\u043A\u0438"},all:{severity:"\u0423\u0441\u0456 \u0440\u0456\u0432\u043D\u0456",rule:"\u0423\u0441\u0456 \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0438",template:"\u0423\u0441\u0456 \u0448\u0430\u0431\u043B\u043E\u043D\u0438",owner:"\u0423\u0441\u0456 \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u043B\u044C\u043D\u0456"},severities:{error:"\u041F\u043E\u043C\u0438\u043B\u043A\u0430",warning:"\u041F\u043E\u043F\u0435\u0440\u0435\u0434\u0436\u0435\u043D\u043D\u044F",info:"\u0406\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0456\u044F"},owners:{seo:"SEO",content:"\u041A\u043E\u043D\u0442\u0435\u043D\u0442",developer:"\u0420\u043E\u0437\u0440\u043E\u0431\u043D\u0438\u043A"},rows:{100:"100 \u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443",250:"250 \u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443",500:"500 \u043D\u0430 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0443"},guide:{error:"\u041F\u043E\u043C\u0438\u043B\u043A\u0438",errorText:"\u043F\u043E\u0442\u0440\u0435\u0431\u0443\u044E\u0442\u044C \u043F\u0435\u0440\u0448\u043E\u0447\u0435\u0440\u0433\u043E\u0432\u043E\u0457 \u0443\u0432\u0430\u0433\u0438.",warning:"\u041F\u043E\u043F\u0435\u0440\u0435\u0434\u0436\u0435\u043D\u043D\u044F",warningText:"\u043F\u043E\u0437\u043D\u0430\u0447\u0430\u044E\u0442\u044C \u0432\u0430\u0436\u043B\u0438\u0432\u0456 \u043F\u043E\u043A\u0440\u0430\u0449\u0435\u043D\u043D\u044F.",info:"\u0406\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0456\u044F",infoText:"\u0434\u0430\u0454 \u043A\u043E\u0440\u0438\u0441\u043D\u0438\u0439 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442.",score:"\u041D\u0435\u043F\u0440\u043E\u0437\u043E\u0440\u0430 SEO-\u043E\u0446\u0456\u043D\u043A\u0430 \u043D\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0454\u0442\u044C\u0441\u044F."},exportCsv:"\u0415\u043A\u0441\u043F\u043E\u0440\u0442 CSV",previous:"\u041D\u0430\u0437\u0430\u0434",next:"\u0414\u0430\u043B\u0456",table:{severity:"\u0412\u0430\u0436\u043B\u0438\u0432\u0456\u0441\u0442\u044C",lifecycle:"\u0421\u0442\u0430\u043D",ruleOwner:"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0430 / \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u043B\u044C\u043D\u0438\u0439",page:"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430",finding:"\u0429\u043E \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u043E",change:"\u0417\u043C\u0456\u043D\u0430",before:"\u0411\u0443\u043B\u043E",evidence:"\u0414\u043E\u043A\u0430\u0437 / \u0441\u0442\u0430\u043B\u043E",remediation:"\u042F\u043A \u0432\u0438\u043F\u0440\u0430\u0432\u0438\u0442\u0438",fingerprint:"\u0412\u0456\u0434\u0431\u0438\u0442\u043E\u043A"},empty:{cleanTitle:"SEO-\u043F\u0440\u043E\u0431\u043B\u0435\u043C \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u043E",cleanMessage:"\u041F\u0435\u0440\u0435\u0432\u0456\u0440\u0435\u043D\u0456 \u0441\u0442\u043E\u0440\u0456\u043D\u043A\u0438 \u043F\u0440\u043E\u0439\u0448\u043B\u0438 \u0432\u0441\u0456 \u0430\u043A\u0442\u0438\u0432\u043D\u0456 \u043F\u0435\u0440\u0435\u0432\u0456\u0440\u043A\u0438.",filteredTitle:"\u0417\u0431\u0456\u0433\u0456\u0432 \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u043E",filteredMessage:"\u041E\u0431\u0435\u0440\u0456\u0442\u044C \u0456\u043D\u0448\u0438\u0439 \u0441\u0442\u0430\u043D \u0430\u0431\u043E \u043E\u0447\u0438\u0441\u0442\u044C\u0442\u0435 \u0444\u0456\u043B\u044C\u0442\u0440\u0438.",clear:"\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u0438 \u0444\u0456\u043B\u044C\u0442\u0440\u0438"},lifecycle:{current:"\u041F\u043E\u0442\u043E\u0447\u043D\u0430",new:"\u041D\u043E\u0432\u0430",ongoing:"\u0422\u0440\u0438\u0432\u0430\u0454",resolved:"\u0412\u0438\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0430",unchanged:"\u0411\u0435\u0437 \u0437\u043C\u0456\u043D"},notPresent:"\u0412\u0456\u0434\u0441\u0443\u0442\u043D\u0454",page:"\u0421\u0442\u043E\u0440\u0456\u043D\u043A\u0430",of:"\u0437",issue:"\u043F\u0440\u043E\u0431\u043B\u0435\u043C\u0430",issues:"\u043F\u0440\u043E\u0431\u043B\u0435\u043C",docs:"\u0434\u043E\u0432\u0456\u0434\u043A\u0430",footer:"\u0421\u0442\u0432\u043E\u0440\u0435\u043D\u043E \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E. \u0414\u0430\u043D\u0456 \u0437\u0432\u0456\u0442\u0443 \u043D\u0456\u043A\u0443\u0434\u0438 \u043D\u0435 \u0437\u0430\u0432\u0430\u043D\u0442\u0430\u0436\u0443\u0432\u0430\u043B\u0438\u0441\u044F."}};function escapeHtml(value){return String(value??"").replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function safeJson(value){return JSON.stringify(value).replaceAll("<","\\u003c").replaceAll(">","\\u003e").replaceAll("&","\\u0026")}function normalizeIssue(candidate,fallbackLifecycle="current"){const ruleId=candidate.ruleId??candidate.rule??"unknown";return{fingerprint:candidate.fingerprint??"legacy",ruleId,rule:candidate.rule??candidate.ruleId??"unknown",severity:candidate.severity??"info",scope:candidate.scope??"page",url:candidate.url??"",message:candidate.message??"",evidence:candidate.evidence??{actual:candidate.after},owner:candidate.owner??"seo",remediation:candidate.remediation??"Review the finding and confirm the intended behavior.",documentationUrl:candidate.documentationUrl??"https://github.com/MelnixDev/seo-crawl-audit/blob/main/docs/rules.md",before:candidate.before,after:candidate.after,lifecycle:candidate.lifecycle??fallbackLifecycle,template:"",localized:localizeIssue(candidate,ruleId)}}function countIssues(issues,key){return issues.reduce((counts,issue)=>{const value=String(issue[key]);counts[value]=(counts[value]??0)+1;return counts},{})}function renderHtmlReport(input,options={}){const mode=input.mode??"scan";const pages=input.pages??[];const current=(input.issues??[]).map(item=>normalizeIssue(item));const lifecycle2=[...(input.newIssues??[]).map(item=>normalizeIssue(item,"new")),...(input.ongoingIssues??[]).map(item=>normalizeIssue(item,"ongoing")),...(input.resolvedIssues??[]).map(item=>normalizeIssue(item,"resolved")),...(input.unchangedIssues??[]).map(item=>normalizeIssue(item,"unchanged"))];const issues=lifecycle2.length>0?lifecycle2:current;const templateGroups=groupIssuesByTemplate(issues);const templateByUrl=new Map(templateGroups.flatMap(group=>group.urls.map(url=>[url,group.template])));for(const issue of issues)issue.template=templateByUrl.get(issue.url)??"";const counts=issues.reduce((summary,item)=>{summary[item.severity]+=1;return summary},{error:0,warning:0,info:0});const affectedPages=new Set(issues.map(item=>item.url)).size;const ruleCounts=countIssues(issues,"rule");const statistics={total:issues.length,pagesChecked:pages.length,targetPages:input.targetPages??null,affectedPages,severity:counts,rules:Object.entries(ruleCounts).map(([id,count])=>({id,count})).sort((left,right)=>right.count-left.count||left.id.localeCompare(right.id)),owners:countIssues(issues,"owner"),lifecycle:countIssues(issues,"lifecycle"),templates:templateGroups.map(({template,issueCount,affectedPages:affectedPages2})=>({template,issueCount,affectedPages:affectedPages2}))};const partial=input.partial??false;const incompleteComparison=mode==="check"&&input.complete===false;const reportTitle=partial?"Partial SEO scan report":mode==="check"?"SEO regression report":"SEO baseline audit";const branding={...input.branding??{},...options.branding??{}};const primaryColor=/^#[0-9a-f]{6}$/i.test(branding.primaryColor??"")?branding.primaryColor:"#3157d5";const logo=branding.logo&&(/^data:image\//.test(branding.logo)||/^https:\/\//.test(branding.logo))?`<img class="logo" src="${escapeHtml(branding.logo)}" alt="${escapeHtml(branding.agencyName??"Report logo")}">`:"";const data=safeJson({mode,issues,statistics,copy:REPORT_COPY,partial,incompleteComparison,comparison:input.comparison??null,history:input.history??null});const generatedAt=input.generatedAt??new Date().toISOString();const startUrl=input.startUrl??"";const targetPages=input.targetPages??null;const isCheck=mode==="check";return`<!doctype html>
|
|
5
|
+
<html lang="en">
|
|
6
|
+
<head>
|
|
7
|
+
<meta charset="utf-8">
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
9
|
+
<title>${escapeHtml(reportTitle)} \xB7 SEO Crawl Audit</title>
|
|
10
|
+
<style>
|
|
11
|
+
:root { color-scheme: light; --bg:#f5f7fb; --surface:#fff; --muted:#64748b; --text:#172033; --line:#dbe2ea; --accent:${primaryColor}; --error:#b42318; --warning:#9a6700; --info:#175cd3; --chart-error:#d92d20; --chart-warning:#f79009; --chart-info:#2e90fa; --chart-resolved:#12b76a; }
|
|
12
|
+
*{box-sizing:border-box}[hidden]{display:none!important}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}main{width:min(1600px,calc(100% - 32px));margin:32px auto 64px}header{display:flex;justify-content:space-between;gap:24px;margin-bottom:22px}.brand{display:flex;align-items:flex-start;gap:14px}.logo{max-width:72px;max-height:52px;object-fit:contain}.eyebrow{color:var(--accent);font-weight:800;letter-spacing:.08em;text-transform:uppercase}h1{margin:4px 0 8px;font-size:clamp(27px,4vw,40px);line-height:1.1}.meta{color:var(--muted);overflow-wrap:anywhere}.header-meta{text-align:right}.language-control{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin-top:10px}.language-control span{margin:0}.language-control select{width:auto;min-height:32px;padding:4px 28px 4px 8px}.notice{margin-bottom:18px;padding:12px 14px;border:1px solid #b2ccff;border-radius:12px;background:#eef4ff;color:#1849a9}.cards{display:grid;grid-template-columns:repeat(5,minmax(120px,1fr));gap:12px;margin-bottom:18px}.card,.panel,.analytics{background:var(--surface);border:1px solid var(--line);box-shadow:0 12px 36px rgba(31,42,68,.07)}.card{padding:15px;border-radius:14px}.card strong{display:block;font-size:27px}.card span{color:var(--muted)}.error strong,.badge.error{color:var(--error)}.warning strong,.badge.warning{color:var(--warning)}.info strong,.badge.info{color:var(--info)}.analytics{margin-bottom:18px;padding:18px;border-radius:16px}.analytics-header{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:15px}.analytics h2,.analytics h3{margin:0}.analytics h2{font-size:20px}.analytics h3{font-size:14px}.analytics-grid{display:grid;grid-template-columns:repeat(4,minmax(240px,1fr));gap:14px}.chart-card{min-width:0;padding:15px;border:1px solid var(--line);border-radius:12px;background:#fbfcfe}.chart-title{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:13px}.chart-title span{color:var(--muted);font-size:12px}.severity-layout{display:grid;grid-template-columns:114px minmax(0,1fr);align-items:center;gap:12px}.donut{display:grid;width:112px;height:112px;padding:12px;border-radius:50%;background:#e2e8f0;place-items:center}.donut-inner{display:grid;width:100%;height:100%;border-radius:50%;background:var(--surface);place-content:center;text-align:center}.donut-inner strong{font-size:24px;line-height:1}.donut-inner span{max-width:76px;margin-top:5px;color:var(--muted);font-size:10px}.chart-list{display:grid;gap:7px}.chart-button{display:grid;width:100%;padding:6px 7px;border-color:transparent;background:transparent;text-align:left}.chart-button:hover,.chart-button:focus-visible{border-color:var(--line);background:#fff}.chart-button[aria-pressed="true"]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}.chart-label{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}.chart-label-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.chart-label strong{font-variant-numeric:tabular-nums}.chart-key{display:inline-block;width:9px;height:9px;margin-right:7px;border-radius:50%}.chart-key.error{background:var(--chart-error)}.chart-key.warning{background:var(--chart-warning)}.chart-key.info{background:var(--chart-info)}.chart-track{height:7px;margin-top:6px;overflow:hidden;border-radius:999px;background:#e8edf3}.chart-fill{display:block;height:100%;min-width:2px;border-radius:inherit;background:var(--accent)}.chart-fill.error{background:var(--chart-error)}.chart-fill.warning{background:var(--chart-warning)}.chart-fill.info{background:var(--chart-info)}.chart-fill.resolved{background:var(--chart-resolved)}.chart-empty{display:grid;min-height:126px;color:var(--muted);place-items:center;text-align:center}.panel{overflow:hidden;border-radius:16px}.tabs{display:flex;gap:6px;padding:12px 16px;border-bottom:1px solid var(--line);overflow:auto}.tabs button[aria-selected="true"]{background:var(--accent);border-color:var(--accent);color:#fff}.filters{display:grid;grid-template-columns:minmax(220px,2fr) repeat(5,minmax(125px,1fr));gap:10px;padding:15px;background:#f8fafc;border-bottom:1px solid var(--line)}label span{display:block;margin-bottom:4px}input,select,button{font:inherit}input,select{width:100%;min-height:40px;padding:8px 10px;border:1px solid var(--line);border-radius:8px;background:#fff;color:var(--text)}button{padding:7px 11px;border:1px solid var(--line);border-radius:8px;background:#fff;color:var(--text);cursor:pointer}button:disabled{opacity:.45}.guide,.results-bar{display:flex;justify-content:space-between;gap:14px;padding:10px 16px;color:var(--muted);border-bottom:1px solid var(--line)}.actions,.pagination{display:flex;align-items:center;gap:8px}.table-wrap{overflow:auto}table{width:100%;min-width:1260px;border-collapse:collapse}th{position:sticky;top:0;background:#f8fafc;color:var(--muted);font-size:11px;letter-spacing:.05em;text-align:left;text-transform:uppercase}th,td{padding:11px 12px;border-top:1px solid var(--line);vertical-align:top}.badge{display:inline-flex;padding:3px 8px;border-radius:999px;background:#f1f5f9;font-size:11px;font-weight:800;text-transform:uppercase}.badge.resolved{color:#067647;background:#ecfdf3}a{color:var(--accent);text-decoration:none;overflow-wrap:anywhere}code{display:block;max-width:320px;white-space:pre-wrap;overflow-wrap:anywhere;color:#344054;font:11px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}.remediation{max-width:260px}.fingerprint{font-size:10px;color:var(--muted)}.empty{padding:50px 20px;text-align:center;color:var(--muted)}.empty strong{display:block;color:var(--text);font-size:17px}.empty button{margin-top:14px}footer{margin-top:16px;color:var(--muted);text-align:center}
|
|
13
|
+
.trend-layout{display:grid;grid-template-columns:minmax(0,3fr) minmax(220px,1fr);gap:18px;align-items:center}.trend-chart{width:100%;height:auto;min-height:220px;overflow:visible}.trend-grid{stroke:#dbe2ea;stroke-width:1}.trend-line{fill:none;stroke-width:3;stroke-linecap:round;stroke-linejoin:round}.trend-point{stroke:#fff;stroke-width:2}.trend-error{stroke:var(--chart-error);fill:var(--chart-error)}.trend-warning{stroke:var(--chart-warning);fill:var(--chart-warning)}.trend-info{stroke:var(--chart-info);fill:var(--chart-info)}.trend-summary{display:grid;gap:9px}.trend-summary div{display:flex;justify-content:space-between;gap:12px;padding:9px 10px;border-radius:9px;background:#f8fafc}.trend-legend{display:flex;gap:14px;flex-wrap:wrap;margin-top:10px;color:var(--muted)}
|
|
14
|
+
@media(max-width:1100px){.analytics-grid{grid-template-columns:1fr 1fr}.trend-layout{grid-template-columns:1fr}.chart-card:last-child{grid-column:1/-1}}
|
|
15
|
+
@media(max-width:950px){main{width:calc(100% - 20px);margin-top:20px}header{display:block}.header-meta{text-align:left;margin-top:12px}.language-control{justify-content:flex-start}.cards{grid-template-columns:repeat(2,1fr)}.analytics-header{align-items:flex-start;flex-direction:column}.analytics-grid{grid-template-columns:1fr}.chart-card:last-child{grid-column:auto}.filters{grid-template-columns:1fr}.results-bar,.guide{align-items:flex-start;flex-direction:column}}
|
|
16
|
+
@media(max-width:430px){.severity-layout{grid-template-columns:1fr}.donut{margin:auto}}
|
|
17
|
+
@media print{body{background:#fff}main{width:100%;margin:0}.filters,.tabs,.actions,.pagination,#clear-filters{display:none!important}.panel,.card,.analytics{box-shadow:none}.analytics-grid{grid-template-columns:1fr 1fr 1fr}.chart-button{padding:4px}.table-wrap{overflow:visible}table{min-width:0;font-size:9px}th{position:static}.remediation,code{max-width:none}a{color:#000}}
|
|
18
|
+
</style>
|
|
19
|
+
</head>
|
|
20
|
+
<body><main>
|
|
21
|
+
<header><div class="brand">${logo}<div><div class="eyebrow">${escapeHtml(branding.agencyName??"SEO Crawl Audit")}</div><h1 id="report-title">${escapeHtml(reportTitle)}</h1><div class="meta">${escapeHtml(startUrl)}</div></div></div><div class="meta header-meta"><span id="generated-label">Generated</span> <time id="generated-at" datetime="${escapeHtml(generatedAt)}">${escapeHtml(generatedAt)}</time><br><span id="engine-label">Engine</span> ${escapeHtml(input.engineVersion??ENGINE_VERSION)} \xB7 <span id="rules-label">Rules</span> ${escapeHtml(input.ruleSetVersion??RULE_SET_VERSION)}<label class="language-control"><span id="language-label">Language</span><select id="language" aria-label="Language"><option value="en">English</option><option value="uk">\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430</option></select></label></div></header>
|
|
22
|
+
${partial?` <div class="notice"><strong id="partial-title">Partial results.</strong> <span id="partial-message">This report contains the pages saved so far. Run the same scan command again to resume without requesting them twice.</span></div>`:""}
|
|
23
|
+
${incompleteComparison?` <div class="notice"><strong id="incomplete-title">Incomplete comparison.</strong> <span id="incomplete-message">Regressions found on checked pages are shown, but unchecked pages are not marked missing or resolved.</span></div>`:""}
|
|
24
|
+
${input.comparison?.kind==="preview"?` <div class="notice"><strong id="preview-title">Preview deployment comparison.</strong> <span id="production-label">Production</span>: <a href="${escapeHtml(input.comparison.productionUrl)}">${escapeHtml(input.comparison.productionUrl)}</a> \xB7 <span id="preview-label">Preview</span>: <a href="${escapeHtml(input.comparison.previewUrl)}">${escapeHtml(input.comparison.previewUrl)}</a></div>`:""}
|
|
25
|
+
<section class="cards"><div class="card"><strong id="pages-count">${pages.length.toLocaleString("en-US")}${targetPages?` / ${targetPages.toLocaleString("en-US")}`:""}</strong><span id="pages-label">Pages checked</span></div><div class="card error"><strong id="errors-count">${counts.error}</strong><span id="errors-label">Errors</span></div><div class="card warning"><strong id="warnings-count">${counts.warning}</strong><span id="warnings-label">Warnings</span></div><div class="card info"><strong id="info-count">${counts.info}</strong><span id="info-label">Info</span></div><div class="card"><strong id="affected-count">${affectedPages.toLocaleString("en-US")}</strong><span id="affected-label">Affected pages</span></div></section>
|
|
26
|
+
${input.history&&input.history.points.length>0?` <section id="history-panel" class="analytics" aria-labelledby="history-title"><div class="analytics-header"><div><h2 id="history-title">Local scan history</h2><div id="history-hint" class="meta">Issue trends from snapshots stored on this device.</div></div></div><div class="trend-layout"><div><svg id="history-chart" class="trend-chart" viewBox="0 0 760 240" role="img"></svg><div class="trend-legend"><span><i class="chart-key error"></i><span id="history-errors-label">Errors</span></span><span><i class="chart-key warning"></i><span id="history-warnings-label">Warnings</span></span><span><i class="chart-key info"></i><span id="history-info-label">Info</span></span></div></div><div id="history-summary" class="trend-summary"></div></div></section>`:""}
|
|
27
|
+
<section id="analytics" class="analytics" aria-labelledby="analytics-title">
|
|
28
|
+
<div class="analytics-header"><div><h2 id="analytics-title">Issue statistics</h2><div id="analytics-hint" class="meta">Select a chart item to filter the issue table.</div></div></div>
|
|
29
|
+
<div class="analytics-grid">
|
|
30
|
+
<article class="chart-card"><div class="chart-title"><h3 id="severity-chart-title">By severity</h3></div><div id="severity-chart"></div></article>
|
|
31
|
+
<article class="chart-card"><div class="chart-title"><h3 id="rules-chart-title">Most frequent checks</h3><span id="rules-chart-summary"></span></div><div id="rules-chart" class="chart-list"></div></article>
|
|
32
|
+
<article class="chart-card"><div class="chart-title"><h3 id="distribution-chart-title">${isCheck?"By lifecycle":"By owner"}</h3></div><div id="distribution-chart" class="chart-list"></div></article>
|
|
33
|
+
<article class="chart-card"><div class="chart-title"><h3 id="templates-chart-title">Affected page templates</h3><span id="templates-chart-summary"></span></div><div id="templates-chart" class="chart-list"></div></article>
|
|
34
|
+
</div>
|
|
35
|
+
</section>
|
|
36
|
+
<section class="panel">
|
|
37
|
+
<nav id="issue-lifecycle-tabs" class="tabs" aria-label="Issue lifecycle"><button data-tab="" aria-selected="true">Current / all</button><button data-tab="new">New</button><button data-tab="ongoing">Ongoing</button><button data-tab="resolved">Resolved</button><button data-tab="unchanged">Unchanged</button></nav>
|
|
38
|
+
<div class="filters"><label><span id="search-label" class="meta">URL or text</span><input id="search" type="search" placeholder="URL, check, or message"></label><label><span id="severity-label" class="meta">Severity</span><select id="severity"><option value="">All severities</option><option value="error">Error</option><option value="warning">Warning</option><option value="info">Info</option></select></label><label><span id="rule-label" class="meta">Check</span><select id="rule"><option value="">All checks</option></select></label><label><span id="template-label" class="meta">Page template</span><select id="template"><option value="">All templates</option></select></label><label><span id="owner-label" class="meta">Owner</span><select id="owner"><option value="">All owners</option><option value="seo">SEO</option><option value="content">Content</option><option value="developer">Developer</option></select></label><label><span id="rows-label" class="meta">Rows</span><select id="page-size"><option value="100">100 per page</option><option value="250">250 per page</option><option value="500">500 per page</option></select></label></div>
|
|
39
|
+
<div class="guide"><span><strong id="guide-error">Errors</strong> <span id="guide-error-text">need attention first.</span> <strong id="guide-warning">Warnings</strong> <span id="guide-warning-text">are important improvements.</span> <strong id="guide-info">Info</strong> <span id="guide-info-text">is useful context.</span></span><span id="score-note">No opaque SEO score is used.</span></div>
|
|
40
|
+
<div class="results-bar"><span id="result-count" aria-live="polite"></span><div class="actions"><button id="export-csv" type="button">Export CSV</button><div id="pagination" class="pagination"><button id="previous" type="button">Previous</button><span id="page-info"></span><button id="next" type="button">Next</button></div></div></div>
|
|
41
|
+
<div id="table-wrap" class="table-wrap"><table><thead><tr><th id="th-severity">Severity</th><th id="th-lifecycle">Lifecycle</th><th id="th-rule-owner">Check / owner</th><th id="th-page">Page</th><th id="th-finding">${isCheck?"Change":"What was found"}</th>${isCheck?'<th id="th-before">Before</th>':""}<th id="th-evidence">Evidence / after</th><th id="th-remediation">Remediation</th><th id="th-fingerprint">Fingerprint</th></tr></thead><tbody id="issues"></tbody></table></div>
|
|
42
|
+
<div id="empty" class="empty" hidden><strong id="empty-title">No SEO issues found</strong><span id="empty-message">The scanned pages passed all current checks.</span><button id="clear-filters" type="button">Clear filters</button></div>
|
|
43
|
+
</section><footer id="report-footer">Generated locally. No report data was uploaded.</footer>
|
|
44
|
+
</main>
|
|
45
|
+
<script>
|
|
46
|
+
const report=${data};
|
|
47
|
+
const byId=(id)=>document.querySelector("#"+id); const generatedAt=byId("generated-at"); const language=byId("language"); const search=byId("search"); const severity=byId("severity"); const rule=byId("rule"); const template=byId("template"); const owner=byId("owner"); const pageSize=byId("page-size"); const tbody=byId("issues"); const empty=byId("empty"); const emptyTitle=byId("empty-title"); const emptyMessage=byId("empty-message"); const clearFilters=byId("clear-filters"); const tableWrap=byId("table-wrap"); const resultCount=byId("result-count"); const pagination=byId("pagination"); const previous=byId("previous"); const next=byId("next"); const pageInfo=byId("page-info"); const severityChart=byId("severity-chart"); const rulesChart=byId("rules-chart"); const distributionChart=byId("distribution-chart"); const templatesChart=byId("templates-chart"); const historyChart=byId("history-chart"); const historySummary=byId("history-summary"); let locale="en"; let currentPage=1; let activeTab=""; let lastFiltered=[];
|
|
48
|
+
const generatedDate=new Date(generatedAt.dateTime); const copy=()=>report.copy[locale]; const issueText=(issue)=>issue.localized[locale]||issue.localized.en; const number=(value)=>Number(value).toLocaleString(locale==="uk"?"uk-UA":"en-US");
|
|
49
|
+
function valueText(value){if(value===undefined)return "\u2014";if(value===null||value==="")return copy().notPresent;return typeof value==="string"?value:JSON.stringify(value)}
|
|
50
|
+
function cell(row,value,className){const element=document.createElement("td");if(className)element.className=className;element.textContent=value;row.append(element);return element}
|
|
51
|
+
function setText(id,value){const element=byId(id);if(element)element.textContent=value}
|
|
52
|
+
function setActiveTab(value){activeTab=value;for(const tab of document.querySelectorAll("[data-tab]"))tab.setAttribute("aria-selected",String(tab.dataset.tab===value))}
|
|
53
|
+
function applyChartFilter(kind,value){if(kind==="severity")severity.value=severity.value===value?"":value;else if(kind==="rule")rule.value=rule.value===value?"":value;else if(kind==="template")template.value=template.value===value?"":value;else if(kind==="owner")owner.value=owner.value===value?"":value;else if(kind==="lifecycle")setActiveTab(activeTab===value?"":value);currentPage=1;render()}
|
|
54
|
+
function chartButton(label,count,max,kind,value,colorClass=""){
|
|
55
|
+
const text=copy();const button=document.createElement("button");button.type="button";button.className="chart-button";button.dataset.chartFilter=kind;button.dataset.chartValue=value;button.setAttribute("aria-pressed","false");button.setAttribute("aria-label",text.analytics.filterBy+" "+label+": "+number(count)+" "+text.issues);
|
|
56
|
+
const labelRow=document.createElement("span");labelRow.className="chart-label";const labelText=document.createElement("span");labelText.className="chart-label-text";if(colorClass){const key=document.createElement("span");key.className="chart-key "+colorClass;labelText.append(key)}labelText.append(document.createTextNode(label));const amount=document.createElement("strong");amount.textContent=number(count);labelRow.append(labelText,amount);
|
|
57
|
+
const track=document.createElement("span");track.className="chart-track";const fill=document.createElement("span");fill.className="chart-fill "+colorClass;fill.style.width=(max>0?count/max*100:0)+"%";track.append(fill);button.append(labelRow,track);button.addEventListener("click",()=>applyChartFilter(kind,value));return button;
|
|
58
|
+
}
|
|
59
|
+
function chartEmpty(container){const message=document.createElement("div");message.className="chart-empty";message.textContent=copy().analytics.noData;container.replaceChildren(message)}
|
|
60
|
+
function syncChartButtons(){for(const button of document.querySelectorAll("[data-chart-filter]")){const kind=button.dataset.chartFilter;const value=button.dataset.chartValue;const selected=kind==="severity"?severity.value===value:kind==="rule"?rule.value===value:kind==="template"?template.value===value:kind==="owner"?owner.value===value:activeTab===value;button.setAttribute("aria-pressed",String(selected))}}
|
|
61
|
+
function renderAnalytics(){
|
|
62
|
+
const text=copy();const stats=report.statistics;setText("analytics-title",text.analytics.title);setText("analytics-hint",text.analytics.hint);setText("severity-chart-title",text.analytics.severity);setText("rules-chart-title",text.analytics.topRules);setText("distribution-chart-title",report.mode==="check"?text.analytics.lifecycle:text.analytics.owners);setText("templates-chart-title",text.analytics.templates);
|
|
63
|
+
if(stats.total===0){setText("rules-chart-summary","");setText("templates-chart-summary","");chartEmpty(severityChart);chartEmpty(rulesChart);chartEmpty(distributionChart);chartEmpty(templatesChart);return}
|
|
64
|
+
const severityOrder=["error","warning","info"];let cursor=0;const segments=severityOrder.map((value,index)=>{const start=cursor;cursor=index===severityOrder.length-1?100:cursor+(stats.severity[value]/stats.total*100);return "var(--chart-"+value+") "+start+"% "+cursor+"%"});
|
|
65
|
+
const layout=document.createElement("div");layout.className="severity-layout";const donut=document.createElement("div");donut.className="donut";donut.style.background="conic-gradient("+segments.join(",")+")";donut.setAttribute("role","img");donut.setAttribute("aria-label",text.analytics.severity+": "+severityOrder.map((value)=>text.severities[value]+" "+number(stats.severity[value])).join(", "));const donutInner=document.createElement("div");donutInner.className="donut-inner";const total=document.createElement("strong");total.textContent=number(stats.total);const totalLabel=document.createElement("span");totalLabel.textContent=text.analytics.total;donutInner.append(total,totalLabel);donut.append(donutInner);const severityList=document.createElement("div");severityList.className="chart-list";for(const value of severityOrder)severityList.append(chartButton(text.severities[value],stats.severity[value],stats.total,"severity",value,value));layout.append(donut,severityList);severityChart.replaceChildren(layout);
|
|
66
|
+
const topRules=stats.rules.slice(0,7);setText("rules-chart-summary",number(topRules.length)+" "+text.of+" "+number(stats.rules.length));const ruleMax=Math.max(...topRules.map((item)=>item.count));rulesChart.replaceChildren(...topRules.map((item)=>{const sample=report.issues.find((issue)=>issue.rule===item.id);return chartButton(sample?issueText(sample).rule:item.id,item.count,ruleMax,"rule",item.id)}));
|
|
67
|
+
const distributionOrder=report.mode==="check"?["new","ongoing","resolved","unchanged"]:["seo","content","developer"];const distribution=report.mode==="check"?stats.lifecycle:stats.owners;const visibleDistribution=distributionOrder.filter((value)=>distribution[value]>0);const distributionMax=Math.max(...visibleDistribution.map((value)=>distribution[value]));distributionChart.replaceChildren(...visibleDistribution.map((value)=>chartButton(report.mode==="check"?text.lifecycle[value]:text.owners[value],distribution[value],distributionMax,report.mode==="check"?"lifecycle":"owner",value,report.mode==="check"?value:"")));const topTemplates=stats.templates.slice(0,7);setText("templates-chart-summary",number(topTemplates.length)+" "+text.of+" "+number(stats.templates.length));const templateMax=Math.max(...topTemplates.map((item)=>item.issueCount));templatesChart.replaceChildren(...topTemplates.map((item)=>chartButton(item.template,item.issueCount,templateMax,"template",item.template)));syncChartButtons();
|
|
68
|
+
}
|
|
69
|
+
function renderHistory(){
|
|
70
|
+
if(!report.history||!historyChart||!historySummary)return;const text=copy();const points=report.history.points.slice(-20);const ns="http://www.w3.org/2000/svg";const width=760,height=240,left=38,right=16,top=18,bottom=34;const maximum=Math.max(1,...points.flatMap((point)=>[point.errors,point.warnings,point.info]));const x=(index)=>left+(points.length===1?0:(width-left-right)*index/(points.length-1));const y=(value)=>top+(height-top-bottom)*(1-value/maximum);historyChart.replaceChildren();historyChart.setAttribute("aria-label",text.history.chartLabel+" "+number(points.length));for(let line=0;line<=4;line+=1){const grid=document.createElementNS(ns,"line");const value=maximum*line/4;grid.setAttribute("x1",String(left));grid.setAttribute("x2",String(width-right));grid.setAttribute("y1",String(y(value)));grid.setAttribute("y2",String(y(value)));grid.setAttribute("class","trend-grid");historyChart.append(grid)}for(const [key,className] of [["errors","error"],["warnings","warning"],["info","info"]]){const polyline=document.createElementNS(ns,"polyline");polyline.setAttribute("points",points.map((point,index)=>x(index)+","+y(point[key])).join(" "));polyline.setAttribute("class","trend-line trend-"+className);historyChart.append(polyline);for(const [index,point] of points.entries()){const circle=document.createElementNS(ns,"circle");circle.setAttribute("cx",String(x(index)));circle.setAttribute("cy",String(y(point[key])));circle.setAttribute("r","4");circle.setAttribute("class","trend-point trend-"+className);const title=document.createElementNS(ns,"title");title.textContent=new Intl.DateTimeFormat(locale==="uk"?"uk-UA":"en-US",{dateStyle:"medium",timeStyle:"short"}).format(new Date(point.generatedAt))+": "+text.severities[className]+" "+number(point[key]);circle.append(title);historyChart.append(circle)}}if(points.length>0){for(const [index,anchor] of [[0,"start"],[points.length-1,"end"]]){const label=document.createElementNS(ns,"text");label.setAttribute("x",String(x(index)));label.setAttribute("y",String(height-9));label.setAttribute("text-anchor",anchor);label.setAttribute("fill","#64748b");label.setAttribute("font-size","11");label.textContent=new Intl.DateTimeFormat(locale==="uk"?"uk-UA":"en-US",{dateStyle:"medium"}).format(new Date(points[index].generatedAt));historyChart.append(label)}}const latest=points.at(-1);historySummary.replaceChildren();if(latest){for(const [label,value] of [[text.history.runs,report.history.points.length],[text.history.pages,latest.pages],[text.history.newIssues,latest.newIssues],[text.history.resolvedIssues,latest.resolvedIssues],[text.history.sitemapUrls,latest.sitemapUrls],[text.history.maxDepth,latest.maxDepth]]){const row=document.createElement("div");const name=document.createElement("span");name.textContent=label;const amount=document.createElement("strong");amount.textContent=number(value);row.append(name,amount);historySummary.append(row)}}
|
|
71
|
+
}
|
|
72
|
+
const ruleIds=[...new Set(report.issues.map((issue)=>issue.rule))].sort(); for(const value of ruleIds){const option=document.createElement("option");option.value=value;rule.append(option)}const templateIds=[...new Set(report.issues.map((issue)=>issue.template).filter(Boolean))].sort();for(const value of templateIds){const option=document.createElement("option");option.value=value;option.textContent=value;template.append(option)}
|
|
73
|
+
function applyLocale(){
|
|
74
|
+
const text=copy(); document.documentElement.lang=locale; language.setAttribute("aria-label",text.language); byId("issue-lifecycle-tabs").setAttribute("aria-label",text.issueLifecycle); setText("language-label",text.language); const titleKey=report.partial?"partial":report.mode==="check"?"check":"scan"; setText("report-title",text.titles[titleKey]); document.title=text.titles[titleKey]+" \xB7 SEO Crawl Audit"; setText("generated-label",text.generated); setText("engine-label",text.engine); setText("rules-label",text.rules);
|
|
75
|
+
if(!Number.isNaN(generatedDate.getTime()))generatedAt.textContent=new Intl.DateTimeFormat(locale==="uk"?"uk-UA":"en-US",{dateStyle:"medium",timeStyle:"short"}).format(generatedDate); setText("partial-title",text.partialTitle); setText("partial-message",text.partialMessage); setText("incomplete-title",text.incompleteTitle); setText("incomplete-message",text.incompleteMessage);setText("preview-title",text.previewTitle);setText("production-label",text.production);setText("preview-label",text.preview);
|
|
76
|
+
setText("pages-count",number(report.statistics.pagesChecked)+(report.statistics.targetPages?" / "+number(report.statistics.targetPages):""));setText("errors-count",number(report.statistics.severity.error));setText("warnings-count",number(report.statistics.severity.warning));setText("info-count",number(report.statistics.severity.info));setText("affected-count",number(report.statistics.affectedPages));setText("pages-label",text.cards.pages);setText("errors-label",text.cards.error);setText("warnings-label",text.cards.warning);setText("info-label",text.cards.info);setText("affected-label",text.cards.affected); for(const tab of document.querySelectorAll("[data-tab]")){const key=tab.dataset.tab||"current";tab.textContent=text.tabs[key]}
|
|
77
|
+
setText("search-label",text.filters.search);search.placeholder=text.filters.searchPlaceholder;setText("severity-label",text.filters.severity);setText("rule-label",text.filters.rule);setText("template-label",text.filters.template);setText("owner-label",text.filters.owner);setText("rows-label",text.filters.rows);severity.options[0].textContent=text.all.severity;for(const option of [...severity.options].slice(1))option.textContent=text.severities[option.value];rule.options[0].textContent=text.all.rule;for(const option of [...rule.options].slice(1)){const sample=report.issues.find((issue)=>issue.rule===option.value);option.textContent=sample?issueText(sample).rule:option.value}template.options[0].textContent=text.all.template;owner.options[0].textContent=text.all.owner;for(const option of [...owner.options].slice(1))option.textContent=text.owners[option.value];for(const option of pageSize.options)option.textContent=text.rows[option.value];
|
|
78
|
+
setText("guide-error",text.guide.error);setText("guide-error-text",text.guide.errorText);setText("guide-warning",text.guide.warning);setText("guide-warning-text",text.guide.warningText);setText("guide-info",text.guide.info);setText("guide-info-text",text.guide.infoText);setText("score-note",text.guide.score);setText("export-csv",text.exportCsv);setText("previous",text.previous);setText("next",text.next);setText("th-severity",text.table.severity);setText("th-lifecycle",text.table.lifecycle);setText("th-rule-owner",text.table.ruleOwner);setText("th-page",text.table.page);setText("th-finding",report.mode==="check"?text.table.change:text.table.finding);setText("th-before",text.table.before);setText("th-evidence",text.table.evidence);setText("th-remediation",text.table.remediation);setText("th-fingerprint",text.table.fingerprint);setText("clear-filters",text.empty.clear);setText("report-footer",text.footer);setText("history-title",text.history.title);setText("history-hint",text.history.hint);setText("history-errors-label",text.severities.error);setText("history-warnings-label",text.severities.warning);setText("history-info-label",text.severities.info);renderHistory();renderAnalytics();render();
|
|
79
|
+
}
|
|
80
|
+
function render(){
|
|
81
|
+
const text=copy();const query=search.value.trim().toLowerCase();lastFiltered=report.issues.filter((issue)=>{if(activeTab&&issue.lifecycle!==activeTab)return false;if(severity.value&&issue.severity!==severity.value)return false;if(rule.value&&issue.rule!==rule.value)return false;if(template.value&&issue.template!==template.value)return false;if(owner.value&&issue.owner!==owner.value)return false;if(!query)return true;const localized=issueText(issue);return [issue.url,issue.template,issue.rule,issue.message,issue.remediation,localized.rule,localized.message,localized.remediation,issue.owner,valueText(issue.evidence),valueText(issue.before),valueText(issue.after)].join(" ").toLowerCase().includes(query)});const rowsPerPage=Number(pageSize.value);const pageCount=Math.max(1,Math.ceil(lastFiltered.length/rowsPerPage));currentPage=Math.min(currentPage,pageCount);const visible=lastFiltered.slice((currentPage-1)*rowsPerPage,currentPage*rowsPerPage);tbody.replaceChildren();
|
|
82
|
+
for(const issue of visible){const localized=issueText(issue);const row=document.createElement("tr");const severityCell=document.createElement("td");const severityBadge=document.createElement("span");severityBadge.className="badge "+issue.severity;severityBadge.textContent=text.severities[issue.severity];severityCell.append(severityBadge);row.append(severityCell);const lifeCell=document.createElement("td");const lifeBadge=document.createElement("span");lifeBadge.className="badge "+issue.lifecycle;lifeBadge.textContent=text.lifecycle[issue.lifecycle]||issue.lifecycle;lifeCell.append(lifeBadge);row.append(lifeCell);cell(row,localized.rule+" \xB7 "+text.owners[issue.owner]);const pageCell=document.createElement("td");const link=document.createElement("a");link.href=issue.url;link.target="_blank";link.rel="noreferrer";link.textContent=issue.url;pageCell.append(link);row.append(pageCell);cell(row,localized.message);if(report.mode==="check"){const beforeCell=document.createElement("td");const code=document.createElement("code");code.textContent=valueText(issue.before);beforeCell.append(code);row.append(beforeCell)}const evidenceCell=document.createElement("td");const evidence=document.createElement("code");evidence.textContent=valueText(issue.after!==undefined?issue.after:issue.evidence);evidenceCell.append(evidence);row.append(evidenceCell);cell(row,localized.remediation,"remediation");const fingerprint=cell(row,issue.fingerprint,"fingerprint");const docs=document.createElement("a");docs.href=locale==="uk"?issue.documentationUrl.replace("/docs/rules.md#","/docs/rules.uk.md#"):issue.documentationUrl;docs.target="_blank";docs.rel="noreferrer";docs.textContent=" "+text.docs;fingerprint.append(docs);tbody.append(row)}
|
|
83
|
+
const issueLabel=locale==="uk"?text.issues:report.issues.length===1?text.issue:text.issues;resultCount.textContent=number(lastFiltered.length)+" "+text.of+" "+number(report.issues.length)+" "+issueLabel;pageInfo.textContent=text.page+" "+number(currentPage)+" "+text.of+" "+number(pageCount);previous.disabled=currentPage===1;next.disabled=currentPage===pageCount;pagination.hidden=lastFiltered.length===0||pageCount===1;tableWrap.hidden=lastFiltered.length===0;empty.hidden=lastFiltered.length!==0;if(lastFiltered.length===0){const reportIsClean=report.issues.length===0;emptyTitle.textContent=reportIsClean?text.empty.cleanTitle:text.empty.filteredTitle;emptyMessage.textContent=reportIsClean?text.empty.cleanMessage:text.empty.filteredMessage;clearFilters.hidden=reportIsClean}syncChartButtons()
|
|
84
|
+
}
|
|
85
|
+
for(const element of [search,severity,rule,template,owner,pageSize]){const update=()=>{currentPage=1;render()};element.addEventListener("input",update);element.addEventListener("change",update)}for(const tab of document.querySelectorAll("[data-tab]")){tab.addEventListener("click",()=>{setActiveTab(tab.dataset.tab);currentPage=1;render()})}previous.addEventListener("click",()=>{currentPage-=1;render()});next.addEventListener("click",()=>{currentPage+=1;render()});clearFilters.addEventListener("click",()=>{search.value="";severity.value="";rule.value="";template.value="";owner.value="";setActiveTab("");currentPage=1;render()});language.addEventListener("change",()=>{locale=language.value;applyLocale()});
|
|
86
|
+
byId("export-csv").addEventListener("click",()=>{const text=copy();const quote=(value)=>'"'+String(value??"").replaceAll('"','""')+'"';const headers=[text.table.severity,text.table.lifecycle,text.table.ruleOwner,text.table.page,report.mode==="check"?text.table.change:text.table.finding,text.table.before,text.table.evidence,text.table.remediation,text.table.fingerprint];const rows=lastFiltered.map((item)=>{const localized=issueText(item);return [text.severities[item.severity],text.lifecycle[item.lifecycle]||item.lifecycle,localized.rule+" \xB7 "+text.owners[item.owner],item.url,localized.message,valueText(item.before),valueText(item.after!==undefined?item.after:item.evidence),localized.remediation,item.fingerprint]});const csv=[headers,...rows].map((row)=>row.map((value)=>quote(typeof value==="object"?JSON.stringify(value):value)).join(",")).join("\\n");const link=document.createElement("a");link.href=URL.createObjectURL(new Blob(["\\uFEFF",csv],{type:"text/csv;charset=utf-8"}));link.download="seo-crawl-audit-"+locale+".csv";link.click();URL.revokeObjectURL(link.href)});applyLocale();
|
|
87
|
+
</script></body></html>`}function severityCounts(issues){return issues.reduce((counts,issue)=>{counts[issue.severity]+=1;return counts},{error:0,warning:0,info:0})}function buildHistorySeries(snapshots){if(snapshots.length===0)return null;const unique=new Map(snapshots.map(snapshot=>[`${snapshot.generatedAt}|${snapshot.configurationHash}|${snapshot.pages.length}`,snapshot]));const ordered=[...unique.values()].sort((left,right)=>left.generatedAt.localeCompare(right.generatedAt));const siteUrl=ordered.at(-1).siteUrl;const compatible2=ordered.filter(snapshot=>snapshot.siteUrl===siteUrl);const points=compatible2.map((snapshot,index)=>{const issues=audit(snapshot);const counts=severityCounts(issues);const previous=index>0?compatible2[index-1]:void 0;const comparison=previous?diff(previous,snapshot):null;return{generatedAt:snapshot.generatedAt,siteUrl:snapshot.siteUrl,pages:snapshot.pages.length,affectedPages:new Set(issues.map(issue=>issue.url)).size,errors:counts.error,warnings:counts.warning,info:counts.info,newIssues:comparison?.newIssues.length??0,resolvedIssues:comparison?.resolvedIssues.length??0,sitemapUrls:snapshot.sitemap?.urls.length??0,maxDepth:snapshot.pages.reduce((maximum,page)=>Math.max(maximum,page.depth),0),partial:snapshot.partial||snapshot.truncated}});return{siteUrl,points}}function audit2(snapshot,ruleSet={}){return audit(snapshot,ruleSet)}function diff2(previous,current,ruleSet={}){return diff(previous,current,ruleSet)}import{access,mkdir,readFile,readdir,rename,writeFile}from"node:fs/promises";import{join,resolve}from"node:path";async function findConfigFile(cwd=process.cwd()){const path=resolve(cwd,DEFAULT_CONFIG_FILE);try{await access(path);return path}catch{return null}}async function loadConfig(path){const resolvedPath=path?resolve(path):await findConfigFile();if(!resolvedPath)return{};try{return validateConfig(JSON.parse(await readFile(resolvedPath,"utf8")))}catch(error){throw new Error(`invalid config ${resolvedPath}: ${error instanceof Error?error.message:String(error)}`,{cause:error})}}async function writeSnapshot(path,snapshot){const temporaryPath=`${path}.${process.pid}.tmp`;await writeFile(temporaryPath,`${JSON.stringify(snapshot,null,2)}
|
|
88
|
+
`,"utf8");await rename(temporaryPath,path)}async function readSnapshot(path){try{return migrateSnapshot(JSON.parse(await readFile(path,"utf8")))}catch(error){if(error instanceof SyntaxError){throw new Error(`invalid snapshot JSON: ${path}`,{cause:error})}if(error instanceof Error&&error.message.startsWith("unsupported")){throw new Error(`unsupported or invalid baseline: ${path}`,{cause:error})}throw error}}async function writeReport(path,data,options={}){const temporaryPath=`${path}.${process.pid}.tmp`;await writeFile(temporaryPath,renderHtmlReport(data,options),"utf8");await rename(temporaryPath,path)}function historyFileName(snapshot){const timestamp=snapshot.generatedAt.replaceAll(":","-").replaceAll(".","-");return`${timestamp}-${snapshot.configurationHash.slice(0,8)}.snapshot.json`}async function writeHistorySnapshot(directory,snapshot){const resolvedDirectory=resolve(directory);await mkdir(resolvedDirectory,{recursive:true});const path=join(resolvedDirectory,historyFileName(snapshot));await writeSnapshot(path,snapshot);return path}async function readHistorySnapshots(directory,siteUrl){const resolvedDirectory=resolve(directory);let names;try{names=await readdir(resolvedDirectory)}catch(error){if(error&&typeof error==="object"&&"code"in error&&error.code==="ENOENT")return[];throw error}const records=[];for(const name of names.filter(candidate=>candidate.endsWith(".snapshot.json")).sort()){const path=join(resolvedDirectory,name);const snapshot=await readSnapshot(path);if(!siteUrl||snapshot.siteUrl===siteUrl)records.push({path,snapshot})}return records.sort((left,right)=>left.snapshot.generatedAt.localeCompare(right.snapshot.generatedAt)||left.path.localeCompare(right.path))}import{appendFile,readFile as readFile2,rename as rename2,unlink,writeFile as writeFile2}from"node:fs/promises";function header(identity){return{type:"seo-audit-checkpoint",schemaVersion:2,identity}}function compatible(saved,identity){if(!saved||typeof saved!=="object")return false;const candidate=saved;if(candidate.type!=="seo-audit-checkpoint")return false;if(candidate.schemaVersion===2){return JSON.stringify(candidate.identity)===JSON.stringify(identity)}if(candidate.schemaVersion!==1)return false;const source=candidate.source;return source?.startUrl===identity.siteUrl&&(source.sitemap??null)===identity.sitemapUrl&&(source.includeQuery??false)===identity.includeQuery&&(source.respectRobots??true)===identity.respectRobots}var FileCheckpointStore=class{path;#identity=null;#writeQueue=Promise.resolve();constructor(path){this.path=path}async#replace(identity){const temporaryPath=`${this.path}.${process.pid}.${Date.now()}.tmp`;await writeFile2(temporaryPath,`${JSON.stringify(header(identity))}
|
|
89
|
+
`,"utf8");await rename2(temporaryPath,this.path);this.#identity=identity}async load(identity){await this.flush();let content;try{content=await readFile2(this.path,"utf8")}catch(error){if(error.code!=="ENOENT")throw error;await this.#replace(identity);return null}const lines=content.split("\n");let savedHeader;try{savedHeader=JSON.parse(lines[0]??"")}catch{await this.#replace(identity);return null}if(!compatible(savedHeader,identity)){await this.#replace(identity);return null}this.#identity=identity;const pages=new Map;const records=lines.slice(1);let lastRecordIndex=records.length-1;while(lastRecordIndex>=0&&!records[lastRecordIndex]?.trim())lastRecordIndex-=1;for(const[index,line]of records.entries()){if(!line.trim())continue;try{const record2=JSON.parse(line);if(record2.type==="page"&&typeof record2.page?.url==="string"){pages.set(record2.page.url,record2.page)}}catch(error){if(index!==lastRecordIndex){throw new Error(`corrupt checkpoint record ${index+2} in ${this.path}`,{cause:error})}}}return{identity,pages:[...pages.values()]}}append(identity,page){this.#writeQueue=this.#writeQueue.then(async()=>{if(!this.#identity||JSON.stringify(this.#identity)!==JSON.stringify(identity)){await this.#replace(identity)}await appendFile(this.path,`${JSON.stringify({type:"page",page})}
|
|
90
|
+
`,"utf8")});return this.#writeQueue}async clear(identity){await this.flush();if(this.#identity&&JSON.stringify(this.#identity)!==JSON.stringify(identity))return;try{await unlink(this.path)}catch(error){if(error.code!=="ENOENT")throw error}this.#identity=null}async flush(){await this.#writeQueue}};function createFileCheckpointStore(path){return new FileCheckpointStore(path)}import{extname}from"node:path";function checkpointPathForOutput(output){const extension=extname(output);if(!extension){return`${output}.checkpoint.ndjson`}return`${output.slice(0,-extension.length)}.checkpoint.ndjson`}import{parseArgs}from"node:util";function parseCliArgs(args){return parseArgs({args,allowPositionals:true,strict:true,options:{baseline:{type:"string"},config:{type:"string"},output:{type:"string"},report:{type:"string"},"no-report":{type:"boolean"},"no-cache":{type:"boolean"},pages:{type:"string"},all:{type:"boolean"},"max-pages":{type:"string"},concurrency:{type:"string"},delay:{type:"string"},timeout:{type:"string"},sitemap:{type:"string"},"no-sitemap":{type:"boolean"},"include-query":{type:"boolean"},"ignore-robots":{type:"boolean"},strict:{type:"boolean"},json:{type:"boolean"},help:{type:"boolean"},version:{type:"boolean"},production:{type:"string"},preview:{type:"string"},"production-headers-env":{type:"string"},"preview-headers-env":{type:"string"},"history-dir":{type:"string"},"no-history":{type:"boolean"},from:{type:"string"},to:{type:"string"}}})}function withFileConfig(values,config){return{...values,__config:config}}function integer2(value,name,fallback,allowZero=false){if(value===void 0)return fallback;const parsed=Number.parseInt(value,10);if(!Number.isInteger(parsed)||parsed<(allowZero?0:1)){throw new Error(`${name} must be a ${allowZero?"non-negative":"positive"} integer`)}return parsed}function scanConfig(url,values,baseline){if(values.sitemap&&values["no-sitemap"])throw new Error("--sitemap and --no-sitemap cannot be used together");const saved=baseline?.config??{};const file=values.__config??{};const cli={url,schemaVersion:1,maxPages:integer2(values.pages??values["max-pages"],values.pages!==void 0?"--pages":"--max-pages",file.maxPages??saved.maxPages??100),concurrency:integer2(values.concurrency,"--concurrency",file.concurrency??saved.concurrency??5),delay:integer2(values.delay,"--delay",file.delay??saved.delay??100,true),timeout:integer2(values.timeout,"--timeout",file.timeout??saved.timeout??1e4)};if(values["no-sitemap"])cli.sitemap="none";else if(values.sitemap)cli.sitemap=values.sitemap;if(values["include-query"]!==void 0)cli.includeQuery=values["include-query"];if(values["ignore-robots"]!==void 0)cli.respectRobots=!values["ignore-robots"];return resolveConfig(cli,file,saved)}import{dirname,join as join2,resolve as resolve2}from"node:path";var useColor=process.stdout.isTTY&&!process.env.NO_COLOR;function color(code,value){return useColor?`\x1B[${code}m${value}\x1B[0m`:value}function summarizeIssues(issues){return issues.reduce((summary,issue)=>{summary[issue.severity]+=1;return summary},{error:0,warning:0,info:0})}function printIssues(issues){if(issues.length===0){console.log(color("32","\u2713 No SEO regressions detected."));return}for(const issue of issues){const marker=issue.severity==="error"?color("31","\u2716 error"):issue.severity==="warning"?color("33","\u26A0 warning"):color("34","\u2139 info");console.log(`${marker} ${issue.rule} ${issue.url}`);console.log(` ${issue.message}`);if(issue.before!==void 0||issue.after!==void 0){console.log(` before: ${JSON.stringify(issue.before)}`);console.log(` after: ${JSON.stringify(issue.after)}`)}}const summary=summarizeIssues(issues);console.log(`
|
|
91
|
+
${summary.error} error(s), ${summary.warning} warning(s) detected.`)}import{createInterface}from"node:readline/promises";function parseScanMenuSelection(input,totalPages){const normalized=input.trim().toLowerCase();if(normalized===""||normalized==="1")return{mode:"fixed",target:Math.min(100,totalPages)};if(normalized==="2"||normalized==="all")return{mode:"all",target:totalPages};if(normalized==="3"||normalized==="step")return{mode:"step",target:totalPages};const number=Number.parseInt(normalized,10);return/^\d+$/.test(normalized)&&number>0?{mode:"fixed",target:Math.min(number,totalPages)}:null}async function ask(question){const readline=createInterface({input:process.stdin,output:process.stdout});try{return(await readline.question(question)).trim()}finally{readline.close()}}async function chooseScanPlan(totalPages){while(true){console.log(`
|
|
92
|
+
Sitemap contains ${totalPages.toLocaleString("en-US")} page(s).`);console.log("How many pages should be scanned?");console.log(" 1) First 100");console.log(` 2) All ${totalPages.toLocaleString("en-US")}`);console.log(" 3) 100 at a time with confirmation");console.log(" Or enter an exact number, for example 500.");const selection=parseScanMenuSelection(await ask("Choose [1]: "),totalPages);if(!selection){console.log("Enter 1, 2, 3, all, step, or a positive number.");continue}if(selection.mode==="all"){const confirmation=await ask(`This will request ${totalPages.toLocaleString("en-US")} pages. Continue? [y/N] `);if(!["y","yes"].includes(confirmation.toLowerCase()))continue}return selection}}function printProgress(checked,target,persistent=false){const ratio=target===0?1:Math.min(checked/target,1);const percent=(ratio*100).toFixed(ratio<.1?1:0);const filled=Math.round(ratio*20);const message=`[${"\u2588".repeat(filled)}${"\u2591".repeat(20-filled)}] ${percent}% \xB7 ${checked.toLocaleString("en-US")} / ${target.toLocaleString("en-US")} pages`;if(process.stdout.isTTY&&!persistent){process.stdout.write(`\r${message}`);if(checked>=target)process.stdout.write("\n")}else if(process.stdout.isTTY||checked>=target||checked%1e3===0)console.log(message)}function health(pages){return pages.reduce((summary,page)=>{if(page.error||page.blockedByRobots||(page.status??500)>=400)summary.unavailable+=1;if(!page.title)summary.missingTitle+=1;if(!page.description)summary.missingDescription+=1;if(!page.canonical)summary.missingCanonical+=1;if(page.h1Count===0)summary.missingH1+=1;if(/(^|[\s,])noindex($|[\s,])/i.test(page.robots??""))summary.noindex+=1;return summary},{unavailable:0,missingTitle:0,missingDescription:0,missingCanonical:0,missingH1:0,noindex:0})}function printHealth(summary){console.log(`Current health: ${summary.unavailable} unavailable, ${summary.missingTitle} missing title, ${summary.missingDescription} missing description, ${summary.missingCanonical} missing canonical, ${summary.missingH1} missing H1, ${summary.noindex} noindex.`)}var DEFAULT_BASELINE=".seo-audit.json";var DEFAULT_REPORT="seo-audit-report.html";var DEFAULT_HISTORY_DIRECTORY=".seo-audit/history";function reportEnabled(values,force=false){return force||!values["no-report"]&&(values.report!==void 0||process.stdin.isTTY&&process.stdout.isTTY&&!values.json)}async function saveReport(values,data,force=false){if(!reportEnabled(values,force))return null;const output=resolve2(values.report??DEFAULT_REPORT);await writeReport(output,data);return output}function mapUrl(url,fromStart,toStart){if(!url)return url;try{const source=new URL(fromStart);const target=new URL(toStart);const candidate=new URL(url);if(candidate.origin!==source.origin)return url;candidate.protocol=target.protocol;candidate.host=target.host;const sourceRoot=source.pathname.replace(/\/$/,"");const targetRoot=target.pathname.replace(/\/$/,"");if(sourceRoot&&candidate.pathname.startsWith(sourceRoot)){candidate.pathname=`${targetRoot}${candidate.pathname.slice(sourceRoot.length)}`||"/"}return candidate.href}catch{return url}}function mapPage(page,fromStart,toStart){const mapList=values=>values.map(value=>mapUrl(value,fromStart,toStart)??value).sort();return{...page,url:mapUrl(page.url,fromStart,toStart)??page.url,finalUrl:mapUrl(page.finalUrl,fromStart,toStart),canonical:mapUrl(page.canonical,fromStart,toStart),canonicalRaw:mapUrl(page.canonicalRaw,fromStart,toStart),links:mapList(page.links),internalLinks:mapList(page.internalLinks),externalLinks:mapList(page.externalLinks),images:page.images.map(image=>({...image,src:mapUrl(image.src,fromStart,toStart)})),hreflang:page.hreflang.map(alternate=>({...alternate,url:mapUrl(alternate.url,fromStart,toStart)})),redirectChain:page.redirectChain.map(redirect=>({...redirect,url:mapUrl(redirect.url,fromStart,toStart)??redirect.url,location:mapUrl(redirect.location,fromStart,toStart)}))}}function headersFromEnvironment(variableName){if(!variableName)return{};const encoded=process.env[variableName];if(!encoded)throw new Error(`environment variable ${variableName} is empty or missing`);let parsed;try{parsed=JSON.parse(encoded)}catch(error){throw new Error(`environment variable ${variableName} must contain a JSON object`,{cause:error})}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)){throw new Error(`environment variable ${variableName} must contain a JSON object`)}const headers={};for(const[name,value]of Object.entries(parsed)){if(typeof value!=="string")throw new Error(`header ${name} in ${variableName} must be a string`);headers[name]=value}return headers}function fetchWithHeaders(headers){if(Object.keys(headers).length===0)return globalThis.fetch;return(input,init)=>{const merged=new Headers(init?.headers);for(const[name,value]of Object.entries(headers))merged.set(name,value);return globalThis.fetch(input,{...init,headers:merged})}}function reportData(snapshot,mode,issues=audit2(snapshot),extra={}){return{mode,startUrl:snapshot.siteUrl,generatedAt:snapshot.generatedAt,pages:snapshot.pages,issues,partial:snapshot.partial,engineVersion:snapshot.engineVersion,ruleSetVersion:snapshot.ruleSetVersion,branding:snapshot.config.report,...extra}}function historyDirectory(values,referencePath){if(values["history-dir"])return resolve2(values["history-dir"]);return referencePath?join2(dirname(referencePath),DEFAULT_HISTORY_DIRECTORY):resolve2(DEFAULT_HISTORY_DIRECTORY)}async function updateHistory(values,snapshot,referencePath,save){if(values["no-history"])return void 0;const directory=historyDirectory(values,referencePath);if(save&&!snapshot.partial)await writeHistorySnapshot(directory,snapshot);const records=await readHistorySnapshots(directory,snapshot.siteUrl);return buildHistorySeries(records.map(record2=>record2.snapshot))??void 0}async function resolvePlan(url,values,baseline,signal){let config=scanConfig(url,values,baseline);let plan=await planScan(config,{signal});if(plan.mode==="links"&&config.sitemap==="auto"&&process.stdin.isTTY&&process.stdout.isTTY&&!values.json){const entered=await ask("Sitemap was not found. Enter its full URL, or press Enter to crawl internal links: ");if(entered){config={...config,sitemap:entered};plan=await planScan(config,{signal})}}return plan}function selectScan(plan,values){if(plan.candidateCount===null){if(values.all)throw new Error("--all requires a sitemap");return{mode:"fixed",target:plan.config.maxPages}}if(values.all)return{mode:"all",target:plan.candidateCount};if(values.pages!==void 0||values["max-pages"]!==void 0){return{mode:"fixed",target:Math.min(plan.config.maxPages,plan.candidateCount)}}if(process.stdin.isTTY&&process.stdout.isTTY&&!values.json)return chooseScanPlan(plan.candidateCount);return{mode:"fixed",target:Math.min(100,plan.candidateCount)}}async function scanCommand(url,values,signal){if(!url)throw new Error("scan requires a URL");const output=resolve2(values.output??DEFAULT_BASELINE);const plan=await resolvePlan(url,values,void 0,signal);const selection=await selectScan(plan,values);const checkpointPath=checkpointPathForOutput(output);const store=values["no-cache"]?void 0:createFileCheckpointStore(checkpointPath);const collected=new Map;const partialReportPath=reportEnabled(values)?resolve2(values.report??DEFAULT_REPORT):null;let lastReportAt=0;let lastReportCount=-1;const writePartial=async(force=false)=>{if(!partialReportPath||collected.size===0)return;const now=Date.now();if(!force&&collected.size-lastReportCount<100&&now-lastReportAt<5e3)return;const partialSnapshot=migrateSnapshot({schemaVersion:1,startUrl:plan.startUrl,robots:plan.robots,sitemap:plan.sitemap,options:{...plan.config,maxPages:selection.target},pages:[...collected.values()],partial:true,truncated:true});await writeReport(partialReportPath,reportData(partialSnapshot,"scan",audit2(partialSnapshot),{partial:true,targetPages:selection.target}));lastReportAt=now;lastReportCount=collected.size};let requested=selection.mode==="step"?Math.min(100,selection.target):selection.target;let result=null;let stoppedEarly=false;while(requested>0){result=await scan(plan,{signal,limit:requested,checkpointStore:store,retainCheckpoint:selection.mode==="step"&&requested<selection.target,async onBatch(pages){for(const page of pages)collected.set(page.url,page);await writePartial()},onEvent(event){if(event.type==="progress"&&!values.json)printProgress(event.completed,requested,selection.mode==="step")}});for(const page of result.pages)collected.set(page.url,page);await writePartial(true);if(result.partial||selection.mode!=="step"||requested>=selection.target)break;printHealth(health(result.pages));const nextSize=Math.min(100,selection.target-requested);const answer=await ask(`Check the next ${nextSize} page(s)? [y/N] `);if(!["y","yes"].includes(answer.toLowerCase())){stoppedEarly=true;break}requested=Math.min(selection.target,requested+100)}if(!result)throw new Error("scan did not produce a result");await writeSnapshot(output,result.snapshot);const incomplete=result.partial||stoppedEarly;const history=await updateHistory(values,result.snapshot,output,!incomplete);const finalReport=incomplete?partialReportPath:await saveReport(values,reportData(result.snapshot,"scan",audit2(result.snapshot),history?{history}:{}));const summary=health(result.snapshot.pages);if(values.json){console.log(JSON.stringify({command:"scan",pages:result.snapshot.pages.length,truncated:result.snapshot.truncated,health:summary,output,report:finalReport,checkpoint:incomplete&&store?checkpointPath:null},null,2))}else{console.log(`Crawled ${result.snapshot.pages.length} page(s)${result.snapshot.truncated?" (limit reached)":""}.`);if(result.snapshot.sitemap)console.log(`Loaded ${result.snapshot.sitemap.sitemapCount} sitemap file(s) from ${result.snapshot.sitemap.url}.`);printHealth(summary);console.log(`Baseline saved to ${output}`);if(finalReport)console.log(`HTML report saved to ${finalReport}`);if(incomplete&&store)console.log(`Resume checkpoint saved to ${checkpointPath}`)}return result.partial?130:0}async function checkCommand(url,values,signal){const baselinePath=resolve2(values.baseline??DEFAULT_BASELINE);const baseline=await readSnapshot(baselinePath);const targetStart=url??baseline.siteUrl;const basePlan=await planScan({...scanConfig(targetStart,values,baseline),sitemap:"none"},{signal});const targets=baseline.pages.map(page=>({baselineUrl:page.url,targetUrl:mapUrl(page.url,baseline.siteUrl,basePlan.startUrl)??page.url}));const targetUrls=[...new Set(targets.map(({targetUrl})=>targetUrl))];const plan={...basePlan,mode:"sitemap",candidateUrls:targetUrls,candidateCount:targetUrls.length,sitemap:{url:`${basePlan.origin}/.seo-audit-targets`,urls:targetUrls,sitemapCount:0,truncated:false,error:null}};const result=await scan(plan,{signal,limit:targetUrls.length,onEvent(event){if(event.type==="progress"&&!values.json)printProgress(event.completed,targetUrls.length)}});const checked=new Map(result.pages.map(page=>[page.url,page]));const pages=targets.flatMap(({baselineUrl,targetUrl})=>{const page=checked.get(targetUrl);return page?[{...page,url:baselineUrl,finalUrl:mapUrl(page.finalUrl,basePlan.startUrl,baseline.siteUrl)}]:[]});const current=migrateSnapshot({...result.snapshot,siteUrl:baseline.siteUrl,config:{...result.snapshot.config,url:baseline.siteUrl},sitemap:baseline.sitemap,pages});const comparison=diff2(baseline,current,{enabledRules:current.config.enabledRules,severityOverrides:current.config.severityOverrides,suppressions:current.config.suppressions});const issues=comparison.newIssues;const summary=summarizeIssues(issues);const history=await updateHistory(values,current,baselinePath,!result.partial);const report=await saveReport(values,reportData(current,"check",issues,{...comparison,...history?{history}:{}}));if(values.json)console.log(JSON.stringify({command:"check",baseline:baselinePath,pages:current.pages.length,summary,issues,lifecycle:comparison,report},null,2));else{console.log(`Checked ${current.pages.length} page(s).
|
|
93
|
+
`);printIssues(issues);if(report)console.log(`HTML report saved to ${report}`)}if(result.partial)return 130;return summary.error>0||comparison.budgetExceeded.length>0||values.strict&&summary.warning>0?1:0}async function compareCommand(values,signal){const productionUrl=values.production;const previewUrl=values.preview;if(!productionUrl||!previewUrl)throw new Error("compare requires --production and --preview URLs");const productionFetch=fetchWithHeaders(headersFromEnvironment(values["production-headers-env"]));const previewFetch=fetchWithHeaders(headersFromEnvironment(values["preview-headers-env"]));const productionPlan=await planScan(scanConfig(productionUrl,values),{signal,fetch:productionFetch});const selection=await selectScan(productionPlan,values);const production=await scan(productionPlan,{signal,fetch:productionFetch,limit:selection.target,onEvent(event){if(event.type==="progress"&&!values.json)printProgress(event.completed,selection.target)}});if(production.partial)return 130;const previewBasePlan=await planScan({...scanConfig(previewUrl,values),sitemap:"none"},{signal,fetch:previewFetch});const targetUrls=production.snapshot.pages.map(page=>mapUrl(page.url,productionUrl,previewUrl)??page.url);const previewPlan={...previewBasePlan,mode:"sitemap",candidateUrls:[...new Set(targetUrls)].sort(),candidateCount:targetUrls.length,sitemap:{url:`${previewBasePlan.origin}/.seo-audit-preview-targets`,urls:[...new Set(targetUrls)].sort(),sitemapCount:0,truncated:false,error:null}};const preview=await scan(previewPlan,{signal,fetch:previewFetch,limit:targetUrls.length,onEvent(event){if(event.type==="progress"&&!values.json)printProgress(event.completed,targetUrls.length)}});const previewPages=preview.snapshot.pages.map(page=>mapPage(page,previewUrl,productionUrl));const current=migrateSnapshot({...preview.snapshot,siteUrl:production.snapshot.siteUrl,startUrl:production.snapshot.siteUrl,config:{...preview.snapshot.config,url:production.snapshot.siteUrl},robots:{...preview.snapshot.robots,url:mapUrl(preview.snapshot.robots.url,previewUrl,productionUrl)??preview.snapshot.robots.url},sitemap:production.snapshot.sitemap,pages:previewPages,partial:preview.snapshot.partial});const comparison=diff2(production.snapshot,current,{enabledRules:current.config.enabledRules,severityOverrides:current.config.severityOverrides,suppressions:current.config.suppressions});const issues=comparison.newIssues;const summary=summarizeIssues(issues);const report=await saveReport(values,reportData(current,"check",issues,{...comparison,comparison:{kind:"preview",productionUrl,previewUrl}}),true);if(values.json){console.log(JSON.stringify({command:"compare",production:productionUrl,preview:previewUrl,pages:current.pages.length,summary,issues,lifecycle:comparison,report},null,2))}else{console.log(`Compared ${current.pages.length} production page(s) with preview.`);printIssues(issues);if(report)console.log(`HTML report saved to ${report}`)}if(preview.partial)return 130;return summary.error>0||comparison.budgetExceeded.length>0||values.strict&&summary.warning>0?1:0}async function reportCommand(inputPath,values){const baselinePath=resolve2(inputPath??values.baseline??DEFAULT_BASELINE);const baseline=await readSnapshot(baselinePath);const history=await updateHistory(values,baseline,baselinePath,false);const report=await saveReport(values,reportData(baseline,"scan",audit2(baseline),history?{history}:{}),true);if(values.json)console.log(JSON.stringify({command:"report",baseline:baselinePath,pages:baseline.pages.length,report},null,2));else console.log(`HTML report saved to ${report}`);return 0}async function historyCommand(siteUrl,values){if(Boolean(values.from)!==Boolean(values.to))throw new Error("history comparison requires both --from and --to");const directory=historyDirectory(values);if(values.from&&values.to){const previous=await readSnapshot(resolve2(values.from));const current=await readSnapshot(resolve2(values.to));if(previous.siteUrl!==current.siteUrl)throw new Error("history snapshots must belong to the same site URL");const records2=await readHistorySnapshots(directory,current.siteUrl);const history2=buildHistorySeries([...records2.map(record2=>record2.snapshot),previous,current]);const comparison=diff2(previous,current,{enabledRules:current.config.enabledRules,severityOverrides:current.config.severityOverrides,suppressions:current.config.suppressions});const report2=await saveReport(values,reportData(current,"check",comparison.newIssues,{...comparison,...history2?{history:history2}:{}}),true);const summary=summarizeIssues(comparison.newIssues);if(values.json)console.log(JSON.stringify({command:"history",from:resolve2(values.from),to:resolve2(values.to),summary,lifecycle:comparison,report:report2},null,2));else{console.log(`Compared local snapshots from ${previous.generatedAt} to ${current.generatedAt}.`);printIssues(comparison.newIssues);if(report2)console.log(`HTML report saved to ${report2}`)}return 0}let normalizedSiteUrl;if(siteUrl){try{normalizedSiteUrl=new URL(siteUrl).href}catch{throw new Error("history URL must be an HTTP(S) URL")}}let records=await readHistorySnapshots(directory,normalizedSiteUrl);if(records.length===0)throw new Error(`no local history snapshots found in ${directory}`);if(!normalizedSiteUrl){const latestSiteUrl=records.at(-1).snapshot.siteUrl;records=records.filter(record2=>record2.snapshot.siteUrl===latestSiteUrl)}const latest=records.at(-1);const history=buildHistorySeries(records.map(record2=>record2.snapshot));const report=await saveReport(values,reportData(latest.snapshot,"scan",audit2(latest.snapshot),history?{history}:{}),true);const points=history?.points??[];if(values.json)console.log(JSON.stringify({command:"history",directory,snapshots:records.map((record2,index)=>({path:record2.path,...points[index]})),report},null,2));else{console.log(`Local history for ${latest.snapshot.siteUrl}:`);for(const[index,record2]of records.entries()){const point=points[index];console.log(` ${record2.snapshot.generatedAt} ${point?.pages??record2.snapshot.pages.length} pages ${point?.errors??0} errors ${point?.warnings??0} warnings ${record2.path}`)}if(report)console.log(`HTML report saved to ${report}`)}return 0}var HELP=`seo-audit ${ENGINE_VERSION}
|
|
94
|
+
|
|
95
|
+
Local-first SEO crawler, audit, and regression checker.
|
|
96
|
+
|
|
97
|
+
Usage:
|
|
98
|
+
seo-audit <url> [options]
|
|
99
|
+
seo-audit scan <url> [options]
|
|
100
|
+
seo-audit check [url] [options]
|
|
101
|
+
seo-audit compare --production <url> --preview <url> [options]
|
|
102
|
+
seo-audit history [url] [options]
|
|
103
|
+
seo-audit report [baseline] [options]
|
|
104
|
+
|
|
105
|
+
Commands:
|
|
106
|
+
<url> Shortcut for scan.
|
|
107
|
+
scan Crawl a site and save its SEO baseline.
|
|
108
|
+
check Crawl again and compare with a saved baseline.
|
|
109
|
+
compare Compare a production site with a preview deployment.
|
|
110
|
+
history View local scan trends or compare two saved history snapshots.
|
|
111
|
+
report Generate HTML from an existing baseline without crawling.
|
|
112
|
+
|
|
113
|
+
Options:
|
|
114
|
+
--baseline <file> Baseline file for check (default: .seo-audit.json)
|
|
115
|
+
--config <file> Configuration file (default: seo-audit.config.json)
|
|
116
|
+
--output <file> Output file for scan (default: .seo-audit.json)
|
|
117
|
+
--report <file> HTML report path (default: seo-audit-report.html)
|
|
118
|
+
--no-report Do not generate the automatic HTML report
|
|
119
|
+
--no-cache Disable scan checkpoint caching and resume
|
|
120
|
+
--pages <number> Scan an exact number of pages
|
|
121
|
+
--all Scan every URL found in the sitemap
|
|
122
|
+
--max-pages <number> Deprecated alias for --pages
|
|
123
|
+
--concurrency <number> Concurrent requests (default: 5)
|
|
124
|
+
--delay <ms> Delay between request starts (default: 100)
|
|
125
|
+
--timeout <ms> Request timeout in milliseconds (default: 10000)
|
|
126
|
+
--sitemap <url> Seed the crawl from a sitemap or sitemap index
|
|
127
|
+
--no-sitemap Skip sitemap discovery and crawl internal links
|
|
128
|
+
--include-query Treat query-string URLs as separate pages
|
|
129
|
+
--ignore-robots Crawl URLs disallowed by robots.txt
|
|
130
|
+
--strict Fail check on warnings as well as errors
|
|
131
|
+
--production <url> Production URL for compare
|
|
132
|
+
--preview <url> Preview deployment URL for compare
|
|
133
|
+
--production-headers-env <name>
|
|
134
|
+
Read production request headers from a JSON environment variable
|
|
135
|
+
--preview-headers-env <name>
|
|
136
|
+
Read preview request headers from a JSON environment variable
|
|
137
|
+
--history-dir <path> Local snapshot history directory
|
|
138
|
+
--no-history Do not save this scan to local history
|
|
139
|
+
--from <snapshot> Older history snapshot for an explicit comparison
|
|
140
|
+
--to <snapshot> Newer history snapshot for an explicit comparison
|
|
141
|
+
--json Print machine-readable command output
|
|
142
|
+
--help Show this help
|
|
143
|
+
--version Show the version
|
|
144
|
+
|
|
145
|
+
Exit codes:
|
|
146
|
+
0 No blocking regressions
|
|
147
|
+
1 SEO regressions detected
|
|
148
|
+
2 Invalid input or crawler failure
|
|
149
|
+
130 Scan interrupted after saving partial results
|
|
150
|
+
`;async function main(args=process.argv.slice(2),options={}){let parsed;try{parsed=parseCliArgs(args)}catch(error){console.error(`${error instanceof Error?error.message:String(error)}
|
|
151
|
+
|
|
152
|
+
${HELP}`);return 2}let{values}=parsed;const{positionals}=parsed;try{values=withFileConfig(values,await loadConfig(values.config))}catch(error){console.error(`seo-audit: ${error instanceof Error?error.message:String(error)}`);return 2}if(values.version){console.log(ENGINE_VERSION);return 0}if(values.help||positionals.length===0){console.log(HELP);return 0}let[command,url,...extra]=positionals;if(command&&/^https?:\/\//i.test(command)){extra=positionals.slice(1);url=command;command="scan"}if((command==="scan"||command==="check")&&!url&&values.__config?.url){url=values.__config.url}if(extra.length>0){console.error(`Unexpected argument: ${extra[0]}`);return 2}try{if(command==="scan")return await scanCommand(url,values,options.signal);if(command==="check")return await checkCommand(url,values,options.signal);if(command==="compare")return await compareCommand(values,options.signal);if(command==="history")return await historyCommand(url,values);if(command==="report")return await reportCommand(url,values);console.error(`Unknown command: ${String(command)}
|
|
153
|
+
|
|
154
|
+
${HELP}`);return 2}catch(error){console.error(`seo-audit: ${error instanceof Error?error.message:String(error)}`);return options.signal?.aborted?130:2}}export{main,parseScanMenuSelection};
|