seo-crawl-audit 0.10.2 → 0.10.3
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/bundle/cli.js +1 -1
- package/bundle/mcp.js +1 -1
- package/bundle/server.js +23 -23
- package/package.json +3 -3
package/bundle/mcp.js
CHANGED
|
@@ -66,7 +66,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
66
66
|
deps: ${deps}}`};let def={keyword:"dependencies",type:"object",schemaType:"object",error:exports2.error,code(cxt){let[propDeps,schDeps]=splitDependencies(cxt);validatePropertyDeps(cxt,propDeps),validateSchemaDeps(cxt,schDeps)}};function splitDependencies({schema}){let propertyDeps={},schemaDeps={};for(let key in schema){if(key==="__proto__")continue;let deps=Array.isArray(schema[key])?propertyDeps:schemaDeps;deps[key]=schema[key]}return[propertyDeps,schemaDeps]}function validatePropertyDeps(cxt,propertyDeps=cxt.schema){let{gen,data,it}=cxt;if(Object.keys(propertyDeps).length===0)return;let missing=gen.let("missing");for(let prop in propertyDeps){let deps=propertyDeps[prop];if(deps.length===0)continue;let hasProperty=(0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties);cxt.setParams({property:prop,depsCount:deps.length,deps:deps.join(", ")}),it.allErrors?gen.if(hasProperty,()=>{for(let depProp of deps)(0,code_1.checkReportMissingProp)(cxt,depProp)}):(gen.if((0,codegen_1._)`${hasProperty} && (${(0,code_1.checkMissingProp)(cxt,deps,missing)})`),(0,code_1.reportMissingProp)(cxt,missing),gen.else())}}exports2.validatePropertyDeps=validatePropertyDeps;function validateSchemaDeps(cxt,schemaDeps=cxt.schema){let{gen,data,keyword,it}=cxt,valid=gen.name("valid");for(let prop in schemaDeps)(0,util_1.alwaysValidSchema)(it,schemaDeps[prop])||(gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties),()=>{let schCxt=cxt.subschema({keyword,schemaProp:prop},valid);cxt.mergeValidEvaluated(schCxt,valid)},()=>gen.var(valid,!0)),cxt.ok(valid))}exports2.validateSchemaDeps=validateSchemaDeps,exports2.default=def})),require_propertyNames=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params})=>(0,codegen_1._)`{propertyName: ${params.propertyName}}`},code(cxt){let{gen,schema,data,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema))return;let valid=gen.name("valid");gen.forIn("key",data,key=>{cxt.setParams({propertyName:key}),cxt.subschema({keyword:"propertyNames",data:key,dataTypes:["string"],propertyName:key,compositeRule:!0},valid),gen.if((0,codegen_1.not)(valid),()=>{cxt.error(!0),it.allErrors||gen.break()})}),cxt.ok(valid)}};exports2.default=def})),require_additionalProperties=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),names_1=require_names(),util_1=require_util(),def={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params})=>(0,codegen_1._)`{additionalProperty: ${params.additionalProperty}}`},code(cxt){let{gen,schema,parentSchema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,opts}=it;if(it.props=!0,opts.removeAdditional!=="all"&&(0,util_1.alwaysValidSchema)(it,schema))return;let props=(0,code_1.allSchemaProperties)(parentSchema.properties),patProps=(0,code_1.allSchemaProperties)(parentSchema.patternProperties);checkAdditionalProperties(),cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function checkAdditionalProperties(){gen.forIn("key",data,key=>{!props.length&&!patProps.length?additionalPropertyCode(key):gen.if(isAdditional(key),()=>additionalPropertyCode(key))})}function isAdditional(key){let definedProp;if(props.length>8){let propsSchema=(0,util_1.schemaRefOrVal)(it,parentSchema.properties,"properties");definedProp=(0,code_1.isOwnProperty)(gen,propsSchema,key)}else props.length?definedProp=(0,codegen_1.or)(...props.map(p=>(0,codegen_1._)`${key} === ${p}`)):definedProp=codegen_1.nil;return patProps.length&&(definedProp=(0,codegen_1.or)(definedProp,...patProps.map(p=>(0,codegen_1._)`${(0,code_1.usePattern)(cxt,p)}.test(${key})`))),(0,codegen_1.not)(definedProp)}function deleteAdditional(key){gen.code((0,codegen_1._)`delete ${data}[${key}]`)}function additionalPropertyCode(key){if(opts.removeAdditional==="all"||opts.removeAdditional&&schema===!1){deleteAdditional(key);return}if(schema===!1){cxt.setParams({additionalProperty:key}),cxt.error(),allErrors||gen.break();return}if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.name("valid");opts.removeAdditional==="failing"?(applyAdditionalSchema(key,valid,!1),gen.if((0,codegen_1.not)(valid),()=>{cxt.reset(),deleteAdditional(key)})):(applyAdditionalSchema(key,valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break()))}}function applyAdditionalSchema(key,valid,errors){let subschema={keyword:"additionalProperties",dataProp:key,dataPropType:util_1.Type.Str};errors===!1&&Object.assign(subschema,{compositeRule:!0,createErrors:!1,allErrors:!1}),cxt.subschema(subschema,valid)}}};exports2.default=def})),require_properties=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let validate_1=require_validate(),code_1=require_code(),util_1=require_util(),additionalProperties_1=require_additionalProperties(),def={keyword:"properties",type:"object",schemaType:"object",code(cxt){let{gen,schema,parentSchema,data,it}=cxt;it.opts.removeAdditional==="all"&&parentSchema.additionalProperties===void 0&&additionalProperties_1.default.code(new validate_1.KeywordCxt(it,additionalProperties_1.default,"additionalProperties"));let allProps=(0,code_1.allSchemaProperties)(schema);for(let prop of allProps)it.definedProperties.add(prop);it.opts.unevaluated&&allProps.length&&it.props!==!0&&(it.props=util_1.mergeEvaluated.props(gen,(0,util_1.toHash)(allProps),it.props));let properties=allProps.filter(p=>!(0,util_1.alwaysValidSchema)(it,schema[p]));if(properties.length===0)return;let valid=gen.name("valid");for(let prop of properties)hasDefault(prop)?applyPropertySchema(prop):(gen.if((0,code_1.propertyInData)(gen,data,prop,it.opts.ownProperties)),applyPropertySchema(prop),it.allErrors||gen.else().var(valid,!0),gen.endIf()),cxt.it.definedProperties.add(prop),cxt.ok(valid);function hasDefault(prop){return it.opts.useDefaults&&!it.compositeRule&&schema[prop].default!==void 0}function applyPropertySchema(prop){cxt.subschema({keyword:"properties",schemaProp:prop,dataProp:prop},valid)}}};exports2.default=def})),require_patternProperties=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let code_1=require_code(),codegen_1=require_codegen(),util_1=require_util(),util_2=require_util(),def={keyword:"patternProperties",type:"object",schemaType:"object",code(cxt){let{gen,schema,data,parentSchema,it}=cxt,{opts}=it,patterns=(0,code_1.allSchemaProperties)(schema),alwaysValidPatterns=patterns.filter(p=>(0,util_1.alwaysValidSchema)(it,schema[p]));if(patterns.length===0||alwaysValidPatterns.length===patterns.length&&(!it.opts.unevaluated||it.props===!0))return;let checkProperties=opts.strictSchema&&!opts.allowMatchingProperties&&parentSchema.properties,valid=gen.name("valid");it.props!==!0&&!(it.props instanceof codegen_1.Name)&&(it.props=(0,util_2.evaluatedPropsToName)(gen,it.props));let{props}=it;validatePatternProperties();function validatePatternProperties(){for(let pat of patterns)checkProperties&&checkMatchingProperties(pat),it.allErrors?validateProperties(pat):(gen.var(valid,!0),validateProperties(pat),gen.if(valid))}function checkMatchingProperties(pat){for(let prop in checkProperties)new RegExp(pat).test(prop)&&(0,util_1.checkStrictMode)(it,`property ${prop} matches pattern ${pat} (use allowMatchingProperties)`)}function validateProperties(pat){gen.forIn("key",data,key=>{gen.if((0,codegen_1._)`${(0,code_1.usePattern)(cxt,pat)}.test(${key})`,()=>{let alwaysValid=alwaysValidPatterns.includes(pat);alwaysValid||cxt.subschema({keyword:"patternProperties",schemaProp:pat,dataProp:key,dataPropType:util_2.Type.Str},valid),it.opts.unevaluated&&props!==!0?gen.assign((0,codegen_1._)`${props}[${key}]`,!0):!alwaysValid&&!it.allErrors&&gen.if((0,codegen_1.not)(valid),()=>gen.break())})})}}};exports2.default=def})),require_not=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let util_1=require_util(),def={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(cxt){let{gen,schema,it}=cxt;if((0,util_1.alwaysValidSchema)(it,schema)){cxt.fail();return}let valid=gen.name("valid");cxt.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},valid),cxt.failResult(valid,()=>cxt.reset(),()=>cxt.error())},error:{message:"must NOT be valid"}};exports2.default=def})),require_anyOf=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let def={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:require_code().validateUnion,error:{message:"must match a schema in anyOf"}};exports2.default=def})),require_oneOf=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params})=>(0,codegen_1._)`{passingSchemas: ${params.passing}}`},code(cxt){let{gen,schema,parentSchema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");if(it.opts.discriminator&&parentSchema.discriminator)return;let schArr=schema,valid=gen.let("valid",!1),passing=gen.let("passing",null),schValid=gen.name("_valid");cxt.setParams({passing}),gen.block(validateOneOf),cxt.result(valid,()=>cxt.reset(),()=>cxt.error(!0));function validateOneOf(){schArr.forEach((sch,i)=>{let schCxt;(0,util_1.alwaysValidSchema)(it,sch)?gen.var(schValid,!0):schCxt=cxt.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},schValid),i>0&&gen.if((0,codegen_1._)`${schValid} && ${valid}`).assign(valid,!1).assign(passing,(0,codegen_1._)`[${passing}, ${i}]`).else(),gen.if(schValid,()=>{gen.assign(valid,!0),gen.assign(passing,i),schCxt&&cxt.mergeEvaluated(schCxt,codegen_1.Name)})})}}};exports2.default=def})),require_allOf=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let util_1=require_util(),def={keyword:"allOf",schemaType:"array",code(cxt){let{gen,schema,it}=cxt;if(!Array.isArray(schema))throw new Error("ajv implementation error");let valid=gen.name("valid");schema.forEach((sch,i)=>{if((0,util_1.alwaysValidSchema)(it,sch))return;let schCxt=cxt.subschema({keyword:"allOf",schemaProp:i},valid);cxt.ok(valid),cxt.mergeEvaluated(schCxt)})}};exports2.default=def})),require_if=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params})=>(0,codegen_1.str)`must match "${params.ifClause}" schema`,params:({params})=>(0,codegen_1._)`{failingKeyword: ${params.ifClause}}`},code(cxt){let{gen,parentSchema,it}=cxt;parentSchema.then===void 0&&parentSchema.else===void 0&&(0,util_1.checkStrictMode)(it,'"if" without "then" and "else" is ignored');let hasThen=hasSchema(it,"then"),hasElse=hasSchema(it,"else");if(!hasThen&&!hasElse)return;let valid=gen.let("valid",!0),schValid=gen.name("_valid");if(validateIf(),cxt.reset(),hasThen&&hasElse){let ifClause=gen.let("ifClause");cxt.setParams({ifClause}),gen.if(schValid,validateClause("then",ifClause),validateClause("else",ifClause))}else hasThen?gen.if(schValid,validateClause("then")):gen.if((0,codegen_1.not)(schValid),validateClause("else"));cxt.pass(valid,()=>cxt.error(!0));function validateIf(){let schCxt=cxt.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},schValid);cxt.mergeEvaluated(schCxt)}function validateClause(keyword,ifClause){return()=>{let schCxt=cxt.subschema({keyword},schValid);gen.assign(valid,schValid),cxt.mergeValidEvaluated(schCxt,valid),ifClause?gen.assign(ifClause,(0,codegen_1._)`${keyword}`):cxt.setParams({ifClause:keyword})}}}};function hasSchema(it,keyword){let schema=it.schema[keyword];return schema!==void 0&&!(0,util_1.alwaysValidSchema)(it,schema)}exports2.default=def})),require_thenElse=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let util_1=require_util(),def={keyword:["then","else"],schemaType:["object","boolean"],code({keyword,parentSchema,it}){parentSchema.if===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "if" is ignored`)}};exports2.default=def})),require_applicator$2=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let additionalItems_1=require_additionalItems(),prefixItems_1=require_prefixItems(),items_1=require_items(),items2020_1=require_items2020(),contains_1=require_contains(),dependencies_1=require_dependencies(),propertyNames_1=require_propertyNames(),additionalProperties_1=require_additionalProperties(),properties_1=require_properties(),patternProperties_1=require_patternProperties(),not_1=require_not(),anyOf_1=require_anyOf(),oneOf_1=require_oneOf(),allOf_1=require_allOf(),if_1=require_if(),thenElse_1=require_thenElse();function getApplicator(draft2020=!1){let applicator=[not_1.default,anyOf_1.default,oneOf_1.default,allOf_1.default,if_1.default,thenElse_1.default,propertyNames_1.default,additionalProperties_1.default,dependencies_1.default,properties_1.default,patternProperties_1.default];return draft2020?applicator.push(prefixItems_1.default,items2020_1.default):applicator.push(additionalItems_1.default,items_1.default),applicator.push(contains_1.default),applicator}exports2.default=getApplicator})),require_format$2=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),def={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode})=>(0,codegen_1.str)`must match format "${schemaCode}"`,params:({schemaCode})=>(0,codegen_1._)`{format: ${schemaCode}}`},code(cxt,ruleType){let{gen,data,$data,schema,schemaCode,it}=cxt,{opts,errSchemaPath,schemaEnv,self}=it;if(!opts.validateFormats)return;$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fDef=gen.const("fDef",(0,codegen_1._)`${fmts}[${schemaCode}]`),fType=gen.let("fType"),format=gen.let("format");gen.if((0,codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,()=>gen.assign(fType,(0,codegen_1._)`${fDef}.type || "string"`).assign(format,(0,codegen_1._)`${fDef}.validate`),()=>gen.assign(fType,(0,codegen_1._)`"string"`).assign(format,fDef)),cxt.fail$data((0,codegen_1.or)(unknownFmt(),invalidFmt()));function unknownFmt(){return opts.strictSchema===!1?codegen_1.nil:(0,codegen_1._)`${schemaCode} && !${format}`}function invalidFmt(){let callFormat=schemaEnv.$async?(0,codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`:(0,codegen_1._)`${format}(${data})`,validData=(0,codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;return(0,codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`}}function validateFormat(){let formatDef=self.formats[schema];if(!formatDef){unknownFormat();return}if(formatDef===!0)return;let[fmtType,format,fmtRef]=getFormat(formatDef);fmtType===ruleType&&cxt.pass(validCondition());function unknownFormat(){if(opts.strictSchema===!1){self.logger.warn(unknownMsg());return}throw new Error(unknownMsg());function unknownMsg(){return`unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`}}function getFormat(fmtDef){let code=fmtDef instanceof RegExp?(0,codegen_1.regexpCode)(fmtDef):opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(schema)}`:void 0,fmt=gen.scopeValue("formats",{key:schema,ref:fmtDef,code});return typeof fmtDef=="object"&&!(fmtDef instanceof RegExp)?[fmtDef.type||"string",fmtDef.validate,(0,codegen_1._)`${fmt}.validate`]:["string",fmtDef,fmt]}function validCondition(){if(typeof formatDef=="object"&&!(formatDef instanceof RegExp)&&formatDef.async){if(!schemaEnv.$async)throw new Error("async format in sync schema");return(0,codegen_1._)`await ${fmtRef}(${data})`}return typeof format=="function"?(0,codegen_1._)`${fmtRef}(${data})`:(0,codegen_1._)`${fmtRef}.test(${data})`}}}};exports2.default=def})),require_format$1=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let format=[require_format$2().default];exports2.default=format})),require_metadata=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.contentVocabulary=exports2.metadataVocabulary=void 0,exports2.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],exports2.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),require_draft7=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let core_1=require_core$2(),validation_1=require_validation$2(),applicator_1=require_applicator$2(),format_1=require_format$1(),metadata_1=require_metadata(),draft7Vocabularies=[core_1.default,validation_1.default,(0,applicator_1.default)(),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary];exports2.default=draft7Vocabularies})),require_types=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.DiscrError=void 0;var DiscrError;(function(DiscrError2){DiscrError2.Tag="tag",DiscrError2.Mapping="mapping"})(DiscrError||(exports2.DiscrError=DiscrError={}))})),require_discriminator=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),types_1=require_types(),compile_1=require_compile(),ref_error_1=require_ref_error(),util_1=require_util(),def={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError,tagName}})=>discrError===types_1.DiscrError.Tag?`tag "${tagName}" must be string`:`value of tag "${tagName}" must be in oneOf`,params:({params:{discrError,tag,tagName}})=>(0,codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`},code(cxt){let{gen,data,schema,parentSchema,it}=cxt,{oneOf}=parentSchema;if(!it.opts.discriminator)throw new Error("discriminator: requires discriminator option");let tagName=schema.propertyName;if(typeof tagName!="string")throw new Error("discriminator: requires propertyName");if(schema.mapping)throw new Error("discriminator: mapping is not supported");if(!oneOf)throw new Error("discriminator: requires oneOf keyword");let valid=gen.let("valid",!1),tag=gen.const("tag",(0,codegen_1._)`${data}${(0,codegen_1.getProperty)(tagName)}`);gen.if((0,codegen_1._)`typeof ${tag} == "string"`,()=>validateMapping(),()=>cxt.error(!1,{discrError:types_1.DiscrError.Tag,tag,tagName})),cxt.ok(valid);function validateMapping(){let mapping=getMapping();gen.if(!1);for(let tagValue in mapping)gen.elseIf((0,codegen_1._)`${tag} === ${tagValue}`),gen.assign(valid,applyTagSchema(mapping[tagValue]));gen.else(),cxt.error(!1,{discrError:types_1.DiscrError.Mapping,tag,tagName}),gen.endIf()}function applyTagSchema(schemaProp){let _valid=gen.name("valid"),schCxt=cxt.subschema({keyword:"oneOf",schemaProp},_valid);return cxt.mergeEvaluated(schCxt,codegen_1.Name),_valid}function getMapping(){var _a3;let oneOfMapping={},topRequired=hasRequired(parentSchema),tagRequired=!0;for(let i=0;i<oneOf.length;i++){let sch=oneOf[i];if(sch?.$ref&&!(0,util_1.schemaHasRulesButRef)(sch,it.self.RULES)){let ref=sch.$ref;if(sch=compile_1.resolveRef.call(it.self,it.schemaEnv.root,it.baseId,ref),sch instanceof compile_1.SchemaEnv&&(sch=sch.schema),sch===void 0)throw new ref_error_1.default(it.opts.uriResolver,it.baseId,ref)}let propSch=(_a3=sch?.properties)===null||_a3===void 0?void 0:_a3[tagName];if(typeof propSch!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);tagRequired=tagRequired&&(topRequired||hasRequired(sch)),addMappings(propSch,i)}if(!tagRequired)throw new Error(`discriminator: "${tagName}" must be required`);return oneOfMapping;function hasRequired({required:required2}){return Array.isArray(required2)&&required2.includes(tagName)}function addMappings(sch,i){if(sch.const)addMapping(sch.const,i);else if(sch.enum)for(let tagValue of sch.enum)addMapping(tagValue,i);else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`)}function addMapping(tagValue,i){if(typeof tagValue!="string"||tagValue in oneOfMapping)throw new Error(`discriminator: "${tagName}" values must be unique strings`);oneOfMapping[tagValue]=i}}}};exports2.default=def})),require_json_schema_draft_07=__commonJSMin(((exports2,module)=>{module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}})),require_ajv=__commonJSMin(((exports2,module)=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.MissingRefError=exports2.ValidationError=exports2.CodeGen=exports2.Name=exports2.nil=exports2.stringify=exports2.str=exports2._=exports2.KeywordCxt=exports2.Ajv=void 0;let core_1=require_core$3(),draft7_1=require_draft7(),discriminator_1=require_discriminator(),draft7MetaSchema=require_json_schema_draft_07(),META_SUPPORT_DATA=["/properties"],META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var Ajv2=class extends core_1.default{_addVocabularies(){super._addVocabularies(),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let metaSchema=this.opts.$data?this.$dataMetaSchema(draft7MetaSchema,META_SUPPORT_DATA):draft7MetaSchema;this.addMetaSchema(metaSchema,META_SCHEMA_ID,!1),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports2.Ajv=Ajv2,module.exports=exports2=Ajv2,module.exports.Ajv=Ajv2,Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.default=Ajv2;var validate_1=require_validate();Object.defineProperty(exports2,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports2,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports2,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports2,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports2,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports2,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports2,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports2,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports2,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_dynamicAnchor=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.dynamicAnchor=void 0;let codegen_1=require_codegen(),names_1=require_names(),compile_1=require_compile(),ref_1=require_ref(),def={keyword:"$dynamicAnchor",schemaType:"string",code:cxt=>dynamicAnchor(cxt,cxt.schema)};function dynamicAnchor(cxt,anchor2){let{gen,it}=cxt;it.schemaEnv.root.dynamicAnchors[anchor2]=!0;let v=(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor2)}`,validate3=it.errSchemaPath==="#"?it.validateName:_getValidate(cxt);gen.if((0,codegen_1._)`!${v}`,()=>gen.assign(v,validate3))}exports2.dynamicAnchor=dynamicAnchor;function _getValidate(cxt){let{schemaEnv,schema,self}=cxt.it,{root,baseId,localRefs,meta:meta3}=schemaEnv.root,{schemaId}=self.opts,sch=new compile_1.SchemaEnv({schema,schemaId,root,baseId,localRefs,meta:meta3});return compile_1.compileSchema.call(self,sch),(0,ref_1.getValidate)(cxt,sch)}exports2.default=def})),require_dynamicRef=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.dynamicRef=void 0;let codegen_1=require_codegen(),names_1=require_names(),ref_1=require_ref(),def={keyword:"$dynamicRef",schemaType:"string",code:cxt=>dynamicRef(cxt,cxt.schema)};function dynamicRef(cxt,ref){let{gen,keyword,it}=cxt;if(ref[0]!=="#")throw new Error(`"${keyword}" only supports hash fragment reference`);let anchor2=ref.slice(1);if(it.allErrors)_dynamicRef();else{let valid=gen.let("valid",!1);_dynamicRef(valid),cxt.ok(valid)}function _dynamicRef(valid){if(it.schemaEnv.root.dynamicAnchors[anchor2]){let v=gen.let("_v",(0,codegen_1._)`${names_1.default.dynamicAnchors}${(0,codegen_1.getProperty)(anchor2)}`);gen.if(v,_callRef(v,valid),_callRef(it.validateName,valid))}else _callRef(it.validateName,valid)()}function _callRef(validate3,valid){return valid?()=>gen.block(()=>{(0,ref_1.callRef)(cxt,validate3),gen.let(valid,!0)}):()=>(0,ref_1.callRef)(cxt,validate3)}}exports2.dynamicRef=dynamicRef,exports2.default=def})),require_recursiveAnchor=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let dynamicAnchor_1=require_dynamicAnchor(),util_1=require_util(),def={keyword:"$recursiveAnchor",schemaType:"boolean",code(cxt){cxt.schema?(0,dynamicAnchor_1.dynamicAnchor)(cxt,""):(0,util_1.checkStrictMode)(cxt.it,"$recursiveAnchor: false is ignored")}};exports2.default=def})),require_recursiveRef=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let dynamicRef_1=require_dynamicRef(),def={keyword:"$recursiveRef",schemaType:"string",code:cxt=>(0,dynamicRef_1.dynamicRef)(cxt,cxt.schema)};exports2.default=def})),require_dynamic=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let dynamicAnchor_1=require_dynamicAnchor(),dynamicRef_1=require_dynamicRef(),recursiveAnchor_1=require_recursiveAnchor(),recursiveRef_1=require_recursiveRef(),dynamic=[dynamicAnchor_1.default,dynamicRef_1.default,recursiveAnchor_1.default,recursiveRef_1.default];exports2.default=dynamic})),require_dependentRequired=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let dependencies_1=require_dependencies(),def={keyword:"dependentRequired",type:"object",schemaType:"object",error:dependencies_1.error,code:cxt=>(0,dependencies_1.validatePropertyDeps)(cxt)};exports2.default=def})),require_dependentSchemas=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let dependencies_1=require_dependencies(),def={keyword:"dependentSchemas",type:"object",schemaType:"object",code:cxt=>(0,dependencies_1.validateSchemaDeps)(cxt)};exports2.default=def})),require_limitContains=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let util_1=require_util(),def={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword,parentSchema,it}){parentSchema.contains===void 0&&(0,util_1.checkStrictMode)(it,`"${keyword}" without "contains" is ignored`)}};exports2.default=def})),require_next=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let dependentRequired_1=require_dependentRequired(),dependentSchemas_1=require_dependentSchemas(),limitContains_1=require_limitContains(),next=[dependentRequired_1.default,dependentSchemas_1.default,limitContains_1.default];exports2.default=next})),require_unevaluatedProperties=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),names_1=require_names(),def={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params})=>(0,codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}`},code(cxt){let{gen,schema,data,errsCount,it}=cxt;if(!errsCount)throw new Error("ajv implementation error");let{allErrors,props}=it;props instanceof codegen_1.Name?gen.if((0,codegen_1._)`${props} !== true`,()=>gen.forIn("key",data,key=>gen.if(unevaluatedDynamic(props,key),()=>unevaluatedPropCode(key)))):props!==!0&&gen.forIn("key",data,key=>props===void 0?unevaluatedPropCode(key):gen.if(unevaluatedStatic(props,key),()=>unevaluatedPropCode(key))),it.props=!0,cxt.ok((0,codegen_1._)`${errsCount} === ${names_1.default.errors}`);function unevaluatedPropCode(key){if(schema===!1){cxt.setParams({unevaluatedProperty:key}),cxt.error(),allErrors||gen.break();return}if(!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.name("valid");cxt.subschema({keyword:"unevaluatedProperties",dataProp:key,dataPropType:util_1.Type.Str},valid),allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())}}function unevaluatedDynamic(evaluatedProps,key){return(0,codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`}function unevaluatedStatic(evaluatedProps,key){let ps=[];for(let p in evaluatedProps)evaluatedProps[p]===!0&&ps.push((0,codegen_1._)`${key} !== ${p}`);return(0,codegen_1.and)(...ps)}}};exports2.default=def})),require_unevaluatedItems=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let codegen_1=require_codegen(),util_1=require_util(),def={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len}})=>(0,codegen_1.str)`must NOT have more than ${len} items`,params:({params:{len}})=>(0,codegen_1._)`{limit: ${len}}`},code(cxt){let{gen,schema,data,it}=cxt,items=it.items||0;if(items===!0)return;let len=gen.const("len",(0,codegen_1._)`${data}.length`);if(schema===!1)cxt.setParams({len:items}),cxt.fail((0,codegen_1._)`${len} > ${items}`);else if(typeof schema=="object"&&!(0,util_1.alwaysValidSchema)(it,schema)){let valid=gen.var("valid",(0,codegen_1._)`${len} <= ${items}`);gen.if((0,codegen_1.not)(valid),()=>validateItems(valid,items)),cxt.ok(valid)}it.items=!0;function validateItems(valid,from){gen.forRange("i",from,len,i=>{cxt.subschema({keyword:"unevaluatedItems",dataProp:i,dataPropType:util_1.Type.Num},valid),it.allErrors||gen.if((0,codegen_1.not)(valid),()=>gen.break())})}}};exports2.default=def})),require_unevaluated$1=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let unevaluatedProperties_1=require_unevaluatedProperties(),unevaluatedItems_1=require_unevaluatedItems(),unevaluated=[unevaluatedProperties_1.default,unevaluatedItems_1.default];exports2.default=unevaluated})),require_schema$1=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}})),require_applicator$1=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}})),require_content$1=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}})),require_core$1=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}})),require_format=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}})),require_meta_data$1=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),require_validation$1=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),require_json_schema_2019_09=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let metaSchema=require_schema$1(),applicator=require_applicator$1(),content=require_content$1(),core=require_core$1(),format=require_format(),metadata=require_meta_data$1(),validation=require_validation$1(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2019($data){return[metaSchema,applicator,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports2.default=addMetaSchema2019})),require__2019=__commonJSMin(((exports2,module)=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.MissingRefError=exports2.ValidationError=exports2.CodeGen=exports2.Name=exports2.nil=exports2.stringify=exports2.str=exports2._=exports2.KeywordCxt=exports2.Ajv2019=void 0;let core_1=require_core$3(),draft7_1=require_draft7(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated$1(),discriminator_1=require_discriminator(),json_schema_2019_09_1=require_json_schema_2019_09(),META_SCHEMA_ID="https://json-schema.org/draft/2019-09/schema";var Ajv2019=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(dynamic_1.default),draft7_1.default.forEach(v=>this.addVocabulary(v)),this.addVocabulary(next_1.default),this.addVocabulary(unevaluated_1.default),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta:meta3}=this.opts;meta3&&(json_schema_2019_09_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports2.Ajv2019=Ajv2019,module.exports=exports2=Ajv2019,module.exports.Ajv2019=Ajv2019,Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.default=Ajv2019;var validate_1=require_validate();Object.defineProperty(exports2,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports2,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports2,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports2,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports2,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports2,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports2,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports2,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports2,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_draft2020=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let core_1=require_core$2(),validation_1=require_validation$2(),applicator_1=require_applicator$2(),dynamic_1=require_dynamic(),next_1=require_next(),unevaluated_1=require_unevaluated$1(),format_1=require_format$1(),metadata_1=require_metadata(),draft2020Vocabularies=[dynamic_1.default,core_1.default,validation_1.default,(0,applicator_1.default)(!0),format_1.default,metadata_1.metadataVocabulary,metadata_1.contentVocabulary,next_1.default,unevaluated_1.default];exports2.default=draft2020Vocabularies})),require_schema=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),require_applicator=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),require_unevaluated=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),require_content=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),require_core=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),require_format_annotation=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),require_meta_data=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),require_validation=__commonJSMin(((exports2,module)=>{module.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),require_json_schema_2020_12=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0});let metaSchema=require_schema(),applicator=require_applicator(),unevaluated=require_unevaluated(),content=require_content(),core=require_core(),format=require_format_annotation(),metadata=require_meta_data(),validation=require_validation(),META_SUPPORT_DATA=["/properties"];function addMetaSchema2020($data){return[metaSchema,applicator,unevaluated,content,core,with$data(this,format),metadata,with$data(this,validation)].forEach(sch=>this.addMetaSchema(sch,void 0,!1)),this;function with$data(ajv,sch){return $data?ajv.$dataMetaSchema(sch,META_SUPPORT_DATA):sch}}exports2.default=addMetaSchema2020})),require__2020=__commonJSMin(((exports2,module)=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.MissingRefError=exports2.ValidationError=exports2.CodeGen=exports2.Name=exports2.nil=exports2.stringify=exports2.str=exports2._=exports2.KeywordCxt=exports2.Ajv2020=void 0;let core_1=require_core$3(),draft2020_1=require_draft2020(),discriminator_1=require_discriminator(),json_schema_2020_12_1=require_json_schema_2020_12(),META_SCHEMA_ID="https://json-schema.org/draft/2020-12/schema";var Ajv2020=class extends core_1.default{constructor(opts={}){super({...opts,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),draft2020_1.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(discriminator_1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data,meta:meta3}=this.opts;meta3&&(json_schema_2020_12_1.default.call(this,$data),this.refs["http://json-schema.org/schema"]=META_SCHEMA_ID)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:void 0)}};exports2.Ajv2020=Ajv2020,module.exports=exports2=Ajv2020,module.exports.Ajv2020=Ajv2020,Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.default=Ajv2020;var validate_1=require_validate();Object.defineProperty(exports2,"KeywordCxt",{enumerable:!0,get:function(){return validate_1.KeywordCxt}});var codegen_1=require_codegen();Object.defineProperty(exports2,"_",{enumerable:!0,get:function(){return codegen_1._}}),Object.defineProperty(exports2,"str",{enumerable:!0,get:function(){return codegen_1.str}}),Object.defineProperty(exports2,"stringify",{enumerable:!0,get:function(){return codegen_1.stringify}}),Object.defineProperty(exports2,"nil",{enumerable:!0,get:function(){return codegen_1.nil}}),Object.defineProperty(exports2,"Name",{enumerable:!0,get:function(){return codegen_1.Name}}),Object.defineProperty(exports2,"CodeGen",{enumerable:!0,get:function(){return codegen_1.CodeGen}});var validation_error_1=require_validation_error();Object.defineProperty(exports2,"ValidationError",{enumerable:!0,get:function(){return validation_error_1.default}});var ref_error_1=require_ref_error();Object.defineProperty(exports2,"MissingRefError",{enumerable:!0,get:function(){return ref_error_1.default}})})),require_formats=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.formatNames=exports2.fastFormats=exports2.fullFormats=void 0;function fmtDef(validate3,compare){return{validate:validate3,compare}}exports2.fullFormats={date:fmtDef(date5,compareDate),time:fmtDef(getTime(!0),compareTime),"date-time":fmtDef(getDateTime(!0),compareDateTime),"iso-time":fmtDef(getTime(),compareIsoTime),"iso-date-time":fmtDef(getDateTime(),compareIsoDateTime),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z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=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte,int32:{type:"number",validate:validateInt32},int64:{type:"number",validate:validateInt64},float:{type:"number",validate:validateNumber},double:{type:"number",validate:validateNumber},password:!0,binary:!0},exports2.fastFormats={...exports2.fullFormats,date:fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,compareDate),time:fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareTime),"date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,compareDateTime),"iso-time":fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoTime),"iso-date-time":fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,compareIsoDateTime),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},exports2.formatNames=Object.keys(exports2.fullFormats);function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}let DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function date5(str){let matches=DATE.exec(str);if(!matches)return!1;let year=+matches[1],month=+matches[2],day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month===2&&isLeapYear(year)?29:DAYS[month])}function compareDate(d1,d2){if(d1&&d2)return d1>d2?1:d1<d2?-1:0}let TIME=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function getTime(strictTimeZone){return function(str){let matches=TIME.exec(str);if(!matches)return!1;let hr=+matches[1],min=+matches[2],sec=+matches[3],tz=matches[4],tzSign=matches[5]==="-"?-1:1,tzH=+(matches[6]||0),tzM=+(matches[7]||0);if(tzH>23||tzM>59||strictTimeZone&&!tz)return!1;if(hr<=23&&min<=59&&sec<60)return!0;let utcMin=min-tzM*tzSign,utcHr=hr-tzH*tzSign-(utcMin<0?1:0);return(utcHr===23||utcHr===-1)&&(utcMin===59||utcMin===-1)&&sec<61}}function compareTime(s1,s2){if(!(s1&&s2))return;let t1=new Date("2020-01-01T"+s1).valueOf(),t2=new Date("2020-01-01T"+s2).valueOf();if(t1&&t2)return t1-t2}function compareIsoTime(t1,t2){if(!(t1&&t2))return;let a1=TIME.exec(t1),a2=TIME.exec(t2);if(a1&&a2)return t1=a1[1]+a1[2]+a1[3],t2=a2[1]+a2[2]+a2[3],t1>t2?1:t1<t2?-1:0}let DATE_TIME_SEPARATOR=/t|\s/i;function getDateTime(strictTimeZone){let time3=getTime(strictTimeZone);return function(str){let dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length===2&&date5(dateTime[0])&&time3(dateTime[1])}}function compareDateTime(dt1,dt2){if(!(dt1&&dt2))return;let d1=new Date(dt1).valueOf(),d2=new Date(dt2).valueOf();if(d1&&d2)return d1-d2}function compareIsoDateTime(dt1,dt2){if(!(dt1&&dt2))return;let[d1,t1]=dt1.split(DATE_TIME_SEPARATOR),[d2,t2]=dt2.split(DATE_TIME_SEPARATOR),res=compareDate(d1,d2);if(res!==void 0)return res||compareTime(t1,t2)}let NOT_URI_FRAGMENT=/\/|:/,URI=/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2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}let BYTE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function byte(str){return BYTE.lastIndex=0,BYTE.test(str)}let MIN_INT32=-(2**31),MAX_INT32=2**31-1;function validateInt32(value){return Number.isInteger(value)&&value<=MAX_INT32&&value>=MIN_INT32}function validateInt64(value){return Number.isInteger(value)}function validateNumber(){return!0}let Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return!1;try{return new RegExp(str),!0}catch{return!1}}})),require_limit=__commonJSMin((exports2=>{Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.formatLimitDefinition=void 0;let ajv_1=require_ajv(),codegen_1=require_codegen(),ops=codegen_1.operators,KWDs={formatMaximum:{okStr:"<=",ok:ops.LTE,fail:ops.GT},formatMinimum:{okStr:">=",ok:ops.GTE,fail:ops.LT},formatExclusiveMaximum:{okStr:"<",ok:ops.LT,fail:ops.GTE},formatExclusiveMinimum:{okStr:">",ok:ops.GT,fail:ops.LTE}},error61={message:({keyword,schemaCode})=>(0,codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,params:({keyword,schemaCode})=>(0,codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`};exports2.formatLimitDefinition={keyword:Object.keys(KWDs),type:"string",schemaType:"string",$data:!0,error:error61,code(cxt){let{gen,data,schemaCode,keyword,it}=cxt,{opts,self}=it;if(!opts.validateFormats)return;let fCxt=new ajv_1.KeywordCxt(it,self.RULES.all.format.definition,"format");fCxt.$data?validate$DataFormat():validateFormat();function validate$DataFormat(){let fmts=gen.scopeValue("formats",{ref:self.formats,code:opts.code.formats}),fmt=gen.const("fmt",(0,codegen_1._)`${fmts}[${fCxt.schemaCode}]`);cxt.fail$data((0,codegen_1.or)((0,codegen_1._)`typeof ${fmt} != "object"`,(0,codegen_1._)`${fmt} instanceof RegExp`,(0,codegen_1._)`typeof ${fmt}.compare != "function"`,compareCode(fmt)))}function validateFormat(){let format=fCxt.schema,fmtDef=self.formats[format];if(!fmtDef||fmtDef===!0)return;if(typeof fmtDef!="object"||fmtDef instanceof RegExp||typeof fmtDef.compare!="function")throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);let fmt=gen.scopeValue("formats",{key:format,ref:fmtDef,code:opts.code.formats?(0,codegen_1._)`${opts.code.formats}${(0,codegen_1.getProperty)(format)}`:void 0});cxt.fail$data(compareCode(fmt))}function compareCode(fmt){return(0,codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`}},dependencies:["format"]};let formatLimitPlugin=ajv=>(ajv.addKeyword(exports2.formatLimitDefinition),ajv);exports2.default=formatLimitPlugin})),require_dist=__commonJSMin(((exports2,module)=>{Object.defineProperty(exports2,"__esModule",{value:!0});let formats_1=require_formats(),limit_1=require_limit(),codegen_1=require_codegen(),fullName=new codegen_1.Name("fullFormats"),fastName=new codegen_1.Name("fastFormats"),formatsPlugin=(ajv,opts={keywords:!0})=>{if(Array.isArray(opts))return addFormats2(ajv,opts,formats_1.fullFormats,fullName),ajv;let[formats,exportName]=opts.mode==="fast"?[formats_1.fastFormats,fastName]:[formats_1.fullFormats,fullName];return addFormats2(ajv,opts.formats||formats_1.formatNames,formats,exportName),opts.keywords&&(0,limit_1.default)(ajv),ajv};formatsPlugin.get=(name,mode="full")=>{let f=(mode==="fast"?formats_1.fastFormats:formats_1.fullFormats)[name];if(!f)throw new Error(`Unknown format "${name}"`);return f};function addFormats2(ajv,list,fs,exportName){var _a3,_b;(_a3=(_b=ajv.opts.code).formats)!==null&&_a3!==void 0||(_b.formats=(0,codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);for(let f of list)ajv.addFormat(f,fs[f])}module.exports=exports2=formatsPlugin,Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.default=formatsPlugin})),import_ajv=require_ajv(),import__2019=require__2019(),import__2020=require__2020(),import_dist=__toESM(require_dist(),1),addFormats=import_dist.default;function createDefaultAjvInstance(engineClass){let ajv=new engineClass({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return addFormats(ajv),ajv}var AjvJsonSchemaValidator=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(ajv){this._userAjv=ajv!==void 0,this._ajv=ajv}get ajv(){return this._ajv??=createDefaultAjvInstance(import__2020.Ajv2020)}_engineFor(schema){if(this._userAjv)return this.ajv;let dialect=declaredDialect(schema,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return dialect==="2020-12"?this.ajv:dialect==="2019-09"?this._ajv2019??=createDefaultAjvInstance(import__2019.Ajv2019):this._ajvDraft7??=createDefaultAjvInstance(import_ajv.Ajv)}getValidator(schema){let engine=this._engineFor(schema),ajvValidator="$id"in schema&&typeof schema.$id=="string"?engine.getSchema(schema.$id)??engine.compile(schema):engine.compile(schema);return input2=>ajvValidator(input2)?{valid:!0,data:input2,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:engine.errorsText(ajvValidator.errors)}}},Ajv=import_ajv.Ajv;import process3 from"node:process";var COMPLETABLE_SYMBOL=Symbol.for("mcp.completable");function isCompletable(schema){return!!schema&&typeof schema=="object"&&COMPLETABLE_SYMBOL in schema}function getCompleter(schema){return schema[COMPLETABLE_SYMBOL]?.complete}var MAX_TIMER_DELAY_MS=2**31-1;function listenFilterAccepts(filter,event){switch(event.kind){case"tools_list_changed":return filter.toolsListChanged===!0;case"prompts_list_changed":return filter.promptsListChanged===!0;case"resources_list_changed":return filter.resourcesListChanged===!0;case"resource_updated":return filter.resourceSubscriptions!==void 0&&filter.resourceSubscriptions.includes(event.uri)}}function honoredSubset(requested,capabilities){let honored={},allow=bit=>capabilities===void 0||bit===!0;return requested.toolsListChanged===!0&&allow(capabilities?.tools?.listChanged)&&(honored.toolsListChanged=!0),requested.promptsListChanged===!0&&allow(capabilities?.prompts?.listChanged)&&(honored.promptsListChanged=!0),requested.resourcesListChanged===!0&&allow(capabilities?.resources?.listChanged)&&(honored.resourcesListChanged=!0),requested.resourceSubscriptions!==void 0&&requested.resourceSubscriptions.length>0&&allow(capabilities?.resources?.subscribe)&&(honored.resourceSubscriptions=[...requested.resourceSubscriptions]),honored}var DEFAULT_MAX_SUBSCRIPTIONS=1024;function stampSubscriptionId(notification,subscriptionId){return{method:notification.method,params:{...notification.params,_meta:{...notification.params?._meta,[SUBSCRIPTION_ID_META_KEY]:subscriptionId}}}}function parseListenFilter(message){let outcome=codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen",message);return outcome.ok?outcome.value.params?.notifications:void 0}var CHANGE_NOTIFICATION_METHODS=new Set(["notifications/tools/list_changed","notifications/prompts/list_changed","notifications/resources/list_changed","notifications/resources/updated"]),StdioListenRouter=class{_subs=new Map;_serverCapabilities;_serverInfo;constructor(_maxSubscriptions=DEFAULT_MAX_SUBSCRIPTIONS,serverCapabilities,serverInfo){this._maxSubscriptions=_maxSubscriptions,this._serverCapabilities=serverCapabilities,this._serverInfo=serverInfo}setServerCapabilities(capabilities,serverInfo){this._serverCapabilities=capabilities,serverInfo!==void 0&&(this._serverInfo=serverInfo)}has(id){return this._subs.has(id)}serve(message){if(this._serverCapabilities===void 0)throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities");if(this._subs.size>=this._maxSubscriptions)return{jsonrpc:"2.0",id:message.id,error:{code:-32603,message:"Subscription limit reached"}};let filter=parseListenFilter(message);if(filter===void 0)return{jsonrpc:"2.0",id:message.id,error:{code:-32602,message:"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"}};let honored=honoredSubset(filter,this._serverCapabilities);return this._subs.set(message.id,honored),stampSubscriptionId({method:"notifications/subscriptions/acknowledged",params:{notifications:honored}},message.id)}cancel(id){return this._subs.delete(id)}routeOutbound(message){if(!CHANGE_NOTIFICATION_METHODS.has(message.method))return"passthrough";let uriParam=message.params?.uri,uri=typeof uriParam=="string"?uriParam:void 0,event=notificationToServerEvent(message.method,uri),out=[];for(let[subscriptionId,filter]of this._subs)listenFilterAccepts(filter,event)&&out.push(stampSubscriptionId({method:message.method,params:message.params??{}},subscriptionId));return out}teardownAll(){let out=[];for(let id of this._subs.keys())out.push({jsonrpc:"2.0",id,result:{resultType:"complete",_meta:{[SUBSCRIPTION_ID_META_KEY]:id,...this._serverInfo!==void 0&&{[SERVER_INFO_META_KEY]:this._serverInfo}}}});return this._subs.clear(),out}};function notificationToServerEvent(method,uri){switch(method){case"notifications/tools/list_changed":return{kind:"tools_list_changed"};case"notifications/prompts/list_changed":return{kind:"prompts_list_changed"};case"notifications/resources/list_changed":return{kind:"resources_list_changed"};default:return{kind:"resource_updated",uri:uri??""}}}var DEFAULT_LEGACY_SHIM_MAX_ROUNDS=8,DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS=6e5;function resolveLegacyShimOptions(options){if(options?.maxRounds!==void 0&&(!Number.isInteger(options.maxRounds)||options.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`);if(options?.roundTimeoutMs!==void 0&&(!Number.isFinite(options.roundTimeoutMs)||options.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`);return{maxRounds:options?.maxRounds??DEFAULT_LEGACY_SHIM_MAX_ROUNDS,roundTimeoutMs:options?.roundTimeoutMs??DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,legacyShim:options?.legacyShim??!0}}function coerceEmbeddedInputRequest(method,key,entry){if(entry===null||typeof entry!="object"||typeof entry.method!="string")throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let embedded=entry,required2=requiredClientCapabilitiesForInputRequest(embedded);if(required2===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded,required:required2}}function syntheticElicitationId(){let webCrypto=globalThis.crypto;if(webCrypto?.randomUUID!==void 0)return webCrypto.randomUUID();let bytes=new Uint8Array(16);webCrypto.getRandomValues(bytes),bytes[6]=bytes[6]&15|64,bytes[8]=bytes[8]&63|128;let hex3=[...bytes].map(byte=>byte.toString(16).padStart(2,"0")).join("");return`${hex3.slice(0,8)}-${hex3.slice(8,12)}-${hex3.slice(12,16)}-${hex3.slice(16,20)}-${hex3.slice(20)}`}function legacyShimFailure(method,message){if(method==="tools/call")return{content:[{type:"text",text:message}],isError:!0};throw new ProtocolError(ProtocolErrorCode.InternalError,message)}var LegacyInputRequiredShim=class{constructor(_host){this._host=_host}async fulfill(method,handler,request,ctx,firstResult){let{maxRounds,roundTimeoutMs}=this._host,outerSignal=ctx.mcpReq.signal,current=firstResult,round=0;for(;;){if(round+=1,round>maxRounds)return legacyShimFailure(method,inputRequiredRoundsExceededMessage(method,maxRounds));let inputRequests=current.inputRequests,hasInputRequests=inputRequests!=null&&Object.keys(inputRequests).length>0,requestState=typeof current.requestState=="string"?current.requestState:void 0;if(!hasInputRequests&&requestState===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let responses;if(hasInputRequests){let declared=this._host.resolvedClientCapabilities(ctx),coerced=[];for(let[key,entry]of Object.entries(inputRequests)){let{embedded,required:required2}=coerceEmbeddedInputRequest(method,key,entry);if(embedded.method!=="roots/list"&&embedded.params===void 0)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`);if(missingClientCapabilities(required2,declared)!==void 0)return legacyShimFailure(method,`Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared===void 0?" (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)":""}`);coerced.push([key,embedded])}let roundAbort=linkedRoundAbort(outerSignal);try{let legOptions={relatedRequestId:ctx.mcpReq.id,timeout:roundTimeoutMs,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:roundAbort.signal},fulfilled=await Promise.all(coerced.map(async([key,embedded])=>{try{return[key,await this._dispatchLeg(embedded,legOptions)]}catch(error61){throw roundAbort.abort(error61),error61}}));responses=Object.fromEntries(fulfilled)}catch(error61){if(outerSignal.aborted)throw error61;return legacyShimFailure(method,`Fulfilling input required by '${method}' failed: ${error61 instanceof Error?error61.message:String(error61)}`)}finally{roundAbort.dispose()}}else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS,outerSignal);let ctxNext={...ctx,mcpReq:{...ctx.mcpReq,inputResponses:responses,droppedInputResponseKeys:void 0,requestState:requestStateAccessor(requestState)}};if(requestState!==void 0){let decoded=await this._host.verifyRequestState(requestState,ctxNext,method);decoded!==void 0&&(ctxNext=withRequestStateValue(ctxNext,decoded))}let next=await handler(request,ctxNext);if(!isInputRequiredResult(next))return next;current=next}}async _dispatchLeg(embedded,options){switch(embedded.method){case"elicitation/create":{let params=embedded.params;return params.mode==="url"&¶ms.elicitationId===void 0&&(params={...params,elicitationId:syntheticElicitationId()}),await this._host.sendElicitation(params,options)}case"sampling/createMessage":return await this._host.sendSampling(embedded.params,options);case"roots/list":return await this._host.listRoots(embedded.params,options)}}},INPUT_REQUIRED_CAPABLE_METHODS=new Set(["tools/call","prompts/get","resources/read"]),writeClientIdentity,installDiscoverHandler,readServerIdentity;function installModernOnlyHandlers(server,servedModernVersions){installDiscoverHandler(server,servedModernVersions)}function serverIdentityOf(server){return readServerIdentity(server)}var Server=class extends Protocol{_clientCapabilities;_clientVersion;static{writeClientIdentity=(server,identity)=>{identity.clientCapabilities!==void 0&&(server._clientCapabilities=identity.clientCapabilities),identity.clientInfo!==void 0&&(server._clientVersion=identity.clientInfo)},installDiscoverHandler=(server,servedModernVersions)=>{let missing=servedModernVersions.filter(version2=>!server._supportedProtocolVersions.includes(version2));missing.length>0&&(server._supportedProtocolVersions=[...server._supportedProtocolVersions,...missing]),server.setRequestHandler("server/discover",()=>server._ondiscover())},readServerIdentity=server=>server._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new LegacyInputRequiredShim({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:ctx=>this._inputRequestCapabilityView(ctx),verifyRequestState:(state,ctx,method)=>this._verifyRequestState(state,ctx,method),sendElicitation:(params,options)=>this._sendElicitationLeg(params,options,{validateAcceptedContent:!1}),sendSampling:(params,options)=>this.createMessage(params,options),listRoots:(params,options)=>this.listRoots(params,options)})}oninitialized;constructor(_serverInfo,options){if(super(options),this._serverInfo=_serverInfo,this._capabilities=options?.capabilities?{...options.capabilities}:{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this._requestStateVerify=options?.requestState?.verify,this._inputRequiredServing=resolveLegacyShimOptions(options?.inputRequired),options?.cacheHints!==void 0){for(let[operation,hint]of Object.entries(options.cacheHints))hint!==void 0&&assertValidCacheHint(hint,`cacheHints['${operation}']`);this._cacheHints=options.cacheHints}this.setRequestHandler("initialize",request=>this._oninitialize(request)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),modernProtocolVersions(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(request,ctx)=>{let transportSessionId=ctx.sessionId||ctx.http?.req?.headers.get("mcp-session-id")||void 0,{level}=request.params,parseResult=parseSchema(LoggingLevelSchema,level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}buildContext(ctx,transportInfo){let hasHttpInfo=ctx.http||transportInfo?.request||transportInfo?.closeSSEStream||transportInfo?.closeStandaloneSSEStream;return{...ctx,mcpReq:{...ctx.mcpReq,log:(level,data,logger)=>{if(!this._capabilities.logging)return Promise.resolve();let threshold;if(this._servedModernEra()){if(threshold=ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY],threshold===void 0)return Promise.resolve()}else threshold=this._loggingLevels.get(ctx.sessionId)??this._loggingLevels.get(void 0);return threshold!==void 0&&this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(threshold)?Promise.resolve():ctx.mcpReq.notify({method:"notifications/message",params:{level,data,logger}})},elicitInput:(params,options)=>this.elicitInput(params,options),requestSampling:(params,options)=>this.createMessage(params,options)},http:hasHttpInfo?{...ctx.http,req:transportInfo?.request,closeSSE:transportInfo?.closeSSEStream,closeStandaloneSSE:transportInfo?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index)=>[level,index]));isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1};registerCapabilities(capabilities){if(this.transport)throw new SdkError(SdkErrorCode.AlreadyConnected,"Cannot register capabilities after connecting to transport");let hadLogging=!!this._capabilities.logging;this._capabilities=mergeCapabilities(this._capabilities,capabilities),!hadLogging&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(method,handler){if(method!=="tools/call"){let cacheHint=this._cacheHints?.[method],isInputRequiredCapable=INPUT_REQUIRED_CAPABLE_METHODS.has(method);return cacheHint===void 0&&!isInputRequiredCapable?async(request,ctx)=>{let result=await handler(request,ctx);if(isInputRequiredResult(result))throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return result}:async(request,ctx)=>{let result=isInputRequiredCapable?await this._invokeInputRequiredCapableHandler(method,handler,request,ctx):await handler(request,ctx);if(isInputRequiredResult(result)){if(!isInputRequiredCapable)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return result}return cacheHint===void 0?result:attachCacheHintFallback(result,cacheHint)}}return async(request,ctx)=>{let codec2=codecForVersion(this._negotiatedProtocolVersion),validatedRequest=codec2.validateRequest("tools/call",request);if(!validatedRequest.ok)throw new ProtocolError(validatedRequest.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validatedRequest.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${validatedRequest.message}`);let result=await this._invokeInputRequiredCapableHandler("tools/call",handler,request,ctx);if(isInputRequiredResult(result))return result;let normalizedResult=normalizeContentlessToolResult(result),validationResult=codec2.validateResult("tools/call",normalizedResult);if(!validationResult.ok)throw new ProtocolError(validationResult.reason==="not-in-era"?ProtocolErrorCode.InternalError:ProtocolErrorCode.InvalidParams,validationResult.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${validationResult.message}`);return validationResult.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&isModernProtocolVersion(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(method,handler,request,ctx){let servedModern=this._servedModernEra(),rawRequestState=ctx.mcpReq.requestState();if(rawRequestState!==void 0&&typeof rawRequestState!="string")throw new ProtocolError(ProtocolErrorCode.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let ctxForHandler=ctx;if(typeof rawRequestState=="string"){let decoded=await this._verifyRequestState(rawRequestState,ctx,method);decoded!==void 0&&(ctxForHandler=withRequestStateValue(ctx,decoded))}let result;try{result=await handler(request,ctxForHandler)}catch(error61){throw error61 instanceof ProtocolError&&error61.code===ProtocolErrorCode.UrlElicitationRequired&&servedModern?new ProtocolError(ProtocolErrorCode.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):error61}if(!isInputRequiredResult(result))return result;if(!servedModern){if(!this._inputRequiredServing.legacyShim)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(method,handler,request,ctxForHandler,result)}let inputRequests=result.inputRequests,hasInputRequests=inputRequests!=null&&Object.keys(inputRequests).length>0,hasRequestState=typeof result.requestState=="string";if(!hasInputRequests&&!hasRequestState)throw new ProtocolError(ProtocolErrorCode.InternalError,`Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(hasInputRequests){let declared=this._inputRequestCapabilityView(ctx);for(let[key,entry]of Object.entries(inputRequests)){let{embedded,required:required2}=coerceEmbeddedInputRequest(method,key,entry),missing=missingClientCapabilities(required2,declared);if(missing!==void 0)throw new MissingRequiredClientCapabilityError({requiredCapabilities:missing},`Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`)}}return result}async _verifyRequestState(state,ctx,method){if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(state,ctx)}catch(error61){throw this.onerror?.(new Error(`requestState verification rejected ${method}: ${error61 instanceof Error?error61.message:String(error61)}`)),new ProtocolError(ProtocolErrorCode.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(ctx){return this._servedModernEra()?ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY]:this._clientCapabilities}_assertPushApiInServedEra(method){if(this._servedModernEra())throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method,era:"2026-07-28"})}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){switch(method){case"completion/complete":if(!this._capabilities.completions)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,`Server does not support tools (required for ${method})`);break;case"ping":case"initialize":break}}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo;let legacyVersions=legacyProtocolVersions(this._supportedProtocolVersions),protocolVersion=legacyVersions.includes(requestedVersion)?requestedVersion:legacyVersions[0]??LATEST_PROTOCOL_VERSION;return this._negotiatedProtocolVersion=protocolVersion,this.transport?.setProtocolVersion?.(protocolVersion),{protocolVersion,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:modernProtocolVersions(this._supportedProtocolVersions),capabilities:discoverAdvertisedCapabilities(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(result,advertisedOutputSchema){return this._wireCodec().projectCallToolResult(result,advertisedOutputSchema)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(params,options){if(this._assertPushApiInServedEra("sampling/createMessage"),(params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages.at(-1),lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages.at(-2):void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new ProtocolError(ProtocolErrorCode.InvalidParams,"The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new ProtocolError(ProtocolErrorCode.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new ProtocolError(ProtocolErrorCode.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let hasTools=!!(params.tools||params.toolChoice),wide=await this.request({method:"sampling/createMessage",params},options),outcome=this._wireCodec().samplingResultVariant(hasTools,wide);if(!outcome.ok)throw new SdkError(SdkErrorCode.InvalidResult,`Invalid sampling/createMessage result: ${outcome.reason==="invalid"?outcome.message:outcome.reason}`);return outcome.value}async elicitInput(params,options){switch(this._assertPushApiInServedEra("elicitation/create"),params.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(params,options)}async _sendElicitationLeg(params,options,behavior){let mode=params.mode??"form",validateAcceptedContent=behavior?.validateAcceptedContent??!0;switch(mode){case"url":{let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},options)}case"form":{let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},options);if(validateAcceptedContent&&result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error61){throw error61 instanceof ProtocolError?error61:new ProtocolError(ProtocolErrorCode.InternalError,`Error validating elicitation response: ${error61 instanceof Error?error61.message:String(error61)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new SdkError(SdkErrorCode.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params},options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};function discoverAdvertisedCapabilities(capabilities){return{...capabilities}}var McpServer=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(name){let tool=this._registeredTools[name];if(!(tool===void 0||!tool.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,name))return this._toolInputSchemaJson[name];if(tool.inputSchema===void 0)return EMPTY_OBJECT_JSON_SCHEMA;try{let json2=standardSchemaToJsonSchema(tool.inputSchema,"input");return this._toolInputSchemaJson[name]=json2,json2}catch{return}}}constructor(serverInfo,options){this.server=new Server(serverInfo,options),options?.capabilities?.tools&&this.setToolRequestHandlers(),options?.capabilities?.resources&&this.setResourceRequestHandlers(),options?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(transport){return await this.server.connect(transport)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,tool])=>tool.enabled).map(([name,tool])=>{let toolDefinition={name,title:tool.title,description:tool.description,inputSchema:tool.inputSchema?standardSchemaToJsonSchema(tool.inputSchema,"input"):EMPTY_OBJECT_JSON_SCHEMA,annotations:tool.annotations,icons:tool.icons,execution:tool.execution,_meta:tool._meta};return tool.outputSchema&&(toolDefinition.outputSchema=standardSchemaToJsonSchema(tool.outputSchema,"output")),toolDefinition})})),this.server.setRequestHandler("tools/call",async(request,ctx)=>{let tool=this._registeredTools[request.params.name];if(!tool)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool ${request.params.name} not found`);if(!tool.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Tool ${request.params.name} disabled`);try{let args=await this.validateToolInput(tool,request.params.arguments,request.params.name),result=await this.executeToolHandler(tool,args,ctx);return await this.validateToolOutput(tool,result,request.params.name),isInputRequiredResult(result)?result:this.server.projectCallToolResult(result,tool.outputSchemaJson)}catch(error61){if(error61 instanceof ProtocolError&&error61.code===ProtocolErrorCode.UrlElicitationRequired)throw error61;return this.createToolError(error61 instanceof Error?error61.message:String(error61))}}),this._toolHandlersInitialized=!0)}createToolError(errorMessage){return{content:[{type:"text",text:errorMessage}],isError:!0}}async validateToolInput(tool,args,toolName){if(!tool.inputSchema)return;let parseResult=await validateStandardSchema(tool.inputSchema,args??{});if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);return parseResult.data}async validateToolOutput(tool,result,toolName){if(!tool.outputSchema||isInputRequiredResult(result)||result.isError)return;if(result.structuredContent===void 0)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);let parseResult=await validateStandardSchema(tool.outputSchema,result.structuredContent);if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`)}async executeToolHandler(tool,args,ctx){return tool.executor(args,ctx)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async request=>{switch(request.params.ref.type){case"ref/prompt":return assertCompleteRequestPrompt(request),this.handlePromptCompletion(request,request.params.ref);case"ref/resource":return assertCompleteRequestResourceTemplate(request),this.handleResourceCompletion(request,request.params.ref);default:throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid completion reference: ${request.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(request,ref){let prompt=this._registeredPrompts[ref.name];if(!prompt)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${ref.name} not found`);if(!prompt.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${ref.name} disabled`);if(!prompt.argsSchema)return EMPTY_COMPLETION_RESULT;let field=unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]);if(!isCompletable(field))return EMPTY_COMPLETION_RESULT;let completer=getCompleter(field);return completer?createCompletionResult(await completer(request.params.argument.value,request.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(request,ref){let template=Object.values(this._registeredResourceTemplates).find(t=>t.resourceTemplate.uriTemplate.toString()===ref.uri);if(!template){if(this._registeredResources[ref.uri])return EMPTY_COMPLETION_RESULT;throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource template ${request.params.ref.uri} not found`)}let completer=template.resourceTemplate.completeCallback(request.params.argument.name);return completer?createCompletionResult(await completer(request.params.argument.value,request.params.context)):EMPTY_COMPLETION_RESULT}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(_request,ctx)=>{let resources=Object.entries(this._registeredResources).filter(([_,resource])=>resource.enabled).map(([uri,resource])=>({uri,name:resource.name,...resource.metadata})),templateResources=[];for(let template of Object.values(this._registeredResourceTemplates)){if(!template.resourceTemplate.listCallback)continue;let result=await template.resourceTemplate.listCallback(ctx);for(let resource of result.resources)templateResources.push({...template.metadata,...resource})}return{resources:[...resources,...templateResources]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([name,template])=>({name,uriTemplate:template.resourceTemplate.uriTemplate.toString(),...template.metadata}))})),this.server.setRequestHandler("resources/read",async(request,ctx)=>{let uri;try{uri=new URL(request.params.uri)}catch{throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource URI ${request.params.uri} is invalid`,{uri:request.params.uri,reason:"invalid_uri"})}let resource=this._registeredResources[uri.toString()];if(resource){if(!resource.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Resource ${uri} disabled`);return attachCacheHintFallback(await resource.readCallback(uri,ctx),resource.cacheHint)}for(let template of Object.values(this._registeredResourceTemplates)){let variables=template.resourceTemplate.uriTemplate.match(uri.toString());if(variables)return attachCacheHintFallback(await template.readCallback(uri,variables,ctx),template.cacheHint)}throw new ResourceNotFoundError(request.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,prompt])=>prompt.enabled).map(([name,prompt])=>({name,title:prompt.title,description:prompt.description,arguments:prompt.argsSchema?promptArgumentsFromStandardSchema(prompt.argsSchema):void 0,icons:prompt.icons,_meta:prompt._meta}))})),this.server.setRequestHandler("prompts/get",async(request,ctx)=>{let prompt=this._registeredPrompts[request.params.name];if(!prompt)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${request.params.name} not found`);if(!prompt.enabled)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Prompt ${request.params.name} disabled`);return prompt.handler(request.params.arguments,ctx)}),this._promptHandlersInitialized=!0)}registerResource(name,uriOrTemplate,config2,readCallback){let cacheHint=config2.cacheHint,metadata=config2;if(cacheHint!==void 0){assertValidCacheHint(cacheHint,`resource ${name}`);let rest={...config2};delete rest.cacheHint,metadata=rest}if(typeof uriOrTemplate=="string"){if(this._registeredResources[uriOrTemplate])throw new Error(`Resource ${uriOrTemplate} is already registered`);let registeredResource=this._createRegisteredResource(name,config2.title,uriOrTemplate,metadata,readCallback);return cacheHint!==void 0&&(registeredResource.cacheHint=cacheHint),this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResource}else{if(this._registeredResourceTemplates[name])throw new Error(`Resource template ${name} is already registered`);let registeredResourceTemplate=this._createRegisteredResourceTemplate(name,config2.title,uriOrTemplate,metadata,readCallback);return cacheHint!==void 0&&(registeredResourceTemplate.cacheHint=cacheHint),this.setResourceRequestHandlers(),this.sendResourceListChanged(),registeredResourceTemplate}}_createRegisteredResource(name,title,uri,metadata,readCallback){let registeredResource={name,title,metadata,readCallback,enabled:!0,disable:()=>registeredResource.update({enabled:!1}),enable:()=>registeredResource.update({enabled:!0}),remove:()=>registeredResource.update({uri:null}),update:updates=>{updates.uri!==void 0&&updates.uri!==uri&&(delete this._registeredResources[uri],updates.uri&&(this._registeredResources[updates.uri]=registeredResource)),updates.name!==void 0&&(registeredResource.name=updates.name),updates.title!==void 0&&(registeredResource.title=updates.title),updates.metadata!==void 0&&(registeredResource.metadata=updates.metadata),updates.callback!==void 0&&(registeredResource.readCallback=updates.callback),updates.enabled!==void 0&&(registeredResource.enabled=updates.enabled),this.sendResourceListChanged()}};return this._registeredResources[uri]=registeredResource,registeredResource}_createRegisteredResourceTemplate(name,title,template,metadata,readCallback){let registeredResourceTemplate={resourceTemplate:template,title,metadata,readCallback,enabled:!0,disable:()=>registeredResourceTemplate.update({enabled:!1}),enable:()=>registeredResourceTemplate.update({enabled:!0}),remove:()=>registeredResourceTemplate.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(delete this._registeredResourceTemplates[name],updates.name&&(this._registeredResourceTemplates[updates.name]=registeredResourceTemplate)),updates.title!==void 0&&(registeredResourceTemplate.title=updates.title),updates.template!==void 0&&(registeredResourceTemplate.resourceTemplate=updates.template),updates.metadata!==void 0&&(registeredResourceTemplate.metadata=updates.metadata),updates.callback!==void 0&&(registeredResourceTemplate.readCallback=updates.callback),updates.enabled!==void 0&&(registeredResourceTemplate.enabled=updates.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[name]=registeredResourceTemplate;let variableNames=template.uriTemplate.variableNames;return Array.isArray(variableNames)&&variableNames.some(v=>!!template.completeCallback(v))&&this.setCompletionRequestHandler(),registeredResourceTemplate}_createRegisteredPrompt(name,title,description,argsSchema,callback,icons,_meta){let currentArgsSchema=argsSchema,currentCallback=callback,registeredPrompt={title,description,argsSchema,icons,_meta,handler:createPromptHandler(name,argsSchema,callback),enabled:!0,disable:()=>registeredPrompt.update({enabled:!1}),enable:()=>registeredPrompt.update({enabled:!0}),remove:()=>registeredPrompt.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(delete this._registeredPrompts[name],updates.name&&(this._registeredPrompts[updates.name]=registeredPrompt)),updates.title!==void 0&&(registeredPrompt.title=updates.title),updates.description!==void 0&&(registeredPrompt.description=updates.description),updates.icons!==void 0&&(registeredPrompt.icons=updates.icons),updates._meta!==void 0&&(registeredPrompt._meta=updates._meta);let needsHandlerRegen=!1;updates.argsSchema!==void 0&&(registeredPrompt.argsSchema=updates.argsSchema,currentArgsSchema=updates.argsSchema,needsHandlerRegen=!0),updates.callback!==void 0&&(currentCallback=updates.callback,needsHandlerRegen=!0),needsHandlerRegen&&(registeredPrompt.handler=createPromptHandler(name,currentArgsSchema,currentCallback)),updates.enabled!==void 0&&(registeredPrompt.enabled=updates.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[name]=registeredPrompt,argsSchema){let shape=getSchemaShape(argsSchema);shape&&Object.values(shape).some(field=>isCompletable(unwrapOptionalSchema(field)))&&this.setCompletionRequestHandler()}return registeredPrompt}_createRegisteredTool(name,title,description,inputSchema,outputSchema,annotations,icons,execution,_meta,handler){if(validateAndWarnToolName(name),inputSchema!==void 0)try{let json2=standardSchemaToJsonSchema(inputSchema,"input");this._toolInputSchemaJson[name]=json2;let scan2=scanXMcpHeaderDeclarations(json2);scan2.valid||console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan2.reason}`)}catch{}let currentHandler=handler,registeredTool={title,description,inputSchema,outputSchema,outputSchemaJson:convertOutputSchemaJson(outputSchema),annotations,icons,execution,_meta,handler,executor:createToolExecutor(inputSchema,handler),enabled:!0,disable:()=>registeredTool.update({enabled:!1}),enable:()=>registeredTool.update({enabled:!0}),remove:()=>registeredTool.update({name:null}),update:updates=>{updates.name!==void 0&&updates.name!==name&&(typeof updates.name=="string"&&validateAndWarnToolName(updates.name),delete this._registeredTools[name],delete this._toolInputSchemaJson[name],updates.name&&(delete this._toolInputSchemaJson[updates.name],this._registeredTools[updates.name]=registeredTool,name=updates.name)),updates.title!==void 0&&(registeredTool.title=updates.title),updates.description!==void 0&&(registeredTool.description=updates.description);let needsExecutorRegen=!1;updates.paramsSchema!==void 0&&(registeredTool.inputSchema=updates.paramsSchema,delete this._toolInputSchemaJson[name],needsExecutorRegen=!0),updates.callback!==void 0&&(registeredTool.handler=updates.callback,currentHandler=updates.callback,needsExecutorRegen=!0),needsExecutorRegen&&(registeredTool.executor=createToolExecutor(registeredTool.inputSchema,currentHandler)),updates.outputSchema!==void 0&&(registeredTool.outputSchema=updates.outputSchema,registeredTool.outputSchemaJson=convertOutputSchemaJson(updates.outputSchema)),updates.annotations!==void 0&&(registeredTool.annotations=updates.annotations),updates.icons!==void 0&&(registeredTool.icons=updates.icons),updates._meta!==void 0&&(registeredTool._meta=updates._meta),updates.enabled!==void 0&&(registeredTool.enabled=updates.enabled),this.sendToolListChanged()}};return this._registeredTools[name]=registeredTool,this.setToolRequestHandlers(),this.sendToolListChanged(),registeredTool}registerTool(name,config2,cb){if(this._registeredTools[name])throw new Error(`Tool ${name} is already registered`);let{title,description,inputSchema,outputSchema,annotations,icons,_meta}=config2;return this._createRegisteredTool(name,title,description,normalizeRawShapeSchema(inputSchema),normalizeRawShapeSchema(outputSchema),annotations,icons,void 0,_meta,cb)}registerPrompt(name,config2,cb){if(this._registeredPrompts[name])throw new Error(`Prompt ${name} is already registered`);let{title,description,argsSchema,icons,_meta}=config2,registeredPrompt=this._createRegisteredPrompt(name,title,description,normalizeRawShapeSchema(argsSchema),cb,icons,_meta);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),registeredPrompt}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(params,sessionId){return this.server.sendLoggingMessage(params,sessionId)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function createToolExecutor(inputSchema,handler){if(inputSchema){let callback$1=handler;return async(args,ctx)=>callback$1(args,ctx)}let callback=handler;return async(_args,ctx)=>callback(ctx)}var EMPTY_OBJECT_JSON_SCHEMA={type:"object",properties:{}};function convertOutputSchemaJson(outputSchema){if(outputSchema!==void 0)try{return standardSchemaToJsonSchema(outputSchema,"output")}catch{return}}function createPromptHandler(name,argsSchema,callback){if(argsSchema){let typedCallback=callback;return async(args,ctx)=>{let parseResult=await validateStandardSchema(argsSchema,args);if(!parseResult.success)throw new ProtocolError(ProtocolErrorCode.InvalidParams,`Invalid arguments for prompt ${name}: ${parseResult.error}`);return typedCallback(parseResult.data,ctx)}}else{let typedCallback=callback;return async(_args,ctx)=>typedCallback(ctx)}}function createCompletionResult(suggestions){return{completion:{values:suggestions.map(String).slice(0,100),total:suggestions.length,hasMore:suggestions.length>100}}}var EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};function getSchemaShape(schema){let candidate=schema;if(candidate.shape&&typeof candidate.shape=="object")return candidate.shape}function isOptionalSchema(schema){return schema?.type==="optional"}function unwrapOptionalSchema(schema){return isOptionalSchema(schema)?schema.def?.innerType??schema:schema}var StdioServerTransport=class{_readBuffer;_started=!1;_closed=!1;constructor(_stdin=process3.stdin,_stdout=process3.stdout,options){this._stdin=_stdin,this._stdout=_stdout,this._readBuffer=new ReadBuffer({maxBufferSize:options?.maxBufferSize})}onclose;onerror;onmessage;_ondata=chunk=>{try{this._readBuffer.append(chunk),this.processReadBuffer()}catch(error61){this.onerror?.(error61),this.close().catch(()=>{})}};_onerror=error61=>{this.onerror?.(error61)};_onstdouterror=error61=>{this.onerror?.(error61),this.close().catch(()=>{})};async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){for(;;)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error61){this.onerror?.(error61)}}async close(){this._closed||(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdout.off("error",this._onstdouterror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(message){return this._closed?Promise.reject(new Error("StdioServerTransport is closed")):new Promise((resolve3,reject)=>{let json2=serializeMessage(message),settled=!1,onError=error61=>{settled||(settled=!0,this._stdout.off("error",onError),this._stdout.off("drain",onDrain),reject(error61))},onDrain=()=>{settled||(settled=!0,this._stdout.off("error",onError),this._stdout.off("drain",onDrain),resolve3())};if(this._stdout.once("error",onError),this._stdout.write(json2)){if(settled)return;settled=!0,this._stdout.off("error",onError),resolve3()}else settled||this._stdout.once("drain",onDrain)})}},DISCARD_ANSWER_TIMEOUT_MS=3e3,StdioConnectionChannel=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(_wire,_onInstanceClose,_outboundIntercept){this._wire=_wire,this._onInstanceClose=_onInstanceClose,this._outboundIntercept=_outboundIntercept}async start(){}async send(message,options){if(isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)){let{id}=message;id!==void 0&&this._settle(id)}if(!this._closed&&this._outboundIntercept?.(message)!=="handled")return this._wire.send(message,options)}setProtocolVersion=version2=>{this._wire.setProtocolVersion?.(version2)};deliver(message,extra){if(!this._closed){if(isJSONRPCRequest(message))this._pendingRequests.add(message.id);else if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){let cancelledId=message.params?.requestId;cancelledId!==void 0&&this._settle(cancelledId)}this.onmessage?.(message,extra)}}async whenRequestsAnswered(timeoutMs){return this._closed||this._pendingRequests.size===0?!0:await new Promise(resolve3=>{let waiter=()=>{clearTimeout(timer),resolve3(!0)},timer=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter(pending=>pending!==waiter),resolve3(!1)},timeoutMs);this._drainWaiters.push(waiter)})}async close(){if(!this._closed){this._closed=!0,this._pendingRequests.clear(),this._releaseDrainWaiters();try{this._onInstanceClose()}finally{this.onclose?.()}}}_settle(id){this._pendingRequests.delete(id),this._pendingRequests.size===0&&this._releaseDrainWaiters()}_releaseDrainWaiters(){let waiters=this._drainWaiters;this._drainWaiters=[];for(let waiter of waiters)waiter()}};function classifyOpeningMessage(message){let params=message.params;if(message.method==="initialize"&&!carriesValidModernEnvelopeClaim(params)){let requestedVersion=params!==null&&typeof params=="object"&&typeof params.protocolVersion=="string"?params.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...requestedVersion!==void 0&&{requestedVersion}}}if(!hasEnvelopeClaim(params))return{kind:"legacy",reason:"no-claim"};let meta3=requestMetaOf(params),firstIssue=(meta3===void 0?[]:validateEnvelopeMeta(meta3))[0];if(firstIssue!==void 0)return{kind:"invalid-envelope",issue:firstIssue};let claimedVersion=envelopeClaimVersion(params);return claimedVersion===void 0||!SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)?{kind:"unsupported-revision",requested:claimedVersion??"unknown"}:{kind:"modern",revision:claimedVersion,classification:{era:"modern",revision:claimedVersion}}}function serveStdio(factory,options={}){let legacyMode=options.legacy??"serve",wire=options.transport??new StdioServerTransport,state={phase:"opening"},discarding,closing=!1,isTornDown=()=>closing||state.phase==="closed",reportError=error61=>{try{options.onerror?.(error61)}catch{}},writeErrorResponse=(id,code,message,data)=>wire.send({jsonrpc:"2.0",id,error:{code,message,...data!==void 0&&{data}}}).catch(error61=>reportError(toError(error61))),listenRouter=new StdioListenRouter(options.maxSubscriptions??DEFAULT_MAX_SUBSCRIPTIONS),modernOutboundIntercept=message=>{if(!isJSONRPCNotification(message))return;let routed=listenRouter.routeOutbound(message);if(routed!=="passthrough"){for(let stamped of routed)wire.send({jsonrpc:"2.0",...stamped}).catch(error61=>reportError(toError(error61)));return"handled"}},tryServeListen=async message=>{if(isJSONRPCRequest(message)&&message.method==="subscriptions/listen"){let meta3=requestMetaOf(message.params),issue2=hasEnvelopeClaim(message.params)?(meta3===void 0?[]:validateEnvelopeMeta(meta3))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},claimedVersion=envelopeClaimVersion(message.params),reply;if(issue2!==void 0)reply={jsonrpc:"2.0",id:message.id,error:{code:-32602,message:`Invalid _meta envelope: ${issue2.key}: ${issue2.problem}`}};else if(claimedVersion===void 0||!SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)){let error61=new UnsupportedProtocolVersionError({supported:[...SUPPORTED_MODERN_PROTOCOL_VERSIONS],requested:claimedVersion??"unknown"});reply={jsonrpc:"2.0",id:message.id,error:{code:error61.code,message:error61.message,data:error61.data}}}else reply=listenRouter.serve(message);return await wire.send("error"in reply?reply:{jsonrpc:"2.0",method:reply.method,params:reply.params}).catch(error61=>reportError(toError(error61))),!0}if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){let cancelledId=message.params?.requestId;if(cancelledId!==void 0&&listenRouter.cancel(cancelledId))return!0}return!1},answerLegacyRejection=(request,reason,requestedVersion)=>{let rejection2=modernOnlyStrictRejection({kind:"legacy",reason,...requestedVersion!==void 0&&{requestedVersion}},SUPPORTED_MODERN_PROTOCOL_VERSIONS);return rejection2===void 0?Promise.resolve():(reportError(new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection2.cell}): ${rejection2.message}`)),writeErrorResponse(request.id,rejection2.code,rejection2.message,rejection2.data))},onInstanceClosed=channel=>{closing||channel===discarding||closeAll()},connectInstance=async(era,revision)=>{let product=await factory({era}),server=product instanceof McpServer?product.server:product;era==="modern"&&(setNegotiatedProtocolVersion(server,revision),installModernOnlyHandlers(server,SUPPORTED_MODERN_PROTOCOL_VERSIONS),listenRouter.setServerCapabilities(server.getCapabilities(),serverIdentityOf(server)));let channel=new StdioConnectionChannel(wire,()=>onInstanceClosed(channel),era==="modern"?modernOutboundIntercept:void 0);return await product.connect(channel),{product,channel}},disposeLateInstance=instance=>instance.product.close().catch(error61=>reportError(toError(error61))),discardProbeInstance=async instance=>{discarding=instance.channel;try{await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)||reportError(new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)),await instance.product.close()}catch(error61){reportError(toError(error61))}finally{discarding=void 0}},processMessage=async message=>{if(state.phase==="closed")return;if(state.phase==="pinned"){if(state.era==="modern"&&isJSONRPCRequest(message)&&message.method==="initialize"&&!carriesValidModernEnvelopeClaim(message.params)){await answerLegacyRejection(message,"initialize",message.params!==null&&typeof message.params=="object"&&typeof message.params.protocolVersion=="string"?message.params.protocolVersion:void 0);return}if(state.era==="modern"&&await tryServeListen(message))return;state.instance.channel.deliver(message);return}if(!isJSONRPCRequest(message)&&!isJSONRPCNotification(message)){reportError(new Error("Discarded a JSON-RPC response received before the connection negotiated an era"));return}let opening=classifyOpeningMessage(message);switch(opening.kind){case"invalid-envelope":{let detail=`Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`;isJSONRPCRequest(message)?await writeErrorResponse(message.id,ProtocolErrorCode.InvalidParams,detail,{envelope:opening.issue}):reportError(new Error(`Discarded a notification with a malformed envelope: ${detail}`));return}case"unsupported-revision":if(isJSONRPCRequest(message)){let error61=new UnsupportedProtocolVersionError({supported:[...SUPPORTED_MODERN_PROTOCOL_VERSIONS],requested:opening.requested});reportError(error61),await writeErrorResponse(message.id,error61.code,error61.message,error61.data)}else reportError(new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`));return;case"modern":if(isJSONRPCRequest(message)&&message.method==="server/discover"){if(state.phase==="probe"){state.instance.channel.deliver(message,{classification:opening.classification});return}let instance=await connectInstance("modern",opening.revision);if(isTornDown()){await disposeLateInstance(instance);return}state={phase:"probe",instance},instance.channel.deliver(message,{classification:opening.classification});return}if(state.phase==="probe"){if(isJSONRPCNotification(message)){state.instance.channel.deliver(message,{classification:opening.classification});return}state={phase:"pinned",era:"modern",instance:state.instance}}else{let instance=await connectInstance("modern",opening.revision);if(isTornDown()){await disposeLateInstance(instance);return}state={phase:"pinned",era:"modern",instance}}if(await tryServeListen(message))return;state.instance.channel.deliver(message,{classification:opening.classification});return;case"legacy":{if(legacyMode==="reject"){isJSONRPCRequest(message)&&await answerLegacyRejection(message,opening.reason,opening.requestedVersion);return}if(state.phase==="probe"){if(await discardProbeInstance(state.instance),isTornDown())return;state={phase:"opening"}}let instance=await connectInstance("legacy");if(isTornDown()){await disposeLateInstance(instance);return}state={phase:"pinned",era:"legacy",instance},state.instance.channel.deliver(message);return}}},queue=[],pumping=!1,pump=async()=>{if(!pumping){pumping=!0;try{for(;queue.length>0;){let message=queue.shift();try{await processMessage(message)}catch(error61){isJSONRPCRequest(message)&&await writeErrorResponse(message.id,ProtocolErrorCode.InternalError,"Internal server error"),reportError(toError(error61))}}}finally{pumping=!1}}},closeAll=async()=>{if(closing||state.phase==="closed")return;closing=!0;let current=state;state={phase:"closed"};for(let result of listenRouter.teardownAll())await wire.send(result).catch(error61=>reportError(toError(error61)));(current.phase==="probe"||current.phase==="pinned")&&await current.instance.product.close().catch(error61=>reportError(toError(error61))),await wire.close().catch(error61=>reportError(toError(error61)))};wire.onmessage=message=>{queue.push(message),pump()},wire.onerror=error61=>{reportError(error61),(state.phase==="probe"||state.phase==="pinned")&&state.instance.channel.onerror?.(error61)},wire.onclose=()=>{if(closing||state.phase==="closed")return;closing=!0;let current=state;state={phase:"closed"},(current.phase==="probe"||current.phase==="pinned")&¤t.instance.product.close().catch(error61=>reportError(toError(error61)))};let started=wire.start().catch(error61=>{throw reportError(toError(error61)),error61});return started.catch(()=>{}),{close:async()=>{await started.catch(()=>{}),await closeAll()}}}function toError(value){return value instanceof Error?value:new Error(String(value))}import{createHash}from"node:crypto";var DOCS_BASE="https://github.com/MelnixDev/seo-crawl-audit/blob/main/docs/rules.md",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."}],RULE_REGISTRY=Object.freeze(definitions.map(definition=>Object.freeze({...definition}))),RULES=new Map(RULE_REGISTRY.map(rule=>[rule.id,rule]));function stableStringify(value){return Array.isArray(value)?`[${value.map(stableStringify).join(",")}]`:value&&typeof value=="object"?`{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,child])=>`${key}:${stableStringify(child)}`).join(",")}}`:JSON.stringify(value)}function getRuleDefinitions(){return RULE_REGISTRY}function issueFingerprint(ruleId,scope,url2,identity){return createHash("sha256").update(`${ruleId}
|
|
67
67
|
${scope}
|
|
68
68
|
${url2}
|
|
69
|
-
${stableStringify(identity??null)}`).digest("hex").slice(0,24)}function createIssue(ruleId,url2,message,evidence={},identity){let definition=RULES.get(ruleId);if(!definition)throw new Error(`unknown rule: ${ruleId}`);return{fingerprint:issueFingerprint(ruleId,definition.scope,url2,identity),ruleId,rule:ruleId,severity:definition.severity,scope:definition.scope,url:url2,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!0;try{return new Intl.Locale(language),!0}catch{return!1}}function duplicateMap(pages,select){let groups=new Map;for(let page of pages){let value=select(page)?.trim().toLowerCase();if(!value)continue;let urls=groups.get(value)??[];urls.push(page.url),groups.set(value,urls)}return new Map([...groups].filter(([,urls])=>urls.length>1))}function evaluateCurrentRules(snapshot){let issues=[],add=candidate=>{issues.push(candidate)},pageByUrl=new Map(snapshot.pages.map(page=>[page.url,page])),sitemapUrls=new Set(snapshot.sitemap?.urls??[]),titles=duplicateMap(snapshot.pages,page=>page.title),descriptions=duplicateMap(snapshot.pages,page=>page.description),content=duplicateMap(snapshot.pages,page=>page.contentHash);snapshot.sitemap?.error&&add(createIssue("sitemap-unavailable",snapshot.sitemap.url,"The configured sitemap could not be loaded",{actual:snapshot.sitemap.error}));for(let page of snapshot.pages){if(page.blockedByRobots){add(createIssue("robots-blocked",page.url,"Page is blocked by robots.txt",{actual:!0}));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})),hasDirective(page.robots,"noindex")&&add(createIssue("noindex",page.url,"Page contains a noindex meta directive",{actual:page.robots})),hasDirective(page.xRobotsTag,"noindex")&&add(createIssue("x-robots-noindex",page.url,"Page contains a noindex X-Robots-Tag",{actual:page.xRobotsTag})),!page.canonicalRaw&&!page.canonical&&add(createIssue("missing-canonical",page.url,"Page does not declare a canonical URL",{actual:null})),page.canonicalRaw&&!page.canonical&&add(createIssue("invalid-canonical",page.url,"Canonical URL is invalid",{actual:page.canonicalRaw})),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})),page.canonical){let target=pageByUrl.get(page.canonical);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))}page.redirectChain.length>3&&add(createIssue("long-redirect-chain",page.url,`Page uses ${page.redirectChain.length} redirects`,{actual:page.redirectChain.length,redirectChain:page.redirectChain})),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})),sitemapUrls.has(page.url)&&page.redirectChain.length>0&&add(createIssue("redirect-in-sitemap",page.url,"Sitemap URL redirects",{actual:page.finalUrl,redirectChain:page.redirectChain})),page.title?(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())),(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}))):add(createIssue("missing-title",page.url,"Page does not have a title",{actual:null})),page.description?(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())),(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}))):add(createIssue("missing-description",page.url,"Page does not have a meta description",{actual:null})),page.h1Count===0?add(createIssue("missing-h1",page.url,"Page does not contain an H1 heading",{actual:0})):page.h1Count>1&&add(createIssue("multiple-h1",page.url,`Page contains ${page.h1Count} H1 headings`,{actual:page.h1Count}));for(let targetUrl of page.internalLinks){let target=pageByUrl.get(targetUrl);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))}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:!0})),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:!1}));for(let alternate of page.hreflang)(!validLanguage(alternate.lang)||!alternate.url)&&add(createIssue("invalid-hreflang",page.url,"Hreflang declaration is invalid",{actual:alternate},alternate));for(let[index,block]of page.jsonLd.entries())block.valid||add(createIssue("malformed-json-ld",page.url,"JSON-LD block contains invalid JSON",{actual:block.error,index},index));snapshot.siteUrl.startsWith("https:")&&[page.url,page.canonical,...page.internalLinks].some(url2=>url2?.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(url2=>url2?.startsWith("http:"))})),page.lang&&!validLanguage(page.lang)&&add(createIssue("invalid-language",page.url,"HTML language declaration is invalid",{actual:page.lang})),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)),(!page.openGraph.title||!page.openGraph.description||!page.openGraph.image)&&add(createIssue("missing-open-graph",page.url,"Open Graph metadata is incomplete",{actual:page.openGraph})),(!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}));let missingAlt=page.images.filter(image=>image.alt===null).map(image=>image.src);missingAlt.length>0&&add(createIssue("image-missing-alt",page.url,`${missingAlt.length} image(s) do not have an alt attribute`,{actual:missingAlt})),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(url2,pattern){let pathname=(()=>{try{return new URL(url2).pathname}catch{return url2}})(),expression=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replaceAll("**","\0").replaceAll("*","[^/]*").replaceAll("\0",".*"),regex=new RegExp(`^${expression}$`);return regex.test(pathname)||regex.test(url2)}function activeSuppression(issue2,suppressions,now){return suppressions.find(suppression=>suppression.rule!==issue2.ruleId||!globMatches(issue2.url,suppression.urlPattern)?!1:suppression.expiresAt?new Date(`${suppression.expiresAt}T23:59:59.999Z`).getTime()>=now.getTime():!0)??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={}){let enabled=ruleSet.enabledRules??snapshot.config.enabledRules,enabledSet=enabled?new Set(enabled):null,overrides={...snapshot.config.severityOverrides,...ruleSet.severityOverrides??{}},suppressions=ruleSet.suppressions??snapshot.config.suppressions,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.10.2",RULE_SET_VERSION="1.1.0",PRODUCT_NAME="seo-crawl-audit",DEFAULT_USER_AGENT=`${PRODUCT_NAME}/${ENGINE_VERSION}`;var DEFAULT_OPEN_GRAPH={title:null,description:null,image:null},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){return Array.isArray(value)?`[${value.map(stableJson).join(",")}]`:value&&typeof value=="object"?`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,child])=>`${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`:JSON.stringify(value)}function hashConfiguration(config2){return createHash2("sha256").update(stableJson(config2)).digest("hex")}function normalizePage(page){return{url:page.url,finalUrl:page.finalUrl??null,status:page.status??null,contentType:page.contentType??null,blockedByRobots:page.blockedByRobots??!1,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(input2){let source=input2.source??{},options=input2.options??{},firstPage=input2.pages?.[0],firstPageUrl=firstPage&&typeof firstPage=="object"?firstPage.url:void 0,url2=input2.siteUrl??input2.startUrl??source.startUrl??(typeof firstPageUrl=="string"?firstPageUrl:void 0);if(!url2)throw new Error("snapshot site URL must be a string");return{schemaVersion:1,url:url2,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??!0,includeQuery:options.includeQuery??source.includeQuery??!1,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){let known=new Set(pages.map(page=>page.url)),linked=new Set(pages.flatMap(page=>page.internalLinks)),broken=new Set;for(let page of pages)(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(url2=>known.has(url2)&&!linked.has(url2)),brokenInternalUrls:[...broken].sort()}}function createStatistics(input2,pages){let blockedByRobots=pages.filter(page=>page.blockedByRobots).length,failed=pages.filter(page=>page.error||(page.status??500)>=400).length;return{requested:input2.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:input2.durationMs??0,truncated:input2.truncated??!1,partial:input2.partial??!1}}function createBaseline(scanInput){let scan2=baselineInput(scanInput),config2=defaultConfig(scan2),pages=(scan2.pages??[]).map(page=>normalizePage(pageInput(page))).sort((left,right)=>left.url.localeCompare(right.url)),sitemapUrls=scan2.sitemap?.urls??[];if(scan2.sitemap&&!scan2.sitemap.url)throw new Error("snapshot sitemap URL must be a string");let sitemap=scan2.sitemap?{url:scan2.sitemap.url,urls:[...sitemapUrls].sort(),sitemapCount:scan2.sitemap.sitemapCount??0,truncated:scan2.sitemap.truncated??!1,error:scan2.sitemap.error??null}:null,siteUrl=scan2.startUrl??config2.url,truncated=scan2.truncated??!1;return{schemaVersion:2,engineVersion:ENGINE_VERSION,ruleSetVersion:RULE_SET_VERSION,generatedAt:scan2.generatedAt??new Date().toISOString(),siteUrl,configurationHash:hashConfiguration(config2),config:config2,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??!1},sitemap,pages,linkGraph:scan2.linkGraph??createLinkGraph(pages,sitemapUrls),statistics:scan2.statistics??createStatistics(scan2,pages),partial:scan2.partial??!1,source:{startUrl:siteUrl,maxPages:config2.maxPages,requestDelay:config2.delay,includeQuery:config2.includeQuery,respectRobots:config2.respectRobots,sitemap:typeof config2.sitemap=="string"&&!["auto","none"].includes(config2.sitemap)?config2.sitemap:null},truncated}}function migrateSnapshot(input2){let value=baselineInput(input2);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(input2){if(input2.schemaVersion===2)return input2;let legacy=input2,firstPage=legacy.pages?.[0],firstPageUrl=firstPage&&typeof firstPage=="object"?firstPage.url:void 0,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={}){let 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,url2,message,before,after){let candidate=createIssue(ruleId,url2,message,{before,after,actual:after});return candidate.before=before,candidate.after=after,candidate}function evaluateRegressionRules(baseline,current){let complete=!current.partial&&!current.truncated,issues=[],currentPages=new Map(current.pages.map(page=>[page.url,page]));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));let previousSitemapCount=baseline.sitemap?.urls.length??0,currentSitemapCount=current.sitemap?.urls.length??0,sitemapDrop=previousSitemapCount-currentSitemapCount;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(let before of baseline.pages){let after=currentPages.get(before.url);if(!after){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",!1,!0));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}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));let beforeRobots=`${before.robots??""},${before.xRobotsTag??""}`,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)),before.title&&!after.title?issues.push(changedIssue("title-removed",before.url,"Page title was removed",before.title,after.title)):before.title&&after.title&&before.title!==after.title&&issues.push(changedIssue("title-changed",before.url,"Page title changed",before.title,after.title)),before.description&&!after.description&&issues.push(changedIssue("description-removed",before.url,"Meta description was removed",before.description,after.description)),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){let candidate=changedIssue("canonical-changed",before.url,"Canonical URL changed",before.canonical,after.canonical);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)),before.finalUrl&&after.finalUrl&&before.finalUrl!==after.finalUrl){let candidate=changedIssue("redirect-changed",before.url,"Final redirect URL changed",before.finalUrl,after.finalUrl);new URL(after.finalUrl).origin!==new URL(before.url).origin&&(candidate.severity="error"),issues.push(candidate)}}return issues}function compareBaselines(baselineInput2,currentInput,ruleSet={}){let baseline=normalizeSnapshotInput(baselineInput2),current=normalizeSnapshotInput(currentInput);return applyRulePolicy(evaluateRegressionRules(baseline,current),current,ruleSet)}function lifecycle(issue2,value){return{...issue2,lifecycle:value}}function diff(previousInput,currentInput,ruleSet={}){let previous=normalizeSnapshotInput(previousInput),current=normalizeSnapshotInput(currentInput),complete=!current.partial&&!current.truncated,checkedUrls=new Set(current.pages.map(page=>page.url)),previousIssues=new Map(audit(previous,ruleSet).map(candidate=>[candidate.fingerprint,candidate])),currentIssues=new Map(audit(current,ruleSet).map(candidate=>[candidate.fingerprint,candidate])),newIssues=[],ongoingIssues=[],unchangedIssues=[],resolvedIssues=[];for(let[fingerprint,candidate]of currentIssues){let before=previousIssues.get(fingerprint);before?JSON.stringify(before.evidence)===JSON.stringify(candidate.evidence)?unchangedIssues.push(lifecycle(candidate,"unchanged")):ongoingIssues.push(lifecycle({...candidate,before:before.evidence,after:candidate.evidence},"ongoing")):newIssues.push(lifecycle(candidate,"new"))}for(let[fingerprint,candidate]of previousIssues)(candidate.scope==="page"?checkedUrls.has(candidate.url):complete)&&!currentIssues.has(fingerprint)&&resolvedIssues.push(lifecycle(candidate,"resolved"));let known=new Set(newIssues.map(candidate=>candidate.fingerprint));for(let regression of compareBaselines(previous,current,ruleSet))known.has(regression.fingerprint)||newIssues.push(lifecycle(regression,"new"));let budgets={...previous.config.regressionBudgets,...current.config.regressionBudgets},budgetExceeded=Object.entries(budgets).flatMap(([budget,allowed])=>{let actual2=newIssues.filter(candidate=>candidate.severity===budget||candidate.ruleId===budget).length;return actual2>allowed?[{budget,allowed,actual:actual2}]:[]});return sortIssues(newIssues),sortIssues(ongoingIssues),sortIssues(unchangedIssues),sortIssues(resolvedIssues),{complete,newIssues,ongoingIssues,resolvedIssues,unchangedIssues,issues:[...newIssues,...ongoingIssues],budgetExceeded}}var DEFAULT_CONFIG_FILE="seo-audit.config.json",DEFAULT_SCAN_CONFIG=Object.freeze({schemaVersion:1,url:"",sitemap:"auto",maxPages:100,concurrency:5,delay:100,timeout:1e4,respectRobots:!0,includeQuery:!1,maxRedirects:10,maxResponseBytes:5242880,enabledRules:null,severityOverrides:{},suppressions:[],regressionBudgets:{},report:{}});function object2(value,field){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(`${field} must be an object`);return value}function integer2(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){if(typeof value!="string")throw new Error(`${field} must be a string`);return value}}function validateConfig(input2){let value=object2(input2,"config"),allowed=new Set(["$schema","schemaVersion","url","sitemap","maxPages","concurrency","delay","timeout","respectRobots","includeQuery","maxRedirects","maxResponseBytes","enabledRules","severityOverrides","suppressions","regressionBudgets","report"]);for(let key of Object.keys(value))if(!allowed.has(key))throw new Error(`unknown config property: ${key}`);let result={};if(value.schemaVersion!==void 0&&value.schemaVersion!==1)throw new Error("schemaVersion must be 1");if(value.url!==void 0){let url2=optionalString(value.url,"url");if(!/^https?:\/\//i.test(url2))throw new Error("url must be an HTTP(S) URL");result.url=url2}if(value.sitemap!==void 0){let 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}value.maxPages!==void 0&&(result.maxPages=integer2(value.maxPages,"maxPages",1)),value.concurrency!==void 0&&(result.concurrency=integer2(value.concurrency,"concurrency",1,50)),value.delay!==void 0&&(result.delay=integer2(value.delay,"delay",0)),value.timeout!==void 0&&(result.timeout=integer2(value.timeout,"timeout",1)),value.maxRedirects!==void 0&&(result.maxRedirects=integer2(value.maxRedirects,"maxRedirects",0,50)),value.maxResponseBytes!==void 0&&(result.maxResponseBytes=integer2(value.maxResponseBytes,"maxResponseBytes",1024));for(let 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){let overrides=object2(value.severityOverrides,"severityOverrides");for(let[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)=>{let suppression=object2(entry,`suppressions[${index}]`);for(let 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){let budgets=object2(value.regressionBudgets,"regressionBudgets");result.regressionBudgets=Object.fromEntries(Object.entries(budgets).map(([key,budget])=>[key,integer2(budget,`regressionBudgets.${key}`,0)]))}if(value.report!==void 0){let report=object2(value.report,"report"),branding={},agencyName=optionalString(report.agencyName,"report.agencyName"),logo=optionalString(report.logo,"report.logo"),primaryColor=optionalString(report.primaryColor,"report.primaryColor");if(agencyName!==void 0&&(branding.agencyName=agencyName),logo!==void 0&&(branding.logo=logo),primaryColor!==void 0&&(branding.primaryColor=primaryColor),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,file2={},baseline={}){return{...{...DEFAULT_SCAN_CONFIG,...baseline,...file2,...cli},schemaVersion:1,severityOverrides:{...baseline.severityOverrides??{},...file2.severityOverrides??{},...cli.severityOverrides??{}},regressionBudgets:{...baseline.regressionBudgets??{},...file2.regressionBudgets??{},...cli.regressionBudgets??{}},report:{...baseline.report??{},...file2.report??{},...cli.report??{}},suppressions:cli.suppressions??file2.suppressions??baseline.suppressions??[]}}function noop(){}var NOOP_LOGGER=Object.freeze({debug:noop,info:noop,warn:noop,error:noop});import{setTimeout as sleep2}from"node:timers/promises";function createRequestGate(intervalMs=0,{now=Date.now,wait=sleep2}={}){let interval=Math.max(0,intervalMs),nextStartAt=0,queue=Promise.resolve();return function(){if(interval===0)return Promise.resolve();let slot=queue.then(async()=>{let remaining=Math.max(0,nextStartAt-now());remaining>0&&await wait(remaining),nextStartAt=now()+interval});return queue=slot.catch(()=>{}),slot}}function createPerOriginRequestGate(intervalMs=0,factory=createRequestGate){let gates=new Map;return url2=>{let origin=new URL(url2).origin,gate=gates.get(origin);return gate||(gate=factory(intervalMs),gates.set(origin,gate)),gate()}}import{createHash as createHash3}from"node:crypto";import{setTimeout as sleep3}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;let seconds=Number(value);if(Number.isFinite(seconds)&&seconds>=0)return Math.min(seconds*1e3,3e4);let date5=Date.parse(value);return Number.isNaN(date5)?null:Math.min(Math.max(0,date5-now),3e4)}function requestSignal(timeout,signal){let timeoutSignal=AbortSignal.timeout(timeout);return signal?AbortSignal.any([signal,timeoutSignal]):timeoutSignal}async function fetchRedirectChain(initialUrl,init,policy2){let chain=[],visited=new Set([initialUrl]),url2=initialUrl;for(;;){policy2.signal?.throwIfAborted(),await policy2.gate?.(url2);let response=await policy2.fetch(url2,{...init,redirect:"manual",signal:requestSignal(policy2.timeout,policy2.signal)}),location=response.headers.get("location");if(response.status<300||response.status>=400||!location)return{response,redirectChain:chain};let next=new URL(location,url2).href;if(chain.push({url:url2,status:response.status,location:next}),await response.body?.cancel(),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),url2=next}}async function fetchWithRetry(url2,init,policy2){let lastError;for(let attempt=0;attempt<=policy2.retries;attempt+=1)try{let result=await fetchRedirectChain(url2,init,policy2);if(!retryableStatus(result.response.status)||attempt===policy2.retries)return result;let serverDelay=retryAfterMs(result.response.headers.get("retry-after"));await result.response.body?.cancel();let jitter=Math.floor((policy2.random??Math.random)()*100),delayMs=serverDelay??Math.min(250*2**attempt+jitter,3e4);await policy2.onEvent?.({type:"retry",url:url2,attempt:attempt+1,delayMs}),await sleep3(delayMs,void 0,{signal:policy2.signal})}catch(error61){if(policy2.signal?.aborted)throw policy2.signal.reason??error61;if(lastError=error61,error61 instanceof RequestFailure||attempt===policy2.retries)break;let jitter=Math.floor((policy2.random??Math.random)()*100),delayMs=Math.min(250*2**attempt+jitter,3e4);await policy2.onEvent?.({type:"retry",url:url2,attempt:attempt+1,delayMs}),await sleep3(delayMs,void 0,{signal:policy2.signal})}throw lastError instanceof RequestFailure?lastError: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)};let reader=response.body.getReader(),chunks=[],total=0;for(;;){let{done,value}=await reader.read();if(done)break;if(total+=value.byteLength,total>maxBytes)throw await reader.cancel(),new RequestFailure(`response exceeds ${maxBytes} bytes`);chunks.push(Buffer.from(value))}let buffer=Buffer.concat(chunks);return{text:buffer.toString("utf8"),bytes:total,buffer}}function patternMatches(pathWithQuery,pattern){if(!pattern)return!1;let anchored=pattern.endsWith("$"),escaped=(anchored?pattern.slice(0,-1):pattern).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replaceAll("*",".*");return new RegExp(`^${escaped}${anchored?"$":""}`).test(pathWithQuery)}function parseRobots(body,userAgent){let groups=[],current=null;for(let rawLine of body.replace(/^\uFEFF/,"").split(/\r?\n/)){let line=rawLine.replace(/#.*$/,"").trim(),separator=line.indexOf(":");if(!line||separator<0)continue;let field=line.slice(0,separator).trim().toLowerCase(),value=line.slice(separator+1).trim();if(field==="user-agent"){(!current||current.hasRules)&&(current={agents:[],rules:[],hasRules:!1},groups.push(current)),value&¤t.agents.push(value.toLowerCase());continue}current&&(field==="allow"||field==="disallow")&&value&&(current.rules.push({type:field,path:value}),current.hasRules=!0)}let normalizedAgent=userAgent.toLowerCase(),specific=groups.filter(group=>group.agents.some(agent=>agent!=="*"&&normalizedAgent.includes(agent)));return(specific.length>0?specific:groups.filter(group=>group.agents.includes("*"))).flatMap(group=>group.rules)}function isAllowedByRobots(url2,robots){if(robots.denyAll)return!1;let parsed=new URL(url2),pathWithQuery=`${parsed.pathname}${parsed.search}`,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){let robotsUrl=new URL("/robots.txt",startUrl).href;try{let{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}),{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(error61){if(options.signal?.aborted)throw error61;return{url:robotsUrl,status:null,body:"",sha256:null,rules:[],denyAll:!1,error:error61 instanceof Error?error61.message:String(error61)}}}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",nameChar=nameStartChar+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",nameRegexp="["+nameStartChar+"]["+nameChar+"]*",regexName=new RegExp("^"+nameRegexp+"$");function getAllMatches(string4,regex){let matches=[],match=regex.exec(string4);for(;match;){let allmatches=[];allmatches.startIndex=regex.lastIndex-match[0].length;let len=match.length;for(let index=0;index<len;index++)allmatches.push(match[index]);matches.push(allmatches),match=regex.exec(string4)}return matches}var isName=function(string4){let match=regexName.exec(string4);return!(match===null||typeof match>"u")};function isExist(v){return typeof v<"u"}var DANGEROUS_PROPERTY_NAMES=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],criticalProperties=["__proto__","constructor","prototype"];var defaultOptions={allowBooleanAttributes:!1,unpairedTags:[]};function validate2(xmlData,options){options=Object.assign({},defaultOptions,options);let tags=[],tagFound=!1,reachedRoot=!1;xmlData[0]==="\uFEFF"&&(xmlData=xmlData.substr(1));for(let i=0;i<xmlData.length;i++)if(xmlData[i]==="<"&&xmlData[i+1]==="?"){if(i+=2,i=readPI(xmlData,i),i.err)return i}else if(xmlData[i]==="<"){let tagStartPos=i;if(i++,xmlData[i]==="!"){i=readCommentAndCDATA(xmlData,i);continue}else{let closingTag=!1;xmlData[i]==="/"&&(closingTag=!0,i++);let tagName="";for(;i<xmlData.length&&xmlData[i]!==">"&&xmlData[i]!==" "&&xmlData[i]!==" "&&xmlData[i]!==`
|
|
69
|
+
${stableStringify(identity??null)}`).digest("hex").slice(0,24)}function createIssue(ruleId,url2,message,evidence={},identity){let definition=RULES.get(ruleId);if(!definition)throw new Error(`unknown rule: ${ruleId}`);return{fingerprint:issueFingerprint(ruleId,definition.scope,url2,identity),ruleId,rule:ruleId,severity:definition.severity,scope:definition.scope,url:url2,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!0;try{return new Intl.Locale(language),!0}catch{return!1}}function duplicateMap(pages,select){let groups=new Map;for(let page of pages){let value=select(page)?.trim().toLowerCase();if(!value)continue;let urls=groups.get(value)??[];urls.push(page.url),groups.set(value,urls)}return new Map([...groups].filter(([,urls])=>urls.length>1))}function evaluateCurrentRules(snapshot){let issues=[],add=candidate=>{issues.push(candidate)},pageByUrl=new Map(snapshot.pages.map(page=>[page.url,page])),sitemapUrls=new Set(snapshot.sitemap?.urls??[]),titles=duplicateMap(snapshot.pages,page=>page.title),descriptions=duplicateMap(snapshot.pages,page=>page.description),content=duplicateMap(snapshot.pages,page=>page.contentHash);snapshot.sitemap?.error&&add(createIssue("sitemap-unavailable",snapshot.sitemap.url,"The configured sitemap could not be loaded",{actual:snapshot.sitemap.error}));for(let page of snapshot.pages){if(page.blockedByRobots){add(createIssue("robots-blocked",page.url,"Page is blocked by robots.txt",{actual:!0}));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})),hasDirective(page.robots,"noindex")&&add(createIssue("noindex",page.url,"Page contains a noindex meta directive",{actual:page.robots})),hasDirective(page.xRobotsTag,"noindex")&&add(createIssue("x-robots-noindex",page.url,"Page contains a noindex X-Robots-Tag",{actual:page.xRobotsTag})),!page.canonicalRaw&&!page.canonical&&add(createIssue("missing-canonical",page.url,"Page does not declare a canonical URL",{actual:null})),page.canonicalRaw&&!page.canonical&&add(createIssue("invalid-canonical",page.url,"Canonical URL is invalid",{actual:page.canonicalRaw})),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})),page.canonical){let target=pageByUrl.get(page.canonical);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))}page.redirectChain.length>3&&add(createIssue("long-redirect-chain",page.url,`Page uses ${page.redirectChain.length} redirects`,{actual:page.redirectChain.length,redirectChain:page.redirectChain})),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})),sitemapUrls.has(page.url)&&page.redirectChain.length>0&&add(createIssue("redirect-in-sitemap",page.url,"Sitemap URL redirects",{actual:page.finalUrl,redirectChain:page.redirectChain})),page.title?(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())),(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}))):add(createIssue("missing-title",page.url,"Page does not have a title",{actual:null})),page.description?(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())),(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}))):add(createIssue("missing-description",page.url,"Page does not have a meta description",{actual:null})),page.h1Count===0?add(createIssue("missing-h1",page.url,"Page does not contain an H1 heading",{actual:0})):page.h1Count>1&&add(createIssue("multiple-h1",page.url,`Page contains ${page.h1Count} H1 headings`,{actual:page.h1Count}));for(let targetUrl of page.internalLinks){let target=pageByUrl.get(targetUrl);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))}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:!0})),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:!1}));for(let alternate of page.hreflang)(!validLanguage(alternate.lang)||!alternate.url)&&add(createIssue("invalid-hreflang",page.url,"Hreflang declaration is invalid",{actual:alternate},alternate));for(let[index,block]of page.jsonLd.entries())block.valid||add(createIssue("malformed-json-ld",page.url,"JSON-LD block contains invalid JSON",{actual:block.error,index},index));snapshot.siteUrl.startsWith("https:")&&[page.url,page.canonical,...page.internalLinks].some(url2=>url2?.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(url2=>url2?.startsWith("http:"))})),page.lang&&!validLanguage(page.lang)&&add(createIssue("invalid-language",page.url,"HTML language declaration is invalid",{actual:page.lang})),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)),(!page.openGraph.title||!page.openGraph.description||!page.openGraph.image)&&add(createIssue("missing-open-graph",page.url,"Open Graph metadata is incomplete",{actual:page.openGraph})),(!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}));let missingAlt=page.images.filter(image=>image.alt===null).map(image=>image.src);missingAlt.length>0&&add(createIssue("image-missing-alt",page.url,`${missingAlt.length} image(s) do not have an alt attribute`,{actual:missingAlt})),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(url2,pattern){let pathname=(()=>{try{return new URL(url2).pathname}catch{return url2}})(),expression=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replaceAll("**","\0").replaceAll("*","[^/]*").replaceAll("\0",".*"),regex=new RegExp(`^${expression}$`);return regex.test(pathname)||regex.test(url2)}function activeSuppression(issue2,suppressions,now){return suppressions.find(suppression=>suppression.rule!==issue2.ruleId||!globMatches(issue2.url,suppression.urlPattern)?!1:suppression.expiresAt?new Date(`${suppression.expiresAt}T23:59:59.999Z`).getTime()>=now.getTime():!0)??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={}){let enabled=ruleSet.enabledRules??snapshot.config.enabledRules,enabledSet=enabled?new Set(enabled):null,overrides={...snapshot.config.severityOverrides,...ruleSet.severityOverrides??{}},suppressions=ruleSet.suppressions??snapshot.config.suppressions,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.10.3",RULE_SET_VERSION="1.1.0",PRODUCT_NAME="seo-crawl-audit",DEFAULT_USER_AGENT=`${PRODUCT_NAME}/${ENGINE_VERSION}`;var DEFAULT_OPEN_GRAPH={title:null,description:null,image:null},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){return Array.isArray(value)?`[${value.map(stableJson).join(",")}]`:value&&typeof value=="object"?`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,child])=>`${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`:JSON.stringify(value)}function hashConfiguration(config2){return createHash2("sha256").update(stableJson(config2)).digest("hex")}function normalizePage(page){return{url:page.url,finalUrl:page.finalUrl??null,status:page.status??null,contentType:page.contentType??null,blockedByRobots:page.blockedByRobots??!1,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(input2){let source=input2.source??{},options=input2.options??{},firstPage=input2.pages?.[0],firstPageUrl=firstPage&&typeof firstPage=="object"?firstPage.url:void 0,url2=input2.siteUrl??input2.startUrl??source.startUrl??(typeof firstPageUrl=="string"?firstPageUrl:void 0);if(!url2)throw new Error("snapshot site URL must be a string");return{schemaVersion:1,url:url2,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??!0,includeQuery:options.includeQuery??source.includeQuery??!1,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){let known=new Set(pages.map(page=>page.url)),linked=new Set(pages.flatMap(page=>page.internalLinks)),broken=new Set;for(let page of pages)(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(url2=>known.has(url2)&&!linked.has(url2)),brokenInternalUrls:[...broken].sort()}}function createStatistics(input2,pages){let blockedByRobots=pages.filter(page=>page.blockedByRobots).length,failed=pages.filter(page=>page.error||(page.status??500)>=400).length;return{requested:input2.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:input2.durationMs??0,truncated:input2.truncated??!1,partial:input2.partial??!1}}function createBaseline(scanInput){let scan2=baselineInput(scanInput),config2=defaultConfig(scan2),pages=(scan2.pages??[]).map(page=>normalizePage(pageInput(page))).sort((left,right)=>left.url.localeCompare(right.url)),sitemapUrls=scan2.sitemap?.urls??[];if(scan2.sitemap&&!scan2.sitemap.url)throw new Error("snapshot sitemap URL must be a string");let sitemap=scan2.sitemap?{url:scan2.sitemap.url,urls:[...sitemapUrls].sort(),sitemapCount:scan2.sitemap.sitemapCount??0,truncated:scan2.sitemap.truncated??!1,error:scan2.sitemap.error??null}:null,siteUrl=scan2.startUrl??config2.url,truncated=scan2.truncated??!1;return{schemaVersion:2,engineVersion:ENGINE_VERSION,ruleSetVersion:RULE_SET_VERSION,generatedAt:scan2.generatedAt??new Date().toISOString(),siteUrl,configurationHash:hashConfiguration(config2),config:config2,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??!1},sitemap,pages,linkGraph:scan2.linkGraph??createLinkGraph(pages,sitemapUrls),statistics:scan2.statistics??createStatistics(scan2,pages),partial:scan2.partial??!1,source:{startUrl:siteUrl,maxPages:config2.maxPages,requestDelay:config2.delay,includeQuery:config2.includeQuery,respectRobots:config2.respectRobots,sitemap:typeof config2.sitemap=="string"&&!["auto","none"].includes(config2.sitemap)?config2.sitemap:null},truncated}}function migrateSnapshot(input2){let value=baselineInput(input2);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(input2){if(input2.schemaVersion===2)return input2;let legacy=input2,firstPage=legacy.pages?.[0],firstPageUrl=firstPage&&typeof firstPage=="object"?firstPage.url:void 0,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={}){let 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,url2,message,before,after){let candidate=createIssue(ruleId,url2,message,{before,after,actual:after});return candidate.before=before,candidate.after=after,candidate}function evaluateRegressionRules(baseline,current){let complete=!current.partial&&!current.truncated,issues=[],currentPages=new Map(current.pages.map(page=>[page.url,page]));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));let previousSitemapCount=baseline.sitemap?.urls.length??0,currentSitemapCount=current.sitemap?.urls.length??0,sitemapDrop=previousSitemapCount-currentSitemapCount;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(let before of baseline.pages){let after=currentPages.get(before.url);if(!after){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",!1,!0));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}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));let beforeRobots=`${before.robots??""},${before.xRobotsTag??""}`,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)),before.title&&!after.title?issues.push(changedIssue("title-removed",before.url,"Page title was removed",before.title,after.title)):before.title&&after.title&&before.title!==after.title&&issues.push(changedIssue("title-changed",before.url,"Page title changed",before.title,after.title)),before.description&&!after.description&&issues.push(changedIssue("description-removed",before.url,"Meta description was removed",before.description,after.description)),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){let candidate=changedIssue("canonical-changed",before.url,"Canonical URL changed",before.canonical,after.canonical);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)),before.finalUrl&&after.finalUrl&&before.finalUrl!==after.finalUrl){let candidate=changedIssue("redirect-changed",before.url,"Final redirect URL changed",before.finalUrl,after.finalUrl);new URL(after.finalUrl).origin!==new URL(before.url).origin&&(candidate.severity="error"),issues.push(candidate)}}return issues}function compareBaselines(baselineInput2,currentInput,ruleSet={}){let baseline=normalizeSnapshotInput(baselineInput2),current=normalizeSnapshotInput(currentInput);return applyRulePolicy(evaluateRegressionRules(baseline,current),current,ruleSet)}function lifecycle(issue2,value){return{...issue2,lifecycle:value}}function diff(previousInput,currentInput,ruleSet={}){let previous=normalizeSnapshotInput(previousInput),current=normalizeSnapshotInput(currentInput),complete=!current.partial&&!current.truncated,checkedUrls=new Set(current.pages.map(page=>page.url)),previousIssues=new Map(audit(previous,ruleSet).map(candidate=>[candidate.fingerprint,candidate])),currentIssues=new Map(audit(current,ruleSet).map(candidate=>[candidate.fingerprint,candidate])),newIssues=[],ongoingIssues=[],unchangedIssues=[],resolvedIssues=[];for(let[fingerprint,candidate]of currentIssues){let before=previousIssues.get(fingerprint);before?JSON.stringify(before.evidence)===JSON.stringify(candidate.evidence)?unchangedIssues.push(lifecycle(candidate,"unchanged")):ongoingIssues.push(lifecycle({...candidate,before:before.evidence,after:candidate.evidence},"ongoing")):newIssues.push(lifecycle(candidate,"new"))}for(let[fingerprint,candidate]of previousIssues)(candidate.scope==="page"?checkedUrls.has(candidate.url):complete)&&!currentIssues.has(fingerprint)&&resolvedIssues.push(lifecycle(candidate,"resolved"));let known=new Set(newIssues.map(candidate=>candidate.fingerprint));for(let regression of compareBaselines(previous,current,ruleSet))known.has(regression.fingerprint)||newIssues.push(lifecycle(regression,"new"));let budgets={...previous.config.regressionBudgets,...current.config.regressionBudgets},budgetExceeded=Object.entries(budgets).flatMap(([budget,allowed])=>{let actual2=newIssues.filter(candidate=>candidate.severity===budget||candidate.ruleId===budget).length;return actual2>allowed?[{budget,allowed,actual:actual2}]:[]});return sortIssues(newIssues),sortIssues(ongoingIssues),sortIssues(unchangedIssues),sortIssues(resolvedIssues),{complete,newIssues,ongoingIssues,resolvedIssues,unchangedIssues,issues:[...newIssues,...ongoingIssues],budgetExceeded}}var DEFAULT_CONFIG_FILE="seo-audit.config.json",DEFAULT_SCAN_CONFIG=Object.freeze({schemaVersion:1,url:"",sitemap:"auto",maxPages:100,concurrency:5,delay:100,timeout:1e4,respectRobots:!0,includeQuery:!1,maxRedirects:10,maxResponseBytes:5242880,enabledRules:null,severityOverrides:{},suppressions:[],regressionBudgets:{},report:{}});function object2(value,field){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(`${field} must be an object`);return value}function integer2(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){if(typeof value!="string")throw new Error(`${field} must be a string`);return value}}function validateConfig(input2){let value=object2(input2,"config"),allowed=new Set(["$schema","schemaVersion","url","sitemap","maxPages","concurrency","delay","timeout","respectRobots","includeQuery","maxRedirects","maxResponseBytes","enabledRules","severityOverrides","suppressions","regressionBudgets","report"]);for(let key of Object.keys(value))if(!allowed.has(key))throw new Error(`unknown config property: ${key}`);let result={};if(value.schemaVersion!==void 0&&value.schemaVersion!==1)throw new Error("schemaVersion must be 1");if(value.url!==void 0){let url2=optionalString(value.url,"url");if(!/^https?:\/\//i.test(url2))throw new Error("url must be an HTTP(S) URL");result.url=url2}if(value.sitemap!==void 0){let 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}value.maxPages!==void 0&&(result.maxPages=integer2(value.maxPages,"maxPages",1)),value.concurrency!==void 0&&(result.concurrency=integer2(value.concurrency,"concurrency",1,50)),value.delay!==void 0&&(result.delay=integer2(value.delay,"delay",0)),value.timeout!==void 0&&(result.timeout=integer2(value.timeout,"timeout",1)),value.maxRedirects!==void 0&&(result.maxRedirects=integer2(value.maxRedirects,"maxRedirects",0,50)),value.maxResponseBytes!==void 0&&(result.maxResponseBytes=integer2(value.maxResponseBytes,"maxResponseBytes",1024));for(let 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){let overrides=object2(value.severityOverrides,"severityOverrides");for(let[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)=>{let suppression=object2(entry,`suppressions[${index}]`);for(let 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){let budgets=object2(value.regressionBudgets,"regressionBudgets");result.regressionBudgets=Object.fromEntries(Object.entries(budgets).map(([key,budget])=>[key,integer2(budget,`regressionBudgets.${key}`,0)]))}if(value.report!==void 0){let report=object2(value.report,"report"),branding={},agencyName=optionalString(report.agencyName,"report.agencyName"),logo=optionalString(report.logo,"report.logo"),primaryColor=optionalString(report.primaryColor,"report.primaryColor");if(agencyName!==void 0&&(branding.agencyName=agencyName),logo!==void 0&&(branding.logo=logo),primaryColor!==void 0&&(branding.primaryColor=primaryColor),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,file2={},baseline={}){return{...{...DEFAULT_SCAN_CONFIG,...baseline,...file2,...cli},schemaVersion:1,severityOverrides:{...baseline.severityOverrides??{},...file2.severityOverrides??{},...cli.severityOverrides??{}},regressionBudgets:{...baseline.regressionBudgets??{},...file2.regressionBudgets??{},...cli.regressionBudgets??{}},report:{...baseline.report??{},...file2.report??{},...cli.report??{}},suppressions:cli.suppressions??file2.suppressions??baseline.suppressions??[]}}function noop(){}var NOOP_LOGGER=Object.freeze({debug:noop,info:noop,warn:noop,error:noop});import{setTimeout as sleep2}from"node:timers/promises";function createRequestGate(intervalMs=0,{now=Date.now,wait=sleep2}={}){let interval=Math.max(0,intervalMs),nextStartAt=0,queue=Promise.resolve();return function(){if(interval===0)return Promise.resolve();let slot=queue.then(async()=>{let remaining=Math.max(0,nextStartAt-now());remaining>0&&await wait(remaining),nextStartAt=now()+interval});return queue=slot.catch(()=>{}),slot}}function createPerOriginRequestGate(intervalMs=0,factory=createRequestGate){let gates=new Map;return url2=>{let origin=new URL(url2).origin,gate=gates.get(origin);return gate||(gate=factory(intervalMs),gates.set(origin,gate)),gate()}}import{createHash as createHash3}from"node:crypto";import{setTimeout as sleep3}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;let seconds=Number(value);if(Number.isFinite(seconds)&&seconds>=0)return Math.min(seconds*1e3,3e4);let date5=Date.parse(value);return Number.isNaN(date5)?null:Math.min(Math.max(0,date5-now),3e4)}function requestSignal(timeout,signal){let timeoutSignal=AbortSignal.timeout(timeout);return signal?AbortSignal.any([signal,timeoutSignal]):timeoutSignal}async function fetchRedirectChain(initialUrl,init,policy2){let chain=[],visited=new Set([initialUrl]),url2=initialUrl;for(;;){policy2.signal?.throwIfAborted(),await policy2.gate?.(url2);let response=await policy2.fetch(url2,{...init,redirect:"manual",signal:requestSignal(policy2.timeout,policy2.signal)}),location=response.headers.get("location");if(response.status<300||response.status>=400||!location)return{response,redirectChain:chain};let next=new URL(location,url2).href;if(chain.push({url:url2,status:response.status,location:next}),await response.body?.cancel(),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),url2=next}}async function fetchWithRetry(url2,init,policy2){let lastError;for(let attempt=0;attempt<=policy2.retries;attempt+=1)try{let result=await fetchRedirectChain(url2,init,policy2);if(!retryableStatus(result.response.status)||attempt===policy2.retries)return result;let serverDelay=retryAfterMs(result.response.headers.get("retry-after"));await result.response.body?.cancel();let jitter=Math.floor((policy2.random??Math.random)()*100),delayMs=serverDelay??Math.min(250*2**attempt+jitter,3e4);await policy2.onEvent?.({type:"retry",url:url2,attempt:attempt+1,delayMs}),await sleep3(delayMs,void 0,{signal:policy2.signal})}catch(error61){if(policy2.signal?.aborted)throw policy2.signal.reason??error61;if(lastError=error61,error61 instanceof RequestFailure||attempt===policy2.retries)break;let jitter=Math.floor((policy2.random??Math.random)()*100),delayMs=Math.min(250*2**attempt+jitter,3e4);await policy2.onEvent?.({type:"retry",url:url2,attempt:attempt+1,delayMs}),await sleep3(delayMs,void 0,{signal:policy2.signal})}throw lastError instanceof RequestFailure?lastError: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)};let reader=response.body.getReader(),chunks=[],total=0;for(;;){let{done,value}=await reader.read();if(done)break;if(total+=value.byteLength,total>maxBytes)throw await reader.cancel(),new RequestFailure(`response exceeds ${maxBytes} bytes`);chunks.push(Buffer.from(value))}let buffer=Buffer.concat(chunks);return{text:buffer.toString("utf8"),bytes:total,buffer}}function patternMatches(pathWithQuery,pattern){if(!pattern)return!1;let anchored=pattern.endsWith("$"),escaped=(anchored?pattern.slice(0,-1):pattern).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replaceAll("*",".*");return new RegExp(`^${escaped}${anchored?"$":""}`).test(pathWithQuery)}function parseRobots(body,userAgent){let groups=[],current=null;for(let rawLine of body.replace(/^\uFEFF/,"").split(/\r?\n/)){let line=rawLine.replace(/#.*$/,"").trim(),separator=line.indexOf(":");if(!line||separator<0)continue;let field=line.slice(0,separator).trim().toLowerCase(),value=line.slice(separator+1).trim();if(field==="user-agent"){(!current||current.hasRules)&&(current={agents:[],rules:[],hasRules:!1},groups.push(current)),value&¤t.agents.push(value.toLowerCase());continue}current&&(field==="allow"||field==="disallow")&&value&&(current.rules.push({type:field,path:value}),current.hasRules=!0)}let normalizedAgent=userAgent.toLowerCase(),specific=groups.filter(group=>group.agents.some(agent=>agent!=="*"&&normalizedAgent.includes(agent)));return(specific.length>0?specific:groups.filter(group=>group.agents.includes("*"))).flatMap(group=>group.rules)}function isAllowedByRobots(url2,robots){if(robots.denyAll)return!1;let parsed=new URL(url2),pathWithQuery=`${parsed.pathname}${parsed.search}`,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){let robotsUrl=new URL("/robots.txt",startUrl).href;try{let{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}),{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(error61){if(options.signal?.aborted)throw error61;return{url:robotsUrl,status:null,body:"",sha256:null,rules:[],denyAll:!1,error:error61 instanceof Error?error61.message:String(error61)}}}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",nameChar=nameStartChar+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",nameRegexp="["+nameStartChar+"]["+nameChar+"]*",regexName=new RegExp("^"+nameRegexp+"$");function getAllMatches(string4,regex){let matches=[],match=regex.exec(string4);for(;match;){let allmatches=[];allmatches.startIndex=regex.lastIndex-match[0].length;let len=match.length;for(let index=0;index<len;index++)allmatches.push(match[index]);matches.push(allmatches),match=regex.exec(string4)}return matches}var isName=function(string4){let match=regexName.exec(string4);return!(match===null||typeof match>"u")};function isExist(v){return typeof v<"u"}var DANGEROUS_PROPERTY_NAMES=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],criticalProperties=["__proto__","constructor","prototype"];var defaultOptions={allowBooleanAttributes:!1,unpairedTags:[]};function validate2(xmlData,options){options=Object.assign({},defaultOptions,options);let tags=[],tagFound=!1,reachedRoot=!1;xmlData[0]==="\uFEFF"&&(xmlData=xmlData.substr(1));for(let i=0;i<xmlData.length;i++)if(xmlData[i]==="<"&&xmlData[i+1]==="?"){if(i+=2,i=readPI(xmlData,i),i.err)return i}else if(xmlData[i]==="<"){let tagStartPos=i;if(i++,xmlData[i]==="!"){i=readCommentAndCDATA(xmlData,i);continue}else{let closingTag=!1;xmlData[i]==="/"&&(closingTag=!0,i++);let tagName="";for(;i<xmlData.length&&xmlData[i]!==">"&&xmlData[i]!==" "&&xmlData[i]!==" "&&xmlData[i]!==`
|
|
70
70
|
`&&xmlData[i]!=="\r";i++)tagName+=xmlData[i];if(tagName=tagName.trim(),tagName[tagName.length-1]==="/"&&(tagName=tagName.substring(0,tagName.length-1),i--),!validateTagName(tagName)){let msg;return tagName.trim().length===0?msg="Invalid space after '<'.":msg="Tag '"+tagName+"' is an invalid name.",getErrorObject("InvalidTag",msg,getLineNumberForPosition(xmlData,i))}let result=readAttributeStr(xmlData,i);if(result===!1)return getErrorObject("InvalidAttr","Attributes for '"+tagName+"' have open quote.",getLineNumberForPosition(xmlData,i));let attrStr=result.value;if(i=result.index,attrStr[attrStr.length-1]==="/"){let attrStrStart=i-attrStr.length;attrStr=attrStr.substring(0,attrStr.length-1);let isValid=validateAttributeString(attrStr,options);if(isValid===!0)tagFound=!0;else return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,attrStrStart+isValid.err.line))}else if(closingTag)if(result.tagClosed){if(attrStr.trim().length>0)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' can't have attributes or invalid starting.",getLineNumberForPosition(xmlData,tagStartPos));if(tags.length===0)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' has not been opened.",getLineNumberForPosition(xmlData,tagStartPos));{let 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))}tags.length==0&&(reachedRoot=!0)}}else return getErrorObject("InvalidTag","Closing tag '"+tagName+"' doesn't have proper closing.",getLineNumberForPosition(xmlData,i));else{let isValid=validateAttributeString(attrStr,options);if(isValid!==!0)return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,i-attrStr.length+isValid.err.line));if(reachedRoot===!0)return getErrorObject("InvalidXml","Multiple possible root nodes found.",getLineNumberForPosition(xmlData,i));options.unpairedTags.indexOf(tagName)!==-1||tags.push({tagName,tagStartPos}),tagFound=!0}for(i++;i<xmlData.length;i++)if(xmlData[i]==="<")if(xmlData[i+1]==="!"){i++,i=readCommentAndCDATA(xmlData,i);continue}else if(xmlData[i+1]==="?"){if(i=readPI(xmlData,++i),i.err)return i}else break;else if(xmlData[i]==="&"){let afterAmp=validateAmpersand(xmlData,i);if(afterAmp==-1)return getErrorObject("InvalidChar","char '&' is not expected.",getLineNumberForPosition(xmlData,i));i=afterAmp}else if(reachedRoot===!0&&!isWhiteSpace(xmlData[i]))return getErrorObject("InvalidXml","Extra text at the end",getLineNumberForPosition(xmlData,i));xmlData[i]==="<"&&i--}}else{if(isWhiteSpace(xmlData[i]))continue;return getErrorObject("InvalidChar","char '"+xmlData[i]+"' is not expected.",getLineNumberForPosition(xmlData,i))}if(tagFound){if(tags.length==1)return getErrorObject("InvalidTag","Unclosed tag '"+tags[0].tagName+"'.",getLineNumberForPosition(xmlData,tags[0].tagStartPos));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})}else return getErrorObject("InvalidXml","Start tag expected.",1);return!0}function isWhiteSpace(char){return char===" "||char===" "||char===`
|
|
71
71
|
`||char==="\r"}function readPI(xmlData,i){let start=i;for(;i<xmlData.length;i++)if(xmlData[i]=="?"||xmlData[i]==" "){let 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));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--,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='"',singleQuote="'";function readAttributeStr(xmlData,i){let attrStr="",startChar="",tagClosed=!1;for(;i<xmlData.length;i++){if(xmlData[i]===doubleQuote||xmlData[i]===singleQuote)startChar===""?startChar=xmlData[i]:startChar!==xmlData[i]||(startChar="");else if(xmlData[i]===">"&&startChar===""){tagClosed=!0;break}attrStr+=xmlData[i]}return startChar!==""?!1:{value:attrStr,index:i,tagClosed}}var validAttrStrRegxp=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function validateAttributeString(attrStr,options){let matches=getAllMatches(attrStr,validAttrStrRegxp),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]));if(matches[i][3]!==void 0&&matches[i][4]===void 0)return getErrorObject("InvalidAttr","Attribute '"+matches[i][2]+"' is without value.",getPositionFromMatch(matches[i]));if(matches[i][3]===void 0&&!options.allowBooleanAttributes)return getErrorObject("InvalidAttr","boolean attribute '"+matches[i][2]+"' is not allowed.",getPositionFromMatch(matches[i]));let 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!0}function validateNumberAmpersand(xmlData,i){let re=/\d/;for(xmlData[i]==="x"&&(i++,re=/[\da-fA-F]/);i<xmlData.length;i++){if(xmlData[i]===";")return i;if(!xmlData[i].match(re))break}return-1}function validateAmpersand(xmlData,i){if(i++,xmlData[i]===";")return-1;if(xmlData[i]==="#")return i++,validateNumberAmpersand(xmlData,i);let count=0;for(;i<xmlData.length;i++,count++)if(!(xmlData[i].match(/\w/)&&count<20)){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){let 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:'"'},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"}),SPECIAL_CHARS=new Set("!?\\\\/[]$%{}^&*()<>|+");function validateEntityName(name){if(name[0]==="#")throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`);for(let ch of name)if(SPECIAL_CHARS.has(ch))throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`);return name}function mergeEntityMaps(...maps2){let out=Object.create(null);for(let map2 of maps2)if(map2)for(let key of Object.keys(map2)){let raw=map2[key];if(typeof raw=="string")out[key]=raw;else if(raw&&typeof raw=="object"&&raw.val!==void 0){let val=raw.val;typeof val=="string"&&(out[key]=val)}}return out}var LIMIT_TIER_EXTERNAL="external",LIMIT_TIER_BASE="base",LIMIT_TIER_ALL="all";function parseLimitTiers(raw){return!raw||raw===LIMIT_TIER_EXTERNAL?new Set([LIMIT_TIER_EXTERNAL]):raw===LIMIT_TIER_ALL?new Set([LIMIT_TIER_ALL]):raw===LIMIT_TIER_BASE?new Set([LIMIT_TIER_BASE]):Array.isArray(raw)?new Set(raw):new Set([LIMIT_TIER_EXTERNAL])}var NCR_LEVEL=Object.freeze({allow:0,leave:1,remove:2,throw:3}),XML10_ALLOWED_C0=new Set([9,10,13]);function parseNCRConfig(ncr){if(!ncr)return{xmlVersion:1,onLevel:NCR_LEVEL.allow,nullLevel:NCR_LEVEL.remove};let xmlVersion=ncr.xmlVersion===1.1?1.1:1,onLevel=NCR_LEVEL[ncr.onNCR]??NCR_LEVEL.allow,nullLevel=NCR_LEVEL[ncr.nullNCR]??NCR_LEVEL.remove,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??!0,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:[]);let 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!0;let action=hook(name,value);if(action===ENTITY_ACTION.BLOCK)return!1;if(action===ENTITY_ACTION.THROW)throw new Error(`[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook`);return!0}setExternalEntities(map2){if(map2)for(let key of Object.keys(map2))validateEntityName(key);if(!this._onExternalEntity){this._externalMap=mergeEntityMaps(map2);return}let flat=mergeEntityMaps(map2),filtered=Object.create(null);for(let[name,value]of Object.entries(flat))this._applyRegistrationHook(this._onExternalEntity,name,value,"external")&&(filtered[name]=value);this._externalMap=filtered}addExternalEntity(key,value){validateEntityName(key),typeof value=="string"&&value.indexOf("&")===-1&&this._applyRegistrationHook(this._onExternalEntity,key,value,"external")&&(this._externalMap[key]=value)}addInputEntities(map2){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity){this._inputMap=mergeEntityMaps(map2);return}let flat=mergeEntityMaps(map2),filtered=Object.create(null);for(let[name,value]of Object.entries(flat))this._applyRegistrationHook(this._onInputEntity,name,value,"input")&&(filtered[name]=value);this._inputMap=filtered}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(version2){this._ncrXmlVersion=version2===1.1?1.1:1}decode(str){if(typeof str!="string"||str.length===0||str.indexOf("&")===-1)return str;let original=str,chunks=[],len=str.length,last=0,i=0,limitExpansions=this._maxTotalExpansions>0,limitLength=this._maxExpandedLength>0,checkLimits=limitExpansions||limitLength;for(;i<len;){if(str.charCodeAt(i)!==38){i++;continue}let j=i+1;for(;j<len&&str.charCodeAt(j)!==59&&j-i<=32;)j++;if(j>=len||str.charCodeAt(j)!==59){i++;continue}let token=str.slice(i+1,j);if(token.length===0){i++;continue}let replacement,tier;if(this._removeSet.has(token))replacement="",tier===void 0&&(tier=LIMIT_TIER_EXTERNAL);else if(this._leaveSet.has(token)){i++;continue}else if(token.charCodeAt(0)===35){let ncrResult=this._resolveNCR(token);if(ncrResult===void 0){i++;continue}replacement=ncrResult,tier=LIMIT_TIER_BASE}else{let 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,checkLimits&&this._tierCounts(tier)){if(limitExpansions&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(limitLength){let delta=replacement.length-(token.length+2);if(delta>0&&(this._expandedLength+=delta,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}last<len&&chunks.push(str.slice(last));let result=chunks.length===0?str:chunks.join("");return this._postCheck(result,original)}_tierCounts(tier){return this._limitTiers.has(LIMIT_TIER_ALL)?!0: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}}_classifyNCR(cp){return cp===0?this._ncrNullLevel:cp>=55296&&cp<=57343||this._ncrXmlVersion===1&&cp>=1&&cp<=31&&!XML10_ALLOWED_C0.has(cp)?NCR_LEVEL.remove:-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;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){let second=token.charCodeAt(1),cp;if(second===120||second===88?cp=parseInt(token.slice(2),16):cp=parseInt(token.slice(1),10),Number.isNaN(cp)||cp<0||cp>1114111)return;let minimum=this._classifyNCR(cp);if(!this._numericAllowed&&minimum<NCR_LEVEL.remove)return;let effective=minimum===-1?this._ncrOnLevel:Math.max(this._ncrOnLevel,minimum);return this._applyNCRAction(effective,token,cp)}};var defaultOnDangerousProperty=name=>DANGEROUS_PROPERTY_NAMES.includes(name)?"__"+name:name,defaultOptions2={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0,unicode:!1},tagValueProcessor:function(tagName,val){return val},attributeValueProcessor:function(attrName,val){return val},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(tagName,jPath,attrs){return tagName},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:defaultOnDangerousProperty};function validatePropertyName(propertyName,optionName){if(typeof propertyName!="string")return;let 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){return typeof value=="boolean"?{enabled:value,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:typeof value=="object"&&value!==null?{enabled:value.enabled!==!1,maxEntitySize:Math.max(1,value.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,value.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,value.maxTotalExpansions??1/0),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"}:normalizeProcessEntities(!0)}var buildOptions=function(options){let built=Object.assign({},defaultOptions2,options),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(let{value,name}of propertyNameOptions)value&&validatePropertyName(value,name);return built.onDangerousProperty===null&&(built.onDangerousProperty=defaultOnDangerousProperty),built.processEntities=normalizeProcessEntities(built.processEntities,built.htmlEntities),built.unpairedTagsSet=new Set(built.unpairedTags),built.stopNodes&&Array.isArray(built.stopNodes)&&(built.stopNodes=built.stopNodes.map(node2=>typeof node2=="string"&&node2.startsWith("*.")?".."+node2.substring(2):node2)),built};var METADATA_SYMBOL;typeof Symbol!="function"?METADATA_SYMBOL="@@xmlMetadata":METADATA_SYMBOL=Symbol("XML Node Metadata");var XmlNode=class{constructor(tagname){this.tagname=tagname,this.child=[],this[":@"]=Object.create(null)}add(key,val){key==="__proto__"&&(key="#__proto__"),this.child.push({[key]:val})}addChild(node2,startIndex){node2.tagname==="__proto__"&&(node2.tagname="#__proto__"),node2[":@"]&&Object.keys(node2[":@"]).length>0?this.child.push({[node2.tagname]:node2.child,":@":node2[":@"]}):this.child.push({[node2.tagname]:node2.child}),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",nameChar10=nameStartChar10+"\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040",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}",nameChar11=nameStartChar11+"\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040",buildRegexes=(startChar,char,flags="")=>{let ncStart=startChar.replace(":",""),ncChar=char.replace(":",""),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)}},regexes10=buildRegexes(nameStartChar10,nameChar10),regexes11=buildRegexes(nameStartChar11,nameChar11,"u"),nameStartCharAscii=":A-Za-z_",nameCharAscii=nameStartCharAscii+"\\-\\.\\d",regexesAscii=buildRegexes(nameStartCharAscii,nameCharAscii),getRegexes=(xmlVersion="1.0",asciiOnly=!1)=>asciiOnly?regexesAscii:xmlVersion==="1.1"?regexes11:regexes10;var qName=(str,{xmlVersion="1.0",asciiOnly=!1}={})=>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){let entities=Object.create(null),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,hasBody=!1,comment=!1,exp="";for(;i<xmlData.length;i++)if(xmlData[i]==="<"&&!comment){if(hasBody&&hasSeq(xmlData,"!ENTITY",i)){i+=7;let entityName,val;if([entityName,val,i]=this.readEntityExp(xmlData,i+1,this.suppressValidationErr),val.indexOf("&")===-1){if(this.options.enabled!==!1&&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;let{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;let{index}=this.readNotationExp(xmlData,i+1,this.suppressValidationErr);i=index}else if(hasSeq(xmlData,"!--",i))comment=!0;else throw new Error("Invalid DOCTYPE");angleBracketsCount++,exp=""}else if(xmlData[i]===">"){if(comment?xmlData[i-1]==="-"&&xmlData[i-2]==="-"&&(comment=!1,angleBracketsCount--):angleBracketsCount--,angleBracketsCount===0)break}else xmlData[i]==="["?hasBody=!0: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);let startIndex=i;for(;i<xmlData.length&&!/\s/.test(xmlData[i])&&xmlData[i]!=='"'&&xmlData[i]!=="'";)i++;let entityName=xmlData.substring(startIndex,i);if(validateEntityName2(entityName,{xmlVersion:this.xmlVersion}),i=skipWhitespace(xmlData,i),!this.suppressValidationErr){if(xmlData.substring(i,i+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(xmlData[i]==="%")throw new Error("Parameter entities are not supported")}let entityValue="";if([i,entityValue]=this.readIdentifierVal(xmlData,i,"entity"),this.options.enabled!==!1&&this.options.maxEntitySize!=null&&entityValue.length>this.options.maxEntitySize)throw new Error(`Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return i--,[entityName,entityValue,i]}readNotationExp(xmlData,i){i=skipWhitespace(xmlData,i);let startIndex=i;for(;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);let 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,systemIdentifier=null;if(identifierType==="PUBLIC")[i,publicIdentifier]=this.readIdentifierVal(xmlData,i,"publicIdentifier"),i=skipWhitespace(xmlData,i),(xmlData[i]==='"'||xmlData[i]==="'")&&([i,systemIdentifier]=this.readIdentifierVal(xmlData,i,"systemIdentifier"));else if(identifierType==="SYSTEM"&&([i,systemIdentifier]=this.readIdentifierVal(xmlData,i,"systemIdentifier"),!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="",startChar=xmlData[i];if(startChar!=='"'&&startChar!=="'")throw new Error(`Expected quoted string, found "${startChar}"`);i++;let startIndex=i;for(;i<xmlData.length&&xmlData[i]!==startChar;)i++;if(identifierVal=xmlData.substring(startIndex,i),xmlData[i]!==startChar)throw new Error(`Unterminated ${type} value`);return i++,[i,identifierVal]}readElementExp(xmlData,i){i=skipWhitespace(xmlData,i);let startIndex=i;for(;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++;let startIndex2=i;for(;i<xmlData.length&&xmlData[i]!==")";)i++;if(contentModel=xmlData.substring(startIndex2,i),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;for(;i<xmlData.length&&!/\s/.test(xmlData[i]);)i++;let elementName=xmlData.substring(startIndex,i);for(validateEntityName2(elementName,{xmlVersion:this.xmlVersion}),i=skipWhitespace(xmlData,i),startIndex=i;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"){if(attributeType="NOTATION",i+=8,i=skipWhitespace(xmlData,i),xmlData[i]!=="(")throw new Error(`Expected '(', found "${xmlData[i]}"`);i++;let allowedNotations=[];for(;i<xmlData.length&&xmlData[i]!==")";){let startIndex2=i;for(;i<xmlData.length&&xmlData[i]!=="|"&&xmlData[i]!==")";)i++;let notation=xmlData.substring(startIndex2,i);if(notation=notation.trim(),!validateEntityName2(notation,{xmlVersion:this.xmlVersion}))throw new Error(`Invalid notation name: "${notation}"`);allowedNotations.push(notation),xmlData[i]==="|"&&(i++,i=skipWhitespace(xmlData,i))}if(xmlData[i]!==")")throw new Error("Unterminated list of notations");i++,attributeType+=" ("+allowedNotations.join("|")+")"}else{let startIndex2=i;for(;i<xmlData.length&&!/\s/.test(xmlData[i]);)i++;attributeType+=xmlData.substring(startIndex2,i);let 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="";return xmlData.substring(i,i+8).toUpperCase()==="#REQUIRED"?(defaultValue="#REQUIRED",i+=8):xmlData.substring(i,i+7).toUpperCase()==="#IMPLIED"?(defaultValue="#IMPLIED",i+=7):[i,defaultValue]=this.readIdentifierVal(xmlData,i,"ATTLIST"),{elementName,attributeName,attributeType,defaultValue,index:i}}},skipWhitespace=(data,index)=>{for(;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!1;return!0}function validateEntityName2(name,xmlVersion){if(qName(name,{xmlVersion}))return name;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],NOT_DIGIT=255,HIGH_MAP=new Map,LOW_MAX=65535,LOW_MIN=1632,TABLE_OFFSET=LOW_MIN,TABLE_SIZE=LOW_MAX-LOW_MIN+1,TABLE=new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT);for(let zero of SCRIPT_ZEROS)for(let d=0;d<10;d++){let cp=zero+d;cp<=LOW_MAX?TABLE[cp-TABLE_OFFSET]=d:HIGH_MAP.set(cp,d)}var CHAR_0=48,CHAR_9=57,CHAR_MINUS=45,MINUS_SET=new Set([8722,65293,65123]);function anynum(str){if(typeof str!="string")return str;let len=str.length;if(len===0)return str;let firstHit=-1;for(let i=0;i<len;i++){let cc=str.charCodeAt(i);if(!(cc>=CHAR_0&&cc<=CHAR_9||cc===CHAR_MINUS)){if(cc<TABLE_OFFSET){if(MINUS_SET.has(cc)){firstHit=i;break}continue}if(cc>=55296&&cc<=56319){if(i+1<len){let low=str.charCodeAt(i+1);if(low>=56320&&low<=57343){let 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;let chars=[];firstHit>0&&chars.push(str.slice(0,firstHit));for(let i=firstHit;i<len;i++){let 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){let low=str.charCodeAt(i+1);if(low>=56320&&low<=57343){let cp=65536+(cc-55296<<10)+(low-56320),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}let 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]+$/,binRegex=/^0b[01]+$/,octRegex=/^0o[0-7]+$/,numRegex=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,consider={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function toNumber(str,options={}){if(options=Object.assign({},consider,options),!str||typeof str!="string")return str;let trimmedStr=str.trim();if(trimmedStr.length===0)return str;if(options.skipLike!==void 0&&options.skipLike.test(trimmedStr))return str;if(trimmedStr==="0"||options.unicode&&(trimmedStr=anynum_default(trimmedStr),trimmedStr==="0"))return 0;if(options.hex&&hexRegex.test(trimmedStr))return parse_int(trimmedStr,16);if(options.binary&&binRegex.test(trimmedStr))return parse_int(trimmedStr,2);if(options.octal&&octRegex.test(trimmedStr))return parse_int(trimmedStr,8);if(isFinite(trimmedStr)){if(trimmedStr.includes("e")||trimmedStr.includes("E"))return resolveEnotation(str,trimmedStr,options);{let match=numRegex.exec(trimmedStr);if(match){let sign=match[1]||"",leadingZeros=match[2],numTrimmedByZeros=trimZeros(match[3]),decimalAdjacentToLeadingZeros=sign?str[leadingZeros.length+1]===".":str[leadingZeros.length]===".";if(!options.leadingZeros&&(leadingZeros.length>1||leadingZeros.length===1&&!decimalAdjacentToLeadingZeros))return str;{let num=Number(trimmedStr),parsedStr=String(num);if(num===0)return num;if(parsedStr.search(/[eE]/)!==-1)return options.eNotation?num:str;if(trimmedStr.indexOf(".")!==-1)return parsedStr==="0"||parsedStr===numTrimmedByZeros||parsedStr===`${sign}${numTrimmedByZeros}`?num:str;let n=leadingZeros?numTrimmedByZeros:trimmedStr;return leadingZeros?n===parsedStr||sign+n===parsedStr?num:str:n===parsedStr||n===sign+parsedStr?num:str}}else return str}}else return handleInfinity(str,Number(trimmedStr),options)}var eNotationRegx=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(str,trimmedStr,options){if(!options.eNotation)return str;let notation=trimmedStr.match(eNotationRegx);if(notation){let sign=notation[1]||"",eChar=notation[3].indexOf("e")===-1?"E":"e",leadingZeros=notation[2],eAdjacentToLeadingZeros=sign?str[leadingZeros.length+1]===eChar:str[leadingZeros.length]===eChar;return leadingZeros.length>1&&eAdjacentToLeadingZeros?str:leadingZeros.length===1&&(notation[3].startsWith(`.${eChar}`)||notation[3][0]===eChar)?Number(trimmedStr):leadingZeros.length>0?options.leadingZeros&&!eAdjacentToLeadingZeros?(trimmedStr=(notation[1]||"")+notation[3],Number(trimmedStr)):str:Number(trimmedStr)}else return str}function trimZeros(numStr){return numStr&&numStr.indexOf(".")!==-1&&(numStr=numStr.replace(/0+$/,""),numStr==="."?numStr="0":numStr[0]==="."?numStr="0"+numStr:numStr[numStr.length-1]==="."&&(numStr=numStr.substring(0,numStr.length-1))),numStr}function parse_int(numStr,base){let str=numStr.trim();if((base===2||base===8)&&(numStr=str.substring(2)),parseInt)return parseInt(numStr,base);if(Number.parseInt)return Number.parseInt(numStr,base);if(window&&window.parseInt)return window.parseInt(numStr,base);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function handleInfinity(str,num,options){let isPositive=num===1/0;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){return typeof ignoreAttributes=="function"?ignoreAttributes:Array.isArray(ignoreAttributes)?attrName=>{for(let pattern of ignoreAttributes)if(typeof pattern=="string"&&attrName===pattern||pattern instanceof RegExp&&pattern.test(attrName))return!0}:()=>!1}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){let segments=[],i=0,currentPart="";for(;i<pattern.length;)pattern[i]===this.separator?i+1<pattern.length&&pattern[i+1]===this.separator?(currentPart.trim()&&(segments.push(this._parseSegment(currentPart.trim())),currentPart=""),segments.push({type:"deep-wildcard"}),i+=2):(currentPart.trim()&&segments.push(this._parseSegment(currentPart.trim())),currentPart="",i++):(currentPart+=pattern[i],i++);return currentPart.trim()&&segments.push(this._parseSegment(currentPart.trim())),segments}_parseSegment(part){let segment={type:"tag"},bracketContent=null,withoutBrackets=part,bracketMatch=part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(bracketMatch&&(withoutBrackets=bracketMatch[1]+bracketMatch[3],bracketMatch[2])){let content=bracketMatch[2].slice(1,-1);content&&(bracketContent=content)}let namespace,tagAndPosition=withoutBrackets;if(withoutBrackets.includes("::")){let nsIndex=withoutBrackets.indexOf("::");if(namespace=withoutBrackets.substring(0,nsIndex).trim(),tagAndPosition=withoutBrackets.substring(nsIndex+2).trim(),!namespace)throw new Error(`Invalid namespace in pattern: ${part}`)}let tag,positionMatch=null;if(tagAndPosition.includes(":")){let colonIndex=tagAndPosition.lastIndexOf(":"),tagPart=tagAndPosition.substring(0,colonIndex).trim(),posPart=tagAndPosition.substring(colonIndex+1).trim();["first","last","odd","even"].includes(posPart)||/^nth\(\d+\)$/.test(posPart)?(tag=tagPart,positionMatch=posPart):tag=tagAndPosition}else tag=tagAndPosition;if(!tag)throw new Error(`Invalid segment pattern: ${part}`);if(segment.tag=tag,namespace&&(segment.namespace=namespace),bracketContent)if(bracketContent.includes("=")){let eqIndex=bracketContent.indexOf("=");segment.attrName=bracketContent.substring(0,eqIndex).trim(),segment.attrValue=bracketContent.substring(eqIndex+1).trim()}else segment.attrName=bracketContent.trim();if(positionMatch){let nthMatch=positionMatch.match(/^nth\((\d+)\)$/);nthMatch?(segment.position="nth",segment.positionValue=parseInt(nthMatch[1],10)):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=!1}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;if(this._patterns.add(expression.pattern),expression.hasDeepWildcard()){let lastSeg2=expression.segments[expression.segments.length-1];if(lastSeg2&&lastSeg2.type!=="deep-wildcard"&&lastSeg2.tag!=="*"){let tag2=lastSeg2.tag;this._deepByTerminalTag.has(tag2)||this._deepByTerminalTag.set(tag2,[]),this._deepByTerminalTag.get(tag2).push(expression)}else this._deepWildcards.push(expression);return this}let depth=expression.length,tag=expression.segments[expression.segments.length-1]?.tag;if(!tag||tag==="*")this._wildcardByDepth.has(depth)||this._wildcardByDepth.set(depth,[]),this._wildcardByDepth.get(depth).push(expression);else{let key=`${depth}:${tag}`;this._byDepthAndTag.has(key)||this._byDepthAndTag.set(key,[]),this._byDepthAndTag.get(key).push(expression)}return this}addAll(expressions){for(let expr of expressions)this.add(expr);return this}has(expression){return this._patterns.has(expression.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(matcher){return this.findMatch(matcher)!==null}findMatch(matcher){let depth=matcher.getDepth(),tag=matcher.getCurrentTag(),exactKey=`${depth}:${tag}`,exactBucket=this._byDepthAndTag.get(exactKey);if(exactBucket){for(let i=0;i<exactBucket.length;i++)if(matcher.matches(exactBucket[i]))return exactBucket[i]}let wildcardBucket=this._wildcardByDepth.get(depth);if(wildcardBucket){for(let i=0;i<wildcardBucket.length;i++)if(matcher.matches(wildcardBucket[i]))return wildcardBucket[i]}let 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(){let path=this._matcher.path;return path.length>0?path[path.length-1].tag:void 0}getCurrentNamespace(){let path=this._matcher.path;return path.length>0?path[path.length-1].namespace:void 0}getAttrValue(attrName){let path=this._matcher.path;if(path.length!==0)return path[path.length-1].values?.[attrName]}hasAttr(attrName){let path=this._matcher.path;if(path.length===0)return!1;let 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(){let path=this._matcher.path;return path.length===0?-1:path[path.length-1].position??0}getCounter(){let path=this._matcher.path;return path.length===0?-1:path[path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(separator,includeNamespace=!0){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)}},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,this.path.length>0&&(this.path[this.path.length-1].values=void 0);let currentLevel=this.path.length,level=this.siblingStacks[currentLevel];level||(level={counts:new Map,total:0},this.siblingStacks[currentLevel]=level);let siblingKey=namespace?`${namespace}:${tagName}`:tagName,counter=level.counts.get(siblingKey)||0,position=level.total;level.counts.set(siblingKey,counter+1),level.total++;let node2={tag:tagName,position,counter};namespace!=null&&(node2.namespace=namespace),attrValues!=null&&(node2.values=attrValues),this.path.push(node2);let depth=this.path.length,keep=options!==null?options.keep:null;if(keep!=null&&keep.length>0&&attrValues)for(let i=0;i<keep.length;i++){let name=keep[i];attrValues[name]!==void 0&&this._keptAttrs.push({depth,name,value:attrValues[name]})}}pop(){if(this.path.length===0)return;this._pathStringCache=null;let node2=this.path.pop();this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1);let poppedDepth=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=poppedDepth;)this._keptAttrs.pop();return node2}updateCurrent(attrValues){if(this.path.length>0){let current=this.path[this.path.length-1];attrValues!=null&&(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 this.path[this.path.length-1].values?.[attrName]}hasAttr(attrName){if(this.path.length===0)return!1;let current=this.path[this.path.length-1];return current.values!==void 0&&attrName in current.values}getAnyParentAttr(attrName){let kept=this._keptAttrs;for(let i=kept.length-1;i>=0;i--)if(kept[i].name===attrName)return kept[i].value}hasAnyParentAttr(attrName){let kept=this._keptAttrs;for(let i=kept.length-1;i>=0;i--)if(kept[i].name===attrName)return!0;return!1}getPosition(){return this.path.length===0?-1:this.path[this.path.length-1].position??0}getCounter(){return this.path.length===0?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(separator,includeNamespace=!0){let sep2=separator||this.separator;if(sep2===this.separator&&includeNamespace===!0){if(this._pathStringCache!==null)return this._pathStringCache;let result=this.path.map(n=>n.namespace?`${n.namespace}:${n.tag}`:n.tag).join(sep2);return this._pathStringCache=result,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){let segments=expression.segments;return segments.length===0?!1:expression.hasDeepWildcard()?this._matchWithDeepWildcard(segments):this._matchSimple(segments)}_matchSimple(segments){if(this.path.length!==segments.length)return!1;for(let i=0;i<segments.length;i++)if(!this._matchSegment(segments[i],this.path[i],i===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(segments){let pathIdx=this.path.length-1,segIdx=segments.length-1;for(;segIdx>=0&&pathIdx>=0;){let segment=segments[segIdx];if(segment.type==="deep-wildcard"){if(segIdx--,segIdx<0)return!0;let nextSeg=segments[segIdx],found=!1;for(let i=pathIdx;i>=0;i--)if(this._matchSegment(nextSeg,this.path[i],i===this.path.length-1)){pathIdx=i-1,segIdx--,found=!0;break}if(!found)return!1}else{if(!this._matchSegment(segment,this.path[pathIdx],pathIdx===this.path.length-1))return!1;pathIdx--,segIdx--}}return segIdx<0}_matchSegment(segment,node2,isCurrentNode){if(segment.tag!=="*"&&segment.tag!==node2.tag||segment.namespace!==void 0&&segment.namespace!=="*"&&segment.namespace!==node2.namespace||segment.attrName!==void 0&&(!isCurrentNode||!node2.values||!(segment.attrName in node2.values)||segment.attrValue!==void 0&&String(node2.values[segment.attrName])!==String(segment.attrValue)))return!1;if(segment.position!==void 0){if(!isCurrentNode)return!1;let counter=node2.counter??0;if(segment.position==="first"&&counter!==0)return!1;if(segment.position==="odd"&&counter%2!==1)return!1;if(segment.position==="even"&&counter%2!==0)return!1;if(segment.position==="nth"&&counter!==segment.positionValue)return!1}return!0}matchesAny(exprSet){return exprSet.matchesAny(this)}snapshot(){return{path:this.path.map(node2=>({...node2})),siblingStacks:this.siblingStacks.map(level=>level&&{counts:new Map(level.counts),total:level.total}),keptAttrs:this._keptAttrs.map(entry=>({...entry}))}}restore(snapshot){this._pathStringCache=null,this.path=snapshot.path.map(node2=>({...node2})),this.siblingStacks=snapshot.siblingStacks.map(level=>level&&{counts:new Map(level.counts),total:level.total}),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}],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:/\?>/}],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}],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}],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}],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,}\)/}],redos_default=REDOS_PATTERNS;var sep=`["'\\s]*:`,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__["']\]/}],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\[/}],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}],SQL_STRICT_PATTERNS=[...sql_default,...SQL_STRICT_EXTRA],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)){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(let 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){return context instanceof RegExp?{lists:null,regex:context}:Array.isArray(context[0])?{lists:context,regex:null}:{lists:[context],regex:null}}function matchList(value,list){let label=list.label??"CUSTOM";for(let 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);let{lists,regex}=normalise(context);if(regex)return regex.test(value);for(let list of lists)if(matchList(value,list)!==null)return!0;return!1}function extractRawAttributes(prefixedAttrs,options){if(!prefixedAttrs)return{};let attrs=options.attributesGroupName?prefixedAttrs[options.attributesGroupName]:prefixedAttrs;if(!attrs)return{};let rawAttrs={};for(let key in attrs)if(key.startsWith(options.attributeNamePrefix)){let 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;let colonIndex=rawTagName.indexOf(":");if(colonIndex!==-1&&colonIndex>0){let ns=rawTagName.substring(0,colonIndex);if(ns!=="xmlns")return ns}}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=!1;let namedEntities={...XML};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:(typeof this.options.htmlEntities=="object"?namedEntities=this.options.htmlEntities:this.options.htmlEntities===!0&&(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=!1,this.stopNodeExpressionsSet=new ExpressionSet;let stopNodesOpts=this.options.stopNodes;if(stopNodesOpts&&stopNodesOpts.length>0){for(let i=0;i<stopNodesOpts.length;i++){let stopNodeExp=stopNodesOpts[i];typeof stopNodeExp=="string"?this.stopNodeExpressionsSet.add(new Expression(stopNodeExp)):stopNodeExp instanceof Expression&&this.stopNodeExpressionsSet.add(stopNodeExp)}this.stopNodeExpressionsSet.seal()}}};function parseTextData(val,tagName,jPath,dontTrim,hasAttributes,isLeafNode,escapeEntities){let options=this.options;if(val!==void 0&&(options.trimValues&&!dontTrim&&(val=val.trim()),val.length>0)){escapeEntities||(val=this.replaceEntitiesValue(val,tagName,jPath));let jPathOrMatcher=options.jPath?jPath.toString():jPath,newval=options.tagValueProcessor(tagName,val,jPathOrMatcher,hasAttributes,isLeafNode);return newval==null?val:typeof newval!=typeof val||newval!==val?newval:options.trimValues||val.trim()===val?parseValue(val,options.parseTagValue,options.numberParseOptions):val}}function resolveNameSpace(tagname){if(this.options.removeNSPrefix){let tags=tagname.split(":"),prefix=tagname.charAt(0)==="/"?"/":"";if(tags[0]==="xmlns")return"";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=!1){let options=this.options;if(force===!0||options.ignoreAttributes!==!0&&typeof attrStr=="string"){let matches=getAllMatches(attrStr,attrsRegx),len=matches.length,attrs={},processedVals=new Array(len),hasRawAttrs=!1,rawAttrsForMatcher={};for(let i=0;i<len;i++){let attrName=this.resolveNameSpace(matches[i][1]),oldVal=matches[i][4];if(attrName.length&&oldVal!==void 0){let val=oldVal;options.trimValues&&(val=val.trim()),val=this.replaceEntitiesValue(val,tagName,this.readonlyMatcher),processedVals[i]=val,rawAttrsForMatcher[attrName]=val,hasRawAttrs=!0}}hasRawAttrs&&typeof jPath=="object"&&jPath.updateCurrent&&jPath.updateCurrent(rawAttrsForMatcher);let jPathStr=options.jPath?jPath.toString():this.readonlyMatcher,hasAttrs=!1;for(let i=0;i<len;i++){let 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),matches[i][4]!==void 0){let oldVal=processedVals[i],newVal=options.attributeValueProcessor(attrName,oldVal,jPathStr);newVal==null?attrs[aName]=oldVal:typeof newVal!=typeof oldVal||newVal!==oldVal?attrs[aName]=newVal:attrs[aName]=parseValue(oldVal,options.parseAttributeValue,options.numberParseOptions),hasAttrs=!0}else options.allowBooleanAttributes&&(attrs[aName]=!0,hasAttrs=!0)}if(!hasAttrs)return;if(options.attributesGroupName&&!options.preserveOrder){let attrCollection={};return attrCollection[options.attributesGroupName]=attrs,attrCollection}return attrs}}var parseXml=function(xmlData){xmlData=xmlData.replace(/\r\n?/g,`
|
|
72
72
|
`);let xmlObj=new XmlNode("!xml"),currentNode=xmlObj,textData="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0,this.doctypefound=!1;let options=this.options,docTypeReader=new DocTypeReader(options.processEntities),xmlLen=xmlData.length;for(let i=0;i<xmlLen;i++)if(xmlData[i]==="<"){let c1=xmlData.charCodeAt(i+1);if(c1===47){let closeIndex=findClosingIndex(xmlData,">",i,"Closing Tag is not closed."),tagName=xmlData.substring(i+2,closeIndex).trim();if(options.removeNSPrefix){let colonIndex=tagName.indexOf(":");colonIndex!==-1&&(tagName=tagName.substr(colonIndex+1))}tagName=transformTagName(options.transformTagName,tagName,"",options).tagName,currentNode&&(textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher));let lastTagName=this.matcher.getCurrentTag();if(tagName&&options.unpairedTagsSet.has(tagName))throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);lastTagName&&options.unpairedTagsSet.has(lastTagName)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,currentNode=this.tagsNodeStack.pop(),textData="",i=closeIndex}else if(c1===63){let tagData=readTagExp(xmlData,i,!1,"?>");if(!tagData)throw new Error("Pi Tag is not closed.");textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher);let attsMap=this.buildAttributesMap(tagData.tagExp,this.matcher,tagData.tagName,!0);if(attsMap){let 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)){let childNode=new XmlNode(tagData.tagName);childNode.add(options.textNodeName,""),tagData.tagName!==tagData.tagExp&&tagData.attrExpPresent&&options.ignoreAttributes!==!0&&(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){let endIndex=findClosingIndex(xmlData,"-->",i+4,"Comment is not closed.");if(options.commentPropName){let 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=!0;let result=docTypeReader.readDocType(xmlData,i);this.entityDecoder.addInputEntities(result.entities),i=result.i}else if(c1===33&&xmlData.charCodeAt(i+2)===91){let closeIndex=findClosingIndex(xmlData,"]]>",i,"CDATA is not closed.")-2,tagExp=xmlData.substring(i+9,closeIndex);textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher);let val=this.parseTextData(tagExp,currentNode.tagname,this.readonlyMatcher,!0,!1,!0,!0);val==null&&(val=""),options.cdataPropName?currentNode.add(options.cdataPropName,[{[options.textNodeName]:tagExp}]):currentNode.add(options.textNodeName,val),i=closeIndex+2}else{let result=readTagExp(xmlData,i,options.removeNSPrefix);if(!result){let 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,rawTagName=result.rawTagName,tagExp=result.tagExp,attrExpPresent=result.attrExpPresent,closeIndex=result.closeIndex;if({tagName,tagExp}=transformTagName(options.transformTagName,tagName,tagExp,options),options.strictReservedNames&&(tagName===options.commentPropName||tagName===options.cdataPropName||tagName===options.textNodeName||tagName===options.attributesGroupName))throw new Error(`Invalid tag name: ${tagName}`);currentNode&&textData&¤tNode.tagname!=="!xml"&&(textData=this.saveTextToParentTag(textData,currentNode,this.readonlyMatcher,!1));let lastTag=currentNode;lastTag&&options.unpairedTagsSet.has(lastTag.tagname)&&(currentNode=this.tagsNodeStack.pop(),this.matcher.pop());let isSelfClosing=!1;tagExp.length>0&&tagExp.lastIndexOf("/")===tagExp.length-1&&(isSelfClosing=!0,tagName[tagName.length-1]==="/"?(tagName=tagName.substr(0,tagName.length-1),tagExp=tagName):tagExp=tagExp.substr(0,tagExp.length-1),attrExpPresent=tagName!==tagExp);let prefixedAttrs=null,rawAttrs={},namespace;namespace=extractNamespace(rawTagName),tagName!==xmlObj.tagname&&this.matcher.push(tagName,{},namespace),tagName!==tagExp&&attrExpPresent&&(prefixedAttrs=this.buildAttributesMap(tagExp,this.matcher,tagName),prefixedAttrs&&(rawAttrs=extractRawAttributes(prefixedAttrs,options))),tagName!==xmlObj.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());let startIndex=i;if(this.isCurrentNodeStopNode){let tagContent="";if(isSelfClosing)i=result.closeIndex;else if(options.unpairedTagsSet.has(tagName))i=result.closeIndex;else{let result2=this.readStopNodeData(xmlData,rawTagName,closeIndex+1);if(!result2)throw new Error(`Unexpected end of ${rawTagName}`);i=result2.i,tagContent=result2.tagContent}let childNode=new XmlNode(tagName);prefixedAttrs&&(childNode[":@"]=prefixedAttrs),childNode.add(options.textNodeName,tagContent),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex)}else{if(isSelfClosing){({tagName,tagExp}=transformTagName(options.transformTagName,tagName,tagExp,options));let childNode=new XmlNode(tagName);prefixedAttrs&&(childNode[":@"]=prefixedAttrs),this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else if(options.unpairedTagsSet.has(tagName)){let childNode=new XmlNode(tagName);prefixedAttrs&&(childNode[":@"]=prefixedAttrs),this.addChild(currentNode,childNode,this.readonlyMatcher,startIndex),this.matcher.pop(),this.isCurrentNodeStopNode=!1,i=result.closeIndex;continue}else{let childNode=new XmlNode(tagName);if(this.tagsNodeStack.length>options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(currentNode),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){this.options.captureMetaData||(startIndex=void 0);let jPathOrMatcher=this.options.jPath?matcher.toString():matcher,result=this.options.updateTag(childNode.tagname,jPathOrMatcher,childNode[":@"]);result===!1||(typeof result=="string"&&(childNode.tagname=result),currentNode.addChild(childNode,startIndex))}function replaceEntitiesValue(val,tagName,jPath){let entityConfig=this.options.processEntities;if(!entityConfig||!entityConfig.enabled)return val;if(entityConfig.allowedTags){let jPathOrMatcher=this.options.jPath?jPath.toString():jPath;if(!(Array.isArray(entityConfig.allowedTags)?entityConfig.allowedTags.includes(tagName):entityConfig.allowedTags(tagName,jPathOrMatcher)))return val}if(entityConfig.tagFilter){let 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){return textData&&(isLeafNode===void 0&&(isLeafNode=parentNode.child.length===0),textData=this.parseTextData(textData,parentNode.tagname,matcher,!1,parentNode[":@"]?Object.keys(parentNode[":@"]).length!==0:!1,isLeafNode),textData!==void 0&&textData!==""&&parentNode.add(this.options.textNodeName,textData),textData=""),textData}function isItStopNode(){return this.stopNodeExpressionsSet.size===0?!1:this.matcher.matchesAny(this.stopNodeExpressionsSet)}function tagExpWithClosingIndex(xmlData,i,closingChar=">"){let attrBoundary=0,len=xmlData.length,closeCode0=closingChar.charCodeAt(0),closeCode1=closingChar.length>1?closingChar.charCodeAt(1):-1,result="",segmentStart=i;for(let index=i;index<len;index++){let code=xmlData.charCodeAt(index);if(attrBoundary)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)return result+=xmlData.substring(segmentStart,index),{data:result,index}}else return result+=xmlData.substring(segmentStart,index),{data:result,index};else code===9&&!attrBoundary&&(result+=xmlData.substring(segmentStart,index)+" ",segmentStart=index+1)}}function findClosingIndex(xmlData,str,i,errMsg){let closingIndex=xmlData.indexOf(str,i);if(closingIndex===-1)throw new Error(errMsg);return closingIndex+str.length-1}function findClosingChar(xmlData,char,i,errMsg){let closingIndex=xmlData.indexOf(char,i);if(closingIndex===-1)throw new Error(errMsg);return closingIndex}function readTagExp(xmlData,i,removeNSPrefix,closingChar=">"){let result=tagExpWithClosingIndex(xmlData,i+1,closingChar);if(!result)return;let tagExp=result.data,closeIndex=result.index,separatorIndex=tagExp.search(/\s/),tagName=tagExp,attrExpPresent=!0;separatorIndex!==-1&&(tagName=tagExp.substring(0,separatorIndex),tagExp=tagExp.substring(separatorIndex+1).trimStart());let rawTagName=tagName;if(removeNSPrefix){let colonIndex=tagName.indexOf(":");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){let startIndex=i,openTagCount=1,xmllen=xmlData.length;for(;i<xmllen;i++)if(xmlData[i]==="<"){let c1=xmlData.charCodeAt(i+1);if(c1===47){let closeIndex=findClosingChar(xmlData,">",i,`${tagName} is not closed`);if(xmlData.substring(i+2,closeIndex).trim()===tagName&&(openTagCount--,openTagCount===0))return{tagContent:xmlData.substring(startIndex,i),i:closeIndex};i=closeIndex}else if(c1===63)i=findClosingIndex(xmlData,"?>",i+1,"StopNode is not closed.");else if(c1===33&&xmlData.charCodeAt(i+2)===45&&xmlData.charCodeAt(i+3)===45)i=findClosingIndex(xmlData,"-->",i+3,"StopNode is not closed.");else if(c1===33&&xmlData.charCodeAt(i+2)===91)i=findClosingIndex(xmlData,"]]>",i,"StopNode is not closed.")-2;else{let tagData=readTagExp(xmlData,i,!1);tagData&&((tagData&&tagData.tagName)===tagName&&tagData.tagExp[tagData.tagExp.length-1]!=="/"&&openTagCount++,i=tagData.closeIndex)}}}function parseValue(val,shouldParse,options){if(shouldParse&&typeof val=="string"){let newval=val.trim();return newval==="true"?!0:newval==="false"?!1:toNumber(val,options)}else return isExist(val)?val:""}function transformTagName(fn,tagName,tagExp,options){if(fn){let newTagName=fn(tagName);tagExp===tagName&&(tagExp=newTagName),tagName=newTagName}return tagName=sanitizeName(tagName,options),{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`);return DANGEROUS_PROPERTY_NAMES.includes(name)?options.onDangerousProperty(name):name}var METADATA_SYMBOL2=XmlNode.getMetaDataSymbol();function stripAttributePrefix(attrs,prefix){if(!attrs||typeof attrs!="object")return{};if(!prefix)return attrs;let rawAttrs={};for(let key in attrs)if(key.startsWith(prefix)){let rawName=key.substring(prefix.length);rawAttrs[rawName]=attrs[key]}else rawAttrs[key]=attrs[key];return rawAttrs}function prettify(node2,options,matcher,readonlyMatcher){return compress(node2,options,matcher,readonlyMatcher)}function compress(arr,options,matcher,readonlyMatcher){let text,compressedObj={};for(let i=0;i<arr.length;i++){let tagObj=arr[i],property=propName(tagObj);if(property!==void 0&&property!==options.textNodeName){let rawAttrs=stripAttributePrefix(tagObj[":@"]||{},options.attributeNamePrefix);matcher.push(property,rawAttrs)}if(property===options.textNodeName)text===void 0?text=tagObj[property]:text+=""+tagObj[property];else{if(property===void 0)continue;if(tagObj[property]){let val=compress(tagObj[property],options,matcher,readonlyMatcher),isLeaf=isLeafTag(val,options);if(Object.keys(val).length===0&&options.alwaysCreateTextNode&&(val[options.textNodeName]=""),tagObj[":@"]?assignAttributes(val,tagObj[":@"],readonlyMatcher,options):Object.keys(val).length===1&&val[options.textNodeName]!==void 0&&!options.alwaysCreateTextNode?val=val[options.textNodeName]:Object.keys(val).length===0&&(options.alwaysCreateTextNode?val[options.textNodeName]="":val=""),tagObj[METADATA_SYMBOL2]!==void 0&&typeof val=="object"&&val!==null&&(val[METADATA_SYMBOL2]=tagObj[METADATA_SYMBOL2]),compressedObj[property]!==void 0&&Object.prototype.hasOwnProperty.call(compressedObj,property))Array.isArray(compressedObj[property])||(compressedObj[property]=[compressedObj[property]]),compressedObj[property].push(val);else{let jPathOrMatcher=options.jPath?readonlyMatcher.toString():readonlyMatcher;options.isArray(property,jPathOrMatcher,isLeaf)?compressedObj[property]=[val]:compressedObj[property]=val}property!==void 0&&property!==options.textNodeName&&matcher.pop()}}}return typeof text=="string"?text.length>0&&(compressedObj[options.textNodeName]=text):text!==void 0&&(compressedObj[options.textNodeName]=text),compressedObj}function propName(obj){let keys=Object.keys(obj);for(let i=0;i<keys.length;i++){let key=keys[i];if(key!==":@")return key}}function assignAttributes(obj,attrMap,readonlyMatcher,options){if(attrMap){let keys=Object.keys(attrMap),len=keys.length;for(let i=0;i<len;i++){let atrrName=keys[i],rawAttrName=atrrName.startsWith(options.attributeNamePrefix)?atrrName.substring(options.attributeNamePrefix.length):atrrName,jPathOrMatcher=options.jPath?readonlyMatcher.toString()+"."+rawAttrName:readonlyMatcher;options.isArray(atrrName,jPathOrMatcher,!0,!0)?obj[atrrName]=[attrMap[atrrName]]:obj[atrrName]=attrMap[atrrName]}}}function isLeafTag(obj,options){let{textNodeName}=options,propCount=Object.keys(obj).length;return!!(propCount===0||propCount===1&&(obj[textNodeName]||typeof obj[textNodeName]=="boolean"||obj[textNodeName]===0))}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){validationOption===!0&&(validationOption={});let result=validate2(xmlData,validationOption);if(result!==!0)throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)}let orderedObjParser=new OrderedObjParser(this.options,this.externalEntities),orderedResult=orderedObjParser.parseXml(xmlData);return this.options.preserveOrder||orderedResult===void 0?orderedResult:prettify(orderedResult,this.options,orderedObjParser.matcher,orderedObjParser.readonlyMatcher)}addEntity(key,value){if(value.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(key.indexOf("&")!==-1||key.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(value==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[key]=value}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}};var XMLValidator={validate:validate2};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(input2,base,{includeQuery=!1}={}){let url2;try{url2=base?new URL(input2,base):new URL(input2)}catch{return null}return url2.protocol!=="http:"&&url2.protocol!=="https:"?null:(url2.hash="",includeQuery||(url2.search=""),url2.pathname.length>1&&url2.pathname.endsWith("/")&&(url2.pathname=url2.pathname.replace(/\/+$/,"")),url2.href)}function isSameOrigin(url2,origin){try{return new URL(url2).origin===origin}catch{return!1}}function isCrawlableUrl(url2){try{let parsed=new URL(url2);return!SKIPPED_EXTENSIONS.test(parsed.pathname)}catch{return!1}}var MAX_SITEMAP_BYTES=10*1024*1024,MAX_SITEMAPS=100,DEFAULT_SITEMAP_LIMIT=5e4,parser=new XMLParser({ignoreAttributes:!1,removeNSPrefix:!0,trimValues:!0});function record2(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function locations(value){return(value===void 0?[]:Array.isArray(value)?value:[value]).flatMap(entry=>{let location=record2(entry)?.loc;return typeof location=="string"?[location]:[]})}function decodeSitemap(buffer,url2,contentType){let decoded=url2.toLowerCase().endsWith(".gz")||contentType.includes("gzip")||buffer[0]===31&&buffer[1]===139?gunzipSync(buffer):buffer;if(decoded.byteLength>MAX_SITEMAP_BYTES)throw new Error(`sitemap exceeds ${MAX_SITEMAP_BYTES} bytes after decompression: ${url2}`);return decoded.toString("utf8").replace(/^\uFEFF/,"")}function parseSitemap(xml,url2){let validation=XMLValidator.validate(xml);if(validation!==!0)throw new Error(`invalid sitemap XML at ${url2}: ${validation.err.msg}`);let data=record2(parser.parse(xml)),sitemapIndex=record2(data?.sitemapindex);if(sitemapIndex)return{kind:"index",locations:locations(sitemapIndex.sitemap)};let urlSet=record2(data?.urlset);if(urlSet)return{kind:"urlset",locations:locations(urlSet.url)};throw new Error(`XML is not a sitemap urlset or sitemapindex: ${url2}`)}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 url2=>options.requestGate?.(url2):void 0,onEvent:options.onEvent}}async function fetchSitemap(url2,options){let{response}=await fetchWithRetry(url2,{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)throw await response.body?.cancel(),new Error(`sitemap returned HTTP ${response.status}: ${url2}`);let{buffer}=await readResponseBody(response,MAX_SITEMAP_BYTES);return decodeSitemap(buffer,url2,response.headers.get("content-type")?.toLowerCase()??"")}async function isSitemapResponse(url2,options){try{let xml=await fetchSitemap(url2,options);return parseSitemap(xml,url2),!0}catch{return!1}}async function discoverSitemapUrl(inputUrl,options){let startUrl=normalizeUrl(inputUrl,void 0);if(!startUrl)throw new Error(`invalid start URL: ${inputUrl}`);let origin=new URL(startUrl).origin,robotsUrl=new URL("/robots.txt",origin).href;try{if(options.robotsBody!==void 0)for(let match of options.robotsBody.matchAll(/^sitemap:\s*(\S+)\s*$/gim)){let location=match[1];if(!location)continue;let candidate=normalizeUrl(location,robotsUrl,{includeQuery:!0});if(candidate&&isSameOrigin(candidate,origin))return candidate}else{let{response}=await fetchWithRetry(robotsUrl,{headers:{accept:"text/plain,*/*;q=0.1","user-agent":options.userAgent}},policy({...options,siteOrigin:origin}));if(response.ok){let{text}=await readResponseBody(response,524288);for(let match of text.matchAll(/^sitemap:\s*(\S+)\s*$/gim)){let location=match[1];if(!location)continue;let candidate=normalizeUrl(location,robotsUrl,{includeQuery:!0});if(candidate&&isSameOrigin(candidate,origin))return candidate}}else await response.body?.cancel()}}catch{}for(let path of["/sitemap.xml","/sitemap.xml.gz","/sitemap_index.xml"]){let candidate=new URL(path,origin).href;if(await isSitemapResponse(candidate,{...options,siteOrigin:origin}))return candidate}return null}async function loadSitemapUrls(inputUrl,options){let sitemapUrl=normalizeUrl(inputUrl,void 0,{includeQuery:!0});if(!sitemapUrl)throw new Error(`invalid sitemap URL: ${inputUrl}`);let sitemapOrigin=new URL(sitemapUrl).origin,sitemapQueue=[sitemapUrl],visitedSitemaps=new Set,pageUrls=[],pageSet=new Set,limit=options.maxUrls??DEFAULT_SITEMAP_LIMIT,truncated=!1;for(;sitemapQueue.length>0&&visitedSitemaps.size<MAX_SITEMAPS&&pageUrls.length<limit;){let currentUrl=sitemapQueue.shift();if(visitedSitemaps.has(currentUrl))continue;visitedSitemaps.add(currentUrl);let parsed=parseSitemap(await fetchSitemap(currentUrl,options),currentUrl);if(parsed.kind==="index"){for(let location of parsed.locations){let child=normalizeUrl(location,currentUrl,{includeQuery:!0});child&&isSameOrigin(child,sitemapOrigin)&&!visitedSitemaps.has(child)&&!sitemapQueue.includes(child)&&sitemapQueue.push(child)}sitemapQueue.sort();continue}for(let location of parsed.locations){let pageUrl=normalizeUrl(location,currentUrl,{includeQuery:options.includeQuery??!1});if(!(!pageUrl||pageSet.has(pageUrl)||!isSameOrigin(pageUrl,options.siteOrigin)||!isCrawlableUrl(pageUrl))&&(pageSet.add(pageUrl),pageUrls.push(pageUrl),pageUrls.length>=limit)){truncated=!0;break}}}return(sitemapQueue.length>0||visitedSitemaps.size>=MAX_SITEMAPS)&&(truncated=!0),{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={}){let config2=resolveConfig(configInput),startUrl=normalizeUrl(config2.url,void 0,{includeQuery:config2.includeQuery});if(!startUrl)throw new Error(`invalid start URL: ${config2.url}`);let origin=new URL(startUrl).origin,fetch2=options.fetch??globalThis.fetch,requestGate=createPerOriginRequestGate(config2.delay),logger=options.logger??NOOP_LOGGER;await emit(options,{type:"plan-start",url:startUrl});let robots=await fetchRobots(startUrl,{userAgent:DEFAULT_USER_AGENT,timeout:config2.timeout,maxRedirects:config2.maxRedirects,retries:2,fetch:fetch2,signal:options.signal,requestGate,onEvent:options.onEvent,logger});await emit(options,{type:"robots",robots});let sitemapUrl=null;config2.sitemap==="auto"?sitemapUrl=await discoverSitemapUrl(startUrl,{timeout:config2.timeout,maxRedirects:config2.maxRedirects,userAgent:DEFAULT_USER_AGENT,fetch:fetch2,signal:options.signal,requestGate,onEvent:options.onEvent,robotsBody:robots.body}):config2.sitemap!=="none"&&(sitemapUrl=config2.sitemap);let sitemap=null;if(sitemapUrl)try{sitemap=await loadSitemapUrls(sitemapUrl,{siteOrigin:origin,includeQuery:config2.includeQuery,maxUrls:5e4,timeout:config2.timeout,maxRedirects:config2.maxRedirects,retries:2,userAgent:DEFAULT_USER_AGENT,fetch:fetch2,signal:options.signal,requestGate,onEvent:options.onEvent})}catch(error61){sitemap={url:sitemapUrl,urls:[],sitemapCount:0,truncated:!1,error:error61 instanceof Error?error61.message:String(error61)},logger.warn(`Could not load sitemap ${sitemapUrl}: ${sitemap.error}`)}let candidateUrls=sitemap?[...new Set([startUrl,...sitemap.urls])].sort((left,right)=>left===startUrl?-1:right===startUrl?1:left.localeCompare(right)):[startUrl],candidateCount=sitemap?candidateUrls.length:null;return await emit(options,{type:"sitemap",sitemap,candidateCount}),{planVersion:1,config:config2,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]),REPLACEMENT_CHARACTER="\uFFFD",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=65536,Preprocessor=class{constructor(handler){this.handler=handler,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=DEFAULT_BUFFER_WATERLINE,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(code,cpOffset){let{line,col,offset}=this,startCol=col+cpOffset,startOffset=offset+cpOffset;return{code,startLine:line,endLine:line,startCol,endCol:startCol,startOffset,endOffset:startOffset}}_err(code){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){let nextCp=this.html.charCodeAt(this.pos+1);if(isSurrogatePair(nextCp))return this.pos++,this._addGap(),getSurrogatePairCodePoint(cp,nextCp)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,CODE_POINTS.EOF;return this._err(ERR.surrogateInInputStream),cp}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){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){this.html.length>0?this.html+=chunk:this.html=chunk,this.endOfChunkHit=!1,this.lastChunkWritten=isLastChunk}insertHtmlAtCurrentPos(chunk){this.html=this.html.substring(0,this.pos+1)+chunk+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(pattern,caseSensitive){if(this.pos+pattern.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(caseSensitive)return this.html.startsWith(pattern,this.pos);for(let i=0;i<pattern.length;i++)if((this.html.charCodeAt(this.pos+i)|32)!==pattern.charCodeAt(i))return!1;return!0}peek(offset){let pos=this.pos+offset;if(pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,CODE_POINTS.EOF;let code=this.html.charCodeAt(pos);return code===CODE_POINTS.CARRIAGE_RETURN?CODE_POINTS.LINE_FEED:code}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,CODE_POINTS.EOF;let cp=this.html.charCodeAt(this.pos);return cp===CODE_POINTS.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,CODE_POINTS.LINE_FEED):cp===CODE_POINTS.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,isSurrogate(cp)&&(cp=this._processSurrogate(cp)),this.handler.onParseError===null||cp>31&&cp<127||cp===CODE_POINTS.LINE_FEED||cp===CODE_POINTS.CARRIAGE_RETURN||cp>159&&cp<64976||this._checkForProblematicCharacters(cp),cp)}_checkForProblematicCharacters(cp){isControlCodePoint(cp)?this._err(ERR.controlCharacterInInputStream):isUndefinedCodePoint(cp)&&this._err(ERR.noncharacterInInputStream)}retreat(count){for(this.pos-=count;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}};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){return codePoint>=55296&&codePoint<=57343||codePoint>1114111?65533:decodeMap.get(codePoint)??codePoint}function decodeBase64(input2){let binary=atob(input2),evenLength=binary.length&-2,out=new Uint16Array(evenLength/2);for(let index=0,outIndex=0;index<evenLength;index+=2){let lo=binary.charCodeAt(index),hi=binary.charCodeAt(index+1);out[outIndex++]=lo|hi<<8}return out}var htmlDecodeTree=decodeBase64("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZ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hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var BinTrieFlags;(function(BinTrieFlags2){BinTrieFlags2[BinTrieFlags2.VALUE_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(input2,offset){switch(this.state){case EntityDecoderState.EntityStart:return input2.charCodeAt(offset)===CharCodes.NUM?(this.state=EntityDecoderState.NumericStart,this.consumed+=1,this.stateNumericStart(input2,offset+1)):(this.state=EntityDecoderState.NamedEntity,this.stateNamedEntity(input2,offset));case EntityDecoderState.NumericStart:return this.stateNumericStart(input2,offset);case EntityDecoderState.NumericDecimal:return this.stateNumericDecimal(input2,offset);case EntityDecoderState.NumericHex:return this.stateNumericHex(input2,offset);case EntityDecoderState.NamedEntity:return this.stateNamedEntity(input2,offset)}}stateNumericStart(input2,offset){return offset>=input2.length?-1:(input2.charCodeAt(offset)|TO_LOWER_BIT)===CharCodes.LOWER_X?(this.state=EntityDecoderState.NumericHex,this.consumed+=1,this.stateNumericHex(input2,offset+1)):(this.state=EntityDecoderState.NumericDecimal,this.stateNumericDecimal(input2,offset))}stateNumericHex(input2,offset){for(;offset<input2.length;){let char=input2.charCodeAt(offset);if(isNumber(char)||isHexadecimalCharacter(char)){let 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(input2,offset){for(;offset<input2.length;){let char=input2.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)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(lastCp===CharCodes.SEMI)this.consumed+=1;else if(this.decodeMode===DecodingMode.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(lastCp!==CharCodes.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(input2,offset){let{decodeTree}=this,current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14;for(;offset<input2.length;){if(valueLength===0&&(current&BinTrieFlags.FLAG13)!==0){let runLength=(current&BinTrieFlags.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let firstChar=current&BinTrieFlags.JUMP_TABLE;if(input2.charCodeAt(offset)!==firstChar)return this.result===0?0:this.emitNotTerminatedNamedEntity();offset++,this.excess++,this.runConsumed++}for(;this.runConsumed<runLength;){if(offset>=input2.length)return-1;let charIndexInPacked=this.runConsumed-1,packedWord=decodeTree[this.treeIndex+1+(charIndexInPacked>>1)],expectedChar=charIndexInPacked%2===0?packedWord&255:packedWord>>8&255;if(input2.charCodeAt(offset)!==expectedChar)return this.runConsumed=0,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>=input2.length)break;let char=input2.charCodeAt(offset);if(char===CharCodes.SEMI&&valueLength!==0&&(current&BinTrieFlags.FLAG13)!==0)return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess);if(this.treeIndex=determineBranch(decodeTree,current,this.treeIndex+Math.max(1,valueLength),char),this.treeIndex<0)return this.result===0||this.decodeMode===DecodingMode.Attribute&&(valueLength===0||isEntityInAttributeInvalidEnd(char))?0:this.emitNotTerminatedNamedEntity();if(current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14,valueLength!==0){if(char===CharCodes.SEMI)return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess);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(){let{result,decodeTree}=this,valueLength=(decodeTree[result]&BinTrieFlags.VALUE_LENGTH)>>14;return this.emitNamedEntityData(result,valueLength,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(result,valueLength,consumed){let{decodeTree}=this;return this.emitCodePoint(valueLength===1?decodeTree[result]&~(BinTrieFlags.VALUE_LENGTH|BinTrieFlags.FLAG13):decodeTree[result+1],consumed),valueLength===3&&this.emitCodePoint(decodeTree[result+2],consumed),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:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case EntityDecoderState.EntityStart:return 0}}};function determineBranch(decodeTree,current,nodeIndex,char){let branchCount=(current&BinTrieFlags.BRANCH_LENGTH)>>7,jumpOffset=current&BinTrieFlags.JUMP_TABLE;if(branchCount===0)return jumpOffset!==0&&char===jumpOffset?nodeIndex:-1;if(jumpOffset){let value=char-jumpOffset;return value<0||value>=branchCount?-1:decodeTree[nodeIndex+value]-1}let packedKeySlots=branchCount+1>>1,lo=0,hi=branchCount-1;for(;lo<=hi;){let mid=lo+hi>>>1,slot=mid>>1,midKey=decodeTree[nodeIndex+slot]>>(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 _a3;return(_a3=TAG_NAME_TO_ID.get(tagName))!==null&&_a3!==void 0?_a3:TAG_ID.UNKNOWN}var $=TAG_ID,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},NUMBERED_HEADERS=new Set([$.H1,$.H2,$.H3,$.H4,$.H5,$.H6]),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){return code===CODE_POINTS.NULL?ERR.nullCharacterReference:code>1114111?ERR.characterReferenceOutsideUnicodeRange:isSurrogate(code)?ERR.surrogateCharacterReference:isUndefinedCodePoint(code)?ERR.noncharacterCharacterReference:isControlCodePoint(code)||code===CODE_POINTS.CARRIAGE_RETURN?ERR.controlCharacterReference:null}var Tokenizer=class{constructor(options,handler){this.options=options,this.handler=handler,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,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=>{let error61=getErrorForNumericCharacterReference(code);error61&&this._err(error61,1)}}:void 0)}_err(code,cpOffset=0){var _a3,_b;(_b=(_a3=this.handler).onParseError)===null||_b===void 0||_b.call(_a3,this.preprocessor.getError(code,cpOffset))}getCurrentLocation(offset){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-offset,startOffset:this.preprocessor.offset-offset,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let cp=this._consume();this._ensureHibernation()||this._callState(cp)}this.inLoop=!1}}pause(){this.paused=!0}resume(writeCallback){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||writeCallback?.())}write(chunk,isLastChunk,writeCallback){this.active=!0,this.preprocessor.write(chunk,isLastChunk),this._runParsingLoop(),this.paused||writeCallback?.()}insertHtmlAtCurrentPos(chunk){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(chunk),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(count){this.consumedAfterSnapshot+=count;for(let i=0;i<count;i++)this.preprocessor.advance()}_consumeSequenceIfMatch(pattern,caseSensitive){return this.preprocessor.startsWith(pattern,caseSensitive)?(this._advanceBy(pattern.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:TokenType.START_TAG,tagName:"",tagID:TAG_ID.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:TokenType.END_TAG,tagName:"",tagID:TAG_ID.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,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:!1,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 _a3,_b;let token=this.currentToken;if(getTokenAttr(token,this.currentAttr.name)===null){if(token.attrs.push(this.currentAttr),token.location&&this.currentLocation){let attrLocations=(_a3=(_b=token.location).attrs)!==null&&_a3!==void 0?_a3:_b.attrs=Object.create(null);attrLocations[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(ERR.duplicateAttribute)}_leaveAttrValue(){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,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(){let ct=this.currentToken;this.prepareToken(ct),ct.tagID=getTagID(ct.tagName),ct.type===TokenType.START_TAG?(this.lastStartTagName=ct.tagName,this.handler.onStartTag(ct)):(ct.attrs.length>0&&this._err(ERR.endTagWithAttributes),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){switch(nextLocation&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=nextLocation.startLine,this.currentCharacterToken.location.endCol=nextLocation.startCol,this.currentCharacterToken.location.endOffset=nextLocation.startOffset),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(){let location=this.getCurrentLocation(0);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=!1}_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){let 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){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(cp):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){let 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){cp===CODE_POINTS.SOLIDUS?this.state=State.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=State.RCDATA,this._stateRcdata(cp))}_stateRcdataEndTagOpen(cp){isAsciiLetter(cp)?(this.state=State.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(cp)):(this._emitChars("</"),this.state=State.RCDATA,this._stateRcdata(cp))}handleSpecialEndTag(_cp){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();let token=this.currentToken;switch(token.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case CODE_POINTS.SPACE:case CODE_POINTS.LINE_FEED:case CODE_POINTS.TABULATION:case CODE_POINTS.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=State.BEFORE_ATTRIBUTE_NAME,!1;case CODE_POINTS.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=State.SELF_CLOSING_START_TAG,!1;case CODE_POINTS.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=State.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(cp){this.handleSpecialEndTag(cp)&&(this._emitChars("</"),this.state=State.RCDATA,this._stateRcdata(cp))}_stateRawtextLessThanSign(cp){cp===CODE_POINTS.SOLIDUS?this.state=State.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=State.RAWTEXT,this._stateRawtext(cp))}_stateRawtextEndTagOpen(cp){isAsciiLetter(cp)?(this.state=State.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(cp)):(this._emitChars("</"),this.state=State.RAWTEXT,this._stateRawtext(cp))}_stateRawtextEndTagName(cp){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){isAsciiLetter(cp)?(this.state=State.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(cp)):(this._emitChars("</"),this.state=State.SCRIPT_DATA,this._stateScriptData(cp))}_stateScriptDataEndTagName(cp){this.handleSpecialEndTag(cp)&&(this._emitChars("</"),this.state=State.SCRIPT_DATA,this._stateScriptData(cp))}_stateScriptDataEscapeStart(cp){cp===CODE_POINTS.HYPHEN_MINUS?(this.state=State.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=State.SCRIPT_DATA,this._stateScriptData(cp))}_stateScriptDataEscapeStartDash(cp){cp===CODE_POINTS.HYPHEN_MINUS?(this.state=State.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(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){cp===CODE_POINTS.SOLIDUS?this.state=State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:isAsciiLetter(cp)?(this._emitChars("<"),this.state=State.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(cp)):(this._emitChars("<"),this.state=State.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(cp))}_stateScriptDataEscapedEndTagOpen(cp){isAsciiLetter(cp)?(this.state=State.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(cp)):(this._emitChars("</"),this.state=State.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(cp))}_stateScriptDataEscapedEndTagName(cp){this.handleSpecialEndTag(cp)&&(this._emitChars("</"),this.state=State.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(cp))}_stateScriptDataDoubleEscapeStart(cp){if(this.preprocessor.startsWith(SEQUENCES.SCRIPT,!1)&&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 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){cp===CODE_POINTS.SOLIDUS?(this.state=State.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=State.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(cp))}_stateScriptDataDoubleEscapeEnd(cp){if(this.preprocessor.startsWith(SEQUENCES.SCRIPT,!1)&&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 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:{let token=this.currentToken;token.selfClosing=!0,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){let 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){this._consumeSequenceIfMatch(SEQUENCES.DASH_DASH,!0)?(this._createCommentToken(SEQUENCES.DASH_DASH.length+1),this.state=State.COMMENT_START):this._consumeSequenceIfMatch(SEQUENCES.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(SEQUENCES.DOCTYPE.length+1),this.state=State.DOCTYPE):this._consumeSequenceIfMatch(SEQUENCES.CDATA_START,!0)?this.inForeignNode?this.state=State.CDATA_SECTION:(this._err(ERR.cdataInHtmlContent),this._createCommentToken(SEQUENCES.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=State.BOGUS_COMMENT):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;let token=this.currentToken;this.emitCurrentComment(token);break}default:this.state=State.COMMENT,this._stateComment(cp)}}_stateCommentStartDash(cp){let 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){let 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){let 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){cp===CODE_POINTS.HYPHEN_MINUS?this.state=State.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=State.COMMENT,this._stateComment(cp))}_stateCommentLessThanSignBangDash(cp){cp===CODE_POINTS.HYPHEN_MINUS?this.state=State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=State.COMMENT_END_DASH,this._stateCommentEndDash(cp))}_stateCommentLessThanSignBangDashDash(cp){cp!==CODE_POINTS.GREATER_THAN_SIGN&&cp!==CODE_POINTS.EOF&&this._err(ERR.nestedComment),this.state=State.COMMENT_END,this._stateCommentEnd(cp)}_stateCommentEndDash(cp){let 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){let 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){let 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);let token=this.currentToken;token.forceQuirks=!0,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);let token=this.currentToken;token.forceQuirks=!0,this.emitCurrentDoctype(token),this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),this._createDoctypeToken(null);let token=this.currentToken;token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(cp)),this.state=State.DOCTYPE_NAME}}_stateDoctypeName(cp){let 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=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:token.name+=String.fromCodePoint(isAsciiUpper(cp)?toAsciiLower(cp):cp)}}_stateAfterDoctypeName(cp){let 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=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(SEQUENCES.PUBLIC,!1)?this.state=State.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(SEQUENCES.SYSTEM,!1)?this.state=State.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(ERR.invalidCharacterSequenceAfterDoctypeName),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp))}}_stateAfterDoctypePublicKeyword(cp){let 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=!0,this.state=State.DATA,this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateBeforeDoctypePublicIdentifier(cp){let 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=!0,this.state=State.DATA,this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateDoctypePublicIdentifierDoubleQuoted(cp){let 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=!0,this.emitCurrentDoctype(token),this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:token.publicId+=String.fromCodePoint(cp)}}_stateDoctypePublicIdentifierSingleQuoted(cp){let 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=!0,this.emitCurrentDoctype(token),this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:token.publicId+=String.fromCodePoint(cp)}}_stateAfterDoctypePublicIdentifier(cp){let 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=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateBetweenDoctypePublicAndSystemIdentifiers(cp){let 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=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateAfterDoctypeSystemKeyword(cp){let 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=!0,this.state=State.DATA,this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateBeforeDoctypeSystemIdentifier(cp){let 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=!0,this.state=State.DATA,this.emitCurrentDoctype(token);break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier),token.forceQuirks=!0,this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateDoctypeSystemIdentifierDoubleQuoted(cp){let 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=!0,this.emitCurrentDoctype(token),this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:token.systemId+=String.fromCodePoint(cp)}}_stateDoctypeSystemIdentifierSingleQuoted(cp){let 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=!0,this.emitCurrentDoctype(token),this.state=State.DATA;break}case CODE_POINTS.EOF:{this._err(ERR.eofInDoctype),token.forceQuirks=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:token.systemId+=String.fromCodePoint(cp)}}_stateAfterDoctypeSystemIdentifier(cp){let 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=!0,this.emitCurrentDoctype(token),this._emitEOFToken();break}default:this._err(ERR.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=State.BOGUS_DOCTYPE,this._stateBogusDoctype(cp)}}_stateBogusDoctype(cp){let 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){cp===CODE_POINTS.RIGHT_SQUARE_BRACKET?this.state=State.CDATA_SECTION_END:(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=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}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):this.state=this.returnState}_stateAmbiguousAmpersand(cp){isAsciiAlphaNumeric2(cp)?this._flushCodePointConsumedAsCharacterReference(cp):(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]),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]),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]),SCOPING_ELEMENTS_HTML_LIST=new Set([...SCOPING_ELEMENTS_HTML,TAG_ID.OL,TAG_ID.UL]),SCOPING_ELEMENTS_HTML_BUTTON=new Set([...SCOPING_ELEMENTS_HTML,TAG_ID.BUTTON]),SCOPING_ELEMENTS_MATHML=new Set([TAG_ID.ANNOTATION_XML,TAG_ID.MI,TAG_ID.MN,TAG_ID.MO,TAG_ID.MS,TAG_ID.MTEXT]),SCOPING_ELEMENTS_SVG=new Set([TAG_ID.DESC,TAG_ID.FOREIGN_OBJECT,TAG_ID.TITLE]),TABLE_ROW_CONTEXT=new Set([TAG_ID.TR,TAG_ID.TEMPLATE,TAG_ID.HTML]),TABLE_BODY_CONTEXT=new Set([TAG_ID.TBODY,TAG_ID.TFOOT,TAG_ID.THEAD,TAG_ID.TEMPLATE,TAG_ID.HTML]),TABLE_CONTEXT=new Set([TAG_ID.TABLE,TAG_ID.TEMPLATE,TAG_ID.HTML]),TABLE_CELLS=new Set([TAG_ID.TD,TAG_ID.TH]),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,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(element,tagID,!0)}pop(){let popped=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(popped,!0)}replace(oldElement,newElement){let idx=this._indexOf(oldElement);this.items[idx]=newElement,idx===this.stackTop&&(this.current=newElement)}insertAfter(referenceElement,newElement,newElementID){let insertionIdx=this._indexOf(referenceElement)+1;this.items.splice(insertionIdx,0,newElement),this.tagIDs.splice(insertionIdx,0,newElementID),this.stackTop++,insertionIdx===this.stackTop&&this._updateCurrentElement(),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){for(;this.stackTop>=idx;){let popped=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(popped,this.stackTop<idx)}}popUntilElementPopped(element){let idx=this._indexOf(element);this.shortenToLength(Math.max(idx,0))}popUntilPopped(tagNames,targetNS){let 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){let 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){let idx=this._indexOf(element);idx>=0&&(idx===this.stackTop?this.pop():(this.items.splice(idx,1),this.tagIDs.splice(idx,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(element,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===TAG_ID.BODY?this.items[1]:null}contains(element){return this._indexOf(element)>-1}getCommonAncestor(element){let 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--){let tn=this.tagIDs[i];switch(this.treeAdapter.getNamespaceURI(this.items[i])){case NS.HTML:{if(tn===tagName)return!0;if(htmlScope.has(tn))return!1;break}case NS.SVG:{if(SCOPING_ELEMENTS_SVG.has(tn))return!1;break}case NS.MATHML:{if(SCOPING_ELEMENTS_MATHML.has(tn))return!1;break}}}return!0}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--){let tn=this.tagIDs[i];switch(this.treeAdapter.getNamespaceURI(this.items[i])){case NS.HTML:{if(NUMBERED_HEADERS.has(tn))return!0;if(SCOPING_ELEMENTS_HTML.has(tn))return!1;break}case NS.SVG:{if(SCOPING_ELEMENTS_SVG.has(tn))return!1;break}case NS.MATHML:{if(SCOPING_ELEMENTS_MATHML.has(tn))return!1;break}}}return!0}hasInTableScope(tagName){for(let i=this.stackTop;i>=0;i--)if(this.treeAdapter.getNamespaceURI(this.items[i])===NS.HTML)switch(this.tagIDs[i]){case tagName:return!0;case TAG_ID.TABLE:case TAG_ID.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let i=this.stackTop;i>=0;i--)if(this.treeAdapter.getNamespaceURI(this.items[i])===NS.HTML)switch(this.tagIDs[i]){case TAG_ID.TBODY:case TAG_ID.THEAD:case TAG_ID.TFOOT:return!0;case TAG_ID.TABLE:case TAG_ID.HTML:return!1}return!0}hasInSelectScope(tagName){for(let i=this.stackTop;i>=0;i--)if(this.treeAdapter.getNamespaceURI(this.items[i])===NS.HTML)switch(this.tagIDs[i]){case tagName:return!0;case TAG_ID.OPTION:case TAG_ID.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(exclusionId){for(;this.currentTagId!==void 0&&this.currentTagId!==exclusionId&&IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId);)this.pop()}};var EntryType;(function(EntryType2){EntryType2[EntryType2.Marker=0]="Marker",EntryType2[EntryType2.Element=1]="Element"})(EntryType||(EntryType={}));var MARKER={type:EntryType.Marker},FormattingElementList=class{constructor(treeAdapter){this.treeAdapter=treeAdapter,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(newElement,neAttrs){let candidates=[],neAttrsLength=neAttrs.length,neTagName=this.treeAdapter.getTagName(newElement),neNamespaceURI=this.treeAdapter.getNamespaceURI(newElement);for(let i=0;i<this.entries.length;i++){let entry=this.entries[i];if(entry.type===EntryType.Marker)break;let{element}=entry;if(this.treeAdapter.getTagName(element)===neTagName&&this.treeAdapter.getNamespaceURI(element)===neNamespaceURI){let elementAttrs=this.treeAdapter.getAttrList(element);elementAttrs.length===neAttrsLength&&candidates.push({idx:i,attrs:elementAttrs})}}return candidates}_ensureNoahArkCondition(newElement){if(this.entries.length<3)return;let neAttrs=this.treeAdapter.getAttrList(newElement),candidates=this._getNoahArkConditionCandidates(newElement,neAttrs);if(candidates.length<3)return;let neAttrsMap=new Map(neAttrs.map(neAttr=>[neAttr.name,neAttr.value])),validCandidates=0;for(let i=0;i<candidates.length;i++){let candidate=candidates[i];candidate.attrs.every(cAttr=>neAttrsMap.get(cAttr.name)===cAttr.value)&&(validCandidates+=1,validCandidates>=3&&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){let bookmarkIdx=this.entries.indexOf(this.bookmark);this.entries.splice(bookmarkIdx,0,{type:EntryType.Element,element,token})}removeEntry(entry){let entryIndex=this.entries.indexOf(entry);entryIndex!==-1&&this.entries.splice(entryIndex,1)}clearToLastMarker(){let markerIdx=this.entries.indexOf(MARKER);markerIdx===-1?this.entries.length=0:this.entries.splice(0,markerIdx+1)}getElementEntryInScopeWithTagName(tagName){let 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){let 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){let doctypeNode=document.childNodes.find(node2=>node2.nodeName==="#documentType");if(doctypeNode)doctypeNode.name=name,doctypeNode.publicId=publicId,doctypeNode.systemId=systemId;else{let node2={nodeName:"#documentType",name,publicId,systemId,parentNode:null};defaultTreeAdapter.appendChild(document,node2)}},setDocumentMode(document,mode){document.mode=mode},getDocumentMode(document){return document.mode},detachNode(node2){if(node2.parentNode){let idx=node2.parentNode.childNodes.indexOf(node2);node2.parentNode.childNodes.splice(idx,1),node2.parentNode=null}},insertText(parentNode,text){if(parentNode.childNodes.length>0){let 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){let prevNode=parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode)-1];prevNode&&defaultTreeAdapter.isTextNode(prevNode)?prevNode.value+=text:defaultTreeAdapter.insertBefore(parentNode,defaultTreeAdapter.createTextNode(text),referenceNode)},adoptAttributes(recipient,attrs){let recipientAttrsMap=new Set(recipient.attrs.map(attr=>attr.name));for(let j=0;j<attrs.length;j++)recipientAttrsMap.has(attrs[j].name)||recipient.attrs.push(attrs[j])},getFirstChild(node2){return node2.childNodes[0]},getChildNodes(node2){return node2.childNodes},getParentNode(node2){return node2.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(node2){return node2.nodeName==="#text"},isCommentNode(node2){return node2.nodeName==="#comment"},isDocumentTypeNode(node2){return node2.nodeName==="#documentType"},isElementNode(node2){return Object.prototype.hasOwnProperty.call(node2,"tagName")},setNodeSourceCodeLocation(node2,location){node2.sourceCodeLocation=location},getNodeSourceCodeLocation(node2){return node2.sourceCodeLocation},updateNodeSourceCodeLocation(node2,endLocation){node2.sourceCodeLocation={...node2.sourceCodeLocation,...endLocation}}};var VALID_DOCTYPE_NAME="html",VALID_SYSTEM_ID="about:legacy-compat",QUIRKS_MODE_SYSTEM_ID="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",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//"],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//"],QUIRKS_MODE_PUBLIC_IDS=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),LIMITED_QUIRKS_PUBLIC_ID_PREFIXES=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],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;let{systemId}=token;if(systemId&&systemId.toLowerCase()===QUIRKS_MODE_SYSTEM_ID)return DOCUMENT_MODE.QUIRKS;let{publicId}=token;if(publicId!==null){if(publicId=publicId.toLowerCase(),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;if(prefixes=systemId===null?LIMITED_QUIRKS_PUBLIC_ID_PREFIXES:LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES,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"},DEFINITION_URL_ATTR="definitionurl",ADJUSTED_DEFINITION_URL_ATTR="definitionURL",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])),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}]]),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])),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){let tn=startTagToken.tagID;return tn===TAG_ID.FONT&&startTagToken.attrs.some(({name})=>name===ATTRS.COLOR||name===ATTRS.SIZE||name===ATTRS.FACE)||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++){let adjustedAttrName=SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);adjustedAttrName!=null&&(token.attrs[i].name=adjustedAttrName)}}function adjustTokenXMLAttrs(token){for(let i=0;i<token.attrs.length;i++){let adjustedAttrEntry=XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);adjustedAttrEntry&&(token.attrs[i].prefix=adjustedAttrEntry.prefix,token.attrs[i].name=adjustedAttrEntry.name,token.attrs[i].namespace=adjustedAttrEntry.namespace)}}function adjustTokenSVGTagName(token){let adjustedTagName=SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);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){let 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",AA_OUTER_LOOP_ITER=8,AA_INNER_LOOP_ITER=3,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},TABLE_STRUCTURE_TAGS=new Set([TAG_ID.TABLE,TAG_ID.TBODY,TAG_ID.TFOOT,TAG_ID.THEAD,TAG_ID.TR]),defaultParserOptions={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:defaultTreeAdapter,onParseError:null},Parser=class{constructor(options,document,fragmentContext=null,scriptHandler=null){this.fragmentContext=fragmentContext,this.scriptHandler=scriptHandler,this.currentToken=null,this.stopped=!1,this.insertionMode=InsertionMode.INITIAL,this.originalInsertionMode=InsertionMode.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...defaultParserOptions,...options},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=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??this.document,this.fragmentContextID),this.openElements=new OpenElementStack(this.document,this.treeAdapter,this)}static parse(html,options){let parser2=new this(options);return parser2.tokenizer.write(html,!0),parser2.document}static getFragmentParser(fragmentContext,options){let opts={...defaultParserOptions,...options};fragmentContext??(fragmentContext=opts.treeAdapter.createElement(TAG_NAMES.TEMPLATE,NS.HTML,[]));let documentMock=opts.treeAdapter.createElement("documentmock",NS.HTML,[]),parser2=new this(opts,documentMock,fragmentContext);return parser2.fragmentContextID===TAG_ID.TEMPLATE&&parser2.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE),parser2._initTokenizerForFragmentParsing(),parser2._insertFakeRootElement(),parser2._resetInsertionMode(),parser2._findFormInFragmentContext(),parser2}getFragment(){let rootElement=this.treeAdapter.getFirstChild(this.document),fragment=this.treeAdapter.createDocumentFragment();return this._adoptNodes(rootElement,fragment),fragment}_err(token,code,beforeToken){var _a3;if(!this.onParseError)return;let loc=(_a3=token.location)!==null&&_a3!==void 0?_a3:BASE_LOC,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(node2,tid,isTop){var _a3,_b;(_b=(_a3=this.treeAdapter).onItemPush)===null||_b===void 0||_b.call(_a3,node2),isTop&&this.openElements.stackTop>0&&this._setContextModes(node2,tid)}onItemPop(node2,isTop){var _a3,_b;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(node2,this.currentToken),(_b=(_a3=this.treeAdapter).onItemPop)===null||_b===void 0||_b.call(_a3,node2,this.openElements.current),isTop){let current,currentTagId;this.openElements.stackTop===0&&this.fragmentContext?(current=this.fragmentContext,currentTagId=this.fragmentContextID):{current,currentTagId}=this.openElements,this._setContextModes(current,currentTagId)}}_setContextModes(current,tid){let 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 node2=this.fragmentContext;for(;node2;){if(this.treeAdapter.getTagName(node2)===TAG_NAMES.FORM){this.formElement=node2;break}node2=this.treeAdapter.getParentNode(node2)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==NS.HTML))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){let name=token.name||"",publicId=token.publicId||"",systemId=token.systemId||"";if(this.treeAdapter.setDocumentType(this.document,name,publicId,systemId),token.location){let docTypeNode=this.treeAdapter.getChildNodes(this.document).find(node2=>this.treeAdapter.isDocumentTypeNode(node2));docTypeNode&&this.treeAdapter.setNodeSourceCodeLocation(docTypeNode,token.location)}}_attachElementToTree(element,location){if(this.options.sourceCodeLocationInfo){let loc=location&&{...location,startTag:location};this.treeAdapter.setNodeSourceCodeLocation(element,loc)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(element);else{let parent=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(parent??this.document,element)}}_appendElement(token,namespaceURI){let element=this.treeAdapter.createElement(token.tagName,namespaceURI,token.attrs);this._attachElementToTree(element,token.location)}_insertElement(token,namespaceURI){let element=this.treeAdapter.createElement(token.tagName,namespaceURI,token.attrs);this._attachElementToTree(element,token.location),this.openElements.push(element,token.tagID)}_insertFakeElement(tagName,tagID){let element=this.treeAdapter.createElement(tagName,NS.HTML,[]);this._attachElementToTree(element,null),this.openElements.push(element,tagID)}_insertTemplate(token){let tmpl=this.treeAdapter.createElement(token.tagName,NS.HTML,token.attrs),content=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(tmpl,content),this._attachElementToTree(tmpl,token.location),this.openElements.push(tmpl,token.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(content,null)}_insertFakeRootElement(){let element=this.treeAdapter.createElement(TAG_NAMES.HTML,NS.HTML,[]);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){let commentNode=this.treeAdapter.createCommentNode(token.data);this.treeAdapter.appendChild(parent,commentNode),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(commentNode,token.location)}_insertCharacters(token){let parent,beforeElement;if(this._shouldFosterParentOnInsertion()?({parent,beforeElement}=this._findFosterParentingLocation(),beforeElement?this.treeAdapter.insertTextBefore(parent,token.chars,beforeElement):this.treeAdapter.insertText(parent,token.chars)):(parent=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(parent,token.chars)),!token.location)return;let siblings=this.treeAdapter.getChildNodes(parent),textNodeIdx=beforeElement?siblings.lastIndexOf(beforeElement):siblings.length,textNode=siblings[textNodeIdx-1];if(this.treeAdapter.getNodeSourceCodeLocation(textNode)){let{endLine,endCol,endOffset}=token.location;this.treeAdapter.updateNodeSourceCodeLocation(textNode,{endLine,endCol,endOffset})}else 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){let ctLoc=closingToken.location,tn=this.treeAdapter.getTagName(element),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!1;let current,currentTagId;return this.openElements.stackTop===0&&this.fragmentContext?(current=this.fragmentContext,currentTagId=this.fragmentContextID):{current,currentTagId}=this.openElements,token.tagID===TAG_ID.SVG&&this.treeAdapter.getTagName(current)===TAG_NAMES.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(current)===NS.MATHML?!1: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){let ns=this.treeAdapter.getNamespaceURI(element),attrs=this.treeAdapter.getAttrList(element);return isIntegrationPoint(tid,ns,attrs,foreignNS)}_reconstructActiveFormattingElements(){let listLength=this.activeFormattingElements.entries.length;if(listLength){let endIndex=this.activeFormattingElements.entries.findIndex(entry=>entry.type===EntryType.Marker||this.openElements.contains(entry.element)),unopenIdx=endIndex===-1?listLength-1:endIndex-1;for(let i=unopenIdx;i>=0;i--){let 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--){let tn=this.openElements.tagIDs[i];if(tn===TAG_ID.TEMPLATE)break;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--){let 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:{let parent=this.treeAdapter.getParentNode(openElement);return parent?{parent,beforeElement:openElement}:{parent:this.openElements.items[i-1],beforeElement:null}}default:}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(element){let location=this._findFosterParentingLocation();location.beforeElement?this.treeAdapter.insertBefore(location.parent,element,location.beforeElement):this.treeAdapter.appendChild(location.parent,element)}_isSpecialElement(element,id){let ns=this.treeAdapter.getNamespaceURI(element);return SPECIAL_ELEMENTS[ns].has(id)}onCharacter(token){if(this.skipNextNewLine=!1,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){if(this.skipNextNewLine=!1,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){if(this.skipNextNewLine=!1,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){switch(this.skipNextNewLine=!1,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=!1,this.currentToken=token,this._processStartTag(token),token.selfClosing&&!token.ackSelfClosing&&this._err(token,ERR.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(token){this.shouldProcessStartTagTokenInForeignContent(token)?startTagInForeignContent(this,token):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=!1,this.currentToken=token,this.currentNotInHTML?endTagInForeignContent(this,token):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=!1,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);return formattingElementEntry?p.openElements.contains(formattingElementEntry.element)?p.openElements.hasInScope(token.tagID)||(formattingElementEntry=null):(p.activeFormattingElements.removeEntry(formattingElementEntry),formattingElementEntry=null):genericEndTagInBody(p,token),formattingElementEntry}function aaObtainFurthestBlock(p,formattingElementEntry){let furthestBlock=null,idx=p.openElements.stackTop;for(;idx>=0;idx--){let element=p.openElements.items[idx];if(element===formattingElementEntry.element)break;p._isSpecialElement(element,p.openElements.tagIDs[idx])&&(furthestBlock=element)}return furthestBlock||(p.openElements.shortenToLength(Math.max(idx,0)),p.activeFormattingElements.removeEntry(formattingElementEntry)),furthestBlock}function aaInnerLoop(p,furthestBlock,formattingElement){let lastElement=furthestBlock,nextElement=p.openElements.getCommonAncestor(furthestBlock);for(let i=0,element=nextElement;element!==formattingElement;i++,element=nextElement){nextElement=p.openElements.getCommonAncestor(element);let elementEntry=p.activeFormattingElements.getElementEntry(element),counterOverflow=elementEntry&&i>=AA_INNER_LOOP_ITER;!elementEntry||counterOverflow?(counterOverflow&&p.activeFormattingElements.removeEntry(elementEntry),p.openElements.remove(element)):(element=aaRecreateElementFromEntry(p,elementEntry),lastElement===furthestBlock&&(p.activeFormattingElements.bookmark=elementEntry),p.treeAdapter.detachNode(lastElement),p.treeAdapter.appendChild(element,lastElement),lastElement=element)}return lastElement}function aaRecreateElementFromEntry(p,elementEntry){let ns=p.treeAdapter.getNamespaceURI(elementEntry.element),newElement=p.treeAdapter.createElement(elementEntry.token.tagName,ns,elementEntry.token.attrs);return p.openElements.replace(elementEntry.element,newElement),elementEntry.element=newElement,newElement}function aaInsertLastNodeInCommonAncestor(p,commonAncestor,lastElement){let tn=p.treeAdapter.getTagName(commonAncestor),tid=getTagID(tn);if(p._isElementCausesFosterParenting(tid))p._fosterParentElement(lastElement);else{let ns=p.treeAdapter.getNamespaceURI(commonAncestor);tid===TAG_ID.TEMPLATE&&ns===NS.HTML&&(commonAncestor=p.treeAdapter.getTemplateContent(commonAncestor)),p.treeAdapter.appendChild(commonAncestor,lastElement)}}function aaReplaceFormattingElement(p,furthestBlock,formattingElementEntry){let ns=p.treeAdapter.getNamespaceURI(formattingElementEntry.element),{token}=formattingElementEntry,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++){let formattingElementEntry=aaObtainFormattingElementEntry(p,token);if(!formattingElementEntry)break;let furthestBlock=aaObtainFurthestBlock(p,formattingElementEntry);if(!furthestBlock)break;p.activeFormattingElements.bookmark=formattingElementEntry;let lastElement=aaInnerLoop(p,furthestBlock,formattingElementEntry.element),commonAncestor=p.openElements.getCommonAncestor(formattingElementEntry.element);p.treeAdapter.detachNode(lastElement),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){if(p.stopped=!0,token.location){let 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){let htmlElement=p.openElements.items[0],htmlLocation=p.treeAdapter.getNodeSourceCodeLocation(htmlElement);if(htmlLocation&&!htmlLocation.endTag&&(p._setEndLocation(htmlElement,token),p.openElements.stackTop>=1)){let bodyElement=p.openElements.items[1],bodyLocation=p.treeAdapter.getNodeSourceCodeLocation(bodyElement);bodyLocation&&!bodyLocation.endTag&&p._setEndLocation(bodyElement,token)}}}}function doctypeInInitialMode(p,token){p._setDocumentType(token);let mode=token.forceQuirks?DOCUMENT_MODE.QUIRKS:getDocumentMode(token);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,!0),p.treeAdapter.setDocumentMode(p.document,DOCUMENT_MODE.QUIRKS),p.insertionMode=InsertionMode.BEFORE_HTML,p._processToken(token)}function startTagBeforeHtml(p,token){token.tagID===TAG_ID.HTML?(p._insertElement(token,NS.HTML),p.insertionMode=InsertionMode.BEFORE_HEAD):tokenBeforeHtml(p,token)}function endTagBeforeHtml(p,token){let tn=token.tagID;(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){let tn=token.tagID;tn===TAG_ID.HEAD||tn===TAG_ID.BODY||tn===TAG_ID.HTML||tn===TAG_ID.BR?tokenBeforeHead(p,token):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=!0;break}case TAG_ID.TITLE:{p._switchToTextParsing(token,TokenizerMode.RCDATA);break}case TAG_ID.NOSCRIPT:{p.options.scriptingEnabled?p._switchToTextParsing(token,TokenizerMode.RAWTEXT):(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=!1,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){p.openElements.tmplCount>0?(p.openElements.generateImpliedEndTagsThoroughly(),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()):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){let 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=!1,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=!1}function htmlStartTagInBody(p,token){p.openElements.tmplCount===0&&p.treeAdapter.adoptAttributes(p.openElements.items[0],token.attrs)}function bodyStartTagInBody(p,token){let bodyElement=p.openElements.tryPeekProperlyNestedBodyElement();bodyElement&&p.openElements.tmplCount===0&&(p.framesetOk=!1,p.treeAdapter.adoptAttributes(bodyElement,token.attrs))}function framesetStartTagInBody(p,token){let bodyElement=p.openElements.tryPeekProperlyNestedBodyElement();p.framesetOk&&bodyElement&&(p.treeAdapter.detachNode(bodyElement),p.openElements.popAllUpToHtmlElement(),p._insertElement(token,NS.HTML),p.insertionMode=InsertionMode.IN_FRAMESET)}function addressStartTagInBody(p,token){p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._insertElement(token,NS.HTML)}function numberedHeaderStartTagInBody(p,token){p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p.openElements.currentTagId!==void 0&&NUMBERED_HEADERS.has(p.openElements.currentTagId)&&p.openElements.pop(),p._insertElement(token,NS.HTML)}function preStartTagInBody(p,token){p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._insertElement(token,NS.HTML),p.skipNextNewLine=!0,p.framesetOk=!1}function formStartTagInBody(p,token){let inTemplate=p.openElements.tmplCount>0;(!p.formElement||inTemplate)&&(p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._insertElement(token,NS.HTML),inTemplate||(p.formElement=p.openElements.current))}function listItemStartTagInBody(p,token){p.framesetOk=!1;let tn=token.tagID;for(let i=p.openElements.stackTop;i>=0;i--){let 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}p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._insertElement(token,NS.HTML)}function plaintextStartTagInBody(p,token){p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._insertElement(token,NS.HTML),p.tokenizer.state=TokenizerMode.PLAINTEXT}function buttonStartTagInBody(p,token){p.openElements.hasInScope(TAG_ID.BUTTON)&&(p.openElements.generateImpliedEndTags(),p.openElements.popUntilTagNamePopped(TAG_ID.BUTTON)),p._reconstructActiveFormattingElements(),p._insertElement(token,NS.HTML),p.framesetOk=!1}function aStartTagInBody(p,token){let activeElementEntry=p.activeFormattingElements.getElementEntryInScopeWithTagName(TAG_NAMES.A);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(),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=!1}function tableStartTagInBody(p,token){p.treeAdapter.getDocumentMode(p.document)!==DOCUMENT_MODE.QUIRKS&&p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._insertElement(token,NS.HTML),p.framesetOk=!1,p.insertionMode=InsertionMode.IN_TABLE}function areaStartTagInBody(p,token){p._reconstructActiveFormattingElements(),p._appendElement(token,NS.HTML),p.framesetOk=!1,token.ackSelfClosing=!0}function isHiddenInput(token){let inputType=getTokenAttr(token,ATTRS.TYPE);return inputType!=null&&inputType.toLowerCase()===HIDDEN_INPUT_TYPE}function inputStartTagInBody(p,token){p._reconstructActiveFormattingElements(),p._appendElement(token,NS.HTML),isHiddenInput(token)||(p.framesetOk=!1),token.ackSelfClosing=!0}function paramStartTagInBody(p,token){p._appendElement(token,NS.HTML),token.ackSelfClosing=!0}function hrStartTagInBody(p,token){p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._appendElement(token,NS.HTML),p.framesetOk=!1,token.ackSelfClosing=!0}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=!0,p.tokenizer.state=TokenizerMode.RCDATA,p.originalInsertionMode=p.insertionMode,p.framesetOk=!1,p.insertionMode=InsertionMode.TEXT}function xmpStartTagInBody(p,token){p.openElements.hasInButtonScope(TAG_ID.P)&&p._closePElement(),p._reconstructActiveFormattingElements(),p.framesetOk=!1,p._switchToTextParsing(token,TokenizerMode.RAWTEXT)}function iframeStartTagInBody(p,token){p.framesetOk=!1,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=!1,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){p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.pop(),p._reconstructActiveFormattingElements(),p._insertElement(token,NS.HTML)}function rbStartTagInBody(p,token){p.openElements.hasInScope(TAG_ID.RUBY)&&p.openElements.generateImpliedEndTags(),p._insertElement(token,NS.HTML)}function rtStartTagInBody(p,token){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),token.selfClosing?p._appendElement(token,NS.MATHML):p._insertElement(token,NS.MATHML),token.ackSelfClosing=!0}function svgStartTagInBody(p,token){p._reconstructActiveFormattingElements(),adjustTokenSVGAttrs(token),adjustTokenXMLAttrs(token),token.selfClosing?p._appendElement(token,NS.SVG):p._insertElement(token,NS.SVG),token.ackSelfClosing=!0}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:{p.options.scriptingEnabled?rawTextStartTagInBody(p,token):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,p.options.sourceCodeLocationInfo)){let bodyElement=p.openElements.tryPeekProperlyNestedBodyElement();bodyElement&&p._setEndLocation(bodyElement,token)}}function htmlEndTagInBody(p,token){p.openElements.hasInScope(TAG_ID.BODY)&&(p.insertionMode=InsertionMode.AFTER_BODY,endTagAfterBody(p,token))}function addressEndTagInBody(p,token){let tn=token.tagID;p.openElements.hasInScope(tn)&&(p.openElements.generateImpliedEndTags(),p.openElements.popUntilTagNamePopped(tn))}function formEndTagInBody(p){let inTemplate=p.openElements.tmplCount>0,{formElement}=p;inTemplate||(p.formElement=null),(formElement||inTemplate)&&p.openElements.hasInScope(TAG_ID.FORM)&&(p.openElements.generateImpliedEndTags(),inTemplate?p.openElements.popUntilTagNamePopped(TAG_ID.FORM):formElement&&p.openElements.remove(formElement))}function pEndTagInBody(p){p.openElements.hasInButtonScope(TAG_ID.P)||p._insertFakeElement(TAG_NAMES.P,TAG_ID.P),p._closePElement()}function liEndTagInBody(p){p.openElements.hasInListItemScope(TAG_ID.LI)&&(p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.LI),p.openElements.popUntilTagNamePopped(TAG_ID.LI))}function ddEndTagInBody(p,token){let tn=token.tagID;p.openElements.hasInScope(tn)&&(p.openElements.generateImpliedEndTagsWithExclusion(tn),p.openElements.popUntilTagNamePopped(tn))}function numberedHeaderEndTagInBody(p){p.openElements.hasNumberedHeaderInScope()&&(p.openElements.generateImpliedEndTags(),p.openElements.popUntilNumberedHeaderPopped())}function appletEndTagInBody(p,token){let tn=token.tagID;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=!1}function genericEndTagInBody(p,token){let tn=token.tagName,tid=token.tagID;for(let i=p.openElements.stackTop;i>0;i--){let element=p.openElements.items[i],elementId=p.openElements.tagIDs[i];if(tid===elementId&&(tid!==TAG_ID.UNKNOWN||p.treeAdapter.getTagName(element)===tn)){p.openElements.generateImpliedEndTagsWithExclusion(tid),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){p.tmplInsertionModeStack.length>0?eofInTemplate(p,token):stopParsing(p,token)}function endTagInText(p,token){var _a3;token.tagID===TAG_ID.SCRIPT&&((_a3=p.scriptHandler)===null||_a3===void 0||_a3.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))switch(p.pendingCharacterTokens.length=0,p.hasNonWhitespacePendingCharacterToken=!1,p.originalInsertionMode=p.insertionMode,p.insertionMode=InsertionMode.IN_TABLE_TEXT,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){p.openElements.hasInTableScope(TAG_ID.TABLE)&&(p.openElements.popUntilTagNamePopped(TAG_ID.TABLE),p._resetInsertionMode(),p._processStartTag(token))}function inputStartTagInTable(p,token){isHiddenInput(token)?p._appendElement(token,NS.HTML):tokenInTable(p,token),token.ackSelfClosing=!0}function formStartTagInTable(p,token){!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:{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){let savedFosterParentingState=p.fosterParentingEnabled;p.fosterParentingEnabled=!0,modeInBody(p,token),p.fosterParentingEnabled=savedFosterParentingState}function whitespaceCharacterInTableText(p,token){p.pendingCharacterTokens.push(token)}function characterInTableText(p,token){p.pendingCharacterTokens.push(token),p.hasNonWhitespacePendingCharacterToken=!0}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){let tn=token.tagID;TABLE_VOID_ELEMENTS.has(tn)?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)):startTagInBody(p,token)}function endTagInCaption(p,token){let tn=token.tagID;switch(tn){case TAG_ID.CAPTION:case TAG_ID.TABLE:{p.openElements.hasInTableScope(TAG_ID.CAPTION)&&(p.openElements.generateImpliedEndTags(),p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION),p.activeFormattingElements.clearToLastMarker(),p.insertionMode=InsertionMode.IN_TABLE,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=!0;break}case TAG_ID.TEMPLATE:{startTagInHead(p,token);break}default:tokenInColumnGroup(p,token)}}function endTagInColumnGroup(p,token){switch(token.tagID){case TAG_ID.COLGROUP:{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){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:{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){let tn=token.tagID;switch(token.tagID){case TAG_ID.TBODY:case TAG_ID.TFOOT:case TAG_ID.THEAD:{p.openElements.hasInTableScope(tn)&&(p.openElements.clearBackToTableBodyContext(),p.openElements.pop(),p.insertionMode=InsertionMode.IN_TABLE);break}case TAG_ID.TABLE:{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:{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:{p.openElements.hasInTableScope(TAG_ID.TR)&&(p.openElements.clearBackToTableRowContext(),p.openElements.pop(),p.insertionMode=InsertionMode.IN_TABLE_BODY);break}case TAG_ID.TABLE:{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:{(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){let tn=token.tagID;TABLE_VOID_ELEMENTS.has(tn)?(p.openElements.hasInTableScope(TAG_ID.TD)||p.openElements.hasInTableScope(TAG_ID.TH))&&(p._closeTableCell(),startTagInRow(p,token)):startTagInBody(p,token)}function endTagInCell(p,token){let tn=token.tagID;switch(tn){case TAG_ID.TD:case TAG_ID.TH:{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:{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:{p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.pop(),p._insertElement(token,NS.HTML);break}case TAG_ID.OPTGROUP:{p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.pop(),p.openElements.currentTagId===TAG_ID.OPTGROUP&&p.openElements.pop(),p._insertElement(token,NS.HTML);break}case TAG_ID.HR:{p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.pop(),p.openElements.currentTagId===TAG_ID.OPTGROUP&&p.openElements.pop(),p._appendElement(token,NS.HTML),token.ackSelfClosing=!0;break}case TAG_ID.INPUT:case TAG_ID.KEYGEN:case TAG_ID.TEXTAREA:case TAG_ID.SELECT:{p.openElements.hasInSelectScope(TAG_ID.SELECT)&&(p.openElements.popUntilTagNamePopped(TAG_ID.SELECT),p._resetInsertionMode(),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:{p.openElements.stackTop>0&&p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.tagIDs[p.openElements.stackTop-1]===TAG_ID.OPTGROUP&&p.openElements.pop(),p.openElements.currentTagId===TAG_ID.OPTGROUP&&p.openElements.pop();break}case TAG_ID.OPTION:{p.openElements.currentTagId===TAG_ID.OPTION&&p.openElements.pop();break}case TAG_ID.SELECT:{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){let tn=token.tagID;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)):startTagInSelect(p,token)}function endTagInSelectInTable(p,token){let tn=token.tagID;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.hasInTableScope(tn)&&(p.openElements.popUntilTagNamePopped(TAG_ID.SELECT),p._resetInsertionMode(),p.onEndTag(token)):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){token.tagID===TAG_ID.TEMPLATE&&templateEndTagInHead(p,token)}function eofInTemplate(p,token){p.openElements.tmplCount>0?(p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE),p.activeFormattingElements.clearToLastMarker(),p.tmplInsertionModeStack.shift(),p._resetInsertionMode(),p.onEof(token)):stopParsing(p,token)}function startTagAfterBody(p,token){token.tagID===TAG_ID.HTML?startTagInBody(p,token):tokenAfterBody(p,token)}function endTagAfterBody(p,token){var _a3;if(token.tagID===TAG_ID.HTML){if(p.fragmentContext||(p.insertionMode=InsertionMode.AFTER_AFTER_BODY),p.options.sourceCodeLocationInfo&&p.openElements.tagIDs[0]===TAG_ID.HTML){p._setEndLocation(p.openElements.items[0],token);let bodyElement=p.openElements.items[1];bodyElement&&!(!((_a3=p.treeAdapter.getNodeSourceCodeLocation(bodyElement))===null||_a3===void 0)&&_a3.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=!0;break}case TAG_ID.NOFRAMES:{startTagInHead(p,token);break}default:}}function endTagInFrameset(p,token){token.tagID===TAG_ID.FRAMESET&&!p.openElements.isRootHtmlElementCurrent()&&(p.openElements.pop(),!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){token.tagID===TAG_ID.HTML&&(p.insertionMode=InsertionMode.AFTER_AFTER_FRAMESET)}function startTagAfterAfterBody(p,token){token.tagID===TAG_ID.HTML?startTagInBody(p,token):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=!1}function popUntilHtmlOrIntegrationPoint(p){for(;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{let current=p._getAdjustedCurrentElement(),currentNs=p.treeAdapter.getNamespaceURI(current);currentNs===NS.MATHML?adjustTokenMathMLAttrs(token):currentNs===NS.SVG&&(adjustTokenSVGTagName(token),adjustTokenSVGAttrs(token)),adjustTokenXMLAttrs(token),token.selfClosing?p._appendElement(token,currentNs):p._insertElement(token,currentNs),token.ackSelfClosing=!0}}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--){let element=p.openElements.items[i];if(p.treeAdapter.getNamespaceURI(element)===NS.HTML){p._endTagOutsideForeignContent(token);break}let 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 parse3(html,options){return Parser.parse(html,options)}function getAttribute(node2,name){return node2.attrs?.find(item=>item.name.toLowerCase()===name.toLowerCase())?.value??null}function getText(node2){return node2.nodeName==="#text"?node2.value??"":(node2.childNodes??[]).map(getText).join("")}function cleanText(value){return value?.replace(/\s+/g," ").trim()||null}function extractSeoData(html){let document=parse3(html),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:""},textParts=[];function visit2(node2,hidden=!1){let tagName=node2.tagName?.toLowerCase(),excludesText=hidden||tagName==="script"||tagName==="style"||tagName==="noscript"||tagName==="template";if(node2.nodeName==="#text"&&!excludesText){let text=cleanText(node2.value);text&&textParts.push(text)}if(tagName==="html"&&result.lang===null&&(result.lang=cleanText(getAttribute(node2,"lang"))),tagName==="title"&&result.title===null&&(result.title=cleanText(getText(node2))),tagName==="h1"&&(result.h1Count+=1),tagName==="meta"){let name=getAttribute(node2,"name")?.toLowerCase(),property=getAttribute(node2,"property")?.toLowerCase(),content=cleanText(getAttribute(node2,"content"));name==="description"&&result.description===null?result.description=content:name==="robots"&&result.robots===null?result.robots=content:property==="og:title"&&result.openGraph.title===null?result.openGraph.title=content:property==="og:description"&&result.openGraph.description===null?result.openGraph.description=content:property==="og:image"&&result.openGraph.image===null?result.openGraph.image=content:name==="twitter:card"&&result.twitter.card===null?result.twitter.card=content:name==="twitter:title"&&result.twitter.title===null?result.twitter.title=content:name==="twitter:description"&&result.twitter.description===null?result.twitter.description=content:name==="twitter:image"&&result.twitter.image===null&&(result.twitter.image=content)}if(tagName==="link"){let rel=getAttribute(node2,"rel")?.toLowerCase().split(/\s+/).filter(Boolean)??[];if(rel.includes("canonical")&&result.canonical===null&&(result.canonical=cleanText(getAttribute(node2,"href"))),rel.includes("alternate")){let lang=cleanText(getAttribute(node2,"hreflang")),url2=cleanText(getAttribute(node2,"href"));lang&&url2&&result.hreflang.push({lang,url:url2})}}if(tagName==="a"){let href=getAttribute(node2,"href");href&&result.links.push(href)}if(tagName==="img"&&result.images.push({src:cleanText(getAttribute(node2,"src")),alt:getAttribute(node2,"alt")}),tagName==="script"&&getAttribute(node2,"type")?.toLowerCase()==="application/ld+json"){let source=getText(node2).trim();if(source)try{result.jsonLd.push({valid:!0,value:JSON.parse(source)})}catch(error61){result.jsonLd.push({valid:!1,error:error61 instanceof Error?error61.message:String(error61)})}}for(let child of node2.childNodes??[])visit2(child,excludesText)}return visit2(document),result.visibleText=textParts.join(" "),result.wordCount=result.visibleText?result.visibleText.split(/\s+/u).length:0,result}function emptyPage(url2,depth){return{url:url2,finalUrl:null,status:null,contentType:null,blockedByRobots:!1,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){let page=emptyPage(requestUrl,depth);if(options.respectRobots&&!isAllowedByRobots(requestUrl,robots))return page.blockedByRobots=!0,page;try{if(options.renderer){options.signal?.throwIfAborted(),await options.requestGate(requestUrl);let rendered=await options.renderer.render({url:requestUrl,timeout:options.timeout,maxResponseBytes:options.maxResponseBytes,userAgent:options.userAgent,...options.signal?{signal:options.signal}:{}});return populateRenderedPage(page,rendered,requestUrl,siteOrigin,options.includeQuery)}let{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}),contentType=response.headers.get("content-type")??"",isHtml=contentType.includes("text/html")||contentType.includes("application/xhtml+xml"),finalUrl=normalizeUrl(response.url,void 0,{includeQuery:options.includeQuery});if(page.finalUrl=finalUrl,page.status=response.status,page.contentType=contentType||null,page.xRobotsTag=response.headers.get("x-robots-tag"),page.redirectChain=redirectChain,!isHtml)return await response.body?.cancel(),page;let{text:body,bytes}=await readResponseBody(response,options.maxResponseBytes),seo=extractSeoData(body),baseUrl=finalUrl??requestUrl,canonical=seo.canonical?normalizeUrl(seo.canonical,baseUrl,{includeQuery:!0}):null,links=[...new Set(seo.links.map(link=>normalizeUrl(link,baseUrl,{includeQuery:options.includeQuery})).filter(link=>!!link))].sort(),hreflang=seo.hreflang.map(item=>({lang:item.lang,url:normalizeUrl(item.url,baseUrl,{includeQuery:!0})}));return 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}),page}catch(error61){if(options.signal?.aborted)throw error61;return page.error=error61 instanceof Error?error61.message:String(error61),error61 instanceof RequestFailure&&(page.redirectChain=error61.redirectChain),page}}function populateRenderedPage(page,rendered,requestUrl,siteOrigin,includeQuery){let contentType=rendered.headers["content-type"]??"text/html",finalUrl=normalizeUrl(rendered.finalUrl,void 0,{includeQuery});if(page.finalUrl=finalUrl,page.status=rendered.status,page.contentType=contentType,page.xRobotsTag=rendered.headers["x-robots-tag"]??null,page.redirectChain=rendered.redirectChain,!contentType.includes("text/html")&&!contentType.includes("application/xhtml+xml"))return page;let seo=extractSeoData(rendered.html),baseUrl=finalUrl??requestUrl,canonical=seo.canonical?normalizeUrl(seo.canonical,baseUrl,{includeQuery:!0}):null,links=[...new Set(seo.links.map(link=>normalizeUrl(link,baseUrl,{includeQuery})).filter(link=>!!link))].sort();return 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:seo.hreflang.map(item=>({lang:item.lang,url:normalizeUrl(item.url,baseUrl,{includeQuery:!0})})),contentHash:seo.visibleText?createHash4("sha256").update(seo.visibleText.toLowerCase()).digest("hex"):null,responseBytes:rendered.responseBytes}),page}function withDefaults(raw={}){let requestDelay=raw.requestDelay??raw.delay??100,providedGate=raw.requestGate;return{...raw,maxPages:raw.maxPages??100,concurrency:Math.max(1,raw.concurrency??5),timeout:raw.timeout??1e4,includeQuery:raw.includeQuery??!1,respectRobots:raw.respectRobots??!0,sitemap:raw.sitemap??null,sitemapData:raw.sitemapData??null,userAgent:raw.userAgent??DEFAULT_USER_AGENT,requestDelay,requestGate:providedGate?async url2=>providedGate(url2):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){let output2=[],workers=Array.from({length:concurrency},async()=>{for(;;){let value=await next();if(value===null)return;output2.push(value)}});return await Promise.all(workers),output2}async function crawlSite(inputUrl,rawOptions={}){let startedAt=Date.now(),options=withDefaults(rawOptions),startUrl=normalizeUrl(inputUrl,void 0,{includeQuery:options.includeQuery});if(!startUrl)throw new Error(`invalid start URL: ${inputUrl}`);let origin=new URL(startUrl).origin;await emit2(options,{type:"scan-start",url:startUrl,total:options.maxPages});let robots=rawOptions.robots??await fetchRobots(startUrl,options),sitemap=options.sitemapData;if(!sitemap&&options.sitemap)try{sitemap=await loadSitemapUrls(options.sitemap,{...options,maxUrls:rawOptions.sitemapMaxUrls??5e4,siteOrigin:origin})}catch(error61){sitemap={url:options.sitemap,urls:[],sitemapCount:0,truncated:!1,error:error61 instanceof Error?error61.message:String(error61)},options.logger.warn(`Could not load sitemap ${options.sitemap}: ${sitemap.error}`)}let frontier=[...new Set([startUrl,...sitemap?.urls??[]])].slice(0,options.maxPages).map(url2=>({url:url2,depth:0})),scheduled=new Set(frontier.map(item=>item.url)),cached2=new Map((rawOptions.cachedPages??[]).map(page=>[page.url,page])),pages=new Map,maxQueueSize=Math.max(options.maxPages*10,options.maxPages),hasMore=!1;for(;frontier.length>0&&pages.size<options.maxPages&&!options.signal?.aborted;){frontier.sort((left,right)=>left.url.localeCompare(right.url));let remaining=options.maxPages-pages.size,current=frontier.slice(0,remaining);frontier.length>current.length&&(hasMore=!0);let cursor=0,completed=await runPool(options.concurrency,async()=>{if(options.signal?.aborted||cursor>=current.length)return null;let item=current[cursor++];if(!item)return null;let page=cached2.get(item.url);if(!page)try{page=await fetchPage(item.url,item.depth,origin,options,robots)}catch(error61){if(options.signal?.aborted)return null;throw error61}return pages.set(item.url,page),cached2.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}),{item,page}}),next=new Map;for(let{item,page}of completed.sort((left,right)=>left.item.url.localeCompare(right.item.url))){let discoveredLinks=page.internalLinks?.length?page.internalLinks:(page.links??[]).filter(link=>isSameOrigin(link,origin));for(let link of[...discoveredLinks].sort())scheduled.size>=maxQueueSize||scheduled.has(link)||!isCrawlableUrl(link)||(scheduled.add(link),next.set(link,{url:link,depth:item.depth+1}))}frontier=[...next.values()]}let sortedPages=[...pages.values()].sort((left,right)=>left.url.localeCompare(right.url)),partial2=!!options.signal?.aborted,truncated=partial2||hasMore||frontier.length>0||(sitemap?sitemap.urls.length>sortedPages.length:!1)||(sitemap?.truncated??!1),result={startUrl,pages:sortedPages,robots,sitemap,truncated,partial:partial2,durationMs:Date.now()-startedAt,options};return result.snapshot=createBaseline(result),partial2||await options.storage?.removeCheckpoint?.(startUrl),partial2?await emit2(options,{type:"cancelled",completed:sortedPages.length,total:options.maxPages,partial:!0}):await emit2(options,{type:"complete",completed:sortedPages.length,total:options.maxPages}),result}function isPlan(input2){return"planVersion"in input2}function checkpointIdentity(plan,rendererId){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,...rendererId?{rendererId}:{}}}function reusableCheckpointPage(page){return!page.error&&(page.status===null||page.status<500)}async function scan(input2,options={}){let plannedRobots=null,plannedSitemap=null,plan;try{plan=isPlan(input2)?input2:await planScan(input2,{...options,async onEvent(event){event.type==="robots"&&(plannedRobots=event.robots),event.type==="sitemap"&&(plannedSitemap=event.sitemap),await options.onEvent?.(event)}})}catch(error61){if(isPlan(input2)||!options.signal?.aborted)throw error61;let config3=resolveConfig(input2),startUrl=normalizeUrl(config3.url,void 0,{includeQuery:config3.includeQuery});if(!startUrl)throw new Error(`invalid start URL: ${config3.url}`,{cause:error61});let robots=plannedRobots??{url:new URL("/robots.txt",startUrl).href,status:null,sha256:null,error:"Scan cancelled before robots.txt planning completed",denyAll:!1},snapshot=createBaseline({startUrl,pages:[],robots,sitemap:plannedSitemap,options:config3,partial:!0,truncated:!0});return await options.checkpointStore?.flush?.(),await options.onEvent?.({type:"cancelled",completed:0,total:config3.maxPages,partial:!0}),{snapshot,startUrl,pages:[],robots,sitemap:plannedSitemap,truncated:!0,partial:!0,durationMs:0,options:config3}}if(plan.planVersion!==1)throw new Error(`unsupported scan plan version: ${String(plan.planVersion)}`);let limit=options.limit??plan.config.maxPages;if(!Number.isInteger(limit)||limit<=0)throw new Error("scan limit must be a positive integer");let config2={...plan.config,maxPages:limit},requestGate=createPerOriginRequestGate(config2.delay),identity=checkpointIdentity(plan,options.renderer?.id),checkpoint=options.checkpointStore&&options.resume!==!1?await options.checkpointStore.load(identity):null,cachedPages=[...options.cachedPages??[],...checkpoint?.pages.filter(reusableCheckpointPage)??[]],uniqueCachedPages=[...new Map(cachedPages.map(page=>[page.url,page])).values()];uniqueCachedPages.length>0&&await options.onEvent?.({type:"resume",completed:uniqueCachedPages.length,total:limit});let result=await crawlSite(plan.startUrl,{...options,maxPages:limit,concurrency:config2.concurrency,requestDelay:config2.delay,timeout:config2.timeout,respectRobots:config2.respectRobots,includeQuery:config2.includeQuery,maxRedirects:config2.maxRedirects,maxResponseBytes:config2.maxResponseBytes,enabledRules:config2.enabledRules,severityOverrides:config2.severityOverrides,suppressions:config2.suppressions,regressionBudgets:config2.regressionBudgets,report:config2.report,requestGate,robots:plan.robots,sitemap:plan.sitemap?.url??null,sitemapData:plan.sitemap,userAgent:plan.userAgent,cachedPages:uniqueCachedPages,async onBatch(pages){for(let page of pages)await options.checkpointStore?.append(identity,page);await options.onBatch?.(pages)}});return await options.checkpointStore?.flush?.(),!result.partial&&!options.retainCheckpoint&&await options.checkpointStore?.clear(identity),result}function segmentToken(segment){return/^\d+$/.test(segment)?":id":/^[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)?":uuid":/^\d{4}-\d{2}-\d{2}$/.test(segment)?":date":/^[0-9a-f]{16,}$/i.test(segment)?":hash":null}function parseIssueUrls(issues){return issues.flatMap(issue2=>{try{let url2=new URL(issue2.url);return[{issue:issue2,url:url2,segments:url2.pathname.split("/").filter(Boolean)}]}catch{return[]}})}function dynamicSegments(pages){let siblings=new Map;for(let page of pages)for(let index=1;index<page.segments.length;index+=1){if(segmentToken(page.segments[index]))continue;let prefix=page.segments.slice(0,index).join("/"),key=`${page.url.origin}|${page.segments.length}|${index}|${prefix}`,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){let segments=page.segments.map((segment,index)=>{let token=segmentToken(segment);if(token)return token;let prefix=page.segments.slice(0,index).join("/"),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){let pages=parseIssueUrls(issues),dynamic=dynamicSegments(pages),grouped=new Map;for(let page of pages){let template=templateFor(page,dynamic),key=`${page.url.origin}${template}`,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=>{let severities={error:0,warning:0,info:0},rules={},owners={};for(let issue2 of group.issues)severities[issue2.severity]+=1,rules[issue2.ruleId]=(rules[issue2.ruleId]??0)+1,owners[issue2.owner]=(owners[issue2.owner]??0)+1;let 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){let 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"},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(issue2){return issue2.evidence?.actual??issue2.after}function ukrainianMessage(issue2,ruleId){let value=actual(issue2);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 issue2.before===!1?"\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(issue2.before??"\u043D\u0435\u0432\u0456\u0434\u043E\u043C\u043E")} \u0434\u043E ${String(issue2.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(issue2.before)||0)-(Number(issue2.after)||0))}`;default:return issue2.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(issue2,ruleId){let englishRemediation=issue2.remediation??"Review the finding and confirm the intended behavior.";return{en:{rule:englishRuleLabel(ruleId),message:issue2.message??"",remediation:englishRemediation},uk:{rule:UK_RULE_LABELS[ruleId]??englishRuleLabel(ruleId),message:ukrainianMessage(issue2,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."}};var PRODUCT_FAVICON="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='16' fill='%233157d5'/%3E%3Ccircle cx='27' cy='27' r='13' fill='none' stroke='white' stroke-width='6'/%3E%3Cpath d='m37 37 12 12' fill='none' stroke='white' stroke-linecap='round' stroke-width='6'/%3E%3Cpath d='m21 27 5 5 9-11' fill='none' stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='4'/%3E%3C/svg%3E";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 productMark(){return'<svg class="logo product-mark" viewBox="0 0 64 64" role="img" aria-label="SEO Crawl Audit logo"><rect width="64" height="64" rx="16" fill="var(--accent)"/><circle cx="27" cy="27" r="13" fill="none" stroke="#fff" stroke-width="6"/><path d="m37 37 12 12" fill="none" stroke="#fff" stroke-linecap="round" stroke-width="6"/><path d="m21 27 5 5 9-11" fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round" stroke-width="4"/></svg>'}function normalizeIssue(candidate,fallbackLifecycle="current"){let 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,issue2)=>{let value=String(issue2[key]);return counts[value]=(counts[value]??0)+1,counts},{})}function renderHtmlReport(input2,options={}){let mode=input2.mode??"scan",pages=input2.pages??[],current=(input2.issues??[]).map(item=>normalizeIssue(item)),lifecycle2=[...(input2.newIssues??[]).map(item=>normalizeIssue(item,"new")),...(input2.ongoingIssues??[]).map(item=>normalizeIssue(item,"ongoing")),...(input2.resolvedIssues??[]).map(item=>normalizeIssue(item,"resolved")),...(input2.unchangedIssues??[]).map(item=>normalizeIssue(item,"unchanged"))],issues=lifecycle2.length>0?lifecycle2:current,templateGroups=groupIssuesByTemplate(issues),templateByUrl=new Map(templateGroups.flatMap(group=>group.urls.map(url2=>[url2,group.template])));for(let issue2 of issues)issue2.template=templateByUrl.get(issue2.url)??"";let counts=issues.reduce((summary2,item)=>(summary2[item.severity]+=1,summary2),{error:0,warning:0,info:0}),affectedPages=new Set(issues.map(item=>item.url)).size,ruleCounts=countIssues(issues,"rule"),severityRank={error:0,warning:1,info:2},priorityMap=new Map;for(let issue2 of issues.filter(item=>item.lifecycle!=="resolved")){let existing=priorityMap.get(issue2.rule);existing?(existing.count+=1,existing.urls.add(issue2.url),severityRank[issue2.severity]<severityRank[existing.severity]&&(existing.severity=issue2.severity)):priorityMap.set(issue2.rule,{rule:issue2.rule,severity:issue2.severity,owner:issue2.owner,count:1,urls:new Set([issue2.url])})}let priorities=[...priorityMap.values()].map(item=>({rule:item.rule,severity:item.severity,owner:item.owner,count:item.count,affectedPages:item.urls.size})).sort((left,right)=>severityRank[left.severity]-severityRank[right.severity]||right.affectedPages-left.affectedPages||right.count-left.count||left.rule.localeCompare(right.rule)).slice(0,5),statistics={total:issues.length,pagesChecked:pages.length,targetPages:input2.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})),priorities},partial2=input2.partial??!1,incompleteComparison=mode==="check"&&input2.complete===!1,reportTitle=partial2?"Partial SEO scan report":mode==="check"?"SEO regression report":"SEO baseline audit",branding={...input2.branding??{},...options.branding??{}},primaryColor=/^#[0-9a-f]{6}$/i.test(branding.primaryColor??"")?branding.primaryColor:"#3157d5",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")}">`:productMark(),data=safeJson({mode,issues,statistics,copy:REPORT_COPY,partial:partial2,incompleteComparison,comparison:input2.comparison??null,history:input2.history??null,siteMetrics:input2.siteMetrics??null}),generatedAt=input2.generatedAt??new Date().toISOString(),startUrl=input2.startUrl??"",targetPages=input2.targetPages??null,isCheck=mode==="check";return`<!doctype html>
|