@tradik/xslt-processor 1.0.3 → 1.3.0
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/LICENSE.md +1 -1
- package/README.md +110 -520
- package/bin/lib/decode.js +15 -0
- package/bin/lib/dom.js +177 -0
- package/bin/lib/loaders.js +127 -0
- package/bin/lib/options.js +131 -0
- package/bin/lib/output.js +114 -0
- package/bin/lib/paths.js +186 -0
- package/bin/lib/transform.js +206 -0
- package/bin/xslt.js +73 -168
- package/dist/xslt-processor.browser.js +9564 -1585
- package/dist/xslt-processor.browser.js.map +4 -4
- package/dist/xslt-processor.browser.min.js +13 -2
- package/dist/xslt-processor.browser.min.js.map +4 -4
- package/dist/xslt-processor.cjs +9572 -1586
- package/dist/xslt-processor.cjs.map +4 -4
- package/dist/xslt-processor.d.cts +658 -0
- package/dist/xslt-processor.d.ts +459 -12
- package/dist/xslt-processor.js +9546 -1582
- package/dist/xslt-processor.js.map +4 -4
- package/package.json +71 -20
- package/src/XSLTProcessor.js +494 -48
- package/src/async/abort.js +63 -0
- package/src/async/documentUris.js +128 -0
- package/src/async/loaders.js +134 -0
- package/src/async/preload.js +159 -0
- package/src/async/processor.js +206 -0
- package/src/async/stream.js +125 -0
- package/src/bridge/engine.js +221 -0
- package/src/bridge/loader.js +78 -0
- package/src/bridge/results.js +75 -0
- package/src/bridge/version.js +63 -0
- package/src/index.js +26 -8
- package/src/io/decode.js +140 -0
- package/src/io/readSource.js +167 -0
- package/src/xpath/axes.js +562 -0
- package/src/xpath/documentOrder.js +270 -0
- package/src/xpath/evaluator.js +518 -357
- package/src/xpath/index.js +8 -2
- package/src/xpath/namespaceNodes.js +172 -0
- package/src/xpath/nodeSetFunctions.js +169 -0
- package/src/xpath/parser.js +30 -5
- package/src/xpath/strings.js +183 -0
- package/src/xpath/tokenizer.js +37 -23
- package/src/xslt/attributeSets.js +95 -0
- package/src/xslt/avt.js +103 -0
- package/src/xslt/computedNames.js +91 -0
- package/src/xslt/copying.js +212 -0
- package/src/xslt/declarationNames.js +80 -0
- package/src/xslt/domParsing.js +95 -0
- package/src/xslt/elements.js +57 -0
- package/src/xslt/engine/bindings.js +195 -0
- package/src/xslt/engine/context.js +105 -0
- package/src/xslt/engine/controlFlow.js +145 -0
- package/src/xslt/engine/copyInstructions.js +133 -0
- package/src/xslt/engine/declarations.js +233 -0
- package/src/xslt/engine/functionSupport.js +103 -0
- package/src/xslt/engine/methods.js +33 -0
- package/src/xslt/engine/nodeConstruction.js +187 -0
- package/src/xslt/engine/numbering.js +104 -0
- package/src/xslt/engine/outputDeclaration.js +77 -0
- package/src/xslt/engine/sequenceConstructor.js +228 -0
- package/src/xslt/engine/stylesheetLoading.js +208 -0
- package/src/xslt/engine/templateInvocation.js +253 -0
- package/src/xslt/engine/templateRules.js +243 -0
- package/src/xslt/engine/textInstructions.js +171 -0
- package/src/xslt/engine/topLevel.js +130 -0
- package/src/xslt/engine/transformation.js +263 -0
- package/src/xslt/engine/workStack.js +245 -0
- package/src/xslt/engine.js +184 -1736
- package/src/xslt/exslt/arguments.js +99 -0
- package/src/xslt/exslt/calendar.js +120 -0
- package/src/xslt/exslt/common.js +44 -0
- package/src/xslt/exslt/dateCalc.js +261 -0
- package/src/xslt/exslt/dateFormat.js +150 -0
- package/src/xslt/exslt/dateParse.js +265 -0
- package/src/xslt/exslt/dates.js +259 -0
- package/src/xslt/exslt/duration.js +207 -0
- package/src/xslt/exslt/dynamic.js +59 -0
- package/src/xslt/exslt/index.js +59 -0
- package/src/xslt/exslt/math.js +177 -0
- package/src/xslt/exslt/sets.js +96 -0
- package/src/xslt/exslt/stringOps.js +163 -0
- package/src/xslt/exslt/strings.js +147 -0
- package/src/xslt/exslt/uri.js +92 -0
- package/src/xslt/formatNumber.js +233 -0
- package/src/xslt/forwardsCompatible.js +75 -0
- package/src/xslt/functions.js +270 -0
- package/src/xslt/index.js +38 -1
- package/src/xslt/keys.js +164 -0
- package/src/xslt/literalResult.js +223 -0
- package/src/xslt/matchScope.js +116 -0
- package/src/xslt/number.js +271 -0
- package/src/xslt/numberFormat.js +253 -0
- package/src/xslt/outputNames.js +58 -0
- package/src/xslt/patternCompiler.js +175 -0
- package/src/xslt/patterns.js +324 -0
- package/src/xslt/qname.js +90 -0
- package/src/xslt/resultDocument.js +98 -0
- package/src/xslt/resultNamespaces.js +219 -0
- package/src/xslt/resultTree.js +211 -0
- package/src/xslt/serializer/baseWriter.js +390 -0
- package/src/xslt/serializer/chunks.js +120 -0
- package/src/xslt/serializer/constants.js +92 -0
- package/src/xslt/serializer/encoding.js +327 -0
- package/src/xslt/serializer/escape.js +135 -0
- package/src/xslt/serializer/frames.js +168 -0
- package/src/xslt/serializer/htmlDoctype.js +102 -0
- package/src/xslt/serializer/htmlEntities.js +77 -0
- package/src/xslt/serializer/htmlSerializer.js +239 -0
- package/src/xslt/serializer/indent.js +51 -0
- package/src/xslt/serializer/namespaces.js +68 -0
- package/src/xslt/serializer/rawText.js +41 -0
- package/src/xslt/serializer/settings.js +179 -0
- package/src/xslt/serializer/textSerializer.js +77 -0
- package/src/xslt/serializer/xhtmlDocument.js +103 -0
- package/src/xslt/serializer/xmlSerializer.js +227 -0
- package/src/xslt/serializer.js +90 -0
- package/src/xslt/sort.js +151 -0
- package/src/xslt/spaceNameTests.js +115 -0
- package/src/xslt/stylesheetChecks.js +206 -0
- package/src/xslt/stylesheetNamespaces.js +266 -0
- package/src/xslt/templatePriority.js +45 -0
- package/src/xslt/uri.js +68 -0
- package/src/xslt/variables.js +152 -0
- package/src/xslt/whitespace.js +200 -0
- package/LICENSE +0 -29
- package/src/XSLTProcessor.test.js +0 -930
- package/src/xpath/evaluator.test.js +0 -1852
- package/src/xpath/tokenizer.test.js +0 -224
- package/src/xslt/engine.test.js +0 -3130
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/xpath/tokenizer.js", "../src/xpath/parser.js", "../src/xpath/evaluator.js", "../src/xslt/engine.js", "../src/XSLTProcessor.js", "../src/xpath/index.js", "../src/index.js"],
|
|
4
|
-
"sourcesContent": ["/**\n * XPath 1.0 Tokenizer\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * Converts XPath expression strings into token streams for parsing.\n */\n\n\"use strict\";\n\nexport const TokenType = {\n // Literals\n NUMBER: \"NUMBER\",\n LITERAL: \"LITERAL\",\n\n // Operators\n SLASH: \"SLASH\",\n DOUBLE_SLASH: \"DOUBLE_SLASH\",\n PIPE: \"PIPE\",\n PLUS: \"PLUS\",\n MINUS: \"MINUS\",\n STAR: \"STAR\",\n DIV: \"DIV\",\n MOD: \"MOD\",\n EQUALS: \"EQUALS\",\n NOT_EQUALS: \"NOT_EQUALS\",\n LT: \"LT\",\n LTE: \"LTE\",\n GT: \"GT\",\n GTE: \"GTE\",\n AND: \"AND\",\n OR: \"OR\",\n\n // Brackets\n LPAREN: \"LPAREN\",\n RPAREN: \"RPAREN\",\n LBRACKET: \"LBRACKET\",\n RBRACKET: \"RBRACKET\",\n\n // Axes\n AXIS: \"AXIS\",\n AT: \"AT\",\n DOT: \"DOT\",\n DOUBLE_DOT: \"DOUBLE_DOT\",\n DOUBLE_COLON: \"DOUBLE_COLON\",\n\n // Names\n NAME: \"NAME\",\n NCNAME: \"NCNAME\",\n PREFIX: \"PREFIX\",\n FUNCTION: \"FUNCTION\",\n NODE_TYPE: \"NODE_TYPE\",\n\n // Other\n COMMA: \"COMMA\",\n DOLLAR: \"DOLLAR\",\n COLON: \"COLON\",\n EOF: \"EOF\",\n};\n\nconst AXIS_NAMES = new Set([\n \"ancestor\",\n \"ancestor-or-self\",\n \"attribute\",\n \"child\",\n \"descendant\",\n \"descendant-or-self\",\n \"following\",\n \"following-sibling\",\n \"namespace\",\n \"parent\",\n \"preceding\",\n \"preceding-sibling\",\n \"self\",\n]);\n\nconst NODE_TYPES = new Set([\n \"comment\",\n \"text\",\n \"processing-instruction\",\n \"node\",\n]);\n\nconst OPERATORS = new Set([\"and\", \"or\", \"mod\", \"div\"]);\n\nexport class Token {\n constructor(type, value, position) {\n this.type = type;\n this.value = value;\n this.position = position;\n }\n\n toString() {\n return `Token(${this.type}, ${JSON.stringify(this.value)}, pos=${this.position})`;\n }\n}\n\n// Tokens that indicate the NEXT token should NOT be treated as an OperatorName\n// Per XPath 1.0 spec: \"If there is a preceding token and the preceding token is not one of\n// @, ::, (, [, , or an Operator, then... an NCName must be recognized as an OperatorName.\"\n// So after these tokens, OperatorNames (div, mod, and, or) should be treated as regular names.\nconst OPERATOR_CONTEXT_BLOCKERS = new Set([\n TokenType.AT,\n TokenType.DOUBLE_COLON,\n TokenType.LPAREN,\n TokenType.LBRACKET,\n TokenType.COMMA,\n // Operators - after an operator, next name token should be a name, not an operator\n TokenType.SLASH,\n TokenType.DOUBLE_SLASH,\n TokenType.PIPE,\n TokenType.PLUS,\n TokenType.MINUS,\n TokenType.STAR,\n TokenType.DIV,\n TokenType.MOD,\n TokenType.EQUALS,\n TokenType.NOT_EQUALS,\n TokenType.LT,\n TokenType.LTE,\n TokenType.GT,\n TokenType.GTE,\n TokenType.AND,\n TokenType.OR,\n]);\n\nexport class XPathTokenizer {\n constructor(expression) {\n this.expression = expression;\n this.position = 0;\n this.tokens = [];\n }\n\n /**\n * Get the last token that was added (if any)\n */\n getLastToken() {\n return this.tokens.length > 0 ? this.tokens[this.tokens.length - 1] : null;\n }\n\n /**\n * Check if the current context allows operator names (div, mod, and, or)\n * Per XPath 1.0 spec disambiguation rules.\n */\n isOperatorContext() {\n const lastToken = this.getLastToken();\n // No preceding token means we're at the start - not an operator context\n if (!lastToken) return false;\n // If preceding token is a \"blocker\", it's not an operator context\n if (OPERATOR_CONTEXT_BLOCKERS.has(lastToken.type)) return false;\n // Otherwise, it IS an operator context (after names, numbers, closing brackets, etc.)\n return true;\n }\n\n tokenize() {\n this.tokens = [];\n this.position = 0;\n\n while (this.position < this.expression.length) {\n this.skipWhitespace();\n if (this.position >= this.expression.length) break;\n\n const token = this.nextToken();\n if (token) {\n this.tokens.push(token);\n }\n }\n\n this.tokens.push(new Token(TokenType.EOF, null, this.position));\n return this.tokens;\n }\n\n skipWhitespace() {\n while (\n this.position < this.expression.length &&\n /\\s/.test(this.expression[this.position])\n ) {\n this.position++;\n }\n }\n\n peek(offset = 0) {\n return this.expression[this.position + offset];\n }\n\n consume() {\n return this.expression[this.position++];\n }\n\n nextToken() {\n const startPos = this.position;\n const char = this.peek();\n\n // String literals\n if (char === '\"' || char === \"'\") {\n return this.readStringLiteral();\n }\n\n // Numbers\n if (/[0-9]/.test(char) || (char === \".\" && /[0-9]/.test(this.peek(1)))) {\n return this.readNumber();\n }\n\n // Multi-character operators\n if (char === \"/\" && this.peek(1) === \"/\") {\n this.position += 2;\n return new Token(TokenType.DOUBLE_SLASH, \"//\", startPos);\n }\n\n if (char === \".\" && this.peek(1) === \".\") {\n this.position += 2;\n return new Token(TokenType.DOUBLE_DOT, \"..\", startPos);\n }\n\n if (char === \":\" && this.peek(1) === \":\") {\n this.position += 2;\n return new Token(TokenType.DOUBLE_COLON, \"::\", startPos);\n }\n\n if (char === \"!\" && this.peek(1) === \"=\") {\n this.position += 2;\n return new Token(TokenType.NOT_EQUALS, \"!=\", startPos);\n }\n\n if (char === \"<\" && this.peek(1) === \"=\") {\n this.position += 2;\n return new Token(TokenType.LTE, \"<=\", startPos);\n }\n\n if (char === \">\" && this.peek(1) === \"=\") {\n this.position += 2;\n return new Token(TokenType.GTE, \">=\", startPos);\n }\n\n // Single-character tokens\n const singleCharTokens = {\n \"/\": TokenType.SLASH,\n \"|\": TokenType.PIPE,\n \"+\": TokenType.PLUS,\n \"-\": TokenType.MINUS,\n \"*\": TokenType.STAR,\n \"=\": TokenType.EQUALS,\n \"<\": TokenType.LT,\n \">\": TokenType.GT,\n \"(\": TokenType.LPAREN,\n \")\": TokenType.RPAREN,\n \"[\": TokenType.LBRACKET,\n \"]\": TokenType.RBRACKET,\n \"@\": TokenType.AT,\n \".\": TokenType.DOT,\n \",\": TokenType.COMMA,\n $: TokenType.DOLLAR,\n \":\": TokenType.COLON,\n };\n\n if (singleCharTokens[char]) {\n this.position++;\n return new Token(singleCharTokens[char], char, startPos);\n }\n\n // Names and keywords\n if (this.isNameStartChar(char)) {\n return this.readName();\n }\n\n throw new Error(\n `Unexpected character '${char}' at position ${this.position} in expression: ${this.expression}`,\n );\n }\n\n readStringLiteral() {\n const startPos = this.position;\n const quote = this.consume();\n let value = \"\";\n\n while (this.position < this.expression.length && this.peek() !== quote) {\n value += this.consume();\n }\n\n if (this.position >= this.expression.length) {\n throw new Error(`Unterminated string literal at position ${startPos}`);\n }\n\n this.consume(); // closing quote\n return new Token(TokenType.LITERAL, value, startPos);\n }\n\n readNumber() {\n const startPos = this.position;\n let value = \"\";\n\n // Integer part\n while (\n this.position < this.expression.length &&\n /[0-9]/.test(this.peek())\n ) {\n value += this.consume();\n }\n\n // Decimal part (handles both 1.5 and .5 style numbers)\n // For .5 style: entry condition ensures digit follows, so this branch handles it\n if (this.peek() === \".\" && /[0-9]/.test(this.peek(1))) {\n value += this.consume(); // .\n while (\n this.position < this.expression.length &&\n /[0-9]/.test(this.peek())\n ) {\n value += this.consume();\n }\n }\n\n return new Token(TokenType.NUMBER, parseFloat(value), startPos);\n }\n\n readName() {\n const startPos = this.position;\n let value = \"\";\n\n while (\n this.position < this.expression.length &&\n this.isNameChar(this.peek())\n ) {\n value += this.consume();\n }\n\n // Check for axis name followed by ::\n this.skipWhitespace();\n if (AXIS_NAMES.has(value) && this.peek() === \":\" && this.peek(1) === \":\") {\n return new Token(TokenType.AXIS, value, startPos);\n }\n\n // Check for function call (followed by '(')\n const savedPos = this.position;\n this.skipWhitespace();\n if (this.peek() === \"(\") {\n // Check if it's a node type test\n if (NODE_TYPES.has(value)) {\n return new Token(TokenType.NODE_TYPE, value, startPos);\n }\n return new Token(TokenType.FUNCTION, value, startPos);\n }\n this.position = savedPos;\n\n // Check for operators - only in operator context per XPath 1.0 disambiguation rules\n if (OPERATORS.has(value) && this.isOperatorContext()) {\n const opTokens = {\n and: TokenType.AND,\n or: TokenType.OR,\n mod: TokenType.MOD,\n div: TokenType.DIV,\n };\n return new Token(opTokens[value], value, startPos);\n }\n\n return new Token(TokenType.NAME, value, startPos);\n }\n\n isNameStartChar(char) {\n if (!char) return false;\n const code = char.charCodeAt(0);\n return (\n char === \"_\" ||\n (code >= 65 && code <= 90) || // A-Z\n (code >= 97 && code <= 122) || // a-z\n code >= 0xc0 // Unicode letters\n );\n }\n\n isNameChar(char) {\n if (!char) return false;\n const code = char.charCodeAt(0);\n return (\n this.isNameStartChar(char) ||\n char === \"-\" ||\n char === \".\" ||\n (code >= 48 && code <= 57) // 0-9\n );\n }\n}\n\nexport function tokenize(expression) {\n const tokenizer = new XPathTokenizer(expression);\n return tokenizer.tokenize();\n}\n", "/**\n * XPath 1.0 Parser\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * Converts token stream into an Abstract Syntax Tree (AST).\n */\n\n\"use strict\";\n\nimport { TokenType, tokenize } from \"./tokenizer.js\";\n\nexport const NodeType = {\n // Expression types\n OR_EXPR: \"OrExpr\",\n AND_EXPR: \"AndExpr\",\n EQUALITY_EXPR: \"EqualityExpr\",\n RELATIONAL_EXPR: \"RelationalExpr\",\n ADDITIVE_EXPR: \"AdditiveExpr\",\n MULTIPLICATIVE_EXPR: \"MultiplicativeExpr\",\n UNARY_EXPR: \"UnaryExpr\",\n UNION_EXPR: \"UnionExpr\",\n\n // Path expressions\n PATH_EXPR: \"PathExpr\",\n LOCATION_PATH: \"LocationPath\",\n STEP: \"Step\",\n PREDICATE: \"Predicate\",\n\n // Primaries\n VARIABLE_REF: \"VariableRef\",\n LITERAL: \"Literal\",\n NUMBER: \"Number\",\n FUNCTION_CALL: \"FunctionCall\",\n\n // Node tests\n NAME_TEST: \"NameTest\",\n NODE_TYPE_TEST: \"NodeTypeTest\",\n PI_TEST: \"ProcessingInstructionTest\",\n};\n\nexport class ASTNode {\n constructor(type, props = {}) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n\nexport class XPathParser {\n constructor(tokens) {\n this.tokens = tokens;\n this.position = 0;\n }\n\n parse() {\n const expr = this.parseExpr();\n if (!this.isAtEnd()) {\n throw new Error(\n `Unexpected token ${this.peek().type} at position ${this.peek().position}`,\n );\n }\n return expr;\n }\n\n // Expr ::= OrExpr\n parseExpr() {\n return this.parseOrExpr();\n }\n\n // OrExpr ::= AndExpr | OrExpr 'or' AndExpr\n parseOrExpr() {\n let left = this.parseAndExpr();\n\n while (this.match(TokenType.OR)) {\n const right = this.parseAndExpr();\n left = new ASTNode(NodeType.OR_EXPR, { left, right });\n }\n\n return left;\n }\n\n // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr\n parseAndExpr() {\n let left = this.parseEqualityExpr();\n\n while (this.match(TokenType.AND)) {\n const right = this.parseEqualityExpr();\n left = new ASTNode(NodeType.AND_EXPR, { left, right });\n }\n\n return left;\n }\n\n // EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr | EqualityExpr '!=' RelationalExpr\n parseEqualityExpr() {\n let left = this.parseRelationalExpr();\n\n while (true) {\n if (this.match(TokenType.EQUALS)) {\n const right = this.parseRelationalExpr();\n left = new ASTNode(NodeType.EQUALITY_EXPR, {\n operator: \"=\",\n left,\n right,\n });\n } else if (this.match(TokenType.NOT_EQUALS)) {\n const right = this.parseRelationalExpr();\n left = new ASTNode(NodeType.EQUALITY_EXPR, {\n operator: \"!=\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // RelationalExpr ::= AdditiveExpr | RelationalExpr '<' AdditiveExpr | ...\n parseRelationalExpr() {\n let left = this.parseAdditiveExpr();\n\n while (true) {\n if (this.match(TokenType.LT)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \"<\",\n left,\n right,\n });\n } else if (this.match(TokenType.LTE)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \"<=\",\n left,\n right,\n });\n } else if (this.match(TokenType.GT)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \">\",\n left,\n right,\n });\n } else if (this.match(TokenType.GTE)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \">=\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // AdditiveExpr ::= MultiplicativeExpr | AdditiveExpr '+' MultiplicativeExpr | AdditiveExpr '-' MultiplicativeExpr\n parseAdditiveExpr() {\n let left = this.parseMultiplicativeExpr();\n\n while (true) {\n if (this.match(TokenType.PLUS)) {\n const right = this.parseMultiplicativeExpr();\n left = new ASTNode(NodeType.ADDITIVE_EXPR, {\n operator: \"+\",\n left,\n right,\n });\n } else if (this.match(TokenType.MINUS)) {\n const right = this.parseMultiplicativeExpr();\n left = new ASTNode(NodeType.ADDITIVE_EXPR, {\n operator: \"-\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // MultiplicativeExpr ::= UnaryExpr | MultiplicativeExpr '*' UnaryExpr | ...\n parseMultiplicativeExpr() {\n let left = this.parseUnaryExpr();\n\n while (true) {\n if (this.match(TokenType.STAR)) {\n const right = this.parseUnaryExpr();\n left = new ASTNode(NodeType.MULTIPLICATIVE_EXPR, {\n operator: \"*\",\n left,\n right,\n });\n } else if (this.match(TokenType.DIV)) {\n const right = this.parseUnaryExpr();\n left = new ASTNode(NodeType.MULTIPLICATIVE_EXPR, {\n operator: \"div\",\n left,\n right,\n });\n } else if (this.match(TokenType.MOD)) {\n const right = this.parseUnaryExpr();\n left = new ASTNode(NodeType.MULTIPLICATIVE_EXPR, {\n operator: \"mod\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // UnaryExpr ::= UnionExpr | '-' UnaryExpr\n parseUnaryExpr() {\n if (this.match(TokenType.MINUS)) {\n const operand = this.parseUnaryExpr();\n return new ASTNode(NodeType.UNARY_EXPR, { operator: \"-\", operand });\n }\n return this.parseUnionExpr();\n }\n\n // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr\n parseUnionExpr() {\n let left = this.parsePathExpr();\n\n while (this.match(TokenType.PIPE)) {\n const right = this.parsePathExpr();\n left = new ASTNode(NodeType.UNION_EXPR, { left, right });\n }\n\n return left;\n }\n\n // PathExpr ::= LocationPath | FilterExpr | FilterExpr '/' RelativeLocationPath | FilterExpr '//' RelativeLocationPath\n parsePathExpr() {\n // Check for absolute location path\n if (this.check(TokenType.SLASH) || this.check(TokenType.DOUBLE_SLASH)) {\n return this.parseLocationPath();\n }\n\n // Check if this looks like a location path starting with step\n if (this.isStepStart()) {\n return this.parseLocationPath();\n }\n\n // Otherwise try to parse as filter expression\n const filter = this.parseFilterExpr();\n\n // Check for path continuation\n if (this.check(TokenType.SLASH) || this.check(TokenType.DOUBLE_SLASH)) {\n const steps = [];\n\n while (\n this.check(TokenType.SLASH) ||\n this.check(TokenType.DOUBLE_SLASH)\n ) {\n const isDescendant = this.match(TokenType.DOUBLE_SLASH);\n if (!isDescendant) this.advance(); // consume /\n\n if (isDescendant) {\n steps.push(\n new ASTNode(NodeType.STEP, {\n axis: \"descendant-or-self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, {\n nodeType: \"node\",\n }),\n predicates: [],\n }),\n );\n }\n\n steps.push(this.parseStep());\n }\n\n return new ASTNode(NodeType.PATH_EXPR, { filter, steps });\n }\n\n return filter;\n }\n\n // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath\n parseLocationPath() {\n let absolute = false;\n const steps = [];\n\n if (this.match(TokenType.DOUBLE_SLASH)) {\n absolute = true;\n // //foo is equivalent to /descendant-or-self::node()/foo\n steps.push(\n new ASTNode(NodeType.STEP, {\n axis: \"descendant-or-self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType: \"node\" }),\n predicates: [],\n }),\n );\n if (!this.isAtEnd() && !this.check(TokenType.EOF)) {\n steps.push(this.parseStep());\n }\n } else if (this.match(TokenType.SLASH)) {\n absolute = true;\n if (this.isStepStart()) {\n steps.push(this.parseStep());\n }\n } else {\n steps.push(this.parseStep());\n }\n\n while (this.check(TokenType.SLASH) || this.check(TokenType.DOUBLE_SLASH)) {\n const isDescendant = this.match(TokenType.DOUBLE_SLASH);\n if (!isDescendant) this.advance(); // consume /\n\n if (isDescendant) {\n steps.push(\n new ASTNode(NodeType.STEP, {\n axis: \"descendant-or-self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, {\n nodeType: \"node\",\n }),\n predicates: [],\n }),\n );\n }\n\n steps.push(this.parseStep());\n }\n\n return new ASTNode(NodeType.LOCATION_PATH, { absolute, steps });\n }\n\n // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep\n parseStep() {\n // Handle abbreviated steps\n if (this.match(TokenType.DOT)) {\n return new ASTNode(NodeType.STEP, {\n axis: \"self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType: \"node\" }),\n predicates: [],\n });\n }\n\n if (this.match(TokenType.DOUBLE_DOT)) {\n return new ASTNode(NodeType.STEP, {\n axis: \"parent\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType: \"node\" }),\n predicates: [],\n });\n }\n\n // Parse axis\n let axis = \"child\"; // default axis\n\n if (this.match(TokenType.AT)) {\n axis = \"attribute\";\n } else if (this.check(TokenType.AXIS)) {\n axis = this.advance().value;\n this.expect(TokenType.DOUBLE_COLON);\n }\n\n // Parse node test\n const nodeTest = this.parseNodeTest();\n\n // Parse predicates\n const predicates = [];\n while (this.check(TokenType.LBRACKET)) {\n predicates.push(this.parsePredicate());\n }\n\n return new ASTNode(NodeType.STEP, { axis, nodeTest, predicates });\n }\n\n // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'\n parseNodeTest() {\n if (this.check(TokenType.NODE_TYPE)) {\n const nodeType = this.advance().value;\n this.expect(TokenType.LPAREN);\n\n if (\n nodeType === \"processing-instruction\" &&\n this.check(TokenType.LITERAL)\n ) {\n const name = this.advance().value;\n this.expect(TokenType.RPAREN);\n return new ASTNode(NodeType.PI_TEST, { name });\n }\n\n this.expect(TokenType.RPAREN);\n return new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType });\n }\n\n // NameTest\n return this.parseNameTest();\n }\n\n // NameTest ::= '*' | NCName ':' '*' | QName\n parseNameTest() {\n if (this.match(TokenType.STAR)) {\n return new ASTNode(NodeType.NAME_TEST, { name: \"*\", prefix: null });\n }\n\n if (!this.check(TokenType.NAME)) {\n throw new Error(`Expected name at position ${this.peek().position}`);\n }\n\n const name = this.advance().value;\n\n // Check for prefix:*\n if (this.match(TokenType.COLON)) {\n if (this.match(TokenType.STAR)) {\n return new ASTNode(NodeType.NAME_TEST, { name: \"*\", prefix: name });\n }\n\n if (this.check(TokenType.NAME)) {\n const localName = this.advance().value;\n return new ASTNode(NodeType.NAME_TEST, {\n name: localName,\n prefix: name,\n });\n }\n\n throw new Error(\n `Expected name or * after : at position ${this.peek().position}`,\n );\n }\n\n return new ASTNode(NodeType.NAME_TEST, { name, prefix: null });\n }\n\n // Predicate ::= '[' Expr ']'\n parsePredicate() {\n this.expect(TokenType.LBRACKET);\n const expr = this.parseExpr();\n this.expect(TokenType.RBRACKET);\n return new ASTNode(NodeType.PREDICATE, { expr });\n }\n\n // FilterExpr ::= PrimaryExpr | FilterExpr Predicate\n parseFilterExpr() {\n let primary = this.parsePrimaryExpr();\n\n while (this.check(TokenType.LBRACKET)) {\n const predicate = this.parsePredicate();\n primary = new ASTNode(NodeType.PATH_EXPR, {\n filter: primary,\n predicates: [predicate],\n });\n }\n\n return primary;\n }\n\n // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall\n parsePrimaryExpr() {\n // Variable reference\n if (this.match(TokenType.DOLLAR)) {\n if (!this.check(TokenType.NAME)) {\n throw new Error(\n `Expected variable name at position ${this.peek().position}`,\n );\n }\n const name = this.advance().value;\n let prefix = null;\n\n if (this.match(TokenType.COLON)) {\n prefix = name;\n if (!this.check(TokenType.NAME)) {\n throw new Error(\n `Expected local name at position ${this.peek().position}`,\n );\n }\n const localName = this.advance().value;\n return new ASTNode(NodeType.VARIABLE_REF, { name: localName, prefix });\n }\n\n return new ASTNode(NodeType.VARIABLE_REF, { name, prefix });\n }\n\n // Parenthesized expression\n if (this.match(TokenType.LPAREN)) {\n const expr = this.parseExpr();\n this.expect(TokenType.RPAREN);\n return expr;\n }\n\n // Literal\n if (this.check(TokenType.LITERAL)) {\n return new ASTNode(NodeType.LITERAL, { value: this.advance().value });\n }\n\n // Number\n if (this.check(TokenType.NUMBER)) {\n return new ASTNode(NodeType.NUMBER, { value: this.advance().value });\n }\n\n // Function call\n if (this.check(TokenType.FUNCTION)) {\n return this.parseFunctionCall();\n }\n\n throw new Error(\n `Unexpected token ${this.peek().type} at position ${this.peek().position}`,\n );\n }\n\n // FunctionCall ::= FunctionName '(' ( Argument ( ',' Argument )* )? ')'\n // Note: Prefixed function calls (prefix:fn()) are not supported because\n // the tokenizer identifies functions by NAME followed by '(' - prefixed\n // names like 'fn:name()' are tokenized as NAME:NAME() which is parsed\n // as a location path, not a function call.\n parseFunctionCall() {\n const name = this.advance().value;\n return this.parseFunctionCallArgs(name, null);\n }\n\n parseFunctionCallArgs(name, prefix) {\n this.expect(TokenType.LPAREN);\n\n const args = [];\n if (!this.check(TokenType.RPAREN)) {\n args.push(this.parseExpr());\n while (this.match(TokenType.COMMA)) {\n args.push(this.parseExpr());\n }\n }\n\n this.expect(TokenType.RPAREN);\n\n return new ASTNode(NodeType.FUNCTION_CALL, { name, prefix, args });\n }\n\n // Helper methods\n isStepStart() {\n const type = this.peek().type;\n return (\n type === TokenType.NAME ||\n type === TokenType.STAR ||\n type === TokenType.AT ||\n type === TokenType.DOT ||\n type === TokenType.DOUBLE_DOT ||\n type === TokenType.AXIS ||\n type === TokenType.NODE_TYPE\n );\n }\n\n peek() {\n return this.tokens[this.position];\n }\n\n advance() {\n if (!this.isAtEnd()) {\n return this.tokens[this.position++];\n }\n return this.tokens[this.position];\n }\n\n check(type) {\n if (this.isAtEnd()) return false;\n return this.peek().type === type;\n }\n\n match(type) {\n if (this.check(type)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n expect(type) {\n if (!this.check(type)) {\n throw new Error(\n `Expected ${type} but got ${this.peek().type} at position ${this.peek().position}`,\n );\n }\n return this.advance();\n }\n\n isAtEnd() {\n return this.peek().type === TokenType.EOF;\n }\n}\n\nexport function parse(expression) {\n const tokens = tokenize(expression);\n const parser = new XPathParser(tokens);\n return parser.parse();\n}\n", "/**\n * XPath 1.0 Evaluator\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * Evaluates XPath AST against DOM nodes.\n */\n\n\"use strict\";\n\nimport { NodeType } from \"./parser.js\";\n\n/**\n * XPath result types matching W3C spec\n */\nexport const XPathResultType = {\n ANY_TYPE: 0,\n NUMBER_TYPE: 1,\n STRING_TYPE: 2,\n BOOLEAN_TYPE: 3,\n UNORDERED_NODE_ITERATOR_TYPE: 4,\n ORDERED_NODE_ITERATOR_TYPE: 5,\n UNORDERED_NODE_SNAPSHOT_TYPE: 6,\n ORDERED_NODE_SNAPSHOT_TYPE: 7,\n ANY_UNORDERED_NODE_TYPE: 8,\n FIRST_ORDERED_NODE_TYPE: 9,\n};\n\n/**\n * Security limits to prevent DoS attacks\n */\nexport const XPathLimits = {\n MAX_RECURSION_DEPTH: 100,\n MAX_RESULT_SIZE: 10000,\n MAX_STRING_LENGTH: 1000000,\n};\n\n/**\n * Forbidden variable names to prevent prototype pollution\n */\nconst FORBIDDEN_VARIABLE_NAMES = Object.freeze([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"__defineGetter__\",\n \"__defineSetter__\",\n \"__lookupGetter__\",\n \"__lookupSetter__\",\n]);\n\n/**\n * XPath evaluation context\n */\nexport class XPathContext {\n constructor(node, position = 1, size = 1, variables = {}, namespaces = {}) {\n this.node = node;\n this.position = position;\n this.size = size;\n this.variables = variables;\n this.namespaces = namespaces;\n }\n\n clone(overrides = {}) {\n return new XPathContext(\n overrides.node ?? this.node,\n overrides.position ?? this.position,\n overrides.size ?? this.size,\n overrides.variables ?? this.variables,\n overrides.namespaces ?? this.namespaces,\n );\n }\n}\n\n/**\n * XPath Evaluator\n */\nexport class XPathEvaluator {\n constructor(options = {}) {\n this.functions = this.initCoreFunctions();\n this.maxRecursionDepth =\n options.maxRecursionDepth ?? XPathLimits.MAX_RECURSION_DEPTH;\n this.maxResultSize = options.maxResultSize ?? XPathLimits.MAX_RESULT_SIZE;\n this.maxStringLength =\n options.maxStringLength ?? XPathLimits.MAX_STRING_LENGTH;\n this.recursionDepth = 0;\n }\n\n /**\n * Evaluate XPath expression against a context\n * @throws {Error} If recursion depth exceeds limit\n * @throws {Error} If AST is invalid\n */\n evaluate(ast, context) {\n if (!ast || typeof ast !== \"object\") {\n throw new Error(\"Invalid AST: expected object\");\n }\n\n if (!ast.type) {\n throw new Error(\"Invalid AST: missing type property\");\n }\n\n this.recursionDepth++;\n if (this.recursionDepth > this.maxRecursionDepth) {\n this.recursionDepth = 0;\n throw new Error(\n `Maximum recursion depth exceeded (${this.maxRecursionDepth})`,\n );\n }\n\n try {\n return this.evaluateInternal(ast, context);\n } finally {\n this.recursionDepth--;\n }\n }\n\n /**\n * Internal evaluation (after validation)\n */\n evaluateInternal(ast, context) {\n switch (ast.type) {\n case NodeType.OR_EXPR:\n return this.evalOrExpr(ast, context);\n case NodeType.AND_EXPR:\n return this.evalAndExpr(ast, context);\n case NodeType.EQUALITY_EXPR:\n return this.evalEqualityExpr(ast, context);\n case NodeType.RELATIONAL_EXPR:\n return this.evalRelationalExpr(ast, context);\n case NodeType.ADDITIVE_EXPR:\n return this.evalAdditiveExpr(ast, context);\n case NodeType.MULTIPLICATIVE_EXPR:\n return this.evalMultiplicativeExpr(ast, context);\n case NodeType.UNARY_EXPR:\n return this.evalUnaryExpr(ast, context);\n case NodeType.UNION_EXPR:\n return this.evalUnionExpr(ast, context);\n case NodeType.PATH_EXPR:\n return this.evalPathExpr(ast, context);\n case NodeType.LOCATION_PATH:\n return this.evalLocationPath(ast, context);\n case NodeType.VARIABLE_REF:\n return this.evalVariableRef(ast, context);\n case NodeType.LITERAL:\n return this.validateString(ast.value);\n case NodeType.NUMBER:\n return ast.value;\n case NodeType.FUNCTION_CALL:\n return this.evalFunctionCall(ast, context);\n default:\n throw new Error(`Unknown AST node type: ${String(ast.type)}`);\n }\n }\n\n /**\n * Validate and limit string length\n */\n validateString(str) {\n if (typeof str === \"string\" && str.length > this.maxStringLength) {\n throw new Error(\n `String exceeds maximum length (${this.maxStringLength})`,\n );\n }\n return str;\n }\n\n /**\n * Validate result size\n */\n validateResultSize(nodes) {\n if (Array.isArray(nodes) && nodes.length > this.maxResultSize) {\n throw new Error(\n `Result set exceeds maximum size (${this.maxResultSize})`,\n );\n }\n return nodes;\n }\n\n evalOrExpr(ast, context) {\n return (\n this.toBoolean(this.evaluate(ast.left, context)) ||\n this.toBoolean(this.evaluate(ast.right, context))\n );\n }\n\n evalAndExpr(ast, context) {\n return (\n this.toBoolean(this.evaluate(ast.left, context)) &&\n this.toBoolean(this.evaluate(ast.right, context))\n );\n }\n\n evalEqualityExpr(ast, context) {\n const left = this.evaluate(ast.left, context);\n const right = this.evaluate(ast.right, context);\n const isEqual = this.compareValues(left, right, \"=\");\n return ast.operator === \"=\" ? isEqual : !isEqual;\n }\n\n evalRelationalExpr(ast, context) {\n const left = this.evaluate(ast.left, context);\n const right = this.evaluate(ast.right, context);\n return this.compareValues(left, right, ast.operator);\n }\n\n evalAdditiveExpr(ast, context) {\n const left = this.toNumber(this.evaluate(ast.left, context));\n const right = this.toNumber(this.evaluate(ast.right, context));\n return ast.operator === \"+\" ? left + right : left - right;\n }\n\n evalMultiplicativeExpr(ast, context) {\n const left = this.toNumber(this.evaluate(ast.left, context));\n const right = this.toNumber(this.evaluate(ast.right, context));\n\n switch (ast.operator) {\n case \"*\":\n return left * right;\n case \"div\":\n return left / right;\n case \"mod\":\n return left % right;\n default:\n throw new Error(`Unknown multiplicative operator: ${ast.operator}`);\n }\n }\n\n evalUnaryExpr(ast, context) {\n const value = this.toNumber(this.evaluate(ast.operand, context));\n return -value;\n }\n\n evalUnionExpr(ast, context) {\n const left = this.evaluate(ast.left, context);\n const right = this.evaluate(ast.right, context);\n\n const leftNodes = Array.isArray(left) ? left : [left];\n const rightNodes = Array.isArray(right) ? right : [right];\n\n // Union in document order, no duplicates\n const seen = new Set();\n const result = [];\n\n for (const node of [...leftNodes, ...rightNodes]) {\n if (!seen.has(node)) {\n seen.add(node);\n result.push(node);\n }\n }\n\n this.validateResultSize(result);\n return this.sortByDocumentOrder(result);\n }\n\n evalPathExpr(ast, context) {\n if (ast.filter) {\n let result = this.evaluate(ast.filter, context);\n\n if (ast.predicates) {\n for (const pred of ast.predicates) {\n result = this.filterByPredicate(result, pred, context);\n }\n }\n\n if (ast.steps) {\n for (const step of ast.steps) {\n result = this.evalStepOnNodes(step, result, context);\n }\n }\n\n return result;\n }\n\n return [];\n }\n\n evalLocationPath(ast, context) {\n let nodes;\n\n if (ast.absolute) {\n // Start from document root node (not document element)\n // XPath absolute paths start from the document node\n const doc = context.node.ownerDocument || context.node;\n nodes = [doc];\n } else {\n nodes = [context.node];\n }\n\n for (const step of ast.steps) {\n nodes = this.evalStepOnNodes(step, nodes, context);\n this.validateResultSize(nodes);\n }\n\n return nodes;\n }\n\n evalStepOnNodes(step, nodes, context) {\n const allNodes = Array.isArray(nodes) ? nodes : [nodes];\n let result = [];\n\n for (const node of allNodes) {\n const stepNodes = this.evalStep(step, context.clone({ node }));\n result = result.concat(stepNodes);\n\n // Early validation to prevent excessive memory use\n if (result.length > this.maxResultSize * 2) {\n this.validateResultSize(result);\n }\n }\n\n // Remove duplicates and sort by document order\n const uniqueResult = [...new Set(result)];\n this.validateResultSize(uniqueResult);\n return this.sortByDocumentOrder(uniqueResult);\n }\n\n evalStep(step, context) {\n // Get nodes along axis\n let nodes = this.getAxisNodes(step.axis, context.node);\n\n // Filter by node test\n nodes = nodes.filter((n) => this.matchNodeTest(step.nodeTest, n, context));\n\n // Apply predicates\n for (const predicate of step.predicates) {\n nodes = this.filterByPredicate(nodes, predicate, context);\n }\n\n return nodes;\n }\n\n getAxisNodes(axis, node) {\n switch (axis) {\n case \"child\":\n return Array.from(node.childNodes || []);\n\n case \"parent\":\n return node.parentNode ? [node.parentNode] : [];\n\n case \"self\":\n return [node];\n\n case \"descendant\":\n return this.getDescendants(node, false);\n\n case \"descendant-or-self\":\n return this.getDescendants(node, true);\n\n case \"ancestor\":\n return this.getAncestors(node, false);\n\n case \"ancestor-or-self\":\n return this.getAncestors(node, true);\n\n case \"following-sibling\":\n return this.getFollowingSiblings(node);\n\n case \"preceding-sibling\":\n return this.getPrecedingSiblings(node);\n\n case \"following\":\n return this.getFollowing(node);\n\n case \"preceding\":\n return this.getPreceding(node);\n\n case \"attribute\":\n if (node.attributes) {\n return Array.from(node.attributes);\n }\n return [];\n\n case \"namespace\":\n // Namespace axis - not commonly used\n return [];\n\n default:\n throw new Error(`Unknown axis: ${axis}`);\n }\n }\n\n getDescendants(node, includeSelf) {\n const result = includeSelf ? [node] : [];\n const stack = Array.from(node.childNodes || []).reverse();\n\n while (stack.length > 0) {\n const current = stack.pop();\n result.push(current);\n if (current.childNodes) {\n for (let i = current.childNodes.length - 1; i >= 0; i--) {\n stack.push(current.childNodes[i]);\n }\n }\n }\n\n return result;\n }\n\n getAncestors(node, includeSelf) {\n const result = includeSelf ? [node] : [];\n let current = node.parentNode;\n\n while (current) {\n result.push(current);\n current = current.parentNode;\n }\n\n return result;\n }\n\n getFollowingSiblings(node) {\n const result = [];\n if (!node) return result;\n let current = node.nextSibling;\n\n while (current) {\n result.push(current);\n current = current.nextSibling;\n }\n\n return result;\n }\n\n getPrecedingSiblings(node) {\n const result = [];\n if (!node) return result;\n let current = node.previousSibling;\n\n while (current) {\n result.push(current);\n current = current.previousSibling;\n }\n\n return result.reverse();\n }\n\n getFollowing(node) {\n const result = [];\n let current = node;\n\n // Go to next sibling, or ancestor's next sibling\n while (current) {\n if (current.nextSibling) {\n current = current.nextSibling;\n result.push(current);\n // Add all descendants\n result.push(...this.getDescendants(current, false));\n } else {\n current = current.parentNode;\n }\n }\n\n return result;\n }\n\n getPreceding(node) {\n const result = [];\n let current = node;\n\n while (current) {\n if (current.previousSibling) {\n current = current.previousSibling;\n // Add descendants in reverse order, then the node\n const descendants = this.getDescendants(current, false);\n result.unshift(...descendants.reverse());\n result.unshift(current);\n } else {\n current = current.parentNode;\n if (current && current.nodeType !== 9) {\n // Not document\n // Don't add ancestors\n }\n }\n }\n\n return result;\n }\n\n matchNodeTest(nodeTest, node, context) {\n switch (nodeTest.type) {\n case NodeType.NAME_TEST:\n return this.matchNameTest(nodeTest, node, context);\n\n case NodeType.NODE_TYPE_TEST:\n return this.matchNodeTypeTest(nodeTest.nodeType, node);\n\n case NodeType.PI_TEST:\n return node.nodeType === 7 && node.nodeName === nodeTest.name;\n\n default:\n return false;\n }\n }\n\n matchNameTest(nodeTest, node, context) {\n // Only element and attribute nodes have names\n if (node.nodeType !== 1 && node.nodeType !== 2) {\n return false;\n }\n\n const name = nodeTest.name;\n const prefix = nodeTest.prefix;\n\n // Wildcard\n if (name === \"*\" && !prefix) {\n return true;\n }\n\n // Get node's local name and namespace\n const nodeName = node.localName || node.nodeName;\n const nodeNs = node.namespaceURI || null;\n\n // Prefix:* matches all nodes in namespace\n if (name === \"*\" && prefix) {\n const ns = context.namespaces[prefix];\n return nodeNs === ns;\n }\n\n // Simple name match\n if (!prefix) {\n // For elements, match local name (case-insensitive for HTML)\n const doc = node.ownerDocument;\n if (doc && doc.contentType === \"text/html\" && node.nodeType === 1) {\n return nodeName.toLowerCase() === name.toLowerCase();\n }\n return nodeName === name;\n }\n\n // Prefixed name match\n const ns = context.namespaces[prefix];\n return nodeName === name && nodeNs === ns;\n }\n\n matchNodeTypeTest(nodeType, node) {\n switch (nodeType) {\n case \"node\":\n return true;\n case \"text\":\n return node.nodeType === 3;\n case \"comment\":\n return node.nodeType === 8;\n case \"processing-instruction\":\n return node.nodeType === 7;\n default:\n return false;\n }\n }\n\n filterByPredicate(nodes, predicate, context) {\n const result = [];\n const nodeArray = Array.isArray(nodes) ? nodes : [nodes];\n const size = nodeArray.length;\n\n for (let i = 0; i < nodeArray.length; i++) {\n const node = nodeArray[i];\n const predicateContext = context.clone({\n node,\n position: i + 1,\n size,\n });\n\n const value = this.evaluate(predicate.expr, predicateContext);\n\n // If predicate evaluates to a number, it's a position test\n if (typeof value === \"number\") {\n if (value === i + 1) {\n result.push(node);\n }\n } else if (this.toBoolean(value)) {\n result.push(node);\n }\n }\n\n return result;\n }\n\n evalVariableRef(ast, context) {\n const name = ast.prefix ? `${ast.prefix}:${ast.name}` : ast.name;\n\n // Security: Prevent prototype pollution\n if (\n FORBIDDEN_VARIABLE_NAMES.includes(name) ||\n FORBIDDEN_VARIABLE_NAMES.includes(ast.name)\n ) {\n throw new Error(`Forbidden variable name: $${name}`);\n }\n\n if (!Object.prototype.hasOwnProperty.call(context.variables, name)) {\n throw new Error(`Undefined variable: $${name}`);\n }\n return context.variables[name];\n }\n\n evalFunctionCall(ast, context) {\n const name = ast.prefix ? `${ast.prefix}:${ast.name}` : ast.name;\n const fn = this.functions[name];\n\n if (!fn) {\n throw new Error(`Unknown function: ${name}`);\n }\n\n return fn.call(this, ast.args, context);\n }\n\n // Type conversion functions\n toBoolean(value) {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return value !== 0 && !isNaN(value);\n if (typeof value === \"string\") return value.length > 0;\n if (Array.isArray(value)) return value.length > 0;\n if (value && value.nodeType) return true;\n return Boolean(value);\n }\n\n toNumber(value) {\n if (typeof value === \"number\") return value;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (trimmed === \"\") return NaN;\n const num = Number(trimmed);\n return num;\n }\n if (Array.isArray(value)) {\n return this.toNumber(this.toString(value));\n }\n if (value && value.nodeType) {\n return this.toNumber(this.getStringValue(value));\n }\n return NaN;\n }\n\n toString(value) {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") {\n if (isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n if (value === 0) return \"0\";\n return String(value);\n }\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (Array.isArray(value)) {\n if (value.length === 0) return \"\";\n return this.getStringValue(value[0]);\n }\n if (value && value.nodeType) {\n return this.getStringValue(value);\n }\n return String(value);\n }\n\n getStringValue(node) {\n if (!node) return \"\";\n\n switch (node.nodeType) {\n case 1: // Element\n case 9: // Document\n case 11: {\n // Document Fragment\n let text = \"\";\n const walker = (n) => {\n if (n.nodeType === 3) {\n text += n.nodeValue || \"\";\n } else if (n.childNodes) {\n for (const child of n.childNodes) {\n walker(child);\n }\n }\n };\n walker(node);\n return text;\n }\n\n case 2: // Attribute\n case 3: // Text\n case 4: // CDATA\n case 7: // Processing Instruction\n case 8: // Comment\n return node.nodeValue || \"\";\n\n default:\n return \"\";\n }\n }\n\n // Comparison helper\n compareValues(left, right, operator) {\n const leftIsNodeSet = Array.isArray(left);\n const rightIsNodeSet = Array.isArray(right);\n\n // Node-set comparisons\n if (leftIsNodeSet && rightIsNodeSet) {\n for (const l of left) {\n for (const r of right) {\n if (\n this.comparePrimitive(\n this.getStringValue(l),\n this.getStringValue(r),\n operator,\n )\n ) {\n return true;\n }\n }\n }\n return false;\n }\n\n if (leftIsNodeSet) {\n for (const l of left) {\n if (this.comparePrimitive(this.getStringValue(l), right, operator)) {\n return true;\n }\n }\n return false;\n }\n\n if (rightIsNodeSet) {\n for (const r of right) {\n if (this.comparePrimitive(left, this.getStringValue(r), operator)) {\n return true;\n }\n }\n return false;\n }\n\n return this.comparePrimitive(left, right, operator);\n }\n\n comparePrimitive(left, right, operator) {\n // If comparing for equality with different types\n if (operator === \"=\" || operator === \"!=\") {\n // If one is boolean, convert both to boolean\n if (typeof left === \"boolean\" || typeof right === \"boolean\") {\n const result = this.toBoolean(left) === this.toBoolean(right);\n return operator === \"=\" ? result : !result;\n }\n // If one is number, convert both to number\n if (typeof left === \"number\" || typeof right === \"number\") {\n const result = this.toNumber(left) === this.toNumber(right);\n return operator === \"=\" ? result : !result;\n }\n // Otherwise compare as strings\n const result = this.toString(left) === this.toString(right);\n return operator === \"=\" ? result : !result;\n }\n\n // Relational operators always compare as numbers\n const leftNum = this.toNumber(left);\n const rightNum = this.toNumber(right);\n\n switch (operator) {\n case \"<\":\n return leftNum < rightNum;\n case \"<=\":\n return leftNum <= rightNum;\n case \">\":\n return leftNum > rightNum;\n case \">=\":\n return leftNum >= rightNum;\n default:\n throw new Error(`Unknown comparison operator: ${operator}`);\n }\n }\n\n sortByDocumentOrder(nodes) {\n if (nodes.length <= 1) return nodes;\n\n return nodes.sort((a, b) => {\n if (a === b) return 0;\n\n const position = a.compareDocumentPosition\n ? a.compareDocumentPosition(b)\n : this.compareDocumentPositionFallback(a, b);\n\n if (position & 4) return -1; // a before b\n if (position & 2) return 1; // a after b\n return 0;\n });\n }\n\n compareDocumentPositionFallback(a, b) {\n // Simple fallback for environments without compareDocumentPosition\n const getPath = (node) => {\n const path = [];\n let current = node;\n while (current) {\n if (current.parentNode) {\n const siblings = Array.from(current.parentNode.childNodes);\n path.unshift(siblings.indexOf(current));\n }\n current = current.parentNode;\n }\n return path;\n };\n\n const pathA = getPath(a);\n const pathB = getPath(b);\n\n for (let i = 0; i < Math.min(pathA.length, pathB.length); i++) {\n if (pathA[i] < pathB[i]) return 4; // a before b\n if (pathA[i] > pathB[i]) return 2; // a after b\n }\n\n return pathA.length < pathB.length ? 4 : 2;\n }\n\n /**\n * Initialize XPath 1.0 core functions\n */\n initCoreFunctions() {\n return {\n // Node set functions\n last: (args, ctx) => ctx.size,\n position: (args, ctx) => ctx.position,\n count: (args, ctx) => {\n const nodeSet = this.evaluate(args[0], ctx);\n return Array.isArray(nodeSet) ? nodeSet.length : 1;\n },\n id: (args, ctx) => {\n const value = this.toString(this.evaluate(args[0], ctx));\n const doc = ctx.node.ownerDocument || ctx.node;\n const ids = value.split(/\\s+/).filter((id) => id);\n const result = [];\n for (const id of ids) {\n const el = doc.getElementById(id);\n if (el) result.push(el);\n }\n return result;\n },\n \"local-name\": (args, ctx) => {\n let node;\n if (args.length === 0) {\n node = ctx.node;\n } else {\n const nodeSet = this.evaluate(args[0], ctx);\n node = Array.isArray(nodeSet) ? nodeSet[0] : nodeSet;\n }\n if (!node) return \"\";\n return node.localName || node.nodeName || \"\";\n },\n \"namespace-uri\": (args, ctx) => {\n let node;\n if (args.length === 0) {\n node = ctx.node;\n } else {\n const nodeSet = this.evaluate(args[0], ctx);\n node = Array.isArray(nodeSet) ? nodeSet[0] : nodeSet;\n }\n if (!node) return \"\";\n return node.namespaceURI || \"\";\n },\n name: (args, ctx) => {\n let node;\n if (args.length === 0) {\n node = ctx.node;\n } else {\n const nodeSet = this.evaluate(args[0], ctx);\n node = Array.isArray(nodeSet) ? nodeSet[0] : nodeSet;\n }\n if (!node) return \"\";\n return node.nodeName || \"\";\n },\n\n // String functions\n string: (args, ctx) => {\n if (args.length === 0) {\n return this.toString([ctx.node]);\n }\n return this.toString(this.evaluate(args[0], ctx));\n },\n concat: (args, ctx) => {\n return args\n .map((arg) => this.toString(this.evaluate(arg, ctx)))\n .join(\"\");\n },\n \"starts-with\": (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const prefix = this.toString(this.evaluate(args[1], ctx));\n return str.startsWith(prefix);\n },\n contains: (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const substr = this.toString(this.evaluate(args[1], ctx));\n return str.includes(substr);\n },\n \"substring-before\": (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const substr = this.toString(this.evaluate(args[1], ctx));\n const idx = str.indexOf(substr);\n return idx === -1 ? \"\" : str.substring(0, idx);\n },\n \"substring-after\": (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const substr = this.toString(this.evaluate(args[1], ctx));\n const idx = str.indexOf(substr);\n return idx === -1 ? \"\" : str.substring(idx + substr.length);\n },\n substring: (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n let start = Math.round(this.toNumber(this.evaluate(args[1], ctx)));\n let length;\n\n if (args.length > 2) {\n length = Math.round(this.toNumber(this.evaluate(args[2], ctx)));\n }\n\n // XPath uses 1-based indexing\n start = start - 1;\n\n if (isNaN(start)) return \"\";\n if (start < 0) {\n if (length !== undefined) {\n length = length + start;\n }\n start = 0;\n }\n\n if (length !== undefined) {\n if (isNaN(length) || length <= 0) return \"\";\n return str.substring(start, start + length);\n }\n\n return str.substring(start);\n },\n \"string-length\": (args, ctx) => {\n const str =\n args.length === 0\n ? this.toString([ctx.node])\n : this.toString(this.evaluate(args[0], ctx));\n return str.length;\n },\n \"normalize-space\": (args, ctx) => {\n const str =\n args.length === 0\n ? this.toString([ctx.node])\n : this.toString(this.evaluate(args[0], ctx));\n return str.trim().replace(/\\s+/g, \" \");\n },\n translate: (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const from = this.toString(this.evaluate(args[1], ctx));\n const to = this.toString(this.evaluate(args[2], ctx));\n\n let result = \"\";\n for (const char of str) {\n const idx = from.indexOf(char);\n if (idx === -1) {\n result += char;\n } else if (idx < to.length) {\n result += to[idx];\n }\n // If idx >= to.length, character is removed\n }\n return result;\n },\n\n // Boolean functions\n boolean: (args, ctx) => {\n return this.toBoolean(this.evaluate(args[0], ctx));\n },\n not: (args, ctx) => {\n return !this.toBoolean(this.evaluate(args[0], ctx));\n },\n true: () => true,\n false: () => false,\n lang: (args, ctx) => {\n const lang = this.toString(this.evaluate(args[0], ctx)).toLowerCase();\n let node = ctx.node;\n\n while (node && node.nodeType === 1) {\n const xmlLang =\n node.getAttribute(\"xml:lang\") || node.getAttribute(\"lang\");\n if (xmlLang) {\n const nodeLang = xmlLang.toLowerCase();\n return nodeLang === lang || nodeLang.startsWith(lang + \"-\");\n }\n node = node.parentNode;\n }\n return false;\n },\n\n // Number functions\n number: (args, ctx) => {\n if (args.length === 0) {\n return this.toNumber([ctx.node]);\n }\n return this.toNumber(this.evaluate(args[0], ctx));\n },\n sum: (args, ctx) => {\n const nodeSet = this.evaluate(args[0], ctx);\n if (!Array.isArray(nodeSet)) return NaN;\n return nodeSet.reduce(\n (sum, node) => sum + this.toNumber(this.getStringValue(node)),\n 0,\n );\n },\n floor: (args, ctx) => {\n return Math.floor(this.toNumber(this.evaluate(args[0], ctx)));\n },\n ceiling: (args, ctx) => {\n return Math.ceil(this.toNumber(this.evaluate(args[0], ctx)));\n },\n round: (args, ctx) => {\n const num = this.toNumber(this.evaluate(args[0], ctx));\n if (isNaN(num)) return NaN;\n if (num === -0.5) return -0;\n return Math.round(num);\n },\n };\n }\n}\n", "/**\n * XSLT 1.0 Processing Engine\n * Based on W3C XSLT 1.0 Specification: http://www.w3.org/TR/1999/REC-xslt-19991116\n *\n * Processes XSLT stylesheets and transforms XML documents.\n */\n\nimport { parse as parseXPath } from \"../xpath/parser.js\";\nimport { XPathEvaluator, XPathContext } from \"../xpath/evaluator.js\";\n\nconst XSLT_NS = \"http://www.w3.org/1999/XSL/Transform\";\n\n/**\n * XSLT Processing Context\n */\nexport class XsltContext {\n constructor(options = {}) {\n this.currentNode = options.currentNode;\n this.currentNodeList = options.currentNodeList || [];\n this.position = options.position || 1;\n this.variables = { ...options.variables };\n this.parameters = { ...options.parameters };\n this.outputDocument = options.outputDocument;\n this.stylesheet = options.stylesheet;\n this.namespaces = { ...options.namespaces };\n this.templates = options.templates || [];\n this.keys = options.keys || {};\n this.decimalFormats = options.decimalFormats || {};\n this.outputMethod = options.outputMethod || \"xml\";\n this.xpathEvaluator = options.xpathEvaluator || new XPathEvaluator();\n }\n\n clone(overrides = {}) {\n return new XsltContext({\n currentNode: overrides.currentNode ?? this.currentNode,\n currentNodeList: overrides.currentNodeList ?? this.currentNodeList,\n position: overrides.position ?? this.position,\n variables: overrides.variables\n ? { ...this.variables, ...overrides.variables }\n : { ...this.variables },\n parameters: overrides.parameters\n ? { ...this.parameters, ...overrides.parameters }\n : { ...this.parameters },\n outputDocument: this.outputDocument,\n stylesheet: this.stylesheet,\n namespaces: overrides.namespaces\n ? { ...this.namespaces, ...overrides.namespaces }\n : { ...this.namespaces },\n templates: this.templates,\n keys: this.keys,\n decimalFormats: this.decimalFormats,\n outputMethod: this.outputMethod,\n xpathEvaluator: this.xpathEvaluator,\n });\n }\n\n getVariable(name) {\n if (name in this.variables) {\n return this.variables[name];\n }\n if (name in this.parameters) {\n return this.parameters[name];\n }\n throw new Error(`Undefined variable: $${name}`);\n }\n\n setVariable(name, value) {\n this.variables[name] = value;\n }\n}\n\n/**\n * XSLT Engine\n */\nexport class XsltEngine {\n constructor(options = {}) {\n this.xpathEvaluator = new XPathEvaluator();\n this.templates = [];\n this.keys = {};\n this.globalVariables = {};\n this.globalParameters = {};\n this.outputSettings = {\n method: \"xml\",\n encoding: \"UTF-8\",\n indent: \"no\",\n omitXmlDeclaration: \"no\",\n doctypePublic: null,\n doctypeSystem: null,\n mediaType: null,\n cdataSectionElements: [],\n };\n this.namespaces = {};\n this.decimalFormats = {};\n this.stylesheetDoc = null;\n this.attributeSets = {};\n this.namespaceAliases = {};\n this.stripSpace = [];\n this.preserveSpace = [];\n\n // Import/Include support\n this.stylesheetLoader = options.stylesheetLoader || null;\n this.currentImportPrecedence = 0;\n this.processedStylesheets = new Set();\n this.baseUri = options.baseUri || \"\";\n }\n\n /**\n * Set the stylesheet loader function for xsl:import and xsl:include\n * @param {Function} loader - Function(href, baseUri) => Document or string (XML)\n */\n setStylesheetLoader(loader) {\n this.stylesheetLoader = loader;\n }\n\n /**\n * Resolve a relative URI against a base URI\n */\n resolveUri(href, baseUri) {\n if (\n !baseUri ||\n href.startsWith(\"http://\") ||\n href.startsWith(\"https://\") ||\n href.startsWith(\"/\")\n ) {\n return href;\n }\n\n // Remove filename from baseUri to get directory\n const lastSlash = baseUri.lastIndexOf(\"/\");\n const baseDir = lastSlash >= 0 ? baseUri.substring(0, lastSlash + 1) : \"\";\n\n return baseDir + href;\n }\n\n /**\n * Load an external stylesheet document\n */\n loadStylesheet(href, baseUri) {\n if (!this.stylesheetLoader) {\n throw new Error(\n `Cannot load stylesheet \"${href}\": no stylesheetLoader configured. ` +\n \"Use engine.setStylesheetLoader(fn) to provide a loader function.\",\n );\n }\n\n const resolvedUri = this.resolveUri(href, baseUri);\n const result = this.stylesheetLoader(resolvedUri, baseUri);\n\n // If result is a string, it needs to be parsed (caller should handle this)\n return { document: result, uri: resolvedUri };\n }\n\n /**\n * Parse XML string to document (helper for stylesheet loading)\n */\n parseXmlString(xmlString) {\n if (typeof DOMParser !== \"undefined\") {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xmlString, \"application/xml\");\n const parseError = doc.querySelector(\"parsererror\");\n if (parseError) {\n throw new Error(`XML parse error: ${parseError.textContent}`);\n }\n return doc;\n }\n throw new Error(\"XML parsing not available in this environment\");\n }\n\n /**\n * Import and compile an XSLT stylesheet\n * @param {Document|Element} stylesheetNode - The stylesheet document or root element\n * @param {string} [stylesheetUri] - Optional URI of the stylesheet for resolving imports\n */\n importStylesheet(stylesheetNode, stylesheetUri) {\n const isMainStylesheet = this.stylesheetDoc === null;\n\n if (isMainStylesheet) {\n this.stylesheetDoc = stylesheetNode.ownerDocument || stylesheetNode;\n if (stylesheetUri) {\n this.baseUri = stylesheetUri;\n this.processedStylesheets.add(stylesheetUri);\n }\n }\n\n const root = stylesheetNode.documentElement || stylesheetNode;\n\n // Validate stylesheet\n if (\n !this.isXsltElement(root, \"stylesheet\") &&\n !this.isXsltElement(root, \"transform\")\n ) {\n // Check for literal result element (simplified stylesheet)\n if (root.getAttribute && root.getAttribute(\"xsl:version\")) {\n this.processLiteralResultStylesheet(root);\n return;\n }\n throw new Error(\n \"Invalid XSLT stylesheet: root element must be xsl:stylesheet or xsl:transform\",\n );\n }\n\n // Collect namespaces from root\n this.collectNamespaces(root);\n\n // XSLT 1.0: xsl:import elements MUST come first and are processed with lower precedence\n // Process imports first (they have lower precedence than the importing stylesheet)\n const imports = [];\n const otherElements = [];\n\n for (const child of root.childNodes) {\n if (child.nodeType !== 1) continue;\n\n if (this.isXsltElement(child, \"import\")) {\n imports.push(child);\n } else {\n otherElements.push(child);\n }\n }\n\n // Process imports (lower precedence - process before current stylesheet)\n for (const importNode of imports) {\n this.processImport(importNode, stylesheetUri || this.baseUri);\n }\n\n // Process other top-level elements (including includes)\n for (const child of otherElements) {\n if (this.isXsltElement(child, \"template\")) {\n this.registerTemplate(child);\n } else if (this.isXsltElement(child, \"output\")) {\n this.processOutput(child);\n } else if (this.isXsltElement(child, \"variable\")) {\n this.processGlobalVariable(child);\n } else if (this.isXsltElement(child, \"param\")) {\n this.processGlobalParam(child);\n } else if (this.isXsltElement(child, \"key\")) {\n this.processKey(child);\n } else if (this.isXsltElement(child, \"decimal-format\")) {\n this.processDecimalFormat(child);\n } else if (this.isXsltElement(child, \"namespace-alias\")) {\n this.processNamespaceAlias(child);\n } else if (this.isXsltElement(child, \"attribute-set\")) {\n this.processAttributeSet(child);\n } else if (this.isXsltElement(child, \"strip-space\")) {\n this.processStripSpace(child);\n } else if (this.isXsltElement(child, \"preserve-space\")) {\n this.processPreserveSpace(child);\n } else if (this.isXsltElement(child, \"include\")) {\n this.processInclude(child, stylesheetUri || this.baseUri);\n }\n }\n\n // Increment import precedence after processing this stylesheet\n if (isMainStylesheet) {\n this.currentImportPrecedence++;\n }\n }\n\n /**\n * Process xsl:include element\n * Includes are merged at the same import precedence level\n */\n processInclude(node, baseUri) {\n const href = node.getAttribute(\"href\");\n if (!href) {\n throw new Error(\"xsl:include requires an href attribute\");\n }\n\n const resolvedUri = this.resolveUri(href, baseUri);\n\n // Check for circular includes\n if (this.processedStylesheets.has(resolvedUri)) {\n throw new Error(`Circular stylesheet reference detected: ${resolvedUri}`);\n }\n\n this.processedStylesheets.add(resolvedUri);\n\n try {\n const { document: stylesheetDoc } = this.loadStylesheet(href, baseUri);\n\n // Parse if string\n let doc = stylesheetDoc;\n if (typeof stylesheetDoc === \"string\") {\n doc = this.parseXmlString(stylesheetDoc);\n }\n\n // Process the included stylesheet at the same import precedence\n const savedPrecedence = this.currentImportPrecedence;\n this.processIncludedStylesheet(doc, resolvedUri);\n this.currentImportPrecedence = savedPrecedence;\n } catch (error) {\n throw new Error(\n `Failed to include stylesheet \"${href}\": ${error.message}`,\n );\n }\n }\n\n /**\n * Process xsl:import element\n * Imports have lower precedence than the importing stylesheet\n */\n processImport(node, baseUri) {\n const href = node.getAttribute(\"href\");\n if (!href) {\n throw new Error(\"xsl:import requires an href attribute\");\n }\n\n const resolvedUri = this.resolveUri(href, baseUri);\n\n // Check for circular imports\n if (this.processedStylesheets.has(resolvedUri)) {\n throw new Error(`Circular stylesheet reference detected: ${resolvedUri}`);\n }\n\n this.processedStylesheets.add(resolvedUri);\n\n try {\n const { document: stylesheetDoc } = this.loadStylesheet(href, baseUri);\n\n // Parse if string\n let doc = stylesheetDoc;\n if (typeof stylesheetDoc === \"string\") {\n doc = this.parseXmlString(stylesheetDoc);\n }\n\n // Process the imported stylesheet (imports have lower precedence)\n // Don't increment precedence yet - imported templates get current (lower) precedence\n this.processIncludedStylesheet(doc, resolvedUri);\n\n // After processing import, increment precedence for next imports and main stylesheet\n this.currentImportPrecedence++;\n } catch (error) {\n throw new Error(\n `Failed to import stylesheet \"${href}\": ${error.message}`,\n );\n }\n }\n\n /**\n * Process an included/imported stylesheet document\n */\n processIncludedStylesheet(stylesheetDoc, stylesheetUri) {\n const root = stylesheetDoc.documentElement || stylesheetDoc;\n\n // Validate stylesheet\n if (\n !this.isXsltElement(root, \"stylesheet\") &&\n !this.isXsltElement(root, \"transform\")\n ) {\n throw new Error(\n \"Included/imported document is not a valid XSLT stylesheet\",\n );\n }\n\n // Collect namespaces\n this.collectNamespaces(root);\n\n // Process imports first (they have lower precedence)\n const imports = [];\n const otherElements = [];\n\n for (const child of root.childNodes) {\n if (child.nodeType !== 1) continue;\n\n if (this.isXsltElement(child, \"import\")) {\n imports.push(child);\n } else {\n otherElements.push(child);\n }\n }\n\n // Process nested imports\n for (const importNode of imports) {\n this.processImport(importNode, stylesheetUri);\n }\n\n // Process other elements\n for (const child of otherElements) {\n if (this.isXsltElement(child, \"template\")) {\n this.registerTemplate(child);\n } else if (this.isXsltElement(child, \"output\")) {\n this.processOutput(child);\n } else if (this.isXsltElement(child, \"variable\")) {\n this.processGlobalVariable(child);\n } else if (this.isXsltElement(child, \"param\")) {\n this.processGlobalParam(child);\n } else if (this.isXsltElement(child, \"key\")) {\n this.processKey(child);\n } else if (this.isXsltElement(child, \"decimal-format\")) {\n this.processDecimalFormat(child);\n } else if (this.isXsltElement(child, \"namespace-alias\")) {\n this.processNamespaceAlias(child);\n } else if (this.isXsltElement(child, \"attribute-set\")) {\n this.processAttributeSet(child);\n } else if (this.isXsltElement(child, \"strip-space\")) {\n this.processStripSpace(child);\n } else if (this.isXsltElement(child, \"preserve-space\")) {\n this.processPreserveSpace(child);\n } else if (this.isXsltElement(child, \"include\")) {\n this.processInclude(child, stylesheetUri);\n }\n }\n }\n\n processLiteralResultStylesheet(root) {\n // Simplified stylesheet - entire document is one template matching /\n this.templates.push({\n match: \"/\",\n name: null,\n mode: null,\n priority: 0.5,\n node: root,\n });\n }\n\n collectNamespaces(node) {\n if (!node.attributes) return;\n\n for (const attr of node.attributes) {\n if (attr.name.startsWith(\"xmlns:\")) {\n const prefix = attr.name.substring(6);\n if (attr.value !== XSLT_NS) {\n this.namespaces[prefix] = attr.value;\n }\n } else if (attr.name === \"xmlns\" && attr.value !== XSLT_NS) {\n this.namespaces[\"\"] = attr.value;\n }\n }\n }\n\n registerTemplate(node) {\n const match = node.getAttribute(\"match\");\n const name = node.getAttribute(\"name\");\n const mode = node.getAttribute(\"mode\") || null;\n const priorityAttr = node.getAttribute(\"priority\");\n const priority = priorityAttr\n ? parseFloat(priorityAttr)\n : this.calculatePriority(match);\n\n this.templates.push({\n match,\n name,\n mode,\n priority,\n importPrecedence: this.currentImportPrecedence,\n node,\n });\n }\n\n calculatePriority(matchPattern) {\n if (!matchPattern) return 0.5;\n\n // Simplified priority calculation based on XPath 1.0 spec\n // - NodeType or * have priority -0.5\n // - NCName:* has priority -0.25\n // - QName has priority 0\n // - Other patterns have priority 0.5\n\n if (\n matchPattern === \"*\" ||\n matchPattern === \"node()\" ||\n matchPattern === \"text()\" ||\n matchPattern === \"comment()\" ||\n matchPattern === \"processing-instruction()\"\n ) {\n return -0.5;\n }\n\n if (matchPattern.includes(\":*\")) {\n return -0.25;\n }\n\n if (/^[a-zA-Z_][\\w.-]*$/.test(matchPattern)) {\n return 0;\n }\n\n return 0.5;\n }\n\n processOutput(node) {\n const method = node.getAttribute(\"method\");\n if (method) this.outputSettings.method = method;\n\n const encoding = node.getAttribute(\"encoding\");\n if (encoding) this.outputSettings.encoding = encoding;\n\n const indent = node.getAttribute(\"indent\");\n if (indent) this.outputSettings.indent = indent;\n\n const omit = node.getAttribute(\"omit-xml-declaration\");\n if (omit) this.outputSettings.omitXmlDeclaration = omit;\n\n const doctypePublic = node.getAttribute(\"doctype-public\");\n if (doctypePublic) this.outputSettings.doctypePublic = doctypePublic;\n\n const doctypeSystem = node.getAttribute(\"doctype-system\");\n if (doctypeSystem) this.outputSettings.doctypeSystem = doctypeSystem;\n\n const mediaType = node.getAttribute(\"media-type\");\n if (mediaType) this.outputSettings.mediaType = mediaType;\n\n const cdataElements = node.getAttribute(\"cdata-section-elements\");\n if (cdataElements) {\n this.outputSettings.cdataSectionElements = cdataElements\n .split(/\\s+/)\n .filter(Boolean);\n }\n }\n\n processGlobalVariable(node) {\n const name = node.getAttribute(\"name\");\n const select = node.getAttribute(\"select\");\n\n this.globalVariables[name] = { node, select };\n }\n\n processGlobalParam(node) {\n const name = node.getAttribute(\"name\");\n const select = node.getAttribute(\"select\");\n\n this.globalParameters[name] = { node, select };\n }\n\n processKey(node) {\n const name = node.getAttribute(\"name\");\n const match = node.getAttribute(\"match\");\n const use = node.getAttribute(\"use\");\n\n this.keys[name] = { match, use };\n }\n\n processDecimalFormat(node) {\n const name = node.getAttribute(\"name\") || \"\";\n\n this.decimalFormats[name] = {\n decimalSeparator: node.getAttribute(\"decimal-separator\") || \".\",\n groupingSeparator: node.getAttribute(\"grouping-separator\") || \",\",\n percent: node.getAttribute(\"percent\") || \"%\",\n perMille: node.getAttribute(\"per-mille\") || \"\\u2030\",\n zeroDigit: node.getAttribute(\"zero-digit\") || \"0\",\n digit: node.getAttribute(\"digit\") || \"#\",\n patternSeparator: node.getAttribute(\"pattern-separator\") || \";\",\n infinity: node.getAttribute(\"infinity\") || \"Infinity\",\n nan: node.getAttribute(\"NaN\") || \"NaN\",\n minusSign: node.getAttribute(\"minus-sign\") || \"-\",\n };\n }\n\n processNamespaceAlias(node) {\n const stylesheet = node.getAttribute(\"stylesheet-prefix\");\n const result = node.getAttribute(\"result-prefix\");\n this.namespaceAliases[stylesheet] = result;\n }\n\n processAttributeSet(node) {\n const name = node.getAttribute(\"name\");\n const useAttributeSets = node.getAttribute(\"use-attribute-sets\");\n\n this.attributeSets[name] = {\n node,\n useAttributeSets: useAttributeSets\n ? useAttributeSets.split(/\\s+/).filter(Boolean)\n : [],\n };\n }\n\n processStripSpace(node) {\n const elements = node.getAttribute(\"elements\");\n if (elements) {\n this.stripSpace.push(...elements.split(/\\s+/).filter(Boolean));\n }\n }\n\n processPreserveSpace(node) {\n const elements = node.getAttribute(\"elements\");\n if (elements) {\n this.preserveSpace.push(...elements.split(/\\s+/).filter(Boolean));\n }\n }\n\n /**\n * Transform a source document\n */\n transform(sourceNode, ownerDocument) {\n const doc =\n ownerDocument || (typeof document !== \"undefined\" ? document : null);\n\n if (!doc) {\n throw new Error(\"No output document available\");\n }\n\n // Create context - use document node as initial context for \"/\" template matching\n // XPath paths like \"RootElement/child\" expect to start from document node\n const context = new XsltContext({\n currentNode: sourceNode,\n currentNodeList: [sourceNode],\n position: 1,\n outputDocument: doc,\n stylesheet: this.stylesheetDoc,\n namespaces: { ...this.namespaces },\n templates: this.templates,\n keys: this.keys,\n decimalFormats: this.decimalFormats,\n outputMethod: this.outputSettings.method,\n xpathEvaluator: this.xpathEvaluator,\n });\n\n // Evaluate global variables\n for (const [name, def] of Object.entries(this.globalParameters)) {\n if (!(name in context.parameters)) {\n context.parameters[name] = this.evaluateVariable(def, context);\n }\n }\n\n for (const [name, def] of Object.entries(this.globalVariables)) {\n context.variables[name] = this.evaluateVariable(def, context);\n }\n\n // Create result document fragment\n const fragment = doc.createDocumentFragment();\n\n // Apply templates to document node (not documentElement)\n // This ensures \"/\" template has document as context, so paths like\n // \"RootElement/child\" work correctly\n this.applyTemplates([sourceNode], null, context, fragment);\n\n return fragment;\n }\n\n /**\n * Transform to a complete document\n */\n transformToDocument(sourceNode) {\n // For Node.js environments, we need a document implementation\n const doc = this.createDocument();\n const fragment = this.transform(sourceNode, doc);\n\n // Move fragment contents to document\n while (fragment.firstChild) {\n doc.appendChild(fragment.firstChild);\n }\n\n return doc;\n }\n\n createDocument() {\n if (typeof document !== \"undefined\") {\n return document.implementation.createDocument(null, null, null);\n }\n\n // For Node.js - would need JSDOM or similar\n throw new Error(\"Document creation not available in this environment\");\n }\n\n evaluateVariable(def, context) {\n if (def.select) {\n return this.evaluateXPath(def.select, context);\n }\n\n // If no select, evaluate content as result tree fragment\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(def.node, context, fragment);\n return fragment;\n }\n\n /**\n * Apply templates to a node list\n */\n applyTemplates(nodes, mode, context, output) {\n const nodeList = Array.isArray(nodes) ? nodes : [nodes];\n\n for (let i = 0; i < nodeList.length; i++) {\n const node = nodeList[i];\n const template = this.findMatchingTemplate(node, mode, context);\n\n if (template) {\n const newContext = context.clone({\n currentNode: node,\n currentNodeList: nodeList,\n position: i + 1,\n });\n\n this.processTemplate(template.node, newContext, output);\n } else {\n // Built-in templates\n this.applyBuiltinTemplate(node, mode, context, output);\n }\n }\n }\n\n /**\n * Find the best matching template for a node\n */\n findMatchingTemplate(node, mode, context) {\n let bestMatch = null;\n let bestPriority = -Infinity;\n let bestImportPrecedence = -Infinity;\n\n for (const template of this.templates) {\n if (template.mode !== mode) continue;\n if (!template.match) continue;\n\n if (this.matchesPattern(node, template.match, context)) {\n const priority = template.priority;\n const importPrecedence = template.importPrecedence || 0;\n\n if (\n importPrecedence > bestImportPrecedence ||\n (importPrecedence === bestImportPrecedence && priority > bestPriority)\n ) {\n bestMatch = template;\n bestPriority = priority;\n bestImportPrecedence = importPrecedence;\n }\n }\n }\n\n return bestMatch;\n }\n\n /**\n * Check if a node matches an XSLT pattern\n */\n matchesPattern(node, pattern, context) {\n // Split union patterns\n const patterns = this.splitUnionPattern(pattern);\n\n for (const p of patterns) {\n if (this.matchesSinglePattern(node, p.trim(), context)) {\n return true;\n }\n }\n\n return false;\n }\n\n splitUnionPattern(pattern) {\n // Simple split on | not inside predicates or strings\n const parts = [];\n let current = \"\";\n let depth = 0;\n let inString = false;\n let stringChar = \"\";\n\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n\n if (inString) {\n current += char;\n if (char === stringChar) {\n inString = false;\n }\n } else if (char === '\"' || char === \"'\") {\n inString = true;\n stringChar = char;\n current += char;\n } else if (char === \"[\") {\n depth++;\n current += char;\n } else if (char === \"]\") {\n depth--;\n current += char;\n } else if (char === \"|\" && depth === 0) {\n parts.push(current);\n current = \"\";\n } else {\n current += char;\n }\n }\n\n if (current) {\n parts.push(current);\n }\n\n return parts;\n }\n\n matchesSinglePattern(node, pattern, context) {\n try {\n // Handle root pattern\n if (pattern === \"/\") {\n return (\n node.nodeType === 9 || node === node.ownerDocument?.documentElement\n );\n }\n\n // Handle patterns like \"item\" (child match)\n // Need to check if node would be selected by pattern from parent\n const ast = parseXPath(pattern);\n\n // For patterns starting with /, evaluate from root\n if (pattern.startsWith(\"/\")) {\n const doc = node.ownerDocument || node;\n const xpathContext = new XPathContext(\n doc,\n 1,\n 1,\n { ...context.variables, ...context.parameters },\n context.namespaces,\n );\n const result = this.xpathEvaluator.evaluate(ast, xpathContext);\n const nodes = Array.isArray(result) ? result : [result];\n return nodes.includes(node);\n }\n\n // For relative patterns, check if this node matches when evaluated from parent\n if (node.parentNode) {\n const xpathContext = new XPathContext(\n node.parentNode,\n 1,\n 1,\n { ...context.variables, ...context.parameters },\n context.namespaces,\n );\n const result = this.xpathEvaluator.evaluate(ast, xpathContext);\n const nodes = Array.isArray(result) ? result : [result];\n return nodes.includes(node);\n }\n\n // For document node without parent\n const xpathContext = new XPathContext(\n node,\n 1,\n 1,\n { ...context.variables, ...context.parameters },\n context.namespaces,\n );\n const result = this.xpathEvaluator.evaluate(ast, xpathContext);\n const nodes = Array.isArray(result) ? result : [result];\n return nodes.includes(node);\n } catch {\n return false;\n }\n }\n\n /**\n * Apply built-in template rules\n */\n applyBuiltinTemplate(node, mode, context, output) {\n switch (node.nodeType) {\n case 1: // Element\n case 9: // Document\n case 11: // Document Fragment\n // Process children\n this.applyTemplates(Array.from(node.childNodes), mode, context, output);\n break;\n\n case 3: // Text\n case 4: {\n // CDATA\n // Copy text value\n const text = context.outputDocument.createTextNode(\n node.nodeValue || \"\",\n );\n output.appendChild(text);\n break;\n }\n\n case 2: {\n // Attribute\n // Copy attribute value as text\n const attrText = context.outputDocument.createTextNode(\n node.nodeValue || \"\",\n );\n output.appendChild(attrText);\n break;\n }\n\n // Comments and PIs have no built-in template\n }\n }\n\n /**\n * Process template content\n */\n processTemplate(templateNode, context, output) {\n // Process template parameters first\n const localContext = context.clone();\n\n for (const child of templateNode.childNodes) {\n if (child.nodeType === 1 && this.isXsltElement(child, \"param\")) {\n const name = child.getAttribute(\"name\");\n if (!(name in localContext.parameters)) {\n localContext.parameters[name] = this.evaluateVariable(\n { node: child, select: child.getAttribute(\"select\") },\n localContext,\n );\n }\n }\n }\n\n this.processChildren(templateNode, localContext, output);\n }\n\n /**\n * Process child nodes of an XSLT element\n */\n processChildren(node, context, output) {\n for (const child of node.childNodes) {\n this.processNode(child, context, output);\n }\n }\n\n /**\n * Process a single node in the stylesheet\n */\n processNode(node, context, output) {\n switch (node.nodeType) {\n case 1: // Element\n this.processElement(node, context, output);\n break;\n\n case 3: // Text\n case 4: {\n // CDATA\n // Output text if not whitespace only (or if preserving space)\n const text = node.nodeValue;\n if (text && (text.trim() || this.shouldPreserveSpace(node))) {\n const textNode = context.outputDocument.createTextNode(text);\n output.appendChild(textNode);\n }\n break;\n }\n }\n }\n\n shouldPreserveSpace(node) {\n // Check xml:space attribute on ancestors\n let current = node.parentNode;\n while (current && current.nodeType === 1) {\n const space = current.getAttribute(\"xml:space\");\n if (space === \"preserve\") return true;\n if (space === \"default\") return false;\n current = current.parentNode;\n }\n return false;\n }\n\n /**\n * Process an element in the stylesheet\n */\n processElement(node, context, output) {\n // Check if XSLT element\n if (this.isXsltNamespace(node)) {\n this.processXsltElement(node, context, output);\n } else {\n // Literal result element\n this.processLiteralResultElement(node, context, output);\n }\n }\n\n /**\n * Process an XSLT instruction element\n */\n processXsltElement(node, context, output) {\n const localName = node.localName || node.nodeName.replace(/^xsl:/, \"\");\n\n switch (localName) {\n case \"apply-templates\":\n this.xslApplyTemplates(node, context, output);\n break;\n\n case \"call-template\":\n this.xslCallTemplate(node, context, output);\n break;\n\n case \"value-of\":\n this.xslValueOf(node, context, output);\n break;\n\n case \"text\":\n this.xslText(node, context, output);\n break;\n\n case \"element\":\n this.xslElement(node, context, output);\n break;\n\n case \"attribute\":\n this.xslAttribute(node, context, output);\n break;\n\n case \"if\":\n this.xslIf(node, context, output);\n break;\n\n case \"choose\":\n this.xslChoose(node, context, output);\n break;\n\n case \"for-each\":\n this.xslForEach(node, context, output);\n break;\n\n case \"copy\":\n this.xslCopy(node, context, output);\n break;\n\n case \"copy-of\":\n this.xslCopyOf(node, context, output);\n break;\n\n case \"variable\":\n this.xslVariable(node, context, output);\n break;\n\n case \"param\":\n // Params are processed at template start\n break;\n\n case \"comment\":\n this.xslComment(node, context, output);\n break;\n\n case \"processing-instruction\":\n this.xslProcessingInstruction(node, context, output);\n break;\n\n case \"number\":\n this.xslNumber(node, context, output);\n break;\n\n case \"sort\":\n // Handled by apply-templates and for-each\n break;\n\n case \"with-param\":\n // Handled by call-template and apply-templates\n break;\n\n case \"message\":\n this.xslMessage(node, context, output);\n break;\n\n case \"fallback\":\n // Used for forward compatibility\n break;\n\n default:\n console.warn(`Unknown XSLT element: ${localName}`);\n }\n }\n\n /**\n * Process a literal result element (non-XSLT)\n */\n processLiteralResultElement(node, context, output) {\n // Create element in output\n let outputElement;\n const namespaceURI = node.namespaceURI;\n const nodeName = node.nodeName;\n\n // Apply namespace aliases\n let resolvedNS = namespaceURI;\n if (namespaceURI) {\n for (const [from, to] of Object.entries(this.namespaceAliases)) {\n if (this.namespaces[from] === namespaceURI) {\n resolvedNS = this.namespaces[to] || to;\n break;\n }\n }\n }\n\n if (resolvedNS && context.outputDocument.createElementNS) {\n outputElement = context.outputDocument.createElementNS(\n resolvedNS,\n nodeName,\n );\n } else {\n outputElement = context.outputDocument.createElement(nodeName);\n }\n\n // Copy attributes (except XSLT namespace)\n if (node.attributes) {\n for (const attr of node.attributes) {\n if (attr.namespaceURI === XSLT_NS) continue;\n if (attr.name.startsWith(\"xmlns\")) continue;\n\n // Process attribute value templates\n const value = this.processAttributeValueTemplate(attr.value, context);\n outputElement.setAttribute(attr.name, value);\n }\n }\n\n // Process children\n this.processChildren(node, context, outputElement);\n\n output.appendChild(outputElement);\n }\n\n /**\n * Process attribute value templates (expressions in curly braces)\n */\n processAttributeValueTemplate(value, context) {\n if (!value.includes(\"{\")) return value;\n\n let result = \"\";\n let i = 0;\n\n while (i < value.length) {\n if (value[i] === \"{\") {\n if (value[i + 1] === \"{\") {\n // Escaped brace\n result += \"{\";\n i += 2;\n } else {\n // Find closing brace\n let depth = 1;\n let j = i + 1;\n while (j < value.length && depth > 0) {\n if (value[j] === \"{\") depth++;\n else if (value[j] === \"}\") depth--;\n j++;\n }\n\n const expr = value.substring(i + 1, j - 1);\n const evalResult = this.evaluateXPath(expr, context);\n result += this.xpathEvaluator.toString(evalResult);\n i = j;\n }\n } else if (value[i] === \"}\") {\n if (value[i + 1] === \"}\") {\n // Escaped brace\n result += \"}\";\n i += 2;\n } else {\n throw new Error(\"Unmatched } in attribute value template\");\n }\n } else {\n result += value[i];\n i++;\n }\n }\n\n return result;\n }\n\n // XSLT Instructions\n xslApplyTemplates(node, context, output) {\n const select = node.getAttribute(\"select\") || \"node()\";\n const mode = node.getAttribute(\"mode\") || null;\n\n // Evaluate select expression\n let nodes = this.evaluateXPath(select, context);\n if (!Array.isArray(nodes)) {\n nodes = nodes ? [nodes] : [];\n }\n\n // Collect sort specifications\n const sortSpecs = [];\n for (const child of node.childNodes) {\n if (child.nodeType === 1 && this.isXsltElement(child, \"sort\")) {\n sortSpecs.push({\n select: child.getAttribute(\"select\") || \".\",\n order: child.getAttribute(\"order\") || \"ascending\",\n dataType: child.getAttribute(\"data-type\") || \"text\",\n caseOrder: child.getAttribute(\"case-order\") || \"upper-first\",\n lang: child.getAttribute(\"lang\"),\n });\n }\n }\n\n // Apply sorting\n if (sortSpecs.length > 0) {\n nodes = this.sortNodes(nodes, sortSpecs, context);\n }\n\n // Collect with-param values\n const params = {};\n for (const child of node.childNodes) {\n if (child.nodeType === 1 && this.isXsltElement(child, \"with-param\")) {\n const name = child.getAttribute(\"name\");\n const selectAttr = child.getAttribute(\"select\");\n if (selectAttr) {\n params[name] = this.evaluateXPath(selectAttr, context);\n } else {\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(child, context, fragment);\n params[name] = fragment;\n }\n }\n }\n\n // Apply templates with new context including params\n const newContext = context.clone({\n parameters: { ...context.parameters, ...params },\n });\n this.applyTemplates(nodes, mode, newContext, output);\n }\n\n xslCallTemplate(node, context, output) {\n const name = node.getAttribute(\"name\");\n\n // Find named template\n const template = this.templates.find((t) => t.name === name);\n if (!template) {\n throw new Error(`Template not found: ${name}`);\n }\n\n // Collect with-param values\n const params = {};\n for (const child of node.childNodes) {\n if (child.nodeType === 1 && this.isXsltElement(child, \"with-param\")) {\n const paramName = child.getAttribute(\"name\");\n const selectAttr = child.getAttribute(\"select\");\n if (selectAttr) {\n params[paramName] = this.evaluateXPath(selectAttr, context);\n } else {\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(child, context, fragment);\n params[paramName] = fragment;\n }\n }\n }\n\n // Call template with params\n const newContext = context.clone({\n parameters: { ...context.parameters, ...params },\n });\n this.processTemplate(template.node, newContext, output);\n }\n\n xslValueOf(node, context, output) {\n const select = node.getAttribute(\"select\");\n const disableOutputEscaping =\n node.getAttribute(\"disable-output-escaping\") === \"yes\";\n\n const result = this.evaluateXPath(select, context);\n const text = this.xpathEvaluator.toString(result);\n\n if (text) {\n const textNode = context.outputDocument.createTextNode(text);\n if (disableOutputEscaping) {\n textNode._disableOutputEscaping = true;\n }\n output.appendChild(textNode);\n }\n }\n\n xslText(node, context, output) {\n const disableOutputEscaping =\n node.getAttribute(\"disable-output-escaping\") === \"yes\";\n let text = \"\";\n\n for (const child of node.childNodes) {\n if (child.nodeType === 3 || child.nodeType === 4) {\n text += child.nodeValue || \"\";\n }\n }\n\n if (text) {\n const textNode = context.outputDocument.createTextNode(text);\n if (disableOutputEscaping) {\n textNode._disableOutputEscaping = true;\n }\n output.appendChild(textNode);\n }\n }\n\n xslElement(node, context, output) {\n const name = this.processAttributeValueTemplate(\n node.getAttribute(\"name\"),\n context,\n );\n const namespace = node.getAttribute(\"namespace\");\n const useAttributeSets = node.getAttribute(\"use-attribute-sets\");\n\n let element;\n if (namespace) {\n const ns = this.processAttributeValueTemplate(namespace, context);\n element = context.outputDocument.createElementNS(ns, name);\n } else {\n element = context.outputDocument.createElement(name);\n }\n\n // Apply attribute sets\n if (useAttributeSets) {\n this.applyAttributeSets(useAttributeSets, context, element);\n }\n\n this.processChildren(node, context, element);\n output.appendChild(element);\n }\n\n xslAttribute(node, context, output) {\n const name = this.processAttributeValueTemplate(\n node.getAttribute(\"name\"),\n context,\n );\n const namespace = node.getAttribute(\"namespace\");\n\n // Collect content\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(node, context, fragment);\n\n // Get text content\n let value = \"\";\n const getText = (n) => {\n if (n.nodeType === 3 || n.nodeType === 4) {\n value += n.nodeValue || \"\";\n } else if (n.childNodes) {\n for (const child of n.childNodes) {\n getText(child);\n }\n }\n };\n getText(fragment);\n\n // Add attribute to parent element\n if (output.nodeType === 1) {\n if (namespace) {\n const ns = this.processAttributeValueTemplate(namespace, context);\n output.setAttributeNS(ns, name, value);\n } else {\n output.setAttribute(name, value);\n }\n }\n }\n\n xslIf(node, context, output) {\n const test = node.getAttribute(\"test\");\n const result = this.evaluateXPath(test, context);\n\n if (this.xpathEvaluator.toBoolean(result)) {\n this.processChildren(node, context, output);\n }\n }\n\n xslChoose(node, context, output) {\n for (const child of node.childNodes) {\n if (child.nodeType !== 1) continue;\n\n if (this.isXsltElement(child, \"when\")) {\n const test = child.getAttribute(\"test\");\n const result = this.evaluateXPath(test, context);\n\n if (this.xpathEvaluator.toBoolean(result)) {\n this.processChildren(child, context, output);\n return;\n }\n } else if (this.isXsltElement(child, \"otherwise\")) {\n this.processChildren(child, context, output);\n return;\n }\n }\n }\n\n xslForEach(node, context, output) {\n const select = node.getAttribute(\"select\");\n\n let nodes = this.evaluateXPath(select, context);\n if (!Array.isArray(nodes)) {\n nodes = nodes ? [nodes] : [];\n }\n\n // Collect sort specifications\n const sortSpecs = [];\n for (const child of node.childNodes) {\n if (child.nodeType === 1 && this.isXsltElement(child, \"sort\")) {\n sortSpecs.push({\n select: child.getAttribute(\"select\") || \".\",\n order: child.getAttribute(\"order\") || \"ascending\",\n dataType: child.getAttribute(\"data-type\") || \"text\",\n caseOrder: child.getAttribute(\"case-order\") || \"upper-first\",\n lang: child.getAttribute(\"lang\"),\n });\n }\n }\n\n // Apply sorting\n if (sortSpecs.length > 0) {\n nodes = this.sortNodes(nodes, sortSpecs, context);\n }\n\n // Process each node\n for (let i = 0; i < nodes.length; i++) {\n const newContext = context.clone({\n currentNode: nodes[i],\n currentNodeList: nodes,\n position: i + 1,\n });\n\n this.processChildren(node, newContext, output);\n }\n }\n\n xslCopy(node, context, output) {\n const currentNode = context.currentNode;\n const useAttributeSets = node.getAttribute(\"use-attribute-sets\");\n\n switch (currentNode.nodeType) {\n case 1: {\n // Element\n let copy;\n if (currentNode.namespaceURI) {\n copy = context.outputDocument.createElementNS(\n currentNode.namespaceURI,\n currentNode.nodeName,\n );\n } else {\n copy = context.outputDocument.createElement(currentNode.nodeName);\n }\n\n if (useAttributeSets) {\n this.applyAttributeSets(useAttributeSets, context, copy);\n }\n\n this.processChildren(node, context, copy);\n output.appendChild(copy);\n break;\n }\n\n case 2: // Attribute\n if (output.nodeType === 1) {\n output.setAttribute(currentNode.name, currentNode.value);\n }\n break;\n\n case 3: // Text\n case 4: {\n // CDATA\n const textCopy = context.outputDocument.createTextNode(\n currentNode.nodeValue || \"\",\n );\n output.appendChild(textCopy);\n break;\n }\n\n case 7: {\n // Processing Instruction\n const piCopy = context.outputDocument.createProcessingInstruction(\n currentNode.target,\n currentNode.data,\n );\n output.appendChild(piCopy);\n break;\n }\n\n case 8: {\n // Comment\n const commentCopy = context.outputDocument.createComment(\n currentNode.nodeValue || \"\",\n );\n output.appendChild(commentCopy);\n break;\n }\n\n case 9: // Document\n case 11: // Document Fragment\n this.processChildren(node, context, output);\n break;\n }\n }\n\n xslCopyOf(node, context, output) {\n const select = node.getAttribute(\"select\");\n const result = this.evaluateXPath(select, context);\n\n this.copyToOutput(result, context, output);\n }\n\n copyToOutput(value, context, output) {\n if (Array.isArray(value)) {\n for (const item of value) {\n this.copyToOutput(item, context, output);\n }\n return;\n }\n\n if (value && value.nodeType) {\n // Deep copy node\n const clone = this.deepCloneNode(value, context.outputDocument);\n output.appendChild(clone);\n } else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n const text = context.outputDocument.createTextNode(String(value));\n output.appendChild(text);\n }\n }\n\n deepCloneNode(node, targetDoc) {\n switch (node.nodeType) {\n case 1: {\n // Element\n let clone;\n if (node.namespaceURI && targetDoc.createElementNS) {\n clone = targetDoc.createElementNS(node.namespaceURI, node.nodeName);\n } else {\n clone = targetDoc.createElement(node.nodeName);\n }\n\n if (node.attributes) {\n for (const attr of node.attributes) {\n clone.setAttribute(attr.name, attr.value);\n }\n }\n\n for (const child of node.childNodes) {\n clone.appendChild(this.deepCloneNode(child, targetDoc));\n }\n\n return clone;\n }\n\n case 3: // Text\n case 4: // CDATA\n return targetDoc.createTextNode(node.nodeValue || \"\");\n\n case 7: // Processing Instruction\n return targetDoc.createProcessingInstruction(node.target, node.data);\n\n case 8: // Comment\n return targetDoc.createComment(node.nodeValue || \"\");\n\n case 11: {\n // Document Fragment\n const frag = targetDoc.createDocumentFragment();\n for (const child of node.childNodes) {\n frag.appendChild(this.deepCloneNode(child, targetDoc));\n }\n return frag;\n }\n\n default:\n return targetDoc.createTextNode(\"\");\n }\n }\n\n xslVariable(node, context, _output) {\n const name = node.getAttribute(\"name\");\n const select = node.getAttribute(\"select\");\n\n let value;\n if (select) {\n value = this.evaluateXPath(select, context);\n } else {\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(node, context, fragment);\n value = fragment;\n }\n\n context.setVariable(name, value);\n }\n\n xslComment(node, context, output) {\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(node, context, fragment);\n\n let text = \"\";\n const getText = (n) => {\n if (n.nodeType === 3 || n.nodeType === 4) {\n text += n.nodeValue || \"\";\n } else if (n.childNodes) {\n for (const child of n.childNodes) {\n getText(child);\n }\n }\n };\n getText(fragment);\n\n const comment = context.outputDocument.createComment(text);\n output.appendChild(comment);\n }\n\n xslProcessingInstruction(node, context, output) {\n const name = this.processAttributeValueTemplate(\n node.getAttribute(\"name\"),\n context,\n );\n\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(node, context, fragment);\n\n let data = \"\";\n const getText = (n) => {\n if (n.nodeType === 3 || n.nodeType === 4) {\n data += n.nodeValue || \"\";\n } else if (n.childNodes) {\n for (const child of n.childNodes) {\n getText(child);\n }\n }\n };\n getText(fragment);\n\n const pi = context.outputDocument.createProcessingInstruction(name, data);\n output.appendChild(pi);\n }\n\n xslNumber(node, context, output) {\n const value = node.getAttribute(\"value\");\n const format = node.getAttribute(\"format\") || \"1\";\n const level = node.getAttribute(\"level\") || \"single\";\n\n let number;\n if (value) {\n number = Math.round(\n this.xpathEvaluator.toNumber(this.evaluateXPath(value, context)),\n );\n } else {\n // Count based on level\n number = this.countNumber(context.currentNode, level, node, context);\n }\n\n const formatted = this.formatNumber(number, format);\n const text = context.outputDocument.createTextNode(formatted);\n output.appendChild(text);\n }\n\n countNumber(node, level, spec, context) {\n const count = spec.getAttribute(\"count\");\n const _from = spec.getAttribute(\"from\");\n\n // Simplified implementation\n if (level === \"single\") {\n // Count preceding siblings matching pattern\n let n = 1;\n let sibling = node.previousSibling;\n while (sibling) {\n if (sibling.nodeType === 1) {\n if (!count || this.matchesPattern(sibling, count, context)) {\n n++;\n }\n }\n sibling = sibling.previousSibling;\n }\n return n;\n }\n\n return 1;\n }\n\n formatNumber(number, format) {\n // Simple format implementation\n if (/^[0-9]+$/.test(format)) {\n return String(number).padStart(format.length, \"0\");\n }\n\n if (format === \"a\") {\n return String.fromCharCode(96 + ((number - 1) % 26) + 1);\n }\n\n if (format === \"A\") {\n return String.fromCharCode(64 + ((number - 1) % 26) + 1);\n }\n\n if (format === \"i\") {\n return this.toRoman(number).toLowerCase();\n }\n\n if (format === \"I\") {\n return this.toRoman(number);\n }\n\n return String(number);\n }\n\n toRoman(num) {\n const romanNumerals = [\n [\"M\", 1000],\n [\"CM\", 900],\n [\"D\", 500],\n [\"CD\", 400],\n [\"C\", 100],\n [\"XC\", 90],\n [\"L\", 50],\n [\"XL\", 40],\n [\"X\", 10],\n [\"IX\", 9],\n [\"V\", 5],\n [\"IV\", 4],\n [\"I\", 1],\n ];\n\n let result = \"\";\n for (const [numeral, value] of romanNumerals) {\n while (num >= value) {\n result += numeral;\n num -= value;\n }\n }\n return result;\n }\n\n xslMessage(node, context, _output) {\n const terminate = node.getAttribute(\"terminate\") === \"yes\";\n\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(node, context, fragment);\n\n let text = \"\";\n const getText = (n) => {\n if (n.nodeType === 3 || n.nodeType === 4) {\n text += n.nodeValue || \"\";\n } else if (n.childNodes) {\n for (const child of n.childNodes) {\n getText(child);\n }\n }\n };\n getText(fragment);\n\n console.log(\"XSLT Message:\", text);\n\n if (terminate) {\n throw new Error(`XSLT terminated: ${text}`);\n }\n }\n\n applyAttributeSets(names, context, element) {\n const setNames = names.split(/\\s+/).filter(Boolean);\n\n for (const name of setNames) {\n const attrSet = this.attributeSets[name];\n if (attrSet) {\n // Apply inherited sets first\n if (attrSet.useAttributeSets.length > 0) {\n this.applyAttributeSets(\n attrSet.useAttributeSets.join(\" \"),\n context,\n element,\n );\n }\n\n // Apply attributes from this set\n for (const child of attrSet.node.childNodes) {\n if (child.nodeType === 1 && this.isXsltElement(child, \"attribute\")) {\n this.xslAttribute(child, context, element);\n }\n }\n }\n }\n }\n\n sortNodes(nodes, sortSpecs, context) {\n return [...nodes].sort((a, b) => {\n for (const spec of sortSpecs) {\n const contextA = context.clone({ currentNode: a });\n const contextB = context.clone({ currentNode: b });\n\n let valueA = this.evaluateXPath(spec.select, contextA);\n let valueB = this.evaluateXPath(spec.select, contextB);\n\n // Convert to string for comparison (ensure non-null values)\n valueA = this.xpathEvaluator.toString(valueA) || \"\";\n valueB = this.xpathEvaluator.toString(valueB) || \"\";\n\n if (spec.dataType === \"number\") {\n valueA = parseFloat(valueA) || 0;\n valueB = parseFloat(valueB) || 0;\n } else {\n // Text comparison\n if (spec.caseOrder === \"lower-first\") {\n valueA = valueA.toLowerCase();\n valueB = valueB.toLowerCase();\n } else {\n valueA = valueA.toUpperCase();\n valueB = valueB.toUpperCase();\n }\n }\n\n let cmp;\n if (typeof valueA === \"number\") {\n cmp = valueA - valueB;\n } else {\n cmp = valueA.localeCompare(valueB, spec.lang || undefined);\n }\n\n if (spec.order === \"descending\") {\n cmp = -cmp;\n }\n\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n });\n }\n\n evaluateXPath(expr, context) {\n const ast = parseXPath(expr);\n const xpathContext = new XPathContext(\n context.currentNode,\n context.position,\n context.currentNodeList.length,\n { ...context.variables, ...context.parameters },\n context.namespaces,\n );\n return this.xpathEvaluator.evaluate(ast, xpathContext);\n }\n\n isXsltNamespace(node) {\n return (\n node.namespaceURI === XSLT_NS ||\n (node.nodeName && node.nodeName.startsWith(\"xsl:\"))\n );\n }\n\n isXsltElement(node, localName) {\n if (node.nodeType !== 1) return false;\n\n const nodeName = node.localName || node.nodeName;\n return (\n (node.namespaceURI === XSLT_NS && nodeName === localName) ||\n node.nodeName === `xsl:${localName}`\n );\n }\n}\n", "/**\n * XSLTProcessor - JavaScript Implementation\n *\n * Native-compatible XSLTProcessor implementation for browser environments.\n * Based on W3C DOM Level 3 XSL Transformations and XSLT 1.0 Specification.\n *\n * Reference: https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor\n * XSLT 1.0: http://www.w3.org/TR/1999/REC-xslt-19991116\n * XPath 1.0: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * This implementation provides 1:1 API compatibility with the native\n * browser XSLTProcessor. It can be used as a replacement when native\n * XSLT support is deprecated or unavailable.\n */\n\nimport { XsltEngine } from \"./xslt/engine.js\";\n\n/**\n * XSLTProcessor\n *\n * Applies XSLT stylesheet transformations to XML documents.\n *\n * @example\n * const processor = new XSLTProcessor();\n * processor.importStylesheet(xsltDoc);\n * const fragment = processor.transformToFragment(xmlDoc, document);\n */\nexport class XSLTProcessor {\n constructor() {\n this._engine = null;\n this._stylesheet = null;\n this._parameters = new Map();\n }\n\n /**\n * Imports the XSLT stylesheet.\n *\n * If the given node is a document node, you can pass in a full XSL Transform\n * or a literal result element transform; otherwise, it must be an\n * <xsl:stylesheet> or <xsl:transform> element.\n *\n * @param {Node} style - The XSLT stylesheet to import (Document or Element)\n * @returns {void}\n *\n * @example\n * const parser = new DOMParser();\n * const xslDoc = parser.parseFromString(xslText, 'application/xml');\n * processor.importStylesheet(xslDoc);\n */\n importStylesheet(style) {\n if (!style) {\n throw new TypeError(\n \"Failed to execute 'importStylesheet' on 'XSLTProcessor': 1 argument required, but only 0 present.\",\n );\n }\n\n // Validate node type\n if (style.nodeType !== 1 && style.nodeType !== 9) {\n throw new TypeError(\n \"Failed to execute 'importStylesheet' on 'XSLTProcessor': The node provided is not a Document or Element.\",\n );\n }\n\n // Check for parser errors\n const errorNode = style.querySelector\n ? style.querySelector(\"parsererror\")\n : null;\n if (errorNode) {\n throw new Error(\"XSLT stylesheet contains parse errors\");\n }\n\n this._stylesheet = style;\n this._engine = new XsltEngine();\n\n // Apply any previously set parameters\n for (const [key, value] of this._parameters) {\n this._engine.globalParameters[key] = { value };\n }\n\n this._engine.importStylesheet(style);\n }\n\n /**\n * Transforms the node source by applying the XSLT stylesheet.\n * Returns a document fragment.\n *\n * @param {Node} source - The XML document to transform\n * @param {Document} output - The document that will own the generated fragment\n * @returns {DocumentFragment} The transformed result as a DocumentFragment\n *\n * @example\n * const fragment = processor.transformToFragment(xmlDoc, document);\n * document.getElementById('output').appendChild(fragment);\n */\n transformToFragment(source, output) {\n if (!source) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': 2 arguments required, but only 0 present.\",\n );\n }\n\n if (!output) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': 2 arguments required, but only 1 present.\",\n );\n }\n\n if (!this._engine || !this._stylesheet) {\n throw new Error(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': No stylesheet has been imported.\",\n );\n }\n\n // Validate source node\n if (\n source.nodeType !== 1 &&\n source.nodeType !== 9 &&\n source.nodeType !== 11\n ) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': The source is not a valid node type.\",\n );\n }\n\n // Validate output document\n if (output.nodeType !== 9) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': The output is not a Document.\",\n );\n }\n\n try {\n return this._engine.transform(source, output);\n } catch (error) {\n // Match native behavior - return null on error\n console.error(\"XSLT transformation error:\", error);\n return null;\n }\n }\n\n /**\n * Transforms the node source by applying the XSLT stylesheet.\n * Returns a full XML document.\n *\n * @param {Node} source - The XML document to transform\n * @returns {XMLDocument} The transformed result as an XMLDocument\n *\n * @example\n * const resultDoc = processor.transformToDocument(xmlDoc);\n * const serialized = new XMLSerializer().serializeToString(resultDoc);\n */\n transformToDocument(source) {\n if (!source) {\n throw new TypeError(\n \"Failed to execute 'transformToDocument' on 'XSLTProcessor': 1 argument required, but only 0 present.\",\n );\n }\n\n if (!this._engine || !this._stylesheet) {\n throw new Error(\n \"Failed to execute 'transformToDocument' on 'XSLTProcessor': No stylesheet has been imported.\",\n );\n }\n\n // Validate source node\n if (\n source.nodeType !== 1 &&\n source.nodeType !== 9 &&\n source.nodeType !== 11\n ) {\n throw new TypeError(\n \"Failed to execute 'transformToDocument' on 'XSLTProcessor': The source is not a valid node type.\",\n );\n }\n\n try {\n return this._engine.transformToDocument(source);\n } catch (error) {\n // Match native behavior - return null on error\n console.error(\"XSLT transformation error:\", error);\n return null;\n }\n }\n\n /**\n * Sets a parameter in the XSLT stylesheet.\n *\n * @param {string|null} namespaceURI - The namespace URI of the XSLT parameter (use null for no namespace)\n * @param {string} localName - The local name of the parameter\n * @param {*} value - The value to set (string, number, boolean, or node-set)\n * @returns {void}\n *\n * @example\n * processor.setParameter(null, 'sortOrder', 'ascending');\n * processor.setParameter('http://example.com/ns', 'limit', 10);\n */\n setParameter(namespaceURI, localName, value) {\n if (arguments.length < 3) {\n throw new TypeError(\n `Failed to execute 'setParameter' on 'XSLTProcessor': 3 arguments required, but only ${arguments.length} present.`,\n );\n }\n\n if (typeof localName !== \"string\" || localName === \"\") {\n throw new TypeError(\n \"Failed to execute 'setParameter' on 'XSLTProcessor': The localName argument must be a non-empty string.\",\n );\n }\n\n const key = namespaceURI ? `{${namespaceURI}}${localName}` : localName;\n this._parameters.set(key, value);\n\n // If engine is already initialized, update it\n if (this._engine) {\n this._engine.globalParameters[key] = { value };\n }\n }\n\n /**\n * Gets the value of a parameter from the XSLT stylesheet.\n *\n * @param {string|null} namespaceURI - The namespace URI of the parameter\n * @param {string} localName - The local name of the parameter\n * @returns {*} The parameter value, or empty string if not set\n *\n * @example\n * const sortOrder = processor.getParameter(null, 'sortOrder');\n */\n getParameter(namespaceURI, localName) {\n if (arguments.length < 2) {\n throw new TypeError(\n `Failed to execute 'getParameter' on 'XSLTProcessor': 2 arguments required, but only ${arguments.length} present.`,\n );\n }\n\n if (typeof localName !== \"string\") {\n throw new TypeError(\n \"Failed to execute 'getParameter' on 'XSLTProcessor': The localName argument must be a string.\",\n );\n }\n\n const key = namespaceURI ? `{${namespaceURI}}${localName}` : localName;\n\n if (this._parameters.has(key)) {\n return this._parameters.get(key);\n }\n\n // Return empty string for unset parameters (matches native behavior)\n return \"\";\n }\n\n /**\n * Removes a parameter from the XSLT processor.\n *\n * The XSLTProcessor will use the default value for the parameter\n * as specified in the XSLT stylesheet.\n *\n * @param {string|null} namespaceURI - The namespace URI of the parameter\n * @param {string} localName - The local name of the parameter\n * @returns {void}\n *\n * @example\n * processor.removeParameter(null, 'sortOrder');\n */\n removeParameter(namespaceURI, localName) {\n if (arguments.length < 2) {\n throw new TypeError(\n `Failed to execute 'removeParameter' on 'XSLTProcessor': 2 arguments required, but only ${arguments.length} present.`,\n );\n }\n\n if (typeof localName !== \"string\") {\n throw new TypeError(\n \"Failed to execute 'removeParameter' on 'XSLTProcessor': The localName argument must be a string.\",\n );\n }\n\n const key = namespaceURI ? `{${namespaceURI}}${localName}` : localName;\n this._parameters.delete(key);\n\n if (this._engine) {\n delete this._engine.globalParameters[key];\n }\n }\n\n /**\n * Removes all set parameters from the XSLTProcessor.\n *\n * The processor will use default values specified in the XSLT stylesheet.\n *\n * @returns {void}\n *\n * @example\n * processor.clearParameters();\n */\n clearParameters() {\n this._parameters.clear();\n\n if (this._engine) {\n this._engine.globalParameters = {};\n }\n }\n\n /**\n * Removes all parameters and stylesheets from the XSLTProcessor.\n *\n * @returns {void}\n *\n * @example\n * processor.reset();\n * // Now need to call importStylesheet() again before transforming\n */\n reset() {\n this._engine = null;\n this._stylesheet = null;\n this._parameters.clear();\n }\n}\n\n/**\n * Check if native XSLTProcessor is available and functional\n *\n * @returns {boolean} True if native XSLTProcessor works correctly\n */\nexport function isNativeXSLTSupported() {\n if (typeof globalThis.XSLTProcessor === \"undefined\") {\n return false;\n }\n\n try {\n const processor = new globalThis.XSLTProcessor();\n const parser = new DOMParser();\n\n const xslt = parser.parseFromString(\n `<?xml version=\"1.0\"?>\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"/\"><test/></xsl:template>\n </xsl:stylesheet>`,\n \"application/xml\",\n );\n\n processor.importStylesheet(xslt);\n\n const xml = parser.parseFromString(\"<root/>\", \"application/xml\");\n const result = processor.transformToFragment(xml, document);\n\n return result !== null && result.childNodes.length > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Install as global XSLTProcessor replacement if native is not functional\n *\n * @param {boolean} force - Force installation even if native is available\n * @returns {boolean} True if installed as global\n */\nexport function installGlobal(force = false) {\n if (!force && isNativeXSLTSupported()) {\n return false;\n }\n\n globalThis.XSLTProcessor = XSLTProcessor;\n return true;\n}\n\nexport default XSLTProcessor;\n", "/**\n * XPath 1.0 Module\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n */\n\n\"use strict\";\n\nexport { TokenType, Token, XPathTokenizer, tokenize } from \"./tokenizer.js\";\nexport { NodeType, ASTNode, XPathParser, parse } from \"./parser.js\";\nexport {\n XPathResultType,\n XPathContext,\n XPathEvaluator,\n XPathLimits,\n} from \"./evaluator.js\";\n\nimport { parse } from \"./parser.js\";\nimport { XPathEvaluator, XPathContext } from \"./evaluator.js\";\n\n/**\n * Evaluate an XPath expression against a node\n *\n * @param {string} expression - XPath expression\n * @param {Node} contextNode - Context node\n * @param {Object} options - Options (variables, namespaces)\n * @returns {*} Evaluation result\n */\nexport function evaluate(expression, contextNode, options = {}) {\n const ast = parse(expression);\n const evaluator = new XPathEvaluator();\n const context = new XPathContext(\n contextNode,\n 1,\n 1,\n options.variables || {},\n options.namespaces || {},\n );\n return evaluator.evaluate(ast, context);\n}\n\n/**\n * Select nodes matching an XPath expression\n *\n * @param {string} expression - XPath expression\n * @param {Node} contextNode - Context node\n * @param {Object} options - Options\n * @returns {Node[]} Matching nodes\n */\nexport function select(expression, contextNode, options = {}) {\n const result = evaluate(expression, contextNode, options);\n if (Array.isArray(result)) return result;\n if (result && result.nodeType) return [result];\n return [];\n}\n\n/**\n * Select first node matching an XPath expression\n *\n * @param {string} expression - XPath expression\n * @param {Node} contextNode - Context node\n * @param {Object} options - Options\n * @returns {Node|null} First matching node or null\n */\nexport function selectFirst(expression, contextNode, options = {}) {\n const nodes = select(expression, contextNode, options);\n return nodes.length > 0 ? nodes[0] : null;\n}\n", "/**\n * xslt-processor\n *\n * JavaScript implementation of XSLTProcessor for browser environments.\n *\n * This package provides a JavaScript implementation of the W3C XSLTProcessor API\n * that can be used as a drop-in replacement for the native browser implementation.\n *\n * Specifications implemented:\n * - XPath 1.0: http://www.w3.org/TR/1999/REC-xpath-19991116\n * - XSLT 1.0: http://www.w3.org/TR/1999/REC-xslt-19991116\n * - DOM Level 3: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/\n *\n * @example\n * // ESM import\n * import { XSLTProcessor, installGlobal } from 'xslt-processor';\n *\n * // Install as global replacement\n * installGlobal();\n *\n * // Or use directly\n * const processor = new XSLTProcessor();\n * processor.importStylesheet(xsltDoc);\n * const result = processor.transformToFragment(xmlDoc, document);\n */\n\n// Main XSLTProcessor class\nexport {\n XSLTProcessor,\n isNativeXSLTSupported,\n installGlobal,\n default as default,\n} from \"./XSLTProcessor.js\";\n\n// XPath module (for advanced users)\nexport {\n evaluate as evaluateXPath,\n select as selectXPath,\n selectFirst as selectFirstXPath,\n XPathEvaluator,\n XPathContext,\n XPathResultType,\n parse as parseXPath,\n} from \"./xpath/index.js\";\n\n// XSLT engine (for advanced users)\nexport { XsltEngine, XsltContext } from \"./xslt/index.js\";\n\n/**\n * Version information\n */\nexport const VERSION = \"1.0.0\";\n\n/**\n * Check if we're running in a browser environment\n */\nexport const isBrowser =\n typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\n/**\n * Check if we're running in Node.js\n */\nexport const isNode =\n typeof process !== \"undefined\" &&\n process.versions != null &&\n process.versions.node != null;\n"],
|
|
5
|
-
"mappings": ";AASO,IAAM,YAAY;AAAA;AAAA,EAEvB,QAAQ;AAAA,EACR,SAAS;AAAA;AAAA,EAGT,OAAO;AAAA,EACP,cAAc;AAAA,EACd,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,KAAK;AAAA,EACL,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,KAAK;AAAA,EACL,IAAI;AAAA;AAAA,EAGJ,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,UAAU;AAAA;AAAA,EAGV,MAAM;AAAA,EACN,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,cAAc;AAAA;AAAA,EAGd,MAAM;AA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pB,QAAQ,SAAS,QAAQ;",
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../src/xpath/tokenizer.js", "../src/xpath/parser.js", "../src/xpath/namespaceNodes.js", "../src/xpath/axes.js", "../src/xpath/documentOrder.js", "../src/xpath/strings.js", "../src/xpath/nodeSetFunctions.js", "../src/xpath/evaluator.js", "../src/xslt/elements.js", "../src/xslt/formatNumber.js", "../src/xslt/exslt/arguments.js", "../src/xslt/exslt/common.js", "../src/xslt/exslt/calendar.js", "../src/xslt/exslt/dateParse.js", "../src/xslt/exslt/duration.js", "../src/xslt/exslt/dateCalc.js", "../src/xslt/exslt/dateFormat.js", "../src/xslt/exslt/dates.js", "../src/xslt/exslt/dynamic.js", "../src/xslt/exslt/math.js", "../src/xslt/exslt/sets.js", "../src/xslt/exslt/stringOps.js", "../src/xslt/exslt/uri.js", "../src/xslt/exslt/strings.js", "../src/xslt/exslt/index.js", "../src/xslt/functions.js", "../src/xslt/keys.js", "../src/xslt/literalResult.js", "../src/xslt/patternCompiler.js", "../src/xslt/matchScope.js", "../src/xslt/patterns.js", "../src/xslt/engine/methods.js", "../src/xslt/qname.js", "../src/xslt/stylesheetNamespaces.js", "../src/xslt/resultNamespaces.js", "../src/xslt/outputNames.js", "../src/xslt/engine/outputDeclaration.js", "../src/xslt/uri.js", "../src/xslt/domParsing.js", "../src/xslt/engine/stylesheetLoading.js", "../src/xslt/stylesheetChecks.js", "../src/xslt/forwardsCompatible.js", "../src/xslt/engine/topLevel.js", "../src/xslt/spaceNameTests.js", "../src/xslt/serializer/constants.js", "../src/xslt/serializer/settings.js", "../src/xslt/declarationNames.js", "../src/xslt/attributeSets.js", "../src/xslt/engine/declarations.js", "../src/xslt/templatePriority.js", "../src/xslt/engine/templateRules.js", "../src/xslt/sort.js", "../src/xslt/engine/workStack.js", "../src/xslt/engine/controlFlow.js", "../src/xslt/engine/templateInvocation.js", "../src/xslt/whitespace.js", "../src/xslt/engine/sequenceConstructor.js", "../src/xslt/variables.js", "../src/xslt/engine/bindings.js", "../src/xslt/avt.js", "../src/xslt/engine/textInstructions.js", "../src/xslt/number.js", "../src/xslt/numberFormat.js", "../src/xslt/engine/numbering.js", "../src/xslt/computedNames.js", "../src/xslt/engine/nodeConstruction.js", "../src/xslt/copying.js", "../src/xslt/engine/copyInstructions.js", "../src/xslt/resultTree.js", "../src/xslt/serializer/escape.js", "../src/xslt/serializer/encoding.js", "../src/xslt/serializer/namespaces.js", "../src/xslt/serializer/indent.js", "../src/xslt/serializer/rawText.js", "../src/xslt/serializer/chunks.js", "../src/xslt/serializer/frames.js", "../src/xslt/serializer/baseWriter.js", "../src/xslt/serializer/xhtmlDocument.js", "../src/xslt/serializer/xmlSerializer.js", "../src/xslt/serializer/htmlEntities.js", "../src/xslt/serializer/htmlDoctype.js", "../src/xslt/serializer/htmlSerializer.js", "../src/xslt/serializer/textSerializer.js", "../src/xslt/serializer.js", "../src/xslt/resultDocument.js", "../src/xslt/engine/context.js", "../src/xslt/engine/transformation.js", "../src/xslt/engine/functionSupport.js", "../src/xslt/engine.js", "../src/async/documentUris.js", "../src/async/preload.js", "../src/io/decode.js", "../src/async/abort.js", "../src/io/readSource.js", "../src/async/loaders.js", "../src/async/stream.js", "../src/async/processor.js", "../src/bridge/loader.js", "../src/bridge/results.js", "../src/bridge/version.js", "../src/bridge/engine.js", "../src/XSLTProcessor.js", "../src/xpath/index.js", "../src/index.js"],
|
|
4
|
+
"sourcesContent": ["/**\n * XPath 1.0 Tokenizer\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * Converts XPath expression strings into token streams for parsing.\n */\n\n\"use strict\";\n\nexport const TokenType = {\n // Literals\n NUMBER: \"NUMBER\",\n LITERAL: \"LITERAL\",\n\n // Operators\n SLASH: \"SLASH\",\n DOUBLE_SLASH: \"DOUBLE_SLASH\",\n PIPE: \"PIPE\",\n PLUS: \"PLUS\",\n MINUS: \"MINUS\",\n STAR: \"STAR\",\n DIV: \"DIV\",\n MOD: \"MOD\",\n EQUALS: \"EQUALS\",\n NOT_EQUALS: \"NOT_EQUALS\",\n LT: \"LT\",\n LTE: \"LTE\",\n GT: \"GT\",\n GTE: \"GTE\",\n AND: \"AND\",\n OR: \"OR\",\n\n // Brackets\n LPAREN: \"LPAREN\",\n RPAREN: \"RPAREN\",\n LBRACKET: \"LBRACKET\",\n RBRACKET: \"RBRACKET\",\n\n // Axes\n AXIS: \"AXIS\",\n AT: \"AT\",\n DOT: \"DOT\",\n DOUBLE_DOT: \"DOUBLE_DOT\",\n DOUBLE_COLON: \"DOUBLE_COLON\",\n\n // Names\n NAME: \"NAME\",\n NCNAME: \"NCNAME\",\n PREFIX: \"PREFIX\",\n FUNCTION: \"FUNCTION\",\n NODE_TYPE: \"NODE_TYPE\",\n\n // Other\n COMMA: \"COMMA\",\n DOLLAR: \"DOLLAR\",\n COLON: \"COLON\",\n EOF: \"EOF\",\n};\n\nconst AXIS_NAMES = new Set([\n \"ancestor\",\n \"ancestor-or-self\",\n \"attribute\",\n \"child\",\n \"descendant\",\n \"descendant-or-self\",\n \"following\",\n \"following-sibling\",\n \"namespace\",\n \"parent\",\n \"preceding\",\n \"preceding-sibling\",\n \"self\",\n]);\n\nconst NODE_TYPES = new Set([\n \"comment\",\n \"text\",\n \"processing-instruction\",\n \"node\",\n]);\n\nconst OPERATORS = new Set([\"and\", \"or\", \"mod\", \"div\"]);\n\n/** Token type of each OperatorName. */\nconst OPERATOR_TOKEN_TYPES = Object.freeze({\n and: TokenType.AND,\n or: TokenType.OR,\n mod: TokenType.MOD,\n div: TokenType.DIV,\n});\n\nexport class Token {\n constructor(type, value, position) {\n this.type = type;\n this.value = value;\n this.position = position;\n }\n\n toString() {\n return `Token(${this.type}, ${JSON.stringify(this.value)}, pos=${this.position})`;\n }\n}\n\n// Tokens that indicate the NEXT token should NOT be treated as an OperatorName\n// Per XPath 1.0 spec: \"If there is a preceding token and the preceding token is not one of\n// @, ::, (, [, , or an Operator, then... an NCName must be recognized as an OperatorName.\"\n// So after these tokens, OperatorNames (div, mod, and, or) should be treated as regular names.\nconst OPERATOR_CONTEXT_BLOCKERS = new Set([\n TokenType.AT,\n TokenType.DOUBLE_COLON,\n TokenType.LPAREN,\n TokenType.LBRACKET,\n TokenType.COMMA,\n // Operators - after an operator, next name token should be a name, not an operator\n TokenType.SLASH,\n TokenType.DOUBLE_SLASH,\n TokenType.PIPE,\n TokenType.PLUS,\n TokenType.MINUS,\n TokenType.STAR,\n TokenType.DIV,\n TokenType.MOD,\n TokenType.EQUALS,\n TokenType.NOT_EQUALS,\n TokenType.LT,\n TokenType.LTE,\n TokenType.GT,\n TokenType.GTE,\n TokenType.AND,\n TokenType.OR,\n]);\n\nexport class XPathTokenizer {\n constructor(expression) {\n this.expression = expression;\n this.position = 0;\n this.tokens = [];\n }\n\n /**\n * Get the last token that was added (if any)\n */\n getLastToken() {\n return this.tokens.length > 0 ? this.tokens[this.tokens.length - 1] : null;\n }\n\n /**\n * Check if the current context allows operator names (div, mod, and, or)\n * Per XPath 1.0 spec disambiguation rules.\n */\n isOperatorContext() {\n const lastToken = this.getLastToken();\n // No preceding token means we're at the start - not an operator context\n if (!lastToken) return false;\n // The local part of a QName (`html:div`) is a name, never an operator\n if (lastToken.type === TokenType.COLON) return false;\n // If preceding token is a \"blocker\", it's not an operator context\n if (OPERATOR_CONTEXT_BLOCKERS.has(lastToken.type)) return false;\n // Otherwise, it IS an operator context (after names, numbers, closing brackets, etc.)\n return true;\n }\n\n tokenize() {\n this.tokens = [];\n this.position = 0;\n\n while (this.position < this.expression.length) {\n this.skipWhitespace();\n if (this.position >= this.expression.length) break;\n\n const token = this.nextToken();\n if (token) {\n this.tokens.push(token);\n }\n }\n\n this.tokens.push(new Token(TokenType.EOF, null, this.position));\n return this.tokens;\n }\n\n skipWhitespace() {\n while (\n this.position < this.expression.length &&\n /\\s/.test(this.expression[this.position])\n ) {\n this.position++;\n }\n }\n\n peek(offset = 0) {\n return this.expression[this.position + offset];\n }\n\n consume() {\n return this.expression[this.position++];\n }\n\n nextToken() {\n const startPos = this.position;\n const char = this.peek();\n\n // String literals\n if (char === '\"' || char === \"'\") {\n return this.readStringLiteral();\n }\n\n // Numbers\n if (/[0-9]/.test(char) || (char === \".\" && /[0-9]/.test(this.peek(1)))) {\n return this.readNumber();\n }\n\n // Multi-character operators\n if (char === \"/\" && this.peek(1) === \"/\") {\n this.position += 2;\n return new Token(TokenType.DOUBLE_SLASH, \"//\", startPos);\n }\n\n if (char === \".\" && this.peek(1) === \".\") {\n this.position += 2;\n return new Token(TokenType.DOUBLE_DOT, \"..\", startPos);\n }\n\n if (char === \":\" && this.peek(1) === \":\") {\n this.position += 2;\n return new Token(TokenType.DOUBLE_COLON, \"::\", startPos);\n }\n\n if (char === \"!\" && this.peek(1) === \"=\") {\n this.position += 2;\n return new Token(TokenType.NOT_EQUALS, \"!=\", startPos);\n }\n\n if (char === \"<\" && this.peek(1) === \"=\") {\n this.position += 2;\n return new Token(TokenType.LTE, \"<=\", startPos);\n }\n\n if (char === \">\" && this.peek(1) === \"=\") {\n this.position += 2;\n return new Token(TokenType.GTE, \">=\", startPos);\n }\n\n // Single-character tokens\n const singleCharTokens = {\n \"/\": TokenType.SLASH,\n \"|\": TokenType.PIPE,\n \"+\": TokenType.PLUS,\n \"-\": TokenType.MINUS,\n \"*\": TokenType.STAR,\n \"=\": TokenType.EQUALS,\n \"<\": TokenType.LT,\n \">\": TokenType.GT,\n \"(\": TokenType.LPAREN,\n \")\": TokenType.RPAREN,\n \"[\": TokenType.LBRACKET,\n \"]\": TokenType.RBRACKET,\n \"@\": TokenType.AT,\n \".\": TokenType.DOT,\n \",\": TokenType.COMMA,\n $: TokenType.DOLLAR,\n \":\": TokenType.COLON,\n };\n\n if (singleCharTokens[char]) {\n this.position++;\n return new Token(singleCharTokens[char], char, startPos);\n }\n\n // Names and keywords\n if (this.isNameStartChar(char)) {\n return this.readName();\n }\n\n throw new Error(\n `Unexpected character '${char}' at position ${this.position} in expression: ${this.expression}`,\n );\n }\n\n readStringLiteral() {\n const startPos = this.position;\n const quote = this.consume();\n let value = \"\";\n\n while (this.position < this.expression.length && this.peek() !== quote) {\n value += this.consume();\n }\n\n if (this.position >= this.expression.length) {\n throw new Error(`Unterminated string literal at position ${startPos}`);\n }\n\n this.consume(); // closing quote\n return new Token(TokenType.LITERAL, value, startPos);\n }\n\n readNumber() {\n const startPos = this.position;\n let value = \"\";\n\n // Integer part\n while (\n this.position < this.expression.length &&\n /[0-9]/.test(this.peek())\n ) {\n value += this.consume();\n }\n\n // Decimal part: Number ::= Digits ('.' Digits?)? | '.' Digits, so `5.`\n // is a number too. A `..` after digits is left alone (never valid there).\n if (this.peek() === \".\" && this.peek(1) !== \".\") {\n value += this.consume(); // .\n while (\n this.position < this.expression.length &&\n /[0-9]/.test(this.peek())\n ) {\n value += this.consume();\n }\n }\n\n return new Token(TokenType.NUMBER, parseFloat(value), startPos);\n }\n\n /**\n * Read an NCName and classify it using the XPath 1.0 lexical\n * disambiguation rules (section 3.7), applied in the order the\n * specification lists them:\n *\n * 1. After an operand (the preceding token is not `@`, `::`, `(`, `[`, `,`\n * or an operator) `and`, `or`, `div` and `mod` are OperatorNames, even\n * when a `(` follows, as in `(a) or (b)`.\n * 2. A name followed by `(` is a NodeType or a FunctionName.\n * 3. A name followed by `::` is an AxisName.\n * 4. Anything else is a NameTest.\n *\n * @returns {Token} The classified token\n */\n readName() {\n const startPos = this.position;\n let value = \"\";\n\n while (\n this.position < this.expression.length &&\n this.isNameChar(this.peek())\n ) {\n value += this.consume();\n }\n\n if (OPERATORS.has(value) && this.isOperatorContext()) {\n return new Token(OPERATOR_TOKEN_TYPES[value], value, startPos);\n }\n\n const savedPos = this.position;\n this.skipWhitespace();\n\n if (this.peek() === \"(\") {\n const type = NODE_TYPES.has(value)\n ? TokenType.NODE_TYPE\n : TokenType.FUNCTION;\n return new Token(type, value, startPos);\n }\n\n if (AXIS_NAMES.has(value) && this.peek() === \":\" && this.peek(1) === \":\") {\n return new Token(TokenType.AXIS, value, startPos);\n }\n\n this.position = savedPos;\n return new Token(TokenType.NAME, value, startPos);\n }\n\n isNameStartChar(char) {\n if (!char) return false;\n const code = char.charCodeAt(0);\n return (\n char === \"_\" ||\n (code >= 65 && code <= 90) || // A-Z\n (code >= 97 && code <= 122) || // a-z\n code >= 0xc0 // Unicode letters\n );\n }\n\n isNameChar(char) {\n if (!char) return false;\n const code = char.charCodeAt(0);\n return (\n this.isNameStartChar(char) ||\n char === \"-\" ||\n char === \".\" ||\n (code >= 48 && code <= 57) // 0-9\n );\n }\n}\n\nexport function tokenize(expression) {\n const tokenizer = new XPathTokenizer(expression);\n return tokenizer.tokenize();\n}\n", "/**\n * XPath 1.0 Parser\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * Converts token stream into an Abstract Syntax Tree (AST).\n */\n\n\"use strict\";\n\nimport { TokenType, tokenize } from \"./tokenizer.js\";\n\nexport const NodeType = {\n // Expression types\n OR_EXPR: \"OrExpr\",\n AND_EXPR: \"AndExpr\",\n EQUALITY_EXPR: \"EqualityExpr\",\n RELATIONAL_EXPR: \"RelationalExpr\",\n ADDITIVE_EXPR: \"AdditiveExpr\",\n MULTIPLICATIVE_EXPR: \"MultiplicativeExpr\",\n UNARY_EXPR: \"UnaryExpr\",\n UNION_EXPR: \"UnionExpr\",\n\n // Path expressions\n PATH_EXPR: \"PathExpr\",\n LOCATION_PATH: \"LocationPath\",\n STEP: \"Step\",\n PREDICATE: \"Predicate\",\n\n // Primaries\n VARIABLE_REF: \"VariableRef\",\n LITERAL: \"Literal\",\n NUMBER: \"Number\",\n FUNCTION_CALL: \"FunctionCall\",\n\n // Node tests\n NAME_TEST: \"NameTest\",\n NODE_TYPE_TEST: \"NodeTypeTest\",\n PI_TEST: \"ProcessingInstructionTest\",\n};\n\nexport class ASTNode {\n constructor(type, props = {}) {\n this.type = type;\n Object.assign(this, props);\n }\n}\n\nexport class XPathParser {\n constructor(tokens) {\n this.tokens = tokens;\n this.position = 0;\n }\n\n parse() {\n const expr = this.parseExpr();\n if (!this.isAtEnd()) {\n throw new Error(\n `Unexpected token ${this.peek().type} at position ${this.peek().position}`,\n );\n }\n return expr;\n }\n\n // Expr ::= OrExpr\n parseExpr() {\n return this.parseOrExpr();\n }\n\n // OrExpr ::= AndExpr | OrExpr 'or' AndExpr\n parseOrExpr() {\n let left = this.parseAndExpr();\n\n while (this.match(TokenType.OR)) {\n const right = this.parseAndExpr();\n left = new ASTNode(NodeType.OR_EXPR, { left, right });\n }\n\n return left;\n }\n\n // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr\n parseAndExpr() {\n let left = this.parseEqualityExpr();\n\n while (this.match(TokenType.AND)) {\n const right = this.parseEqualityExpr();\n left = new ASTNode(NodeType.AND_EXPR, { left, right });\n }\n\n return left;\n }\n\n // EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr | EqualityExpr '!=' RelationalExpr\n parseEqualityExpr() {\n let left = this.parseRelationalExpr();\n\n while (true) {\n if (this.match(TokenType.EQUALS)) {\n const right = this.parseRelationalExpr();\n left = new ASTNode(NodeType.EQUALITY_EXPR, {\n operator: \"=\",\n left,\n right,\n });\n } else if (this.match(TokenType.NOT_EQUALS)) {\n const right = this.parseRelationalExpr();\n left = new ASTNode(NodeType.EQUALITY_EXPR, {\n operator: \"!=\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // RelationalExpr ::= AdditiveExpr | RelationalExpr '<' AdditiveExpr | ...\n parseRelationalExpr() {\n let left = this.parseAdditiveExpr();\n\n while (true) {\n if (this.match(TokenType.LT)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \"<\",\n left,\n right,\n });\n } else if (this.match(TokenType.LTE)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \"<=\",\n left,\n right,\n });\n } else if (this.match(TokenType.GT)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \">\",\n left,\n right,\n });\n } else if (this.match(TokenType.GTE)) {\n const right = this.parseAdditiveExpr();\n left = new ASTNode(NodeType.RELATIONAL_EXPR, {\n operator: \">=\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // AdditiveExpr ::= MultiplicativeExpr | AdditiveExpr '+' MultiplicativeExpr | AdditiveExpr '-' MultiplicativeExpr\n parseAdditiveExpr() {\n let left = this.parseMultiplicativeExpr();\n\n while (true) {\n if (this.match(TokenType.PLUS)) {\n const right = this.parseMultiplicativeExpr();\n left = new ASTNode(NodeType.ADDITIVE_EXPR, {\n operator: \"+\",\n left,\n right,\n });\n } else if (this.match(TokenType.MINUS)) {\n const right = this.parseMultiplicativeExpr();\n left = new ASTNode(NodeType.ADDITIVE_EXPR, {\n operator: \"-\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // MultiplicativeExpr ::= UnaryExpr | MultiplicativeExpr '*' UnaryExpr | ...\n parseMultiplicativeExpr() {\n let left = this.parseUnaryExpr();\n\n while (true) {\n if (this.match(TokenType.STAR)) {\n const right = this.parseUnaryExpr();\n left = new ASTNode(NodeType.MULTIPLICATIVE_EXPR, {\n operator: \"*\",\n left,\n right,\n });\n } else if (this.match(TokenType.DIV)) {\n const right = this.parseUnaryExpr();\n left = new ASTNode(NodeType.MULTIPLICATIVE_EXPR, {\n operator: \"div\",\n left,\n right,\n });\n } else if (this.match(TokenType.MOD)) {\n const right = this.parseUnaryExpr();\n left = new ASTNode(NodeType.MULTIPLICATIVE_EXPR, {\n operator: \"mod\",\n left,\n right,\n });\n } else {\n break;\n }\n }\n\n return left;\n }\n\n // UnaryExpr ::= UnionExpr | '-' UnaryExpr\n parseUnaryExpr() {\n if (this.match(TokenType.MINUS)) {\n const operand = this.parseUnaryExpr();\n return new ASTNode(NodeType.UNARY_EXPR, { operator: \"-\", operand });\n }\n return this.parseUnionExpr();\n }\n\n // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr\n parseUnionExpr() {\n let left = this.parsePathExpr();\n\n while (this.match(TokenType.PIPE)) {\n const right = this.parsePathExpr();\n left = new ASTNode(NodeType.UNION_EXPR, { left, right });\n }\n\n return left;\n }\n\n // PathExpr ::= LocationPath | FilterExpr | FilterExpr '/' RelativeLocationPath | FilterExpr '//' RelativeLocationPath\n parsePathExpr() {\n // Check for absolute location path\n if (this.check(TokenType.SLASH) || this.check(TokenType.DOUBLE_SLASH)) {\n return this.parseLocationPath();\n }\n\n // Check if this looks like a location path starting with step\n if (this.isStepStart() && !this.isPrefixedFunctionCall()) {\n return this.parseLocationPath();\n }\n\n // Otherwise try to parse as filter expression\n const filter = this.parseFilterExpr();\n\n // Check for path continuation\n if (this.check(TokenType.SLASH) || this.check(TokenType.DOUBLE_SLASH)) {\n const steps = [];\n\n while (\n this.check(TokenType.SLASH) ||\n this.check(TokenType.DOUBLE_SLASH)\n ) {\n const isDescendant = this.match(TokenType.DOUBLE_SLASH);\n if (!isDescendant) this.advance(); // consume /\n\n if (isDescendant) {\n steps.push(\n new ASTNode(NodeType.STEP, {\n axis: \"descendant-or-self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, {\n nodeType: \"node\",\n }),\n predicates: [],\n }),\n );\n }\n\n steps.push(this.parseStep());\n }\n\n return new ASTNode(NodeType.PATH_EXPR, { filter, steps });\n }\n\n return filter;\n }\n\n // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath\n parseLocationPath() {\n let absolute = false;\n const steps = [];\n\n if (this.match(TokenType.DOUBLE_SLASH)) {\n absolute = true;\n // //foo is equivalent to /descendant-or-self::node()/foo\n steps.push(\n new ASTNode(NodeType.STEP, {\n axis: \"descendant-or-self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType: \"node\" }),\n predicates: [],\n }),\n );\n if (!this.isAtEnd() && !this.check(TokenType.EOF)) {\n steps.push(this.parseStep());\n }\n } else if (this.match(TokenType.SLASH)) {\n absolute = true;\n if (this.isStepStart()) {\n steps.push(this.parseStep());\n }\n } else {\n steps.push(this.parseStep());\n }\n\n while (this.check(TokenType.SLASH) || this.check(TokenType.DOUBLE_SLASH)) {\n const isDescendant = this.match(TokenType.DOUBLE_SLASH);\n if (!isDescendant) this.advance(); // consume /\n\n if (isDescendant) {\n steps.push(\n new ASTNode(NodeType.STEP, {\n axis: \"descendant-or-self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, {\n nodeType: \"node\",\n }),\n predicates: [],\n }),\n );\n }\n\n steps.push(this.parseStep());\n }\n\n return new ASTNode(NodeType.LOCATION_PATH, { absolute, steps });\n }\n\n // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep\n parseStep() {\n // Handle abbreviated steps\n if (this.match(TokenType.DOT)) {\n return new ASTNode(NodeType.STEP, {\n axis: \"self\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType: \"node\" }),\n predicates: [],\n });\n }\n\n if (this.match(TokenType.DOUBLE_DOT)) {\n return new ASTNode(NodeType.STEP, {\n axis: \"parent\",\n nodeTest: new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType: \"node\" }),\n predicates: [],\n });\n }\n\n // Parse axis\n let axis = \"child\"; // default axis\n\n if (this.match(TokenType.AT)) {\n axis = \"attribute\";\n } else if (this.check(TokenType.AXIS)) {\n axis = this.advance().value;\n this.expect(TokenType.DOUBLE_COLON);\n }\n\n // Parse node test\n const nodeTest = this.parseNodeTest();\n\n // Parse predicates\n const predicates = [];\n while (this.check(TokenType.LBRACKET)) {\n predicates.push(this.parsePredicate());\n }\n\n return new ASTNode(NodeType.STEP, { axis, nodeTest, predicates });\n }\n\n // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'\n parseNodeTest() {\n if (this.check(TokenType.NODE_TYPE)) {\n const nodeType = this.advance().value;\n this.expect(TokenType.LPAREN);\n\n if (\n nodeType === \"processing-instruction\" &&\n this.check(TokenType.LITERAL)\n ) {\n const name = this.advance().value;\n this.expect(TokenType.RPAREN);\n return new ASTNode(NodeType.PI_TEST, { name });\n }\n\n this.expect(TokenType.RPAREN);\n return new ASTNode(NodeType.NODE_TYPE_TEST, { nodeType });\n }\n\n // NameTest\n return this.parseNameTest();\n }\n\n // NameTest ::= '*' | NCName ':' '*' | QName\n parseNameTest() {\n if (this.match(TokenType.STAR)) {\n return new ASTNode(NodeType.NAME_TEST, { name: \"*\", prefix: null });\n }\n\n if (!this.check(TokenType.NAME)) {\n throw new Error(`Expected name at position ${this.peek().position}`);\n }\n\n const name = this.advance().value;\n\n // Check for prefix:*\n if (this.match(TokenType.COLON)) {\n if (this.match(TokenType.STAR)) {\n return new ASTNode(NodeType.NAME_TEST, { name: \"*\", prefix: name });\n }\n\n if (this.check(TokenType.NAME)) {\n const localName = this.advance().value;\n return new ASTNode(NodeType.NAME_TEST, {\n name: localName,\n prefix: name,\n });\n }\n\n throw new Error(\n `Expected name or * after : at position ${this.peek().position}`,\n );\n }\n\n return new ASTNode(NodeType.NAME_TEST, { name, prefix: null });\n }\n\n // Predicate ::= '[' Expr ']'\n parsePredicate() {\n this.expect(TokenType.LBRACKET);\n const expr = this.parseExpr();\n this.expect(TokenType.RBRACKET);\n return new ASTNode(NodeType.PREDICATE, { expr });\n }\n\n // FilterExpr ::= PrimaryExpr | FilterExpr Predicate\n parseFilterExpr() {\n let primary = this.parsePrimaryExpr();\n\n while (this.check(TokenType.LBRACKET)) {\n const predicate = this.parsePredicate();\n primary = new ASTNode(NodeType.PATH_EXPR, {\n filter: primary,\n predicates: [predicate],\n });\n }\n\n return primary;\n }\n\n // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall\n parsePrimaryExpr() {\n // Variable reference\n if (this.match(TokenType.DOLLAR)) {\n if (!this.check(TokenType.NAME)) {\n throw new Error(\n `Expected variable name at position ${this.peek().position}`,\n );\n }\n const name = this.advance().value;\n let prefix = null;\n\n if (this.match(TokenType.COLON)) {\n prefix = name;\n if (!this.check(TokenType.NAME)) {\n throw new Error(\n `Expected local name at position ${this.peek().position}`,\n );\n }\n const localName = this.advance().value;\n return new ASTNode(NodeType.VARIABLE_REF, { name: localName, prefix });\n }\n\n return new ASTNode(NodeType.VARIABLE_REF, { name, prefix });\n }\n\n // Parenthesized expression\n if (this.match(TokenType.LPAREN)) {\n const expr = this.parseExpr();\n this.expect(TokenType.RPAREN);\n return expr;\n }\n\n // Literal\n if (this.check(TokenType.LITERAL)) {\n return new ASTNode(NodeType.LITERAL, { value: this.advance().value });\n }\n\n // Number\n if (this.check(TokenType.NUMBER)) {\n return new ASTNode(NodeType.NUMBER, { value: this.advance().value });\n }\n\n // Function call\n if (this.check(TokenType.FUNCTION)) {\n return this.parseFunctionCall();\n }\n\n // Prefixed function call: the tokenizer emits NAME ':' FUNCTION\n if (this.isPrefixedFunctionCall()) {\n const prefix = this.advance().value;\n this.advance(); // ':'\n return this.parseFunctionCallArgs(this.advance().value, prefix);\n }\n\n throw new Error(\n `Unexpected token ${this.peek().type} at position ${this.peek().position}`,\n );\n }\n\n // FunctionCall ::= FunctionName '(' ( Argument ( ',' Argument )* )? ')'\n // FunctionName is a QName: an unprefixed name arrives as one FUNCTION\n // token, a prefixed one as NAME ':' FUNCTION (see isPrefixedFunctionCall).\n parseFunctionCall() {\n const name = this.advance().value;\n return this.parseFunctionCallArgs(name, null);\n }\n\n parseFunctionCallArgs(name, prefix) {\n this.expect(TokenType.LPAREN);\n\n const args = [];\n if (!this.check(TokenType.RPAREN)) {\n args.push(this.parseExpr());\n while (this.match(TokenType.COMMA)) {\n args.push(this.parseExpr());\n }\n }\n\n this.expect(TokenType.RPAREN);\n\n return new ASTNode(NodeType.FUNCTION_CALL, { name, prefix, args });\n }\n\n // Helper methods\n\n /**\n * Whether the next tokens form a prefixed function name, `prefix:name(`.\n *\n * The tokenizer classifies the local part as a FUNCTION token (or as a\n * NODE_TYPE token when it is spelled like one, as in `f:node()`), so\n * `NAME ':' (FUNCTION | NODE_TYPE)` can only start a function call; a\n * prefixed name test is `NAME ':' (NAME | '*')`.\n *\n * @returns {boolean} True when a prefixed function call follows\n */\n isPrefixedFunctionCall() {\n const next = this.tokens[this.position + 2];\n return (\n this.check(TokenType.NAME) &&\n this.tokens[this.position + 1].type === TokenType.COLON &&\n (next.type === TokenType.FUNCTION || next.type === TokenType.NODE_TYPE)\n );\n }\n\n isStepStart() {\n const type = this.peek().type;\n return (\n type === TokenType.NAME ||\n type === TokenType.STAR ||\n type === TokenType.AT ||\n type === TokenType.DOT ||\n type === TokenType.DOUBLE_DOT ||\n type === TokenType.AXIS ||\n type === TokenType.NODE_TYPE\n );\n }\n\n peek() {\n return this.tokens[this.position];\n }\n\n advance() {\n if (!this.isAtEnd()) {\n return this.tokens[this.position++];\n }\n return this.tokens[this.position];\n }\n\n check(type) {\n if (this.isAtEnd()) return false;\n return this.peek().type === type;\n }\n\n match(type) {\n if (this.check(type)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n expect(type) {\n if (!this.check(type)) {\n throw new Error(\n `Expected ${type} but got ${this.peek().type} at position ${this.peek().position}`,\n );\n }\n return this.advance();\n }\n\n isAtEnd() {\n return this.peek().type === TokenType.EOF;\n }\n}\n\nexport function parse(expression) {\n const tokens = tokenize(expression);\n const parser = new XPathParser(tokens);\n return parser.parse();\n}\n", "/**\n * Namespace nodes and the `namespace` axis (XPath 1.0 sections 2.2, 5.4).\n *\n * The DOM has no namespace nodes, so they are synthesized: an element has one\n * namespace node for every namespace binding in scope on it, the implicit\n * `xml` binding included, and an undeclared default namespace (`xmlns=\"\"`)\n * has none. Bindings come from `xmlns` attributes of the element and its\n * ancestors and, for trees built with `createElementNS`, from the prefixes of\n * the element and attribute names themselves. HTML documents are treated as\n * libxslt sees them after re-parsing their markup: their elements are in no\n * namespace, so only explicit `xmlns` attributes (and `xml`) bind prefixes.\n *\n * A namespace node looks like a DOM node where the processor reads one:\n * `nodeType` 13, `localName`/`nodeName` = the prefix (\"\" for the default\n * namespace), `namespaceURI` = null (the expanded-name of a namespace node\n * has a null URI), `nodeValue`/`textContent` = the namespace URI and\n * `ownerElement` = its parent element. Nodes are created once per element and\n * cache, so the same binding is the same object: unions deduplicate it and\n * `generate-id()` is stable. In document order the namespace nodes of an\n * element follow the element and precede its attributes (section 5).\n *\n * @module xpath/namespaceNodes\n */\n\n\"use strict\";\n\n/** Node type of a namespace node (the DOM XPath XPathNamespace type). */\nexport const NAMESPACE_NODE = 13;\n\n/** Namespace bound to the `xml` prefix (Namespaces in XML 1.0). */\nconst XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\n\n/** Namespace of `xmlns` and `xmlns:*` attributes. */\nconst XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\n\n/**\n * A synthesized XPath namespace node.\n */\nexport class NamespaceNode {\n /**\n * @param {Element} element - The element the node belongs to (its parent)\n * @param {string} prefix - The bound prefix, \"\" for the default namespace\n * @param {string} uri - The namespace URI\n * @param {number} index - Position among the element's namespace nodes\n */\n constructor(element, prefix, uri, index) {\n this.nodeType = NAMESPACE_NODE;\n this.ownerElement = element;\n this.ownerDocument = element.ownerDocument;\n this.localName = prefix;\n this.nodeName = prefix;\n this.namespaceURI = null;\n this.prefix = null;\n this.nodeValue = uri;\n this.textContent = uri;\n this.index = index;\n this.parentNode = null;\n this.firstChild = null;\n this.lastChild = null;\n this.previousSibling = null;\n this.nextSibling = null;\n this.childNodes = [];\n }\n}\n\n/**\n * Whether a node is a synthesized namespace node.\n *\n * @param {*} node - Any value\n * @returns {boolean} True for namespace nodes\n */\nexport function isNamespaceNode(node) {\n return node?.nodeType === NAMESPACE_NODE;\n}\n\n/**\n * The prefix declared by an `xmlns` or `xmlns:*` attribute.\n *\n * @param {Attr} attr - Any attribute\n * @returns {string|null} The prefix (\"\" for `xmlns`), or null for any other attribute\n */\nfunction declaredPrefix(attr) {\n const name = attr.name;\n if (name === \"xmlns\") return \"\";\n return name.startsWith(\"xmlns:\") ? name.slice(6) : null;\n}\n\n/**\n * Record the bindings one element contributes, nearest binding first: an\n * ancestor cannot override what a descendant already bound.\n *\n * @param {Element} element - An element on the ancestor-or-self axis\n * @param {boolean} fromNames - Whether prefixes of element and attribute names count\n * @param {Map<string, string>} bindings - URIs by prefix, \"\" marking an undeclared prefix\n * @returns {void}\n */\nfunction addBindings(element, fromNames, bindings) {\n const bind = (prefix, uri) => {\n if (prefix !== \"xml\" && !bindings.has(prefix)) bindings.set(prefix, uri);\n };\n for (const attr of element.attributes) {\n const prefix = declaredPrefix(attr);\n if (prefix !== null) bind(prefix, attr.value);\n }\n if (!fromNames) return;\n bind(element.prefix ?? \"\", element.namespaceURI ?? \"\");\n for (const attr of element.attributes) {\n if (attr.prefix && attr.namespaceURI !== XMLNS_NAMESPACE) {\n bind(attr.prefix, attr.namespaceURI);\n }\n }\n}\n\n/**\n * The namespace bindings in scope on an element, `xml` first.\n *\n * @param {Element} element - The element\n * @returns {Array<[string, string]>} `[prefix, uri]` pairs\n *\n * @example\n * // <r xmlns:a=\"u\"/>\n * inScopeBindings(r); // [[\"xml\", \"http://www.w3.org/XML/1998/namespace\"], [\"a\", \"u\"]]\n */\nexport function inScopeBindings(element) {\n const fromNames = element.ownerDocument?.contentType !== \"text/html\";\n const bindings = new Map();\n for (let node = element; node?.nodeType === 1; node = node.parentNode) {\n addBindings(node, fromNames, bindings);\n }\n const result = [[\"xml\", XML_NAMESPACE]];\n for (const [prefix, uri] of bindings) {\n if (uri !== \"\") result.push([prefix, uri]);\n }\n return result;\n}\n\n/**\n * The namespace axis of a node: the namespace nodes of an element, nothing\n * for any other node. Nodes are cached per element in `cache`, so repeated\n * evaluations return identical objects.\n *\n * @param {Node} node - Context node\n * @param {WeakMap<Element, NamespaceNode[]>} cache - Namespace nodes by element\n * @returns {NamespaceNode[]} The namespace nodes, in document order\n *\n * @example\n * namespaceAxis(element, new WeakMap()).map((ns) => ns.localName); // [\"xml\", \"a\"]\n */\nexport function namespaceAxis(node, cache) {\n if (node.nodeType !== 1) return [];\n let nodes = cache.get(node);\n if (!nodes) {\n nodes = inScopeBindings(node).map(\n ([prefix, uri], index) => new NamespaceNode(node, prefix, uri, index),\n );\n cache.set(node, nodes);\n }\n return nodes.slice();\n}\n\n/**\n * Match a name test against a namespace node: its name is the prefix, with a\n * null namespace URI, so only unprefixed tests can match (section 2.3).\n *\n * @param {{name: string, prefix: (string|null)}} nodeTest - Name test AST node\n * @param {NamespaceNode} node - The namespace node\n * @returns {boolean} Whether the node matches\n */\nexport function matchNamespaceNameTest(nodeTest, node) {\n if (nodeTest.prefix) return false;\n return nodeTest.name === \"*\" || nodeTest.name === node.localName;\n}\n", "/**\n * XPath 1.0 axes (section 2.2).\n *\n * Every axis is walked with `firstChild`, `nextSibling`, `previousSibling`,\n * `lastChild` and `parentNode` instead of indexing `childNodes`: in jsdom each\n * `childNodes[i]` access goes through a Proxy and was the single largest cost\n * of a transformation. Results are built with `push` only, never with spread\n * arguments, so very wide documents cannot overflow the call stack.\n *\n * Forward axes return nodes in document order. Reverse axes (`ancestor`,\n * `ancestor-or-self`, `preceding`, `preceding-sibling`) return nodes in\n * reverse document order, nearest first, so that predicates see proximity\n * positions: `preceding-sibling::*[1]` is the nearest preceding sibling.\n *\n * The XPath data model has no CDATA sections and never has two adjacent text\n * nodes (section 5.7), while the DOM may have both. A run of adjacent Text and\n * CDATASection siblings is therefore one XPath text node, represented by the\n * first DOM node of the run: the axes never return the other nodes of a run,\n * and the evaluator gives the first node the string value of the whole run.\n * Forward walks remember the previous sibling, so recognising a run costs no\n * extra DOM access.\n *\n * A document has no text children, in the DOM as in XPath (section 5.1),\n * and the XML declaration is not a processing instruction. xmldom keeps\n * both anyway: the whitespace between top-level nodes as Text nodes and the\n * declaration as a processing instruction named `xml`. The axes skip these\n * artifacts among the children of a document.\n *\n * @module xpath/axes\n */\n\nimport { NAMESPACE_NODE } from \"./namespaceNodes.js\";\n\n/** Namespace of `xmlns` and `xmlns:*` attributes (Namespaces in XML 1.0). */\nexport const XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\n\n/**\n * Whether a node is a DOM Text or CDATASection node.\n *\n * @param {Node|null} node - Any node\n * @returns {boolean} True for text and CDATA nodes\n */\nexport function isTextNode(node) {\n if (!node) return false;\n const type = node.nodeType;\n return type === 3 || type === 4;\n}\n\n/**\n * Whether a node continues a run of adjacent text/CDATA nodes, that is,\n * whether it is not the node that represents the run in the XPath data model.\n *\n * @param {Node} node - Any node\n * @returns {boolean} True when the node directly follows another text node\n *\n * @example\n * // <r>a<![CDATA[b]]></r>: only the \"a\" node is an XPath text node\n * isTextContinuation(cdataNode); // true\n */\nexport function isTextContinuation(node) {\n return isTextNode(node) && isTextNode(node.previousSibling);\n}\n\n/**\n * Whether `node` continues a text run given its previous sibling.\n *\n * @param {Node|null} previous - The previous sibling, or null for a first child\n * @param {Node} node - The node\n * @returns {boolean} True when both are text nodes\n */\nfunction continuesRun(previous, node) {\n return isTextNode(previous) && isTextNode(node);\n}\n\n/**\n * Whether an attribute is a namespace declaration. Parsed XML documents put\n * them in the xmlns namespace; attributes of HTML documents or created with\n * `setAttribute` only carry the `xmlns` name.\n *\n * @param {Attr} attr - An attribute node\n * @returns {boolean} True for `xmlns` and `xmlns:*` attributes\n */\nfunction isNamespaceDeclaration(attr) {\n const namespaceUri = attr.namespaceURI;\n if (namespaceUri === XMLNS_NAMESPACE) return true;\n if (namespaceUri !== null) return false;\n const name = attr.name;\n return name === \"xmlns\" || name.startsWith(\"xmlns:\");\n}\n\n/** Axes whose proximity positions run in reverse document order. */\nexport const REVERSE_AXES = new Set([\n \"ancestor\",\n \"ancestor-or-self\",\n \"preceding\",\n \"preceding-sibling\",\n]);\n\n/**\n * An axis walker calls `visit` for every node of an axis, in axis order\n * (proximity order for reverse axes), and stops as soon as `visit` returns\n * true. It returns whether the walk was stopped, so walkers can be nested.\n * Walking lets the evaluator stop after the n-th node of `axis::test[n]`\n * instead of materializing the whole axis.\n *\n * @callback AxisVisitor\n * @param {Node} node - A node on the axis\n * @returns {boolean} True to stop the walk\n */\n\n/**\n * Collect every node an axis walker visits.\n *\n * @param {(node: Node, visit: AxisVisitor) => boolean} walk - Axis walker\n * @param {Node} node - Context node\n * @returns {Node[]} The nodes, in axis order\n */\nfunction collect(walk, node) {\n const result = [];\n walk(node, (found) => {\n result.push(found);\n return false;\n });\n return result;\n}\n\n/**\n * Whether a child of a document is an artifact of the parser rather than a\n * node of the data model (see the module comment): text, or the XML\n * declaration as a processing instruction (the `xml` target is reserved).\n *\n * @param {Node} node - A child of a document\n * @returns {boolean} True for nodes the axes skip\n */\nfunction isDocumentArtifact(node) {\n const type = node.nodeType;\n return type === 3 || type === 4 || (type === 7 && node.target === \"xml\");\n}\n\n/**\n * Whether a node is a child of a document, where artifacts may be.\n *\n * @param {Node} node - Any node\n * @returns {boolean} True when the parent is a Document\n */\nfunction isDocumentChild(node) {\n return node.parentNode?.nodeType === 9;\n}\n\n/**\n * Whether a node is a parser artifact among the children of a document\n * (see the module comment), for walks that do not go through the axes.\n *\n * @param {Node} node - Any node\n * @returns {boolean} True for the artifacts the axes skip\n *\n * @example\n * // xmldom: <?xml version=\"1.0\"?><r/>\n * isParserArtifact(doc.firstChild); // true\n */\nexport function isParserArtifact(node) {\n return isDocumentArtifact(node) && isDocumentChild(node);\n}\n\n/**\n * Skip test of a sibling among the children of a document.\n *\n * @param {Node|null} previous - The previous sibling (unused)\n * @param {Node} node - The sibling\n * @returns {boolean} True for an artifact\n */\nfunction skipsArtifact(previous, node) {\n return isDocumentArtifact(node);\n}\n\n/**\n * How forward sibling walks skip siblings of a node: document artifacts\n * among the children of a document, text run continuations elsewhere.\n *\n * @param {Node} node - A node whose siblings are walked\n * @returns {(previous: Node|null, node: Node) => boolean} The skip test\n */\nfunction forwardSkipOf(node) {\n return isDocumentChild(node) ? skipsArtifact : continuesRun;\n}\n\n/**\n * Walk the children of a document in document order, without artifacts.\n *\n * @param {Document} doc - A document\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nfunction walkDocumentChildren(doc, visit) {\n for (let child = doc.firstChild; child; child = child.nextSibling) {\n if (!isDocumentArtifact(child) && visit(child)) return true;\n }\n return false;\n}\n\n/**\n * Walk the children of a node in document order.\n *\n * @param {Node} node - Context node\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkChildren(node, visit) {\n if (node.nodeType === 9) return walkDocumentChildren(node, visit);\n let previous = null;\n for (let child = node.firstChild; child; child = child.nextSibling) {\n if (!continuesRun(previous, child) && visit(child)) return true;\n previous = child;\n }\n return false;\n}\n\n/**\n * Child nodes in document order.\n *\n * @param {Node} node - Context node\n * @returns {Node[]} The children\n */\nexport function childAxis(node) {\n return collect(walkChildren, node);\n}\n\n/**\n * Attributes of an element, without namespace declarations: XPath models\n * those on the namespace axis, never on the attribute axis.\n *\n * @param {Node} node - Context node\n * @returns {Attr[]} The attributes\n */\nexport function attributeAxis(node) {\n const result = [];\n const attributes = node.attributes;\n if (!attributes) return result;\n for (const attr of attributes) {\n if (!isNamespaceDeclaration(attr)) result.push(attr);\n }\n return result;\n}\n\n/**\n * Walk the descendants of a node in document order (pre-order), optionally\n * starting with the node itself.\n *\n * @param {Node} node - Context node\n * @param {boolean} includeSelf - Whether to visit the node itself first\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkDescendants(node, includeSelf, visit) {\n if (includeSelf && visit(node)) return true;\n if (node.nodeType === 9) {\n return walkDocumentChildren(node, (child) =>\n walkDescendants(child, true, visit),\n );\n }\n\n let current = node.firstChild;\n let previous = null;\n while (current) {\n if (!continuesRun(previous, current) && visit(current)) return true;\n if (current.firstChild) {\n current = current.firstChild;\n previous = null;\n continue;\n }\n while (current && current !== node && !current.nextSibling) {\n current = current.parentNode;\n }\n previous = current;\n current = current && current !== node ? current.nextSibling : null;\n }\n return false;\n}\n\n/**\n * Descendants in document order (pre-order), optionally with the node itself.\n *\n * @param {Node} node - Context node\n * @param {boolean} includeSelf - Whether to start with the node itself\n * @param {Node[]} [result] - Array to append to\n * @returns {Node[]} The descendants\n */\nexport function descendantAxis(node, includeSelf, result = []) {\n walkDescendants(node, includeSelf, (found) => {\n result.push(found);\n return false;\n });\n return result;\n}\n\n/**\n * Walk the descendants of a node in reverse document order (reverse\n * pre-order): the last descendant first and the node's first child last.\n *\n * @param {Node} node - Subtree root, not visited\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nfunction walkReverseDescendants(node, visit) {\n let current = node.lastChild;\n while (current) {\n if (current.lastChild) {\n current = current.lastChild;\n continue;\n }\n if (!isTextContinuation(current) && visit(current)) return true;\n while (current !== node && !current.previousSibling) {\n current = current.parentNode;\n if (current !== node && visit(current)) return true;\n }\n current = current === node ? null : current.previousSibling;\n }\n return false;\n}\n\n/**\n * Walk the ancestors of a node, nearest first, optionally starting with the\n * node itself.\n *\n * @param {Node} node - Context node\n * @param {boolean} includeSelf - Whether to visit the node itself first\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkAncestors(node, includeSelf, visit) {\n if (includeSelf && visit(node)) return true;\n for (let current = parentOf(node); current; current = current.parentNode) {\n if (visit(current)) return true;\n }\n return false;\n}\n\n/**\n * Ancestors, nearest first, optionally starting with the node itself.\n *\n * @param {Node} node - Context node\n * @param {boolean} includeSelf - Whether to start with the node itself\n * @returns {Node[]} The ancestors\n */\nexport function ancestorAxis(node, includeSelf) {\n return collect(\n (start, visit) => walkAncestors(start, includeSelf, visit),\n node,\n );\n}\n\n/**\n * Walk the following siblings of a node in document order. Attributes have\n * no siblings.\n *\n * @param {Node} node - Context node\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkFollowingSiblings(node, visit) {\n if (node.nodeType === 2) return false;\n const skip = forwardSkipOf(node);\n let previous = node;\n for (let current = node.nextSibling; current; current = current.nextSibling) {\n if (!skip(previous, current) && visit(current)) return true;\n previous = current;\n }\n return false;\n}\n\n/**\n * Following siblings in document order.\n *\n * @param {Node} node - Context node\n * @returns {Node[]} The siblings\n */\nexport function followingSiblingAxis(node) {\n return collect(walkFollowingSiblings, node);\n}\n\n/**\n * Walk the preceding siblings of a node, nearest first. Attributes have no\n * siblings.\n *\n * @param {Node} node - Context node\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkPrecedingSiblings(node, visit) {\n if (node.nodeType === 2) return false;\n const skip = isDocumentChild(node) ? isDocumentArtifact : isTextContinuation;\n for (\n let current = node.previousSibling;\n current;\n current = current.previousSibling\n ) {\n if (!skip(current) && visit(current)) return true;\n }\n return false;\n}\n\n/**\n * Preceding siblings, nearest first.\n *\n * @param {Node} node - Context node\n * @returns {Node[]} The siblings\n */\nexport function precedingSiblingAxis(node) {\n return collect(walkPrecedingSiblings, node);\n}\n\n/**\n * Walk the nodes after the context node in document order, excluding its\n * descendants.\n *\n * @param {Node} node - Context node\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkFollowing(node, visit) {\n // An attribute or namespace node precedes the children of its element.\n if (\n hasOwnerElement(node) &&\n node.ownerElement &&\n walkDescendants(node.ownerElement, false, visit)\n ) {\n return true;\n }\n for (let current = startOf(node); current; current = current.parentNode) {\n const skip = forwardSkipOf(current);\n let previous = current;\n for (\n let sibling = current.nextSibling;\n sibling;\n sibling = sibling.nextSibling\n ) {\n if (!skip(previous, sibling) && walkDescendants(sibling, true, visit)) {\n return true;\n }\n previous = sibling;\n }\n }\n return false;\n}\n\n/**\n * Nodes after the context node in document order, excluding descendants.\n *\n * @param {Node} node - Context node\n * @returns {Node[]} The following nodes in document order\n */\nexport function followingAxis(node) {\n return collect(walkFollowing, node);\n}\n\n/**\n * Walk the nodes before the context node, excluding its ancestors, nearest\n * first.\n *\n * @param {Node} node - Context node\n * @param {AxisVisitor} visit - Visitor\n * @returns {boolean} True when the visitor stopped the walk\n */\nexport function walkPreceding(node, visit) {\n for (let current = startOf(node); current; current = current.parentNode) {\n const artifacts = isDocumentChild(current);\n for (\n let sibling = current.previousSibling;\n sibling;\n sibling = sibling.previousSibling\n ) {\n if (artifacts && isDocumentArtifact(sibling)) continue;\n if (walkReverseDescendants(sibling, visit)) return true;\n if (!isTextContinuation(sibling) && visit(sibling)) return true;\n }\n }\n return false;\n}\n\n/**\n * Nodes before the context node, excluding ancestors, nearest first.\n *\n * @param {Node} node - Context node\n * @returns {Node[]} The preceding nodes in reverse document order\n */\nexport function precedingAxis(node) {\n return collect(walkPreceding, node);\n}\n\n/**\n * Walkers of the axes that can be walked lazily, by axis name.\n *\n * @type {Readonly<Object<string, (node: Node, visit: AxisVisitor) => boolean>>}\n */\nexport const AXIS_WALKERS = Object.freeze({\n child: walkChildren,\n descendant: (node, visit) => walkDescendants(node, false, visit),\n \"descendant-or-self\": (node, visit) => walkDescendants(node, true, visit),\n ancestor: (node, visit) => walkAncestors(node, false, visit),\n \"ancestor-or-self\": (node, visit) => walkAncestors(node, true, visit),\n \"following-sibling\": walkFollowingSiblings,\n \"preceding-sibling\": walkPrecedingSiblings,\n following: walkFollowing,\n preceding: walkPreceding,\n});\n\n/**\n * The root node of the tree containing a node (XPath 2.1): the topmost\n * ancestor when that is a Document or a DocumentFragment (a result tree\n * fragment converted with `exsl:node-set()`), otherwise, for a node that is\n * not attached to any such tree, its owner document.\n *\n * @param {Node} node - Any node\n * @returns {Node} The root node\n *\n * @example\n * rootNodeOf(fragment.firstChild); // fragment\n */\nexport function rootNodeOf(node) {\n const owner = node.ownerDocument;\n let top = parentOf(node) ?? node;\n // Stop at the owner document without reading its properties: a jsdom\n // Document is a Proxy (named properties), slow on every access\n while (top !== owner && top.parentNode) top = top.parentNode;\n if (top === owner) return owner;\n const type = top.nodeType;\n return type === 9 || type === 11 ? top : node.ownerDocument || top;\n}\n\n/**\n * Whether a node's parent is its `ownerElement`: attributes and (synthesized)\n * namespace nodes, which are not children of their element.\n *\n * @param {Node} node - Any node\n * @returns {boolean} True for attribute and namespace nodes\n */\nfunction hasOwnerElement(node) {\n const type = node.nodeType;\n return type === 2 || type === NAMESPACE_NODE;\n}\n\n/**\n * Parent of a node in the XPath data model; for an attribute or a namespace\n * node this is its element.\n *\n * @param {Node} node - Any node\n * @returns {Node|null} The parent\n */\nexport function parentOf(node) {\n return hasOwnerElement(node) ? node.ownerElement : node.parentNode;\n}\n\n/**\n * Starting point for the following/preceding axes: an attribute or\n * namespace node behaves as if it were positioned at its element.\n *\n * @param {Node} node - Context node\n * @returns {Node} The node whose siblings and ancestors are walked\n */\nfunction startOf(node) {\n return hasOwnerElement(node) ? node.ownerElement : node;\n}\n", "/**\n * Document order of nodes that are not children of their parent: attributes\n * and synthesized namespace nodes (XPath 1.0 section 5).\n *\n * An element comes first, then its namespace nodes, then its attributes, then\n * its children. `Node.compareDocumentPosition` cannot order namespace nodes,\n * which are not DOM nodes, and jsdom reports an element and one of its own\n * attributes as equal, so both kinds are ordered through their element here.\n *\n * Browsers implement `compareDocumentPosition` natively. The JavaScript DOMs\n * of Node.js walk the ancestors of both nodes on every call, and xmldom also\n * looks each ancestor up in its parent's child list, which makes sorting a\n * large node-set take minutes; some DOMs have no such method at all. A\n * {@link DocumentOrderIndex} numbers the nodes of a tree once instead, in one\n * walk, and sorts node-sets by those numbers: the XSLT engine uses one per\n * transformation (the source tree does not change while it runs) unless the\n * DOM compares positions natively.\n *\n * @module xpath/documentOrder\n */\n\n\"use strict\";\n\nimport { NAMESPACE_NODE } from \"./namespaceNodes.js\";\n\n/**\n * Rank of a node among the nodes anchored at the same element: the element,\n * its namespace nodes, its attributes.\n *\n * @param {Node} node - Any node\n * @returns {number} 0 for the element (or any other node), 1 for a namespace\n * node, 2 for an attribute\n */\nfunction rankOf(node) {\n const type = node.nodeType;\n if (type === NAMESPACE_NODE) return 1;\n return type === 2 ? 2 : 0;\n}\n\n/**\n * The node whose position in the tree stands for a node: the element of an\n * attached attribute or namespace node, else the node itself.\n *\n * @param {Node} node - Any node\n * @param {number} rank - The node's rank (see rankOf)\n * @returns {Node} The anchor\n */\nfunction anchorOf(node, rank) {\n return rank === 0 ? node : (node.ownerElement ?? node);\n}\n\n/**\n * Compare two distinct nodes in document order.\n *\n * @param {Node} a - First node\n * @param {Node} b - Second node\n * @param {(a: Node, b: Node) => number} compareDom - Order of two DOM nodes\n * in different positions of the tree (compareDocumentPosition based)\n * @returns {number} Negative when a comes first, positive when b does\n *\n * @example\n * compareNodeOrder(attribute, ownerElement, compareDom); // 1\n */\nexport function compareNodeOrder(a, b, compareDom) {\n const rankA = rankOf(a);\n const rankB = rankOf(b);\n if (rankA === 0 && rankB === 0) return compareDom(a, b);\n const anchorA = anchorOf(a, rankA);\n const anchorB = anchorOf(b, rankB);\n if (anchorA !== anchorB) return compareDom(anchorA, anchorB);\n if (rankA !== rankB) return rankA - rankB;\n // Two namespace nodes, or two attributes, of the same element\n return rankA === 1 ? a.index - b.index : compareDom(a, b);\n}\n\n/**\n * Order of two DOM nodes in different positions of a tree, from\n * `compareDocumentPosition`.\n *\n * @param {Node} a - First node\n * @param {Node} b - Second node\n * @returns {number} -1 when a comes first, 1 when b does, 0 when the DOM\n * gives no order\n */\nexport function compareDomPositions(a, b) {\n const position = a.compareDocumentPosition(b);\n if (position & 4) return -1; // b follows a\n if (position & 2) return 1; // b precedes a\n return 0;\n}\n\n/**\n * Whether a node's DOM compares positions in native code (browsers), as\n * opposed to a JavaScript implementation (jsdom, xmldom) or none.\n *\n * @param {Node} node - A DOM node\n * @returns {boolean} True for a built-in `compareDocumentPosition`\n *\n * @example\n * hasNativePositionComparison(document.body); // true in a browser\n */\nexport function hasNativePositionComparison(node) {\n const compare = node.compareDocumentPosition;\n return (\n typeof compare === \"function\" &&\n Function.prototype.toString.call(compare).includes(\"[native code]\")\n );\n}\n\n/**\n * The topmost ancestor of a node.\n *\n * @param {Node} node - A DOM node\n * @returns {Node} The document, or the root of a detached tree\n */\nfunction rootOf(node) {\n let root = node;\n while (root.parentNode) root = root.parentNode;\n return root;\n}\n\n/**\n * Sort key offset of attributes among the nodes anchored at an element:\n * after the element (0) and its namespace nodes (1 + index).\n */\nconst ATTRIBUTE_KEY = 2 ** 30;\n\n/**\n * Document order positions of DOM nodes, computed tree by tree.\n *\n * The first time a node of a tree is looked up, the whole tree is numbered\n * in document order (attributes are not: they are ordered through their\n * element, and among themselves by their index in the element's attribute\n * list, looked up only when two attributes of one element are sorted). Trees are numbered in\n * the order they are first seen, so nodes of different documents have a\n * stable, implementation-defined order (XPath 1.0 section 5). A node added\n * to a tree after it was numbered makes the tree numbered again; nodes\n * moved within a numbered tree are not noticed, so an index must not\n * outlive changes to its trees.\n *\n * @example\n * const order = new DocumentOrderIndex();\n * order.sort([lastChild, firstChild]); // [firstChild, lastChild]\n */\nexport class DocumentOrderIndex {\n constructor() {\n /** @type {WeakMap<Node, number>} */\n this.positions = new WeakMap();\n /** @type {WeakMap<Attr, number>} */\n this.attributeIndexes = new WeakMap();\n this.nextPosition = 0;\n }\n\n /**\n * The position of a tree node in document order.\n *\n * @param {Node} node - A DOM node, not an attribute of an element nor a\n * namespace node (see {@link DocumentOrderIndex#sort})\n * @returns {number} Its position; larger for later nodes\n */\n positionOf(node) {\n let position = this.positions.get(node);\n if (position === undefined) {\n this.numberTree(rootOf(node));\n position = this.positions.get(node);\n }\n return position ?? this.assign(node);\n }\n\n /**\n * Give a node the next position.\n *\n * @param {Node} node - A DOM node\n * @returns {number} The assigned position\n */\n assign(node) {\n const position = this.nextPosition++;\n this.positions.set(node, position);\n return position;\n }\n\n /**\n * Number a tree in document order, without recursion (deep trees).\n *\n * @param {Node} root - The root of the tree\n * @returns {void}\n */\n numberTree(root) {\n let node = root;\n for (;;) {\n this.assign(node);\n if (node.firstChild) {\n node = node.firstChild;\n continue;\n }\n while (node !== root && !node.nextSibling) node = node.parentNode;\n if (node === root) return;\n node = node.nextSibling;\n }\n }\n\n /**\n * The index of an attribute in the attribute list of its element.\n *\n * @param {Attr} attribute - An attribute with an ownerElement\n * @returns {number} Its index (0 when the element does not list it)\n */\n attributeIndexOf(attribute) {\n let index = this.attributeIndexes.get(attribute);\n if (index === undefined) {\n const attributes = attribute.ownerElement.attributes;\n for (let i = 0; i < attributes.length; i++) {\n this.attributeIndexes.set(attributes[i], i);\n }\n index = this.attributeIndexes.get(attribute) ?? 0;\n }\n return index;\n }\n\n /**\n * The sort key of a node: the position of the node, or of the element it\n * hangs off, then its rank among the nodes anchored at that element. All\n * attributes of an element share one key (see\n * {@link DocumentOrderIndex#compareKeys}): walking the attribute list of\n * every element up front would dominate sorting `$items/@v`, where no two\n * attributes share an element.\n *\n * @param {Node} node - A DOM node or namespace node\n * @returns {{node: Node, major: number, minor: number}} The key\n */\n keyOf(node) {\n if (node.nodeType === NAMESPACE_NODE) {\n const major = this.positionOf(node.ownerElement);\n return { node, major, minor: 1 + node.index };\n }\n if (node.nodeType === 2 && node.ownerElement) {\n const major = this.positionOf(node.ownerElement);\n return { node, major, minor: ATTRIBUTE_KEY };\n }\n return { node, major: this.positionOf(node), minor: 0 };\n }\n\n /**\n * Order of two sort keys; attributes of the same element are ordered by\n * their index in its attribute list, looked up only for such a tie.\n *\n * @param {{node: Node, major: number, minor: number}} a - First key\n * @param {{node: Node, major: number, minor: number}} b - Second key\n * @returns {number} Negative when a comes first, positive when b does\n */\n compareKeys(a, b) {\n const order = a.major - b.major || a.minor - b.minor;\n if (order !== 0 || a.minor !== ATTRIBUTE_KEY) return order;\n return this.attributeIndexOf(a.node) - this.attributeIndexOf(b.node);\n }\n\n /**\n * Sort nodes in document order: an element, then its namespace nodes (by\n * index), then its attributes, then its children.\n *\n * @param {Node[]} nodes - DOM nodes and namespace nodes, sorted in place\n * @returns {Node[]} The same array\n */\n sort(nodes) {\n const keyed = nodes.map((node) => this.keyOf(node));\n keyed.sort((a, b) => this.compareKeys(a, b));\n for (let i = 0; i < keyed.length; i++) nodes[i] = keyed[i].node;\n return nodes;\n }\n}\n", "/**\n * String and number conversions of the XPath 1.0 data model.\n *\n * JavaScript's own conversions are close to XPath's but not equal: `\\s` and\n * `trim()` know Unicode spaces, `Number()` reads exponents, hexadecimal and\n * `Infinity`, `String()` writes exponents, and string indexes count UTF-16\n * code units. The helpers here follow the recommendation instead: XML\n * whitespace only (#x20 #x9 #xD #xA), the Number grammar of section 4.4, the\n * decimal form of section 4.2 and characters counted as code points.\n *\n * @module xpath/strings\n */\n\n/** A run of XML whitespace characters. */\nconst XML_WHITESPACE_RUN = /[ \\t\\r\\n]+/g;\n\n/**\n * Whether a character is XML whitespace (#x20, #x9, #xD, #xA).\n *\n * @param {string} char - A single character\n * @returns {boolean} True for XML whitespace\n */\nfunction isXmlSpace(char) {\n return char === \" \" || char === \"\\t\" || char === \"\\r\" || char === \"\\n\";\n}\n\n/**\n * Strip leading and trailing XML whitespace in linear time (a regular\n * expression such as `/\\s+$/` backtracks quadratically on long runs).\n *\n * @param {string} str - Any string\n * @returns {string} The trimmed string\n */\nexport function trimXmlSpace(str) {\n let start = 0;\n let end = str.length;\n while (start < end && isXmlSpace(str[start])) start++;\n while (end > start && isXmlSpace(str[end - 1])) end--;\n return str.slice(start, end);\n}\n\n/** `S? '-'? (Digits ('.' Digits?)? | '.' Digits) S?` (XPath 4.4 number()). */\nconst XPATH_NUMBER = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\n\n/** Any UTF-16 surrogate code unit. */\nconst SURROGATE = /[\\uD800-\\uDFFF]/;\n\n/**\n * Strip leading and trailing XML whitespace and collapse inner runs of it to\n * one space, as `normalize-space()` does.\n *\n * @param {string} str - Any string\n * @returns {string} The normalized string\n *\n * @example\n * normalizeXmlSpace(\" a \\n b \"); // \"a b\" - a no-break space is kept\n */\nexport function normalizeXmlSpace(str) {\n return trimXmlSpace(str).replace(XML_WHITESPACE_RUN, \" \");\n}\n\n/**\n * Split a string on XML whitespace, dropping empty tokens.\n *\n * @param {string} str - Whitespace separated tokens\n * @returns {string[]} The tokens\n */\nexport function splitXmlSpace(str) {\n return str.split(XML_WHITESPACE_RUN).filter((token) => token !== \"\");\n}\n\n/**\n * Convert a string to a number following the XPath Number grammar: optional\n * XML whitespace, an optional minus sign, digits with an optional decimal\n * point. Anything else, including the empty string, is NaN.\n *\n * @param {string} str - The string to convert\n * @returns {number} The number, or NaN\n *\n * @example\n * parseXPathNumber(\" -3.5 \"); // -3.5\n * parseXPathNumber(\"1e3\"); // NaN\n */\nexport function parseXPathNumber(str) {\n const trimmed = trimXmlSpace(str);\n if (!XPATH_NUMBER.test(trimmed)) return Number.NaN;\n return Number(trimmed);\n}\n\n/**\n * Convert a number to its XPath string form: NaN, Infinity and -Infinity by\n * name, zero as \"0\", every other number in decimal notation without an\n * exponent. The digits are those of `Number#toString`; exponent forms are\n * rewritten by moving the decimal point in the string, so no floating point\n * arithmetic can alter them.\n *\n * @param {number} value - The number\n * @returns {string} The string form\n *\n * @example\n * formatXPathNumber(1e21); // \"1000000000000000000000\"\n * formatXPathNumber(1e-7); // \"0.0000001\"\n */\nexport function formatXPathNumber(value) {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n if (value === 0) return \"0\";\n\n const text = String(value);\n const exponentAt = text.indexOf(\"e\");\n if (exponentAt === -1) return text;\n\n // Exponent forms are \"d.ddde+NN\" (|value| >= 1e21) or \"d.ddde-N\" (< 1e-6)\n const sign = value < 0 ? \"-\" : \"\";\n const exponent = Number(text.substring(exponentAt + 1));\n const digits = text.substring(sign.length, exponentAt).replace(\".\", \"\");\n\n if (exponent < 0) {\n return `${sign}0.${\"0\".repeat(-exponent - 1)}${digits}`;\n }\n return sign + digits + \"0\".repeat(exponent + 1 - digits.length);\n}\n\n/**\n * Number of characters (Unicode code points) in a string.\n *\n * @param {string} str - Any string\n * @returns {number} The number of code points\n */\nexport function codePointLength(str) {\n if (!SURROGATE.test(str)) return str.length;\n return Array.from(str).length;\n}\n\n/**\n * XPath `substring()` on code points: the characters whose 1-based position\n * p satisfies `p >= round(start)` and, with a length, `p < round(start) +\n * round(length)`. NaN and infinite arguments follow from those comparisons.\n *\n * @param {string} str - The string\n * @param {number} start - Start position, not yet rounded\n * @param {number} [length] - Number of characters, not yet rounded\n * @returns {string} The substring\n *\n * @example\n * xpathSubstring(\"12345\", 1.5, 2.6); // \"234\"\n */\nexport function xpathSubstring(str, start, length) {\n const first = Math.round(start);\n const end = length === undefined ? Infinity : first + Math.round(length);\n const from = Math.max(first, 1);\n if (Number.isNaN(end) || Number.isNaN(from) || end <= from) return \"\";\n\n const chars = SURROGATE.test(str) ? Array.from(str) : null;\n if (chars === null) return str.slice(from - 1, end - 1);\n return chars.slice(from - 1, end - 1).join(\"\");\n}\n\n/**\n * XPath `translate()` on code points: each character of `str` found in\n * `from` is replaced by the character at the same position in `to`, or\n * removed when `to` is shorter. The first occurrence in `from` wins.\n *\n * @param {string} str - The string to translate\n * @param {string} from - Characters to replace\n * @param {string} to - Replacement characters\n * @returns {string} The translated string\n */\nexport function xpathTranslate(str, from, to) {\n const fromChars = Array.from(from);\n const toChars = Array.from(to);\n let result = \"\";\n for (const char of str) {\n const index = fromChars.indexOf(char);\n if (index === -1) {\n result += char;\n } else if (index < toChars.length) {\n result += toChars[index];\n }\n }\n return result;\n}\n", "/**\n * XPath 1.0 node-set functions (section 4.1), plus `sum()` (4.4) and `lang()`\n * (4.3), which also take node-sets or walk the tree.\n *\n * Functions whose argument must be a node-set raise a type error for any other\n * value, as libxslt does (\"count() expects a node-set\"). A single node, which\n * is how this processor represents a result tree fragment, is accepted as a\n * node-set of that node: XSLT 1.0 forbids it, but libxslt accepts\n * `count($rtf)` and stylesheets rely on it.\n *\n * @module xpath/nodeSetFunctions\n */\n\n\"use strict\";\n\nimport { splitXmlSpace } from \"./strings.js\";\nimport { parentOf } from \"./axes.js\";\nimport { NAMESPACE_NODE } from \"./namespaceNodes.js\";\n\n/** Qualified name of the attribute read by `lang()`. */\nconst XML_LANG = \"xml:lang\";\n\n/**\n * Whether a node has an expanded name made of a namespace URI and a local\n * part: elements and attributes (XPath 5.2, 5.3).\n *\n * @param {Node} node - Any node\n * @returns {boolean} True for element and attribute nodes\n */\nfunction hasQualifiedName(node) {\n const type = node.nodeType;\n return type === 1 || type === 2;\n}\n\n/**\n * Whether a node has a name without a namespace part: processing\n * instructions (their target) and namespace nodes (their prefix).\n *\n * @param {Node} node - Any node\n * @returns {boolean} True for processing instruction and namespace nodes\n */\nfunction hasLocalNameOnly(node) {\n const type = node.nodeType;\n return type === 7 || type === NAMESPACE_NODE;\n}\n\n/**\n * The element whose `xml:lang` decides the language of a node: the node\n * itself for an element, the element of an attribute or namespace node, the\n * parent of any other node.\n *\n * @param {Node} node - Context node\n * @returns {Node|null} The first node to inspect\n */\nfunction languageStart(node) {\n return node.nodeType === 1 ? node : parentOf(node);\n}\n\n/**\n * Build the node-set functions for an evaluator.\n *\n * @param {import('./evaluator.js').XPathEvaluator} evaluator - The evaluator\n * @returns {Object<string, Function>} Functions by name\n */\nexport function createNodeSetFunctions(evaluator) {\n /**\n * Evaluate an argument that must be a node-set.\n *\n * @param {string} name - Function name, for the error message\n * @param {object} arg - Argument expression\n * @param {import('./evaluator.js').XPathContext} ctx - Evaluation context\n * @returns {Node[]} The node-set\n * @throws {TypeError} When the argument is not a node-set\n */\n const nodeSetArgument = (name, arg, ctx) => {\n const value = evaluator.evaluate(arg, ctx);\n if (Array.isArray(value)) return value;\n if (value?.nodeType) return [value];\n throw new TypeError(`${name}() expects a node-set`);\n };\n\n /**\n * The node a name function applies to: the context node without argument,\n * otherwise the first node of the node-set argument.\n *\n * @param {string} name - Function name, for the error message\n * @param {object[]} args - Argument expressions\n * @param {import('./evaluator.js').XPathContext} ctx - Evaluation context\n * @returns {Node|undefined} The node, undefined for an empty node-set\n */\n const nameTarget = (name, args, ctx) =>\n args.length === 0 ? ctx.node : nodeSetArgument(name, args[0], ctx)[0];\n\n return {\n count: (args, ctx) => nodeSetArgument(\"count\", args[0], ctx).length,\n\n /**\n * `id(object)`: every whitespace separated token of the argument (of the\n * string value of every node, for a node-set) names an ID; the result is\n * in document order without duplicates.\n */\n id: (args, ctx) => {\n const value = evaluator.evaluate(args[0], ctx);\n const strings = Array.isArray(value)\n ? value.map((node) => evaluator.getStringValue(node))\n : [evaluator.toString(value)];\n const doc = ctx.node.ownerDocument || ctx.node;\n const found = new Set();\n for (const string of strings) {\n for (const token of splitXmlSpace(string)) {\n const element = doc.getElementById(token);\n if (element) found.add(element);\n }\n }\n return evaluator.sortByDocumentOrder([...found]);\n },\n\n \"local-name\": (args, ctx) => {\n const node = nameTarget(\"local-name\", args, ctx);\n if (!node) return \"\";\n if (hasQualifiedName(node)) return node.localName;\n return hasLocalNameOnly(node) ? node.nodeName : \"\";\n },\n\n \"namespace-uri\": (args, ctx) => {\n const node = nameTarget(\"namespace-uri\", args, ctx);\n return node && hasQualifiedName(node) ? node.namespaceURI || \"\" : \"\";\n },\n\n name: (args, ctx) => {\n const node = nameTarget(\"name\", args, ctx);\n if (!node) return \"\";\n return hasQualifiedName(node) || hasLocalNameOnly(node)\n ? node.nodeName\n : \"\";\n },\n\n sum: (args, ctx) =>\n nodeSetArgument(\"sum\", args[0], ctx).reduce(\n (total, node) =>\n total + evaluator.toNumber(evaluator.getStringValue(node)),\n 0,\n ),\n\n /**\n * `lang(string)`: whether the `xml:lang` of the nearest element at or\n * above the context node (an attribute or text node looks from its\n * element) is the language or one of its sublanguages. A plain `lang`\n * attribute is not `xml:lang` and is ignored.\n */\n lang: (args, ctx) => {\n const wanted = evaluator.toString(evaluator.evaluate(args[0], ctx));\n const lang = wanted.toLowerCase();\n for (\n let node = languageStart(ctx.node);\n node?.nodeType === 1;\n node = node.parentNode\n ) {\n // The xml prefix is always bound to one namespace, so the qualified\n // name also finds attributes created without a namespace URI\n if (node.hasAttribute(XML_LANG)) {\n const actual = node.getAttribute(XML_LANG).toLowerCase();\n return actual === lang || actual.startsWith(`${lang}-`);\n }\n }\n return false;\n },\n };\n}\n", "/**\n * XPath 1.0 Evaluator\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * Evaluates XPath AST against DOM nodes.\n */\n\n\"use strict\";\n\nimport { NodeType } from \"./parser.js\";\nimport {\n AXIS_WALKERS,\n REVERSE_AXES,\n ancestorAxis,\n attributeAxis,\n childAxis,\n descendantAxis,\n followingAxis,\n followingSiblingAxis,\n precedingAxis,\n precedingSiblingAxis,\n isTextNode,\n parentOf,\n rootNodeOf,\n} from \"./axes.js\";\nimport {\n NAMESPACE_NODE,\n matchNamespaceNameTest,\n namespaceAxis,\n} from \"./namespaceNodes.js\";\nimport {\n DocumentOrderIndex,\n compareDomPositions,\n compareNodeOrder,\n hasNativePositionComparison,\n} from \"./documentOrder.js\";\nimport { createNodeSetFunctions } from \"./nodeSetFunctions.js\";\nimport {\n codePointLength,\n formatXPathNumber,\n normalizeXmlSpace,\n parseXPathNumber,\n xpathSubstring,\n xpathTranslate,\n} from \"./strings.js\";\n\n/**\n * Namespace the `xml` prefix is bound to in every context; it cannot be\n * undeclared or rebound (Namespaces in XML 1.0, section 3).\n */\nexport const XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\n\n/**\n * Resolve a namespace prefix: `xml` is predeclared, every other prefix comes\n * from the context bindings.\n *\n * @param {string} prefix - The prefix\n * @param {Object<string, string>} namespaces - Bindings by prefix\n * @returns {string|null} The namespace URI, or null when undeclared\n */\nexport function resolveNamespacePrefix(prefix, namespaces) {\n if (prefix === \"xml\") return XML_NAMESPACE;\n return Object.hasOwn(namespaces, prefix) ? namespaces[prefix] : null;\n}\n\n/**\n * Key of a function registered by expanded name, as used by\n * {@link XPathEvaluator#registerFunctions}: `{namespace-uri}local-name`.\n *\n * @param {string} namespaceUri - The function's namespace\n * @param {string} localName - The function's local name\n * @returns {string} The registry key\n *\n * @example\n * expandedFunctionName(\"http://exslt.org/common\", \"node-set\");\n * // \"{http://exslt.org/common}node-set\"\n */\nexport function expandedFunctionName(namespaceUri, localName) {\n return `{${namespaceUri}}${localName}`;\n}\n\n/**\n * Whether an expression is a call of the core `position()` function.\n *\n * @param {object} expr - Expression AST node\n * @returns {boolean} True for `position()`\n */\nfunction isPositionCall(expr) {\n return (\n expr.type === NodeType.FUNCTION_CALL &&\n expr.name === \"position\" &&\n !expr.prefix &&\n expr.args.length === 0\n );\n}\n\n/**\n * Whether a node has the principal node type of an axis, the only type a\n * name test can match there: attributes on the attribute axis, namespace\n * nodes on the namespace axis, elements elsewhere (XPath 1.0 section 2.3).\n *\n * @param {number} type - The candidate node's `nodeType`\n * @param {string|null} axis - The axis, or null when the caller checks types\n * @returns {boolean} True when a name test may match the node\n */\nfunction isPrincipalNodeType(type, axis) {\n if (axis === null) return true;\n if (axis === \"attribute\") return type === 2;\n if (axis === \"namespace\") return type === NAMESPACE_NODE;\n return type === 1;\n}\n\n/**\n * Whether a node belongs to an HTML document (`contentType` \"text/html\").\n * Two jsdom getters, so name tests read it last.\n *\n * @param {Node} node - An element\n * @returns {boolean} True for a node of an HTML document\n */\nfunction isInHtmlDocument(node) {\n return node.ownerDocument?.contentType === \"text/html\";\n}\n\n/**\n * XPath result types matching W3C spec\n */\nexport const XPathResultType = {\n ANY_TYPE: 0,\n NUMBER_TYPE: 1,\n STRING_TYPE: 2,\n BOOLEAN_TYPE: 3,\n UNORDERED_NODE_ITERATOR_TYPE: 4,\n ORDERED_NODE_ITERATOR_TYPE: 5,\n UNORDERED_NODE_SNAPSHOT_TYPE: 6,\n ORDERED_NODE_SNAPSHOT_TYPE: 7,\n ANY_UNORDERED_NODE_TYPE: 8,\n FIRST_ORDERED_NODE_TYPE: 9,\n};\n\n/**\n * Security limits to prevent DoS attacks\n */\nexport const XPathLimits = {\n MAX_RECURSION_DEPTH: 100,\n MAX_RESULT_SIZE: 10000,\n MAX_STRING_LENGTH: 1000000,\n};\n\n/**\n * Forbidden variable names to prevent prototype pollution\n */\nconst FORBIDDEN_VARIABLE_NAMES = Object.freeze([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"__defineGetter__\",\n \"__defineSetter__\",\n \"__lookupGetter__\",\n \"__lookupSetter__\",\n]);\n\n/**\n * XPath evaluation context\n */\nexport class XPathContext {\n /**\n * @param {Node} node - The context node\n * @param {number} [position] - The context position (1-based)\n * @param {number} [size] - The context size\n * @param {Object} [variables] - Variable bindings by name\n * @param {Object} [namespaces] - Namespace bindings by prefix\n * @param {*} [hostContext] - Opaque context of the host language (XSLT),\n * carried through unchanged so host defined functions can reach it\n */\n constructor(\n node,\n position = 1,\n size = 1,\n variables = {},\n namespaces = {},\n hostContext = null,\n ) {\n this.node = node;\n this.position = position;\n this.size = size;\n this.variables = variables;\n this.namespaces = namespaces;\n this.hostContext = hostContext;\n }\n\n clone(overrides = {}) {\n return new XPathContext(\n overrides.node ?? this.node,\n overrides.position ?? this.position,\n overrides.size ?? this.size,\n overrides.variables ?? this.variables,\n overrides.namespaces ?? this.namespaces,\n overrides.hostContext ?? this.hostContext,\n );\n }\n}\n\n/**\n * XPath Evaluator\n */\nexport class XPathEvaluator {\n /**\n * @param {object} [options] - Evaluator options\n * @param {number} [options.maxRecursionDepth] - Deepest expression nesting\n * @param {number} [options.maxResultSize] - Largest node-set of one step\n * @param {number} [options.maxStringLength] - Longest string literal\n * @param {boolean} [options.legacyNameTests] - Deprecated: let unprefixed\n * name tests also match nodes in a namespace, as before 1.2.0\n */\n constructor(options = {}) {\n this.legacyNameTests = options.legacyNameTests === true;\n this.resetNamespaceNodes();\n this.resetDocumentOrder();\n this.functions = Object.assign(\n Object.create(null),\n this.initCoreFunctions(),\n );\n this.maxRecursionDepth =\n options.maxRecursionDepth ?? XPathLimits.MAX_RECURSION_DEPTH;\n this.maxResultSize = options.maxResultSize ?? XPathLimits.MAX_RESULT_SIZE;\n this.maxStringLength =\n options.maxStringLength ?? XPathLimits.MAX_STRING_LENGTH;\n this.recursionDepth = 0;\n }\n\n /**\n * Forget the namespace nodes synthesized so far (see namespaceNodes.js),\n * e.g. before a new transformation: the declarations of the source tree\n * may have changed. Until then each element keeps the same namespace node\n * objects, so they have a stable identity.\n *\n * @returns {void}\n */\n resetNamespaceNodes() {\n this.namespaceNodes = new WeakMap();\n }\n\n /**\n * Evaluate XPath expression against a context\n * @throws {Error} If recursion depth exceeds limit\n * @throws {Error} If AST is invalid\n */\n evaluate(ast, context) {\n if (!ast || typeof ast !== \"object\") {\n throw new Error(\"Invalid AST: expected object\");\n }\n\n if (!ast.type) {\n throw new Error(\"Invalid AST: missing type property\");\n }\n\n // An index created during an earlier evaluation may describe trees\n // that have changed since; one set with resetDocumentOrder() stays\n if (this.recursionDepth === 0 && this.ownsDocumentOrder) {\n this.resetDocumentOrder();\n }\n this.recursionDepth++;\n if (this.recursionDepth > this.maxRecursionDepth) {\n this.recursionDepth = 0;\n throw new Error(\n `Maximum recursion depth exceeded (${this.maxRecursionDepth})`,\n );\n }\n\n try {\n return this.evaluateInternal(ast, context);\n } finally {\n this.recursionDepth--;\n }\n }\n\n /**\n * Internal evaluation (after validation)\n */\n evaluateInternal(ast, context) {\n switch (ast.type) {\n case NodeType.OR_EXPR:\n return this.evalOrExpr(ast, context);\n case NodeType.AND_EXPR:\n return this.evalAndExpr(ast, context);\n case NodeType.EQUALITY_EXPR:\n case NodeType.RELATIONAL_EXPR:\n return this.evalComparisonExpr(ast, context);\n case NodeType.ADDITIVE_EXPR:\n return this.evalAdditiveExpr(ast, context);\n case NodeType.MULTIPLICATIVE_EXPR:\n return this.evalMultiplicativeExpr(ast, context);\n case NodeType.UNARY_EXPR:\n return this.evalUnaryExpr(ast, context);\n case NodeType.UNION_EXPR:\n return this.evalUnionExpr(ast, context);\n case NodeType.PATH_EXPR:\n return this.evalPathExpr(ast, context);\n case NodeType.LOCATION_PATH:\n return this.evalLocationPath(ast, context);\n case NodeType.VARIABLE_REF:\n return this.evalVariableRef(ast, context);\n case NodeType.LITERAL:\n return this.validateString(ast.value);\n case NodeType.NUMBER:\n return ast.value;\n case NodeType.FUNCTION_CALL:\n return this.evalFunctionCall(ast, context);\n default:\n throw new Error(`Unknown AST node type: ${String(ast.type)}`);\n }\n }\n\n /**\n * Validate and limit string length\n */\n validateString(str) {\n if (typeof str === \"string\" && str.length > this.maxStringLength) {\n throw new Error(\n `String exceeds maximum length (${this.maxStringLength})`,\n );\n }\n return str;\n }\n\n /**\n * Validate result size\n */\n validateResultSize(nodes) {\n if (Array.isArray(nodes) && nodes.length > this.maxResultSize) {\n throw new Error(\n `Result set exceeds maximum size (${this.maxResultSize})`,\n );\n }\n return nodes;\n }\n\n evalOrExpr(ast, context) {\n return (\n this.toBoolean(this.evaluate(ast.left, context)) ||\n this.toBoolean(this.evaluate(ast.right, context))\n );\n }\n\n evalAndExpr(ast, context) {\n return (\n this.toBoolean(this.evaluate(ast.left, context)) &&\n this.toBoolean(this.evaluate(ast.right, context))\n );\n }\n\n /**\n * Evaluate `=`, `!=`, `<`, `<=`, `>` or `>=`. Comparisons involving\n * node-sets are existential, so `!=` is not `not(=)` (XPath 3.4).\n *\n * @param {object} ast - Equality or relational expression node\n * @param {XPathContext} context - Evaluation context\n * @returns {boolean} The comparison result\n */\n evalComparisonExpr(ast, context) {\n const left = this.evaluate(ast.left, context);\n const right = this.evaluate(ast.right, context);\n return this.compareValues(left, right, ast.operator);\n }\n\n evalAdditiveExpr(ast, context) {\n const left = this.toNumber(this.evaluate(ast.left, context));\n const right = this.toNumber(this.evaluate(ast.right, context));\n return ast.operator === \"+\" ? left + right : left - right;\n }\n\n evalMultiplicativeExpr(ast, context) {\n const left = this.toNumber(this.evaluate(ast.left, context));\n const right = this.toNumber(this.evaluate(ast.right, context));\n\n switch (ast.operator) {\n case \"*\":\n return left * right;\n case \"div\":\n return left / right;\n case \"mod\":\n return left % right;\n default:\n throw new Error(`Unknown multiplicative operator: ${ast.operator}`);\n }\n }\n\n evalUnaryExpr(ast, context) {\n const value = this.toNumber(this.evaluate(ast.operand, context));\n return -value;\n }\n\n evalUnionExpr(ast, context) {\n const left = this.evaluate(ast.left, context);\n const right = this.evaluate(ast.right, context);\n\n const leftNodes = Array.isArray(left) ? left : [left];\n const rightNodes = Array.isArray(right) ? right : [right];\n\n // Union in document order, no duplicates\n const seen = new Set();\n const result = [];\n\n for (const node of [...leftNodes, ...rightNodes]) {\n if (!seen.has(node)) {\n seen.add(node);\n result.push(node);\n }\n }\n\n this.validateResultSize(result);\n return this.sortByDocumentOrder(result);\n }\n\n evalPathExpr(ast, context) {\n if (ast.filter) {\n let result = this.evaluate(ast.filter, context);\n\n if (ast.predicates) {\n for (const pred of ast.predicates) {\n result = this.filterByPredicate(result, pred, context);\n }\n }\n\n if (ast.steps) {\n for (const step of ast.steps) {\n result = this.evalStepOnNodes(step, result, context);\n }\n }\n\n return result;\n }\n\n return [];\n }\n\n evalLocationPath(ast, context) {\n let nodes;\n\n if (ast.absolute) {\n // The root node of the tree containing the context node: a document,\n // or the fragment of a result tree fragment turned into a node-set\n nodes = [rootNodeOf(context.node)];\n } else {\n nodes = [context.node];\n }\n\n for (const step of ast.steps) {\n nodes = this.evalStepOnNodes(step, nodes, context);\n this.validateResultSize(nodes);\n }\n\n return nodes;\n }\n\n /**\n * Apply one location step to every node of a node-set.\n *\n * The result is in document order without duplicates. With a single context\n * node the axis output is already duplicate free, so it only needs to be\n * reversed for reverse axes; merging several context nodes needs a sort.\n *\n * @param {object} step - Step AST node\n * @param {Node|Node[]} nodes - Context nodes\n * @param {XPathContext} context - Evaluation context\n * @returns {Node[]} The selected nodes in document order\n */\n evalStepOnNodes(step, nodes, context) {\n const allNodes = Array.isArray(nodes) ? nodes : [nodes];\n const reverse = REVERSE_AXES.has(step.axis);\n\n if (allNodes.length === 1) {\n const single = this.evalStep(step, context.clone({ node: allNodes[0] }));\n this.validateResultSize(single);\n return reverse ? single.reverse() : single;\n }\n\n const seen = new Set();\n const result = [];\n for (const node of allNodes) {\n for (const found of this.evalStep(step, context.clone({ node }))) {\n if (!seen.has(found)) {\n seen.add(found);\n result.push(found);\n }\n }\n this.validateResultSize(result);\n }\n\n return this.sortByDocumentOrder(result);\n }\n\n /**\n * Apply one location step to a single context node.\n *\n * When the first predicate selects one position (`[n]` or\n * `[position() = n]`) and the axis can be walked lazily, the walk stops at\n * the n-th node that passes the node test instead of materializing the\n * whole axis: `following-sibling::x[1]` in a loop is then linear.\n *\n * @param {object} step - Step AST node\n * @param {XPathContext} context - Evaluation context\n * @returns {Node[]} The selected nodes in axis order\n */\n evalStep(step, context) {\n const { predicates } = step;\n const position = this.positionalPredicate(step);\n let nodes;\n let first = 0;\n\n if (position !== null && Object.hasOwn(AXIS_WALKERS, step.axis)) {\n nodes = this.nthOnAxis(step, context, position);\n first = 1;\n } else {\n nodes = this.getAxisNodes(step.axis, context.node).filter((n) =>\n this.matchNodeTest(step.nodeTest, n, context, step.axis),\n );\n }\n\n for (let i = first; i < predicates.length; i++) {\n nodes = this.filterByPredicate(nodes, predicates[i], context);\n }\n\n return nodes;\n }\n\n /**\n * The position selected by the first predicate of a step, when that\n * predicate is a number literal `[n]` or `[position() = n]`.\n *\n * @param {object} step - Step AST node\n * @returns {number|null} The position, or null for any other predicate\n */\n positionalPredicate(step) {\n const expr = step.predicates[0]?.expr;\n if (!expr) return null;\n if (expr.type === NodeType.NUMBER) return expr.value;\n if (expr.type !== NodeType.EQUALITY_EXPR || expr.operator !== \"=\") {\n return null;\n }\n const { left, right } = expr;\n if (isPositionCall(left) && right.type === NodeType.NUMBER) {\n return right.value;\n }\n if (isPositionCall(right) && left.type === NodeType.NUMBER) {\n return left.value;\n }\n return null;\n }\n\n /**\n * The n-th node of an axis passing the node test of a step, found by\n * walking the axis only as far as needed.\n *\n * @param {object} step - Step AST node\n * @param {XPathContext} context - Evaluation context\n * @param {number} position - The wanted proximity position\n * @returns {Node[]} The node, or an empty node-set\n */\n nthOnAxis(step, context, position) {\n // Positions are whole numbers from 1: [0], [1.5] or [NaN] select nothing\n if (!Number.isInteger(position) || position < 1) return [];\n let remaining = position;\n let found = null;\n AXIS_WALKERS[step.axis](context.node, (node) => {\n if (!this.matchNodeTest(step.nodeTest, node, context, step.axis)) {\n return false;\n }\n remaining--;\n if (remaining > 0) return false;\n found = node;\n return true;\n });\n return found ? [found] : [];\n }\n\n /**\n * Nodes on an axis (see axes.js). Reverse axes are returned nearest first,\n * so predicates see proximity positions.\n *\n * @param {string} axis - Axis name\n * @param {Node} node - Context node\n * @returns {Node[]} The nodes on the axis\n */\n getAxisNodes(axis, node) {\n switch (axis) {\n case \"child\":\n return childAxis(node);\n case \"parent\": {\n const parent = parentOf(node);\n return parent ? [parent] : [];\n }\n case \"self\":\n return [node];\n case \"descendant\":\n return descendantAxis(node, false);\n case \"descendant-or-self\":\n return descendantAxis(node, true);\n case \"ancestor\":\n return ancestorAxis(node, false);\n case \"ancestor-or-self\":\n return ancestorAxis(node, true);\n case \"following-sibling\":\n return followingSiblingAxis(node);\n case \"preceding-sibling\":\n return precedingSiblingAxis(node);\n case \"following\":\n return followingAxis(node);\n case \"preceding\":\n return precedingAxis(node);\n case \"attribute\":\n return attributeAxis(node);\n case \"namespace\":\n return namespaceAxis(node, this.namespaceNodes);\n default:\n throw new Error(`Unknown axis: ${axis}`);\n }\n }\n\n /**\n * Match a node test against a node.\n *\n * @param {object} nodeTest - Node test AST node\n * @param {Node} node - Candidate node\n * @param {XPathContext} context - Evaluation context (for prefixes)\n * @param {string|null} [axis] - Axis of the step, which decides the\n * principal node type of name tests; null for XSLT patterns, whose\n * matcher checks node types itself\n * @returns {boolean} Whether the node matches\n */\n matchNodeTest(nodeTest, node, context, axis = null) {\n switch (nodeTest.type) {\n case NodeType.NAME_TEST: {\n const type = node.nodeType;\n return (\n isPrincipalNodeType(type, axis) &&\n this.matchNameTest(nodeTest, node, context, type)\n );\n }\n\n case NodeType.NODE_TYPE_TEST:\n return this.matchNodeTypeTest(nodeTest.nodeType, node);\n\n case NodeType.PI_TEST:\n return node.nodeType === 7 && node.nodeName === nodeTest.name;\n\n default:\n return false;\n }\n }\n\n /**\n * Match a name test against a node.\n *\n * Cheap checks run first: in jsdom every DOM getter crosses a wrapper, so\n * `namespaceURI` and the owner document's content type are only read when\n * the outcome depends on them.\n *\n * @param {object} nodeTest - Name test AST node\n * @param {Node} node - Candidate node\n * @param {XPathContext} context - Evaluation context (for prefixes)\n * @param {number} [type] - The node's `nodeType`, when already read\n * @returns {boolean} Whether the node matches\n */\n matchNameTest(nodeTest, node, context, type = node.nodeType) {\n if (type === NAMESPACE_NODE) return matchNamespaceNameTest(nodeTest, node);\n // Only element and attribute nodes have names\n if (type !== 1 && type !== 2) return false;\n\n const { name, prefix } = nodeTest;\n\n if (!prefix) return this.matchUnprefixedName(name, node, type);\n\n const namespaceUri = resolveNamespacePrefix(prefix, context.namespaces);\n if (!namespaceUri) {\n // An undeclared prefix is an error (XPath 1.0 section 2.3), as in\n // libxslt; it must not silently match names in no namespace\n throw new Error(`Undefined namespace prefix: ${prefix}`);\n }\n if ((node.namespaceURI || null) !== namespaceUri) return false;\n return name === \"*\" || (node.localName || node.nodeName) === name;\n }\n\n /**\n * Match a name test without prefix (`name` or `*`) against an element or\n * attribute. The owner document's content type (two jsdom getters) is\n * read last, only for HTML-specific outcomes.\n *\n * @param {string} name - The tested name, or \"*\"\n * @param {Node} node - An element or attribute\n * @param {number} type - The node's `nodeType`\n * @returns {boolean} Whether the node matches\n */\n matchUnprefixedName(name, node, type) {\n if (name === \"*\") return true;\n const nodeName = node.localName || node.nodeName;\n if (nodeName !== name) {\n // HTML documents match element names case-insensitively\n return (\n type === 1 &&\n nodeName.toLowerCase() === name.toLowerCase() &&\n isInHtmlDocument(node)\n );\n }\n // A QName without prefix only matches nodes in no namespace (2.3).\n // HTML elements are in the XHTML namespace in the DOM but in none for\n // libxslt, which receives HTML documents re-parsed from their markup.\n if (this.legacyNameTests || node.namespaceURI === null) return true;\n return type === 1 && isInHtmlDocument(node);\n }\n\n matchNodeTypeTest(nodeType, node) {\n switch (nodeType) {\n case \"node\":\n return true;\n case \"text\":\n // The XPath data model has no CDATA sections: they are text nodes\n return node.nodeType === 3 || node.nodeType === 4;\n case \"comment\":\n return node.nodeType === 8;\n case \"processing-instruction\":\n return node.nodeType === 7;\n default:\n return false;\n }\n }\n\n filterByPredicate(nodes, predicate, context) {\n const result = [];\n const nodeArray = Array.isArray(nodes) ? nodes : [nodes];\n const size = nodeArray.length;\n\n for (let i = 0; i < nodeArray.length; i++) {\n const node = nodeArray[i];\n const predicateContext = context.clone({\n node,\n position: i + 1,\n size,\n });\n\n const value = this.evaluate(predicate.expr, predicateContext);\n\n // If predicate evaluates to a number, it's a position test\n if (typeof value === \"number\") {\n if (value === i + 1) {\n result.push(node);\n }\n } else if (this.toBoolean(value)) {\n result.push(node);\n }\n }\n\n return result;\n }\n\n evalVariableRef(ast, context) {\n const name = ast.prefix ? `${ast.prefix}:${ast.name}` : ast.name;\n\n // Security: Prevent prototype pollution\n if (\n FORBIDDEN_VARIABLE_NAMES.includes(name) ||\n FORBIDDEN_VARIABLE_NAMES.includes(ast.name)\n ) {\n throw new Error(`Forbidden variable name: $${name}`);\n }\n\n if (!Object.prototype.hasOwnProperty.call(context.variables, name)) {\n throw new Error(`Undefined variable: $${name}`);\n }\n return context.variables[name];\n }\n\n /**\n * Register additional functions, for example the XSLT function library.\n *\n * Existing names are overwritten, so a host language can also specialise a\n * core function. Each function is called as `fn(args, context)` with the\n * evaluator as `this`.\n *\n * Extension functions are keyed by expanded name, `{namespace-uri}local`\n * (see {@link expandedFunctionName}), and are found through whatever prefix\n * the expression binds to that namespace. A literal `prefix:local` key is\n * still honoured when the prefix does not resolve to a registered function.\n *\n * @param {Object<string, Function>} functions - Functions by name\n * @returns {XPathEvaluator} This evaluator, to allow chaining\n *\n * @example\n * evaluator.registerFunctions({ '{urn:my}double': (args, ctx) => 2 });\n * // callable as my:double() when my is bound to urn:my\n */\n registerFunctions(functions) {\n for (const [name, fn] of Object.entries(functions)) {\n this.functions[name] = fn;\n }\n return this;\n }\n\n /**\n * Find the implementation of a possibly prefixed function name.\n *\n * @param {string} localName - The local part of the function name\n * @param {string|null} prefix - The prefix, or null for core functions\n * @param {Object<string, string>} namespaces - Prefix bindings\n * @returns {Function|null} The function, or null when none is registered\n */\n resolveFunction(localName, prefix, namespaces) {\n if (!prefix) return this.getFunction(localName);\n\n const namespaceUri = resolveNamespacePrefix(prefix, namespaces);\n const byUri =\n namespaceUri === null\n ? null\n : this.getFunction(expandedFunctionName(namespaceUri, localName));\n return byUri ?? this.getFunction(`${prefix}:${localName}`);\n }\n\n /**\n * Whether a function is registered under an expanded name.\n *\n * @param {string} localName - The local part of the function name\n * @param {string|null} [namespaceUri] - The namespace, null for core functions\n * @returns {boolean} True when the function exists\n */\n hasFunction(localName, namespaceUri = null) {\n const key = namespaceUri\n ? expandedFunctionName(namespaceUri, localName)\n : localName;\n return this.getFunction(key) !== null;\n }\n\n /**\n * Own entry of the function table, never an inherited property.\n *\n * @param {string} key - Registry key\n * @returns {Function|null} The function, or null\n */\n getFunction(key) {\n return Object.hasOwn(this.functions, key) ? this.functions[key] : null;\n }\n\n evalFunctionCall(ast, context) {\n const fn = this.resolveFunction(ast.name, ast.prefix, context.namespaces);\n\n if (!fn) {\n const name = ast.prefix ? `${ast.prefix}:${ast.name}` : ast.name;\n throw new Error(`Unknown function: ${name}`);\n }\n\n return fn.call(this, ast.args, context);\n }\n\n // Type conversion functions\n toBoolean(value) {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return value !== 0 && !isNaN(value);\n if (typeof value === \"string\") return value.length > 0;\n if (Array.isArray(value)) return value.length > 0;\n if (value && value.nodeType) return true;\n return Boolean(value);\n }\n\n toNumber(value) {\n if (typeof value === \"number\") return value;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (typeof value === \"string\") return parseXPathNumber(value);\n if (Array.isArray(value)) {\n return this.toNumber(this.toString(value));\n }\n if (value && value.nodeType) {\n return this.toNumber(this.getStringValue(value));\n }\n return NaN;\n }\n\n toString(value) {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return formatXPathNumber(value);\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (Array.isArray(value)) {\n if (value.length === 0) return \"\";\n return this.getStringValue(value[0]);\n }\n if (value && value.nodeType) {\n return this.getStringValue(value);\n }\n return String(value);\n }\n\n getStringValue(node) {\n if (!node) return \"\";\n\n switch (node.nodeType) {\n case 1: // Element\n case 9: // Document\n case 11: {\n // Document Fragment\n let text = \"\";\n const walker = (n) => {\n if (n.nodeType === 3 || n.nodeType === 4) {\n text += n.nodeValue || \"\";\n } else if (n.childNodes) {\n for (const child of n.childNodes) {\n walker(child);\n }\n }\n };\n walker(node);\n return text;\n }\n\n case 3: // Text\n case 4: {\n // CDATA. A run of adjacent text nodes is one XPath text node (5.7)\n let text = node.nodeValue;\n for (let next = node.nextSibling; isTextNode(next);) {\n text += next.nodeValue;\n next = next.nextSibling;\n }\n return text;\n }\n\n case 2: // Attribute\n case 7: // Processing Instruction\n case 8: // Comment\n case NAMESPACE_NODE: // The namespace URI\n return node.nodeValue || \"\";\n\n default:\n return \"\";\n }\n }\n\n // Comparison helper\n compareValues(left, right, operator) {\n const leftIsNodeSet = Array.isArray(left);\n const rightIsNodeSet = Array.isArray(right);\n\n // A node-set compared with a boolean is converted with boolean() (3.4)\n if (\n (leftIsNodeSet && typeof right === \"boolean\") ||\n (rightIsNodeSet && typeof left === \"boolean\")\n ) {\n return this.comparePrimitive(\n this.toBoolean(left),\n this.toBoolean(right),\n operator,\n );\n }\n\n // Node-set comparisons\n if (leftIsNodeSet && rightIsNodeSet) {\n for (const l of left) {\n for (const r of right) {\n if (\n this.comparePrimitive(\n this.getStringValue(l),\n this.getStringValue(r),\n operator,\n )\n ) {\n return true;\n }\n }\n }\n return false;\n }\n\n if (leftIsNodeSet) {\n for (const l of left) {\n if (this.comparePrimitive(this.getStringValue(l), right, operator)) {\n return true;\n }\n }\n return false;\n }\n\n if (rightIsNodeSet) {\n for (const r of right) {\n if (this.comparePrimitive(left, this.getStringValue(r), operator)) {\n return true;\n }\n }\n return false;\n }\n\n return this.comparePrimitive(left, right, operator);\n }\n\n comparePrimitive(left, right, operator) {\n // If comparing for equality with different types\n if (operator === \"=\" || operator === \"!=\") {\n // If one is boolean, convert both to boolean\n if (typeof left === \"boolean\" || typeof right === \"boolean\") {\n const result = this.toBoolean(left) === this.toBoolean(right);\n return operator === \"=\" ? result : !result;\n }\n // If one is number, convert both to number\n if (typeof left === \"number\" || typeof right === \"number\") {\n const result = this.toNumber(left) === this.toNumber(right);\n return operator === \"=\" ? result : !result;\n }\n // Otherwise compare as strings\n const result = this.toString(left) === this.toString(right);\n return operator === \"=\" ? result : !result;\n }\n\n // Relational operators always compare as numbers\n const leftNum = this.toNumber(left);\n const rightNum = this.toNumber(right);\n\n switch (operator) {\n case \"<\":\n return leftNum < rightNum;\n case \"<=\":\n return leftNum <= rightNum;\n case \">\":\n return leftNum > rightNum;\n case \">=\":\n return leftNum >= rightNum;\n default:\n throw new Error(`Unknown comparison operator: ${operator}`);\n }\n }\n\n /**\n * Sort nodes in document order; attributes and namespace nodes sort after\n * their element and before its children (see documentOrder.js).\n *\n * With a {@link DocumentOrderIndex} (set by the XSLT engine for each\n * transformation, or created on first use when the DOM has no\n * `compareDocumentPosition`, as xmldom 0.8), nodes are sorted by their\n * precomputed positions; otherwise through `compareDocumentPosition`.\n *\n * @param {Node[]} nodes - The nodes, sorted in place\n * @returns {Node[]} The same array\n */\n sortByDocumentOrder(nodes) {\n if (nodes.length <= 1) return nodes;\n // Number the trees once per evaluation unless the DOM compares positions\n // natively: compareDocumentPosition written in JavaScript (xmldom,\n // jsdom) costs a tree walk per comparison\n if (!this.documentOrder && !hasNativePositionComparison(nodes[0])) {\n this.documentOrder = new DocumentOrderIndex();\n this.ownsDocumentOrder = true;\n }\n if (this.documentOrder) return this.documentOrder.sort(nodes);\n\n return nodes.sort((a, b) =>\n a === b ? 0 : compareNodeOrder(a, b, compareDomPositions),\n );\n }\n\n /**\n * Use a new {@link DocumentOrderIndex} from now on, e.g. for a new\n * transformation (the trees may have changed since the previous one), or\n * none (null): `compareDocumentPosition` then orders the nodes whenever\n * the DOM has it.\n *\n * @param {DocumentOrderIndex|null} [index] - The index to use\n * @returns {void}\n */\n resetDocumentOrder(index = null) {\n this.documentOrder = index;\n this.ownsDocumentOrder = false;\n }\n\n /**\n * Initialize XPath 1.0 core functions\n */\n initCoreFunctions() {\n return {\n // Node set functions\n last: (args, ctx) => ctx.size,\n position: (args, ctx) => ctx.position,\n ...createNodeSetFunctions(this),\n\n // String functions\n string: (args, ctx) => {\n if (args.length === 0) {\n return this.toString([ctx.node]);\n }\n return this.toString(this.evaluate(args[0], ctx));\n },\n concat: (args, ctx) => {\n return args\n .map((arg) => this.toString(this.evaluate(arg, ctx)))\n .join(\"\");\n },\n \"starts-with\": (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const prefix = this.toString(this.evaluate(args[1], ctx));\n return str.startsWith(prefix);\n },\n contains: (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const substr = this.toString(this.evaluate(args[1], ctx));\n return str.includes(substr);\n },\n \"substring-before\": (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const substr = this.toString(this.evaluate(args[1], ctx));\n const idx = str.indexOf(substr);\n return idx === -1 ? \"\" : str.substring(0, idx);\n },\n \"substring-after\": (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const substr = this.toString(this.evaluate(args[1], ctx));\n const idx = str.indexOf(substr);\n return idx === -1 ? \"\" : str.substring(idx + substr.length);\n },\n substring: (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const start = this.toNumber(this.evaluate(args[1], ctx));\n const length =\n args.length > 2\n ? this.toNumber(this.evaluate(args[2], ctx))\n : undefined;\n return xpathSubstring(str, start, length);\n },\n \"string-length\": (args, ctx) => {\n const str =\n args.length === 0\n ? this.toString([ctx.node])\n : this.toString(this.evaluate(args[0], ctx));\n return codePointLength(str);\n },\n \"normalize-space\": (args, ctx) => {\n const str =\n args.length === 0\n ? this.toString([ctx.node])\n : this.toString(this.evaluate(args[0], ctx));\n return normalizeXmlSpace(str);\n },\n translate: (args, ctx) => {\n const str = this.toString(this.evaluate(args[0], ctx));\n const from = this.toString(this.evaluate(args[1], ctx));\n const to = this.toString(this.evaluate(args[2], ctx));\n return xpathTranslate(str, from, to);\n },\n\n // Boolean functions\n boolean: (args, ctx) => {\n return this.toBoolean(this.evaluate(args[0], ctx));\n },\n not: (args, ctx) => {\n return !this.toBoolean(this.evaluate(args[0], ctx));\n },\n true: () => true,\n false: () => false,\n\n // Number functions\n number: (args, ctx) => {\n if (args.length === 0) {\n return this.toNumber([ctx.node]);\n }\n return this.toNumber(this.evaluate(args[0], ctx));\n },\n floor: (args, ctx) => {\n return Math.floor(this.toNumber(this.evaluate(args[0], ctx)));\n },\n ceiling: (args, ctx) => {\n return Math.ceil(this.toNumber(this.evaluate(args[0], ctx)));\n },\n round: (args, ctx) => {\n const num = this.toNumber(this.evaluate(args[0], ctx));\n if (isNaN(num)) return NaN;\n if (num === -0.5) return -0;\n return Math.round(num);\n },\n };\n }\n}\n", "/**\n * XSLT element vocabulary.\n *\n * Single source of truth for the XSLT namespace URI and for the element names\n * the engine can instantiate. `element-available()` reports against this table,\n * so it stays in step with what {@link XsltEngine#instructionMethod} dispatches.\n */\n\n\"use strict\";\n\n/** The XSLT 1.0 namespace URI. */\nexport const XSLT_NAMESPACE = \"http://www.w3.org/1999/XSL/Transform\";\n\n/**\n * Element names the engine dispatches, i.e. every element that\n * `element-available()` must report as supported.\n */\nexport const XSLT_ELEMENTS = Object.freeze([\n \"apply-imports\",\n \"apply-templates\",\n \"attribute\",\n \"call-template\",\n \"choose\",\n \"comment\",\n \"copy\",\n \"copy-of\",\n \"element\",\n \"fallback\",\n \"for-each\",\n \"if\",\n \"message\",\n \"number\",\n \"otherwise\",\n \"param\",\n \"processing-instruction\",\n \"sort\",\n \"text\",\n \"value-of\",\n \"variable\",\n \"when\",\n \"with-param\",\n]);\n\nconst ELEMENT_SET = new Set(XSLT_ELEMENTS);\n\n/**\n * Check whether an XSLT element local name is supported by the engine.\n *\n * @param {string} localName - Element local name, e.g. `for-each`\n * @returns {boolean} True when the engine instantiates the element\n *\n * @example\n * isXsltElementAvailable('for-each'); // true\n */\nexport function isXsltElementAvailable(localName) {\n return ELEMENT_SET.has(localName);\n}\n", "/**\n * XSLT 1.0 `format-number()` picture string formatting.\n *\n * Implements the subset of the JDK `DecimalFormat` picture syntax that XSLT 1.0\n * requires: grouping separator, decimal separator, minimum/maximum fraction\n * digits, minimum integer digits, percent and per-mille scaling and an optional\n * negative subpattern. All symbols are taken from an `xsl:decimal-format`\n * declaration so alternative digits and separators are honoured.\n */\n\n\"use strict\";\n\n/** Symbols of the unnamed, default `xsl:decimal-format`. */\nexport const DEFAULT_DECIMAL_FORMAT = Object.freeze({\n decimalSeparator: \".\",\n groupingSeparator: \",\",\n percent: \"%\",\n perMille: \"\u2030\",\n zeroDigit: \"0\",\n digit: \"#\",\n patternSeparator: \";\",\n infinity: \"Infinity\",\n nan: \"NaN\",\n minusSign: \"-\",\n});\n\n/**\n * Split a picture string into its positive and optional negative subpattern.\n *\n * @param {string} pattern - The picture string\n * @param {Object} format - Decimal format symbols\n * @returns {{positive: string, negative: (string|null)}} The subpatterns\n */\nfunction splitSubPatterns(pattern, format) {\n const index = pattern.indexOf(format.patternSeparator);\n if (index === -1) return { positive: pattern, negative: null };\n return {\n positive: pattern.substring(0, index),\n negative: pattern.substring(index + format.patternSeparator.length),\n };\n}\n\n/**\n * Parse a single subpattern into a formatting description.\n *\n * @param {string} subPattern - One subpattern of a picture string\n * @param {Object} format - Decimal format symbols\n * @returns {Object} Prefix, suffix, digit counts, grouping size and multiplier\n */\nfunction parseSubPattern(subPattern, format) {\n const special = new Set([\n format.digit,\n format.zeroDigit,\n format.groupingSeparator,\n format.decimalSeparator,\n ]);\n\n let start = 0;\n while (start < subPattern.length && !special.has(subPattern[start])) start++;\n\n let end = start;\n while (end < subPattern.length && special.has(subPattern[end])) end++;\n\n const prefix = subPattern.substring(0, start);\n const numeric = subPattern.substring(start, end);\n const suffix = subPattern.substring(end);\n\n const decimalIndex = numeric.indexOf(format.decimalSeparator);\n const integerPart =\n decimalIndex === -1 ? numeric : numeric.substring(0, decimalIndex);\n const fractionPart =\n decimalIndex === -1 ? \"\" : numeric.substring(decimalIndex + 1);\n\n const groupingIndex = integerPart.lastIndexOf(format.groupingSeparator);\n const affixes = prefix + suffix;\n\n let multiplier = 1;\n if (affixes.includes(format.percent)) multiplier = 100;\n else if (affixes.includes(format.perMille)) multiplier = 1000;\n\n return {\n prefix,\n suffix,\n multiplier,\n minInteger: countOccurrences(integerPart, format.zeroDigit),\n integerHash: countOccurrences(integerPart, format.digit),\n hasDecimal: decimalIndex !== -1,\n minFraction: countOccurrences(fractionPart, format.zeroDigit),\n maxFraction: Math.min(fractionPart.length, 100),\n groupingSize:\n groupingIndex === -1 ? 0 : integerPart.length - groupingIndex - 1,\n };\n}\n\n/**\n * Count occurrences of a character inside a string.\n *\n * @param {string} text - The text to scan\n * @param {string} char - The character to count\n * @returns {number} Number of occurrences\n */\nfunction countOccurrences(text, char) {\n let total = 0;\n for (const current of text) {\n if (current === char) total++;\n }\n return total;\n}\n\n/**\n * Insert grouping separators into a run of integer digits.\n *\n * @param {string} digits - Integer digits, most significant first\n * @param {number} size - Grouping size, 0 disables grouping\n * @param {string} separator - The grouping separator\n * @returns {string} The grouped digits\n */\nfunction applyGrouping(digits, size, separator) {\n if (size <= 0 || digits.length <= size) return digits;\n\n let result = \"\";\n for (let i = 0; i < digits.length; i++) {\n const fromEnd = digits.length - i;\n if (i > 0 && fromEnd % size === 0) result += separator;\n result += digits[i];\n }\n return result;\n}\n\n/**\n * Translate ASCII digits to the digits of the decimal format.\n *\n * @param {string} text - Text containing ASCII digits\n * @param {string} zeroDigit - The format's zero digit\n * @returns {string} Text using the format's digit family\n */\nfunction translateDigits(text, zeroDigit) {\n const offset = zeroDigit.codePointAt(0) - 48;\n if (offset === 0) return text;\n return text.replaceAll(/\\d/g, (digit) =>\n String.fromCodePoint(digit.codePointAt(0) + offset),\n );\n}\n\n/**\n * Format the magnitude of a finite number according to a parsed subpattern.\n *\n * Follows libxslt (and so Chrome) where the JDK rules leave room: a pattern\n * without integer digits and zero fraction digits (`.#`) shows one fraction\n * digit, as the JDK does; an integer part of zero is written as `0` unless\n * the pattern asks for fraction zeros (`#.#` gives `0.5`, `.#` gives `.5`);\n * and a decimal separator with no fraction digits after it is kept (`#.`\n * gives `1.`).\n *\n * @param {number} magnitude - Absolute, already scaled value\n * @param {Object} spec - Parsed subpattern\n * @param {Object} format - Decimal format symbols\n * @returns {string} The formatted number without prefix or suffix\n */\nfunction formatMagnitude(magnitude, spec, format) {\n const noDigits = spec.minInteger + spec.integerHash + spec.minFraction === 0;\n const minFraction = noDigits && spec.maxFraction > 0 ? 1 : spec.minFraction;\n const fixed = magnitude.toFixed(spec.maxFraction);\n const [rawInteger, rawFraction = \"\"] = fixed.split(\".\");\n\n let fraction = rawFraction;\n while (fraction.length > minFraction && fraction.endsWith(\"0\")) {\n fraction = fraction.slice(0, -1);\n }\n\n let integer = (rawInteger === \"0\" ? \"\" : rawInteger).padStart(\n spec.minInteger,\n \"0\",\n );\n if (integer === \"\" && spec.minInteger + minFraction === 0) integer = \"0\";\n\n integer = applyGrouping(integer, spec.groupingSize, format.groupingSeparator);\n\n let body = integer;\n if (fraction.length > 0) body += format.decimalSeparator + fraction;\n else if (spec.maxFraction === 0 && spec.hasDecimal) {\n body += format.decimalSeparator;\n }\n\n return translateDigits(body, format.zeroDigit);\n}\n\n/**\n * Format a number using an XSLT 1.0 picture string.\n *\n * @param {number} value - The number to format\n * @param {string} pattern - The picture string, e.g. `#,##0.00`\n * @param {Object} [decimalFormat] - `xsl:decimal-format` symbols\n * @returns {string} The formatted number\n *\n * @example\n * formatNumber(1234.5, '#,##0.00'); // '1,234.50'\n * formatNumber(-1234, '#,##0;(#,##0)'); // '(1,234)'\n */\nexport function formatNumber(\n value,\n pattern,\n decimalFormat = DEFAULT_DECIMAL_FORMAT,\n) {\n const format = { ...DEFAULT_DECIMAL_FORMAT, ...decimalFormat };\n\n if (typeof value !== \"number\" || Number.isNaN(value)) return format.nan;\n\n const subPatterns = splitSubPatterns(pattern, format);\n const positive = parseSubPattern(subPatterns.positive, format);\n const isNegative = value < 0;\n\n let spec = positive;\n let prefix = positive.prefix;\n let suffix = positive.suffix;\n\n if (isNegative) {\n if (subPatterns.negative !== null) {\n spec = parseSubPattern(subPatterns.negative, format);\n prefix = spec.prefix;\n suffix = spec.suffix;\n } else {\n prefix = format.minusSign + positive.prefix;\n }\n }\n\n const magnitude = Math.abs(value) * spec.multiplier;\n const body = Number.isFinite(magnitude)\n ? formatMagnitude(magnitude, spec, format)\n : format.infinity;\n\n return prefix + body + suffix;\n}\n", "/**\n * Argument helpers shared by the EXSLT modules.\n *\n * EXSLT functions follow libexslt (the implementation bundled with libxslt,\n * which Chrome uses): a wrong number of arguments or a non node-set where a\n * node-set is required is an XPath error, so both throw here.\n */\n\n\"use strict\";\n\n// A namespace name is an identifier, not a URL that is fetched; EXSLT defines them with http.\n/** Namespace of the EXSLT common module. */\nexport const EXSLT_COMMON = \"http://exslt.org/common\"; // NOSONAR\n/** Namespace of the EXSLT math module. */\nexport const EXSLT_MATH = \"http://exslt.org/math\"; // NOSONAR\n/** Namespace of the EXSLT sets module. */\nexport const EXSLT_SETS = \"http://exslt.org/sets\"; // NOSONAR\n/** Namespace of the EXSLT strings module. */\nexport const EXSLT_STRINGS = \"http://exslt.org/strings\"; // NOSONAR\n/** Namespace of the EXSLT dates-and-times module. */\nexport const EXSLT_DATES = \"http://exslt.org/dates-and-times\"; // NOSONAR\n/** Namespace of the EXSLT dynamic module. */\nexport const EXSLT_DYNAMIC = \"http://exslt.org/dynamic\"; // NOSONAR\n\n/**\n * Throw unless a call has an allowed number of arguments.\n *\n * @param {string} name - Function name, for the error message\n * @param {Array} args - Argument expressions\n * @param {number} min - Minimum number of arguments\n * @param {number} [max] - Maximum number of arguments, `min` by default\n * @throws {Error} When the number of arguments is outside `min..max`\n */\nexport function checkArity(name, args, min, max = min) {\n if (args.length < min || args.length > max) {\n const expected = min === max ? `${min}` : `${min} to ${max}`;\n throw new Error(\n `${name}() expects ${expected} argument(s), got ${args.length}`,\n );\n }\n}\n\n/**\n * Whether an evaluated value is a node-set: an array of nodes, or a single\n * node such as a result tree fragment (libxslt accepts both).\n *\n * @param {*} value - An evaluated XPath value\n * @returns {boolean} True for a node-set or a node\n */\nexport function isNodeSetValue(value) {\n return Array.isArray(value) || Boolean(value?.nodeType);\n}\n\n/**\n * Convert an evaluated argument that must be a node-set to an array.\n *\n * @param {string} name - Function name, for the error message\n * @param {*} value - An evaluated XPath value\n * @returns {Node[]} The nodes\n * @throws {TypeError} When the value is not a node-set\n */\nexport function toNodeSet(name, value) {\n if (Array.isArray(value)) return value;\n if (value?.nodeType) return [value];\n throw new TypeError(`${name}() expects a node-set`);\n}\n\n/**\n * Nodes without duplicates, in document order.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Sorts the nodes\n * @param {Node[]} nodes - Any nodes\n * @returns {Node[]} A new, sorted array\n */\nexport function inDocumentOrder(evaluator, nodes) {\n return evaluator.sortByDocumentOrder([...new Set(nodes)]);\n}\n\n/**\n * Create the container of the nodes an extension function returns, the\n * counterpart of the result tree fragment libexslt creates for them.\n *\n * @param {import('../../xpath/evaluator.js').XPathContext} ctx - Evaluation context\n * @returns {DocumentFragment} An empty fragment\n */\nexport function createContainer(ctx) {\n const doc = ctx.node.ownerDocument || ctx.node;\n return doc.createDocumentFragment();\n}\n\n/**\n * Split a string into its characters (Unicode code points).\n *\n * @param {string} str - Any string\n * @returns {string[]} The characters\n */\nexport function characters(str) {\n return Array.from(str);\n}\n", "/**\n * EXSLT common module (http://exslt.org/common), following libexslt\n * `common.c`. `exsl:node-set()` lives in `../functions.js` next to its\n * `msxsl:node-set()` alias; this module adds `exsl:object-type()`.\n */\n\n\"use strict\";\n\nimport { expandedFunctionName } from \"../../xpath/evaluator.js\";\nimport { EXSLT_COMMON, checkArity } from \"./arguments.js\";\n\n/** Node type of a DocumentFragment, how this engine holds a result tree fragment. */\nconst DOCUMENT_FRAGMENT_NODE = 11;\n\n/**\n * The EXSLT type name of an evaluated value.\n *\n * @param {*} value - An evaluated XPath value\n * @returns {string} \"string\", \"number\", \"boolean\", \"node-set\" or \"RTF\"\n * @throws {TypeError} For a value that is not an XPath object\n */\nexport function objectType(value) {\n if (typeof value === \"string\") return \"string\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"boolean\") return \"boolean\";\n if (value?.nodeType === DOCUMENT_FRAGMENT_NODE) return \"RTF\";\n if (Array.isArray(value) || value?.nodeType) return \"node-set\";\n throw new TypeError(\"exsl:object-type() invalid argument\");\n}\n\n/**\n * Build the EXSLT common functions implemented here.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluates the arguments\n * @returns {Object<string, Function>} Functions keyed by expanded name\n */\nexport function createCommonFunctions(evaluator) {\n return {\n [expandedFunctionName(EXSLT_COMMON, \"object-type\")]: (args, ctx) => {\n checkArity(\"exsl:object-type\", args, 1);\n return objectType(evaluator.evaluate(args[0], ctx));\n },\n };\n}\n", "/**\n * Calendar primitives of the EXSLT dates-and-times module, ported from\n * libexslt `date.c`: date types, leap years, month lengths and validity.\n *\n * A date value is `{type, year, mon, day, hour, min, sec, tzFlag, tzo}`:\n * years are continuous (year 0 is 1 BCE), `tzo` is the offset in minutes and\n * `tzFlag` is set only by an explicit \"Z\" (as in libexslt).\n */\n\n\"use strict\";\n\n/** Date types, bit sets of the fields they carry (libexslt `exsltDateType`). */\nexport const DateType = Object.freeze({\n TIME: 1,\n GDAY: 2,\n GMONTH: 4,\n GMONTHDAY: 6,\n GYEAR: 8,\n GYEARMONTH: 12,\n DATE: 14,\n DATETIME: 15,\n});\n\n/** Seconds in a day. */\nexport const SECS_PER_DAY = 86400;\n\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n/**\n * Non-negative remainder, the result of C `&` masks on two's complement.\n *\n * @param {number} value - An integer\n * @param {number} divisor - A power of two\n * @returns {number} `value mod divisor` in `0..divisor-1`\n */\nfunction mask(value, divisor) {\n return ((value % divisor) + divisor) % divisor;\n}\n\n/**\n * Whether a (continuous) year is a leap year, as libexslt `IS_LEAP`.\n *\n * @param {number} year - The year\n * @returns {boolean} True for a leap year\n */\nexport function isLeapYear(year) {\n return mask(year, 4) === 0 && (year % 25 !== 0 || mask(year, 16) === 0);\n}\n\n/**\n * Number of days of a month.\n *\n * @param {number} year - The year\n * @param {number} mon - The month, 1-12\n * @returns {number} Days in the month\n */\nexport function daysInMonth(year, mon) {\n return mon === 2 && isLeapYear(year) ? 29 : DAYS_IN_MONTH[mon - 1];\n}\n\n/**\n * Day of the year of a date, 1-366 (libexslt `DAY_IN_YEAR`).\n *\n * @param {number} day - Day of the month\n * @param {number} mon - Month, 1-12\n * @param {number} year - Year\n * @returns {number} The day in the year\n */\nexport function dayInYear(day, mon, year) {\n let days = day;\n for (let m = 1; m < mon; m++) days += daysInMonth(year, m);\n return days;\n}\n\n/**\n * Whether a date value has a valid time part (libexslt `VALID_TIME`).\n *\n * @param {object} dt - Date value\n * @returns {boolean} True when valid\n */\nexport function isValidTime(dt) {\n return (\n dt.hour <= 23 &&\n dt.min <= 59 &&\n dt.sec >= 0 &&\n dt.sec < 60 &&\n dt.tzo > -1440 &&\n dt.tzo < 1440\n );\n}\n\n/**\n * Whether a date value has a valid date part (libexslt `VALID_DATE`).\n *\n * @param {object} dt - Date value\n * @returns {boolean} True when valid\n */\nexport function isValidDate(dt) {\n return dt.mon >= 1 && dt.mon <= 12 && dt.day <= daysInMonth(dt.year, dt.mon);\n}\n\n/**\n * Create a date value with libexslt defaults (January 1st, midnight).\n *\n * @param {number} type - A {@link DateType}, 0 when unknown yet\n * @returns {object} The date value\n */\nexport function createDate(type) {\n return {\n type,\n year: 0,\n mon: 1,\n day: 1,\n hour: 0,\n min: 0,\n sec: 0,\n tzFlag: false,\n tzo: 0,\n };\n}\n", "/**\n * Parsing of the XML Schema date/time lexical forms used by the EXSLT\n * dates-and-times module, ported from libexslt `date.c` (`exsltDateParse`).\n * Date values are described in `./calendar.js`.\n */\n\n\"use strict\";\n\nimport { DateType, createDate, isValidDate, isValidTime } from \"./calendar.js\";\n\n/** Largest integer the parsers accept, the analogue of C `LONG_MAX`. */\nconst MAX_NUMBER = Number.MAX_SAFE_INTEGER;\n\n/**\n * A cursor over the text being parsed, mirroring libexslt's `cur` pointer.\n */\nclass Cursor {\n /** @param {string} text - The text */\n constructor(text) {\n this.text = text;\n this.at = 0;\n }\n\n /** @returns {string} The current character, \"\" at the end */\n get char() {\n return this.text.charAt(this.at);\n }\n\n /** @returns {boolean} Whether the current character is a digit */\n get isDigit() {\n const char = this.char;\n return char >= \"0\" && char <= \"9\";\n }\n\n /**\n * Read two digits (libexslt `PARSE_2_DIGITS`), advancing past them.\n *\n * @param {(value: number) => boolean} valid - Range check\n * @returns {number|null} The value, null when invalid\n */\n twoDigits(valid) {\n const digits = this.text.substring(this.at, this.at + 2);\n this.at += 2;\n if (!/^\\d\\d$/.test(digits)) return null;\n const value = Number(digits);\n return valid(value) ? value : null;\n }\n}\n\nconst inRange = (min, max) => (value) => value >= min && value <= max;\n\n/**\n * Parse a time zone (\"\", \"Z\" or \"\u00B1hh:mm\"); updates `dt` and the cursor only\n * as far as libexslt does.\n *\n * @param {object} dt - Date value\n * @param {Cursor} cur - Cursor at the time zone\n * @returns {boolean} True when a time zone was parsed\n */\nfunction parseTimeZone(dt, cur) {\n const sign = cur.char;\n if (sign === \"\") {\n dt.tzFlag = false;\n dt.tzo = 0;\n return true;\n }\n if (sign === \"Z\") {\n dt.tzFlag = true;\n dt.tzo = 0;\n cur.at++;\n return true;\n }\n if (sign !== \"+\" && sign !== \"-\") return false;\n\n const probe = new Cursor(cur.text);\n probe.at = cur.at + 1;\n const hours = probe.twoDigits(inRange(0, 23));\n if (hours === null || probe.char !== \":\") return false;\n probe.at++;\n dt.tzo = hours * 60;\n const minutes = probe.twoDigits(inRange(0, 59));\n if (minutes === null) return false;\n dt.tzo = (dt.tzo + minutes) * (sign === \"-\" ? -1 : 1);\n cur.at = probe.at;\n return true;\n}\n\n/**\n * Parse \"hh:mm:ss(.s+)?\" into `dt` (libexslt `_exsltDateParseTime`).\n *\n * @param {object} dt - Date value\n * @param {Cursor} cur - Cursor at the time\n * @returns {boolean} True when a valid time was parsed\n */\nfunction parseTime(dt, cur) {\n const hour = cur.twoDigits(inRange(0, 23));\n if (hour === null || cur.char !== \":\") return false;\n cur.at++;\n dt.hour = hour;\n const min = cur.twoDigits(inRange(0, 59));\n if (min === null) return false;\n dt.min = min;\n if (cur.char !== \":\") return false;\n cur.at++;\n\n const seconds = cur.twoDigits(() => true);\n if (seconds === null) return false;\n let sec = seconds;\n if (cur.char === \".\") {\n cur.at++;\n if (!cur.isDigit) return false;\n let scale = 1;\n while (cur.isDigit) {\n scale /= 10;\n sec += Number(cur.char) * scale;\n cur.at++;\n }\n }\n dt.sec = sec;\n return isValidTime(dt);\n}\n\n/**\n * Parse a year of at least four digits (libexslt `_exsltDateParseGYear`).\n *\n * @param {object} dt - Date value\n * @param {Cursor} cur - Cursor at the year\n * @returns {boolean} True when a valid year was parsed\n */\nfunction parseYear(dt, cur) {\n const match = /^(-?)(\\d+)/.exec(cur.text.substring(cur.at));\n if (!match) return false;\n const digits = match[2];\n // At least four digits, and no leading zero beyond four\n const badLength =\n digits.length < 4 || (digits.length > 4 && digits[0] === \"0\");\n if (badLength) return false;\n const year = Number(digits);\n if (year === 0 || year >= MAX_NUMBER / 10) return false;\n dt.year = match[1] ? 1 - year : year;\n cur.at += match[0].length;\n return true;\n}\n\n/** Outcomes of {@link typedByTimeZone}. */\nconst Ending = Object.freeze({\n TYPED: \"typed\",\n NONE: \"none\",\n INVALID: \"invalid\",\n});\n\n/**\n * Parse a time zone that must end the text (libexslt `RETURN_TYPE_IF_VALID`).\n *\n * @param {object} dt - Date value, typed on success\n * @param {Cursor} cur - Cursor after the date fields\n * @param {number} type - Type of the value on success\n * @returns {string} TYPED when the rest is a time zone, INVALID when a time\n * zone is followed by more text, NONE when parsing may go on\n */\nfunction typedByTimeZone(dt, cur, type) {\n if (![\"\", \"Z\", \"+\", \"-\"].includes(cur.char)) return Ending.NONE;\n if (!parseTimeZone(dt, cur)) return Ending.NONE;\n if (cur.at !== cur.text.length) return Ending.INVALID;\n dt.type = type;\n return Ending.TYPED;\n}\n\n/**\n * Finish a form that must end with a time zone.\n *\n * @param {object} dt - Date value\n * @param {Cursor} cur - Cursor after the date fields\n * @param {number} type - Type of the value on success\n * @returns {object|null} The typed value, null when invalid\n */\nfunction endWithTimeZone(dt, cur, type) {\n return typedByTimeZone(dt, cur, type) === Ending.TYPED ? dt : null;\n}\n\n/**\n * Parse \"--MM-DD\", \"--MM--\" or \"---DD\", each followed by a time zone.\n *\n * @param {object} dt - Date value\n * @param {Cursor} cur - Cursor after the leading \"--\"\n * @returns {object|null} The date value, null when invalid\n */\nfunction parseTruncatedDate(dt, cur) {\n if (cur.char === \"-\") {\n cur.at++;\n dt.day = cur.twoDigits(inRange(1, 31));\n return dt.day === null ? null : endWithTimeZone(dt, cur, DateType.GDAY);\n }\n dt.mon = cur.twoDigits(inRange(1, 12));\n if (dt.mon === null || cur.char !== \"-\") return null;\n cur.at++;\n if (cur.char === \"-\") {\n cur.at++;\n return endWithTimeZone(dt, cur, DateType.GMONTH);\n }\n dt.day = cur.twoDigits(inRange(1, 31));\n return dt.day === null ? null : endWithTimeZone(dt, cur, DateType.GMONTHDAY);\n}\n\n/**\n * Fields after the year, each preceded by \"-\": the type a time zone after\n * the previous field gives, and the parser of the field.\n */\nconst DATE_FIELDS = [\n [\n DateType.GYEAR,\n (dt, cur) => {\n dt.mon = cur.twoDigits(inRange(1, 12));\n return dt.mon !== null;\n },\n ],\n [\n DateType.GYEARMONTH,\n (dt, cur) => {\n dt.day = cur.twoDigits(inRange(1, 31));\n return dt.day !== null && isValidDate(dt);\n },\n ],\n];\n\n/**\n * Parse any date/time form libexslt accepts (`exsltDateParse`): xs:dateTime,\n * xs:date, xs:time, xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gMonth\n * (\"--MM--\") and xs:gDay.\n *\n * @param {string} text - The lexical form\n * @returns {object|null} The date value, null when invalid\n */\nexport function parseDate(text) {\n const dt = createDate(0);\n const cur = new Cursor(text);\n\n if (text.startsWith(\"--\")) {\n cur.at = 2;\n return parseTruncatedDate(dt, cur);\n }\n\n if (cur.isDigit && parseTime(dt, cur)) {\n const ending = typedByTimeZone(dt, cur, DateType.TIME);\n if (ending !== Ending.NONE) return ending === Ending.TYPED ? dt : null;\n }\n\n cur.at = 0;\n if (!parseYear(dt, cur)) return null;\n for (const [type, parseField] of DATE_FIELDS) {\n const ending = typedByTimeZone(dt, cur, type);\n if (ending !== Ending.NONE) return ending === Ending.TYPED ? dt : null;\n if (cur.char !== \"-\") return null;\n cur.at++;\n if (!parseField(dt, cur)) return null;\n }\n const ending = typedByTimeZone(dt, cur, DateType.DATE);\n if (ending !== Ending.NONE) return ending === Ending.TYPED ? dt : null;\n if (cur.char !== \"T\") return null;\n cur.at++;\n if (!parseTime(dt, cur) || !parseTimeZone(dt, cur)) return null;\n if (cur.at !== text.length || !isValidTime(dt)) return null;\n dt.type = DateType.DATETIME;\n return dt;\n}\n", "/**\n * xs:duration values of the EXSLT dates-and-times module, ported from\n * libexslt `date.c`: parsing, formatting and addition.\n *\n * A duration is `{mon, day, sec}`: years are folded into months, hours and\n * minutes into seconds, and `0 <= sec < 86400`. A negative duration has\n * negative months/days and borrows one day for a non-zero `sec`.\n */\n\n\"use strict\";\n\nimport { SECS_PER_DAY } from \"./calendar.js\";\n\n/** Designators in the order they may appear; \"T\" precedes index 3. */\nconst DESIGNATORS = \"YMDHMS\";\n\n/** Index of the first time designator. */\nconst TIME_PART = 3;\n\n/** Index of the seconds designator, the only one allowing a fraction. */\nconst SECONDS_PART = 5;\n\n/** Seconds per unit of the time designators, by index. */\nconst UNIT_SECONDS = [0, 0, 0, 3600, 60, 1];\n\n/**\n * Create a zero duration.\n *\n * @returns {{mon: number, day: number, sec: number}} The duration\n */\nexport function createDuration() {\n return { mon: 0, day: 0, sec: 0 };\n}\n\n/**\n * Read the number before a designator: digits and an optional fraction.\n *\n * @param {string} text - The duration text\n * @param {number} at - Start index\n * @returns {{num: number, fraction: number, hasDigits: boolean, hasFraction: boolean, end: number}} The number\n */\nfunction readNumber(text, at) {\n const [whole, digits, dot, fractionDigits] = /^(\\d*)(\\.?)(\\d*)/.exec(\n text.substring(at),\n );\n let fraction = 0;\n let scale = 1;\n for (const digit of dot ? fractionDigits : \"\") {\n scale /= 10;\n fraction += Number(digit) * scale;\n }\n return {\n num: Number(digits || \"0\"),\n fraction,\n hasDigits: digits !== \"\" || (dot !== \"\" && fractionDigits !== \"\"),\n hasFraction: dot !== \"\",\n end: at + whole.length,\n };\n}\n\n/**\n * Parse an xs:duration such as \"-P1Y2M3DT4H5M6.5S\"\n * (libexslt `exsltDateParseDuration`).\n *\n * @param {string} text - The lexical form\n * @returns {{mon: number, day: number, sec: number}|null} The duration, null when invalid\n */\nexport function parseDuration(text) {\n const negative = text.startsWith(\"-\");\n let at = negative ? 1 : 0;\n if (text.charAt(at) !== \"P\" || at + 1 === text.length) return null;\n at++;\n\n const dur = createDuration();\n let seq = 0;\n let secs = 0;\n let fraction = 0;\n while (at < text.length) {\n if (seq >= DESIGNATORS.length) return null;\n if (text.charAt(at) === \"T\") {\n if (seq > TIME_PART) return null;\n at++;\n seq = TIME_PART;\n } else if (seq === TIME_PART) {\n return null;\n }\n\n const number = readNumber(text, at);\n at = number.end;\n while (text.charAt(at) !== DESIGNATORS[seq]) {\n seq++;\n if (seq === TIME_PART || seq === DESIGNATORS.length) return null;\n }\n at++;\n if (!number.hasDigits || (number.hasFraction && seq !== SECONDS_PART)) {\n return null;\n }\n if (!Number.isSafeInteger(number.num)) return null;\n fraction += number.fraction;\n\n if (seq === 0) dur.mon = number.num * 12;\n else if (seq === 1) dur.mon += number.num;\n else if (seq === 2) dur.day = number.num;\n else {\n const seconds = number.num * UNIT_SECONDS[seq];\n dur.day += Math.floor(seconds / SECS_PER_DAY);\n secs += seconds % SECS_PER_DAY;\n }\n seq++;\n }\n\n dur.day += Math.floor(secs / SECS_PER_DAY);\n dur.sec = (secs % SECS_PER_DAY) + fraction;\n if (negative) {\n // 0 - x rather than -x: integers in C have no negative zero\n dur.mon = 0 - dur.mon;\n dur.day = 0 - dur.day;\n if (dur.sec !== 0) {\n dur.sec = SECS_PER_DAY - dur.sec;\n dur.day -= 1;\n }\n }\n return dur;\n}\n\n/**\n * Decimal digits of a fraction of a second, without trailing zeros\n * (libexslt `exsltFormatNanoseconds`).\n *\n * @param {number} nanoseconds - Nanoseconds, 0-999999999\n * @returns {string} \"\" for zero, else \".\" and up to nine digits\n */\nexport function formatNanoseconds(nanoseconds) {\n if (nanoseconds <= 0) return \"\";\n return `.${String(nanoseconds).padStart(9, \"0\").replace(/0+$/, \"\")}`;\n}\n\n/**\n * Format a duration (libexslt `exsltDateFormatDuration`), e.g. \"P1Y2MT3S\".\n *\n * @param {{mon: number, day: number, sec: number}} dur - The duration\n * @returns {string} The lexical form, \"P0D\" for a zero duration\n */\nexport function formatDuration(dur) {\n if (dur.sec === 0 && dur.day === 0 && dur.mon === 0) return \"P0D\";\n\n let { sec: secs, day: days, mon: months } = dur;\n let sign = \"\";\n if (days < 0) {\n if (secs !== 0) {\n secs = SECS_PER_DAY - secs;\n days += 1;\n }\n days = -days;\n sign = \"-\";\n }\n if (months < 0) {\n months = -months;\n sign = \"-\";\n }\n\n let result = `${sign}P`;\n const years = Math.trunc(months / 12);\n months -= years * 12;\n if (years > 0) result += `${years}Y`;\n if (months !== 0) result += `${months}M`;\n if (days !== 0) result += `${days}D`;\n\n let intSecs = Math.floor(secs);\n let nanoseconds = Math.floor((secs - intSecs) * 1e9 + 0.5);\n if (nanoseconds >= 1e9) {\n nanoseconds -= 1e9;\n intSecs += 1;\n }\n if (intSecs === 0 && nanoseconds === 0) return result;\n\n result += \"T\";\n const hours = Math.floor(intSecs / 3600);\n const minutes = Math.floor((intSecs % 3600) / 60);\n intSecs %= 60;\n if (hours > 0) result += `${hours}H`;\n if (minutes > 0) result += `${minutes}M`;\n if (intSecs > 0 || nanoseconds > 0) {\n result += `${intSecs}${formatNanoseconds(nanoseconds)}S`;\n }\n return result;\n}\n\n/**\n * Add two durations (libexslt `_exsltDateAddDurCalc`).\n *\n * @param {{mon: number, day: number, sec: number}} x - First duration\n * @param {{mon: number, day: number, sec: number}} y - Second duration\n * @returns {{mon: number, day: number, sec: number}|null} The sum, null when\n * months and days would have opposite signs (an indeterminate result)\n */\nexport function addDurations(x, y) {\n const sum = { mon: x.mon + y.mon, day: x.day + y.day, sec: x.sec + y.sec };\n if (sum.sec >= SECS_PER_DAY) {\n sum.sec -= SECS_PER_DAY;\n sum.day += 1;\n }\n if (sum.day >= 0) {\n return (sum.day > 0 || sum.sec > 0) && sum.mon < 0 ? null : sum;\n }\n return sum.mon > 0 ? null : sum;\n}\n", "/**\n * Date arithmetic of the EXSLT dates-and-times module, ported from libexslt\n * `date.c`: calendar positions, `date:add()`, `date:difference()` and\n * `date:seconds()`. C integer division truncates, hence `Math.trunc`.\n */\n\n\"use strict\";\n\nimport {\n DateType,\n SECS_PER_DAY,\n createDate,\n dayInYear,\n daysInMonth,\n} from \"./calendar.js\";\nimport { parseDate } from \"./dateParse.js\";\nimport { createDuration, parseDuration } from \"./duration.js\";\n\n/** Days in a 400-year Gregorian cycle. */\nconst DAYS_PER_EPOCH = 146097;\n\n/** Years in a Gregorian cycle. */\nconst YEARS_PER_EPOCH = 400;\n\nconst trunc = Math.trunc;\n\n/**\n * Leap days before a year's start term of `_exsltDateCastYMToDays`.\n *\n * @param {number} year - Year\n * @returns {number} `year/4 - year/100 + year/400` with C division\n */\nfunction leapDays(year) {\n return trunc(year / 4) - trunc(year / 100) + trunc(year / 400);\n}\n\n/**\n * Days from the calendar origin to the start of a value's month\n * (libexslt `_exsltDateCastYMToDays`).\n *\n * @param {object} dt - Date value\n * @returns {number} The day count\n */\nfunction monthStartDays(dt) {\n const beforeMonth = dayInYear(0, dt.mon, dt.year);\n if (dt.year <= 0) {\n return (dt.year - 1) * 365 + leapDays(dt.year) + beforeMonth - 1;\n }\n return (dt.year - 1) * 365 + leapDays(dt.year - 1) + beforeMonth;\n}\n\n/**\n * Seconds since midnight of a value.\n *\n * @param {object} dt - Date value\n * @returns {number} The seconds\n */\nfunction timeToNumber(dt) {\n return dt.hour * 3600 + dt.min * 60 + dt.sec;\n}\n\n/**\n * Day of the week, 0 for Sunday (libexslt `_exsltDateDayInWeek`).\n *\n * @param {number} yday - Day in the year\n * @param {number} year - Year\n * @returns {number} 0-6\n */\nexport function dayOfWeek(yday, year) {\n if (year <= 0) {\n const day = ((year % 7) - 2 + leapDays(year) + yday) % 7;\n return day < 0 ? day + 7 : day;\n }\n return ((year % 7) - 1 + leapDays(year - 1) + yday) % 7;\n}\n\n/**\n * ISO 8601 week of the year (libexslt `exsltDateWeekInYear`).\n *\n * @param {object} dt - Date value\n * @returns {number} The week number\n */\nexport function weekInYear(dt) {\n let diy = dayInYear(dt.day, dt.mon, dt.year);\n // Monday is day 0 of the ISO week, Thursday decides the year\n const diw = (dayOfWeek(diy, dt.year) + 6) % 7;\n diy += 3 - diw;\n if (diy < 1) {\n let year = dt.year - 1;\n if (year === 0) year--;\n diy += dayInYear(31, 12, year);\n } else if (diy > dayInYear(31, 12, dt.year)) {\n diy -= dayInYear(31, 12, dt.year);\n }\n return trunc((diy - 1) / 7) + 1;\n}\n\n/**\n * Week of the month, weeks starting on Monday (libexslt `exsltDateWeekInMonth`).\n *\n * @param {object} dt - Date value\n * @returns {number} The week number\n */\nexport function weekInMonth(dt) {\n const firstDay = (dayOfWeek(dayInYear(1, dt.mon, dt.year), dt.year) + 6) % 7;\n return trunc((dt.day + firstDay - 1) / 7) + 1;\n}\n\n/**\n * Keep only the fields of a less specific type (`_exsltDateTruncateDate`).\n *\n * @param {object} dt - Date value, modified\n * @param {number} type - The target {@link DateType}\n */\nfunction truncateDate(dt, type) {\n if ((type & DateType.TIME) !== DateType.TIME) {\n dt.hour = 0;\n dt.min = 0;\n dt.sec = 0;\n }\n if ((type & DateType.GDAY) !== DateType.GDAY) dt.day = 1;\n if ((type & DateType.GMONTH) !== DateType.GMONTH) dt.mon = 1;\n if ((type & DateType.GYEAR) !== DateType.GYEAR) dt.year = 0;\n dt.type = type;\n}\n\n/**\n * Whether a value is a gYear, gYearMonth, date or dateTime.\n *\n * @param {object} dt - Date value\n * @returns {boolean} True for the types with a year\n */\nexport function hasYear(dt) {\n return dt.type >= DateType.GYEAR && dt.type <= DateType.DATETIME;\n}\n\n/**\n * Duration from x to y (libexslt `_exsltDateDifference`); the more specific\n * operand is truncated to the type of the other. Without `inSeconds`, gYear\n * and gYearMonth differences are counted in months.\n *\n * @param {object} x - Start date value, may be truncated\n * @param {object} y - End date value, may be truncated\n * @param {boolean} inSeconds - Always compute days and seconds\n * @returns {object|null} The duration, null for unsupported types\n */\nexport function dateDifference(x, y, inSeconds) {\n if (!hasYear(x) || !hasYear(y)) return null;\n if (x.type < y.type) truncateDate(y, x.type);\n else if (x.type > y.type) truncateDate(x, y.type);\n\n const dur = createDuration();\n if (x.type <= DateType.GYEARMONTH && !inSeconds) {\n dur.mon = (y.year - x.year) * 12 + (y.mon - x.mon);\n return dur;\n }\n const sec = timeToNumber(y) - timeToNumber(x) + (x.tzo - y.tzo) * 60;\n const carry = Math.floor(sec / SECS_PER_DAY);\n dur.sec = sec - carry * SECS_PER_DAY;\n dur.day = monthStartDays(y) - monthStartDays(x) + y.day - x.day + carry;\n return dur;\n}\n\n/**\n * Add a duration to a date value (libexslt `_exsltDateAdd`). A day past\n * the end of the resulting month is clamped first; the type grows to show\n * the fields the addition made significant.\n *\n * @param {object} dt - Date value\n * @param {{mon: number, day: number, sec: number}} dur - Duration\n * @returns {object} The new date value\n */\nexport function addDuration(dt, dur) {\n const ret = createDate(dt.type);\n let mon = dt.mon + (dur.mon % 12);\n let carry = trunc(dur.mon / 12);\n if (mon < 1) {\n mon += 12;\n carry -= 1;\n } else if (mon > 12) {\n mon -= 12;\n carry += 1;\n }\n ret.mon = mon;\n carry += trunc(dur.day / DAYS_PER_EPOCH) * YEARS_PER_EPOCH;\n ret.year = dt.year + carry;\n ret.tzo = dt.tzo;\n ret.tzFlag = dt.tzFlag;\n\n const sum = dt.sec + dur.sec;\n ret.sec = sum % 60;\n carry = trunc(sum / 60);\n ret.min = dt.min + (carry % 60);\n carry = trunc(carry / 60);\n if (ret.min >= 60) {\n ret.min -= 60;\n carry += 1;\n }\n ret.hour = dt.hour + (carry % 24);\n carry = trunc(carry / 24);\n if (ret.hour >= 24) {\n ret.hour -= 24;\n carry += 1;\n }\n\n let day = Math.min(Math.max(dt.day, 1), daysInMonth(ret.year, ret.mon));\n day += (dur.day % DAYS_PER_EPOCH) + carry;\n while (day < 1 || day > daysInMonth(ret.year, ret.mon)) {\n if (day < 1) {\n ret.mon -= 1;\n if (ret.mon < 1) {\n ret.mon = 12;\n ret.year -= 1;\n }\n day += daysInMonth(ret.year, ret.mon);\n } else {\n day -= daysInMonth(ret.year, ret.mon);\n ret.mon += 1;\n if (ret.mon > 12) {\n ret.mon = 1;\n ret.year += 1;\n }\n }\n }\n ret.day = day;\n\n if (ret.type !== DateType.DATETIME) {\n if (ret.hour || ret.min || ret.sec) ret.type = DateType.DATETIME;\n else if (ret.type !== DateType.DATE) {\n if (ret.day !== 1) ret.type = DateType.DATE;\n else if (ret.type !== DateType.GYEARMONTH && ret.mon !== 1) {\n ret.type = DateType.GYEARMONTH;\n }\n }\n }\n return ret;\n}\n\n/**\n * `date:seconds()`: seconds from 1970-01-01T00:00:00Z to a date value (a\n * gYear, gYearMonth, date or dateTime), or the length of a duration without\n * months.\n *\n * @param {object|string} value - A date value, or the text to parse\n * @returns {number} The seconds, NaN when not applicable\n */\nexport function secondsOf(value) {\n const dt = typeof value === \"string\" ? parseDate(value) : value;\n if (dt !== null) {\n if (dt.type < DateType.GYEAR) return Number.NaN;\n const epoch = createDate(DateType.DATETIME);\n epoch.year = 1970;\n epoch.tzFlag = true;\n const diff = dateDifference(epoch, dt, true);\n return diff.day * SECS_PER_DAY + diff.sec;\n }\n const dur = parseDuration(value);\n return dur !== null && dur.mon === 0\n ? dur.day * SECS_PER_DAY + dur.sec\n : Number.NaN;\n}\n", "/**\n * Formatting of date values for the EXSLT dates-and-times module, ported\n * from libexslt `date.c` (`exsltDateFormat*`).\n *\n * Quirks kept from libexslt: an xs:dateTime always ends with a time zone\n * (\"Z\" for a zero offset), while the other types show one only for an\n * explicit \"Z\" or a non-zero offset.\n */\n\n\"use strict\";\n\nimport { DateType, isValidDate, isValidTime } from \"./calendar.js\";\nimport { formatNanoseconds } from \"./duration.js\";\n\n/**\n * Two-digit form of a number.\n *\n * @param {number} num - 0-99\n * @returns {string} The digits\n */\nfunction twoDigits(num) {\n return String(num).padStart(2, \"0\");\n}\n\n/**\n * Format a continuous year: at least four digits, \"-\" before BCE years.\n *\n * @param {number} year - The year (0 is 1 BCE)\n * @returns {string} The year\n */\nexport function formatYear(year) {\n const sign = year <= 0 ? \"-\" : \"\";\n return sign + String(year <= 0 ? 1 - year : year).padStart(4, \"0\");\n}\n\n/**\n * Format a time zone offset.\n *\n * @param {number} tzo - Offset in minutes\n * @returns {string} \"Z\" or \"\u00B1hh:mm\"\n */\nexport function formatTimeZone(tzo) {\n if (tzo === 0) return \"Z\";\n const offset = Math.abs(tzo);\n const sign = tzo < 0 ? \"-\" : \"+\";\n return `${sign}${twoDigits(Math.floor(offset / 60))}:${twoDigits(offset % 60)}`;\n}\n\n/**\n * Format \"hh:mm:ss\" with the fraction of a second, rounded to nanoseconds\n * without carrying into the minute.\n *\n * @param {object} dt - Date value\n * @returns {string} The time\n */\nfunction formatClock(dt) {\n const intSecs = Math.floor(dt.sec);\n const nanoseconds = Math.min(\n Math.floor((dt.sec - intSecs) * 1e9 + 0.5),\n 999999999,\n );\n return `${twoDigits(dt.hour)}:${twoDigits(dt.min)}:${twoDigits(intSecs)}${formatNanoseconds(nanoseconds)}`;\n}\n\n/**\n * The time zone suffix of the types other than xs:dateTime.\n *\n * @param {object} dt - Date value\n * @returns {string} The suffix, possibly empty\n */\nfunction optionalTimeZone(dt) {\n return dt.tzFlag || dt.tzo !== 0 ? formatTimeZone(dt.tzo) : \"\";\n}\n\n/**\n * \"CCYY-MM-DD\" of a date value.\n *\n * @param {object} dt - Date value\n * @returns {string} The date\n */\nfunction formatYearMonthDay(dt) {\n return `${formatYear(dt.year)}-${twoDigits(dt.mon)}-${twoDigits(dt.day)}`;\n}\n\n/**\n * Whether both the date and time parts of a value are valid.\n *\n * @param {object} dt - Date value\n * @returns {boolean} True when valid\n */\nfunction isValidDateTime(dt) {\n return isValidDate(dt) && isValidTime(dt);\n}\n\n/**\n * Format as xs:dateTime, always with a time zone.\n *\n * @param {object} dt - Date value\n * @returns {string|null} The dateTime, null when invalid\n */\nexport function formatDateTime(dt) {\n if (!isValidDateTime(dt)) return null;\n return `${formatYearMonthDay(dt)}T${formatClock(dt)}${formatTimeZone(dt.tzo)}`;\n}\n\n/**\n * Format as xs:date.\n *\n * @param {object} dt - Date value\n * @returns {string|null} The date, null when invalid\n */\nexport function formatDateOnly(dt) {\n if (!isValidDateTime(dt)) return null;\n return formatYearMonthDay(dt) + optionalTimeZone(dt);\n}\n\n/**\n * Format as xs:time.\n *\n * @param {object} dt - Date value\n * @returns {string|null} The time, null when invalid\n */\nexport function formatTimeOnly(dt) {\n if (!isValidTime(dt)) return null;\n return formatClock(dt) + optionalTimeZone(dt);\n}\n\n/**\n * Format a value in the lexical form of its own type\n * (xs:dateTime, xs:date, xs:time, xs:gYearMonth or xs:gYear).\n *\n * @param {object} dt - Date value\n * @returns {string|null} The lexical form, null for other types\n */\nexport function formatByType(dt) {\n switch (dt.type) {\n case DateType.DATETIME:\n return formatDateTime(dt);\n case DateType.DATE:\n return formatDateOnly(dt);\n case DateType.TIME:\n return formatTimeOnly(dt);\n case DateType.GYEAR:\n return formatYear(dt.year) + optionalTimeZone(dt);\n case DateType.GYEARMONTH:\n return `${formatYear(dt.year)}-${twoDigits(dt.mon)}${optionalTimeZone(dt)}`;\n default:\n return null;\n }\n}\n", "/**\n * EXSLT dates-and-times module (http://exslt.org/dates-and-times): the\n * functions libexslt `date.c` implements. `format-date()`, `parse-date()`\n * and the `date:date-format` element are not implemented by libexslt either.\n *\n * Invalid input yields the empty string for string results and NaN for\n * numbers (and for `leap-year()`, as in libexslt). Without an argument the\n * functions use the current local date and time, read from the clock.\n */\n\n\"use strict\";\n\nimport { expandedFunctionName } from \"../../xpath/evaluator.js\";\nimport { EXSLT_DATES, checkArity, toNodeSet } from \"./arguments.js\";\nimport {\n DateType,\n SECS_PER_DAY,\n createDate,\n dayInYear,\n isLeapYear,\n} from \"./calendar.js\";\nimport { parseDate } from \"./dateParse.js\";\nimport {\n addDuration,\n dateDifference,\n dayOfWeek,\n hasYear,\n secondsOf,\n weekInMonth,\n weekInYear,\n} from \"./dateCalc.js\";\nimport {\n formatByType,\n formatDateOnly,\n formatDateTime,\n formatTimeOnly,\n} from \"./dateFormat.js\";\nimport {\n addDurations,\n createDuration,\n formatDuration,\n parseDuration,\n} from \"./duration.js\";\n\nconst MONTH_NAMES = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\nconst DAY_NAMES = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n];\n\nconst { DATETIME, DATE, TIME, GYEAR, GYEARMONTH, GMONTH, GMONTHDAY, GDAY } =\n DateType;\n\n/**\n * The default clock: now, or `SOURCE_DATE_EPOCH` (seconds, read as UTC)\n * when set, as libexslt does for reproducible builds.\n *\n * @returns {{getTime: () => number, getTimezoneOffset: () => number}} A Date-like instant\n */\nexport function systemClock() {\n const epoch = Number.parseInt(\n globalThis.process?.env?.SOURCE_DATE_EPOCH ?? \"\",\n 10,\n );\n if (Number.isNaN(epoch)) return new Date();\n return { getTime: () => epoch * 1000, getTimezoneOffset: () => 0 };\n}\n\n/**\n * The local date and time of an instant as a dateTime value, with the local\n * offset but no explicit time zone (libexslt `exsltDateCurrent`).\n *\n * @param {{getTime: () => number, getTimezoneOffset: () => number}} now - A Date-like instant\n * @returns {object} The date value\n */\nexport function currentDate(now) {\n const tzo = -now.getTimezoneOffset();\n const local = new Date(now.getTime() + tzo * 60000);\n const dt = createDate(DATETIME);\n dt.year = local.getUTCFullYear();\n dt.mon = local.getUTCMonth() + 1;\n dt.day = local.getUTCDate();\n dt.hour = local.getUTCHours();\n dt.min = local.getUTCMinutes();\n dt.sec = local.getUTCSeconds();\n dt.tzo = tzo;\n return dt;\n}\n\n/**\n * Build the EXSLT dates-and-times functions.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluates the arguments\n * @param {() => {getTime: () => number, getTimezoneOffset: () => number}} [clock] - Current instant\n * @returns {Object<string, Function>} Functions keyed by expanded name\n */\nexport function createDatesFunctions(evaluator, clock = systemClock) {\n const string = (arg, ctx) => evaluator.toString(evaluator.evaluate(arg, ctx));\n const key = (local) => expandedFunctionName(EXSLT_DATES, local);\n const functions = {};\n\n /**\n * Register a function of an optional date argument.\n *\n * @param {string} local - Local name\n * @param {number[]} types - Types accepted from the argument\n * @param {(dt: object) => *} compute - Result from the date value\n * @param {*} invalid - Result for an invalid or unaccepted argument\n */\n const define = (local, types, compute, invalid) => {\n functions[key(local)] = (args, ctx) => {\n checkArity(`date:${local}`, args, 0, 1);\n const dt =\n args.length === 0\n ? currentDate(clock())\n : parseDate(string(args[0], ctx));\n if (dt === null || !types.includes(dt.type)) return invalid;\n return compute(dt) ?? invalid;\n };\n };\n\n const yearTypes = [DATETIME, DATE, GYEARMONTH, GYEAR];\n const dayTypes = [DATETIME, DATE];\n const timeTypes = [DATETIME, TIME];\n const monthTypes = [DATETIME, DATE, GYEARMONTH, GMONTH, GMONTHDAY];\n const weekday = (dt) =>\n dayOfWeek(dayInYear(dt.day, dt.mon, dt.year), dt.year);\n\n define(\"date\", dayTypes, formatDateOnly, \"\");\n define(\"time\", timeTypes, formatTimeOnly, \"\");\n define(\n \"year\",\n yearTypes,\n (dt) => (dt.year <= 0 ? dt.year - 1 : dt.year),\n Number.NaN,\n );\n define(\"leap-year\", yearTypes, (dt) => isLeapYear(dt.year), Number.NaN);\n define(\"month-in-year\", monthTypes, (dt) => dt.mon, Number.NaN);\n define(\"month-name\", monthTypes, (dt) => MONTH_NAMES[dt.mon - 1], \"\");\n define(\n \"month-abbreviation\",\n monthTypes,\n (dt) => MONTH_NAMES[dt.mon - 1].substring(0, 3),\n \"\",\n );\n define(\"week-in-year\", dayTypes, weekInYear, Number.NaN);\n define(\"week-in-month\", dayTypes, weekInMonth, Number.NaN);\n define(\n \"day-in-year\",\n dayTypes,\n (dt) => dayInYear(dt.day, dt.mon, dt.year),\n Number.NaN,\n );\n define(\n \"day-in-month\",\n [DATETIME, DATE, GMONTHDAY, GDAY],\n (dt) => dt.day,\n Number.NaN,\n );\n define(\n \"day-of-week-in-month\",\n dayTypes,\n (dt) => Math.trunc((dt.day - 1) / 7) + 1,\n Number.NaN,\n );\n define(\"day-in-week\", dayTypes, (dt) => weekday(dt) + 1, Number.NaN);\n define(\"day-name\", dayTypes, (dt) => DAY_NAMES[weekday(dt)], \"\");\n define(\n \"day-abbreviation\",\n dayTypes,\n (dt) => DAY_NAMES[weekday(dt)].substring(0, 3),\n \"\",\n );\n define(\"hour-in-day\", timeTypes, (dt) => dt.hour, Number.NaN);\n define(\"minute-in-hour\", timeTypes, (dt) => dt.min, Number.NaN);\n define(\"second-in-minute\", timeTypes, (dt) => dt.sec, Number.NaN);\n\n functions[key(\"date-time\")] = (args) => {\n checkArity(\"date:date-time\", args, 0);\n return formatDateTime(currentDate(clock())) ?? \"\";\n };\n\n functions[key(\"seconds\")] = (args, ctx) => {\n checkArity(\"date:seconds\", args, 0, 1);\n return secondsOf(\n args.length === 0 ? currentDate(clock()) : string(args[0], ctx),\n );\n };\n\n functions[key(\"duration\")] = (args, ctx) => {\n checkArity(\"date:duration\", args, 0, 1);\n const secs =\n args.length === 0\n ? secondsOf(currentDate(clock()))\n : evaluator.toNumber(string(args[0], ctx));\n if (!Number.isFinite(secs)) return \"\";\n const dur = createDuration();\n dur.day = Math.floor(secs / SECS_PER_DAY);\n dur.sec = secs - dur.day * SECS_PER_DAY;\n return formatDuration(dur);\n };\n\n functions[key(\"add\")] = (args, ctx) => {\n checkArity(\"date:add\", args, 2);\n const dt = parseDate(string(args[0], ctx));\n const dur = parseDuration(string(args[1], ctx));\n if (dt === null || !hasYear(dt) || dur === null) return \"\";\n return formatByType(addDuration(dt, dur)) ?? \"\";\n };\n\n functions[key(\"add-duration\")] = (args, ctx) => {\n checkArity(\"date:add-duration\", args, 2);\n const x = parseDuration(string(args[0], ctx));\n const y = parseDuration(string(args[1], ctx));\n const sum = x === null || y === null ? null : addDurations(x, y);\n return sum === null ? \"\" : formatDuration(sum);\n };\n\n functions[key(\"difference\")] = (args, ctx) => {\n checkArity(\"date:difference\", args, 2);\n const x = parseDate(string(args[0], ctx));\n const y = parseDate(string(args[1], ctx));\n const dur = x === null || y === null ? null : dateDifference(x, y, false);\n return dur === null ? \"\" : formatDuration(dur);\n };\n\n functions[key(\"sum\")] = (args, ctx) => {\n checkArity(\"date:sum\", args, 1);\n const nodes = toNodeSet(\"date:sum\", evaluator.evaluate(args[0], ctx));\n if (nodes.length === 0) return \"\";\n let total = createDuration();\n for (const node of nodes) {\n const dur = parseDuration(evaluator.getStringValue(node));\n total = dur === null ? null : addDurations(total, dur);\n if (total === null) return \"\";\n }\n return formatDuration(total);\n };\n\n return functions;\n}\n", "/**\n * EXSLT dynamic module (http://exslt.org/dynamic): `dyn:evaluate()` only,\n * following libexslt `dynamic.c`.\n *\n * Security: a stylesheet is trusted code, but the string handed to\n * `dyn:evaluate()` often comes from the transformed document. The function\n * is therefore disabled unless the engine opts in with\n * `engine.enableDynamicEvaluate = true`; while disabled,\n * `function-available('dyn:evaluate')` is false and a call throws. The\n * expression runs with the evaluator's recursion and result size limits.\n */\n\n\"use strict\";\n\nimport { expandedFunctionName } from \"../../xpath/evaluator.js\";\nimport { parse } from \"../../xpath/parser.js\";\nimport { EXSLT_DYNAMIC, checkArity } from \"./arguments.js\";\n\n/**\n * Build the EXSLT dynamic functions.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluates the expressions\n * @param {() => boolean} isEnabled - Whether `dyn:evaluate()` may run, asked at each call\n * @returns {Object<string, Function>} Functions keyed by expanded name\n */\nexport function createDynamicFunctions(evaluator, isEnabled) {\n /**\n * `dyn:evaluate(string)`: evaluate the string as an XPath expression in\n * the current context (context node, position, size, variables and\n * namespaces). An empty string, or an expression that fails to parse,\n * yields an empty node-set, as in libexslt. Evaluation errors propagate,\n * so the evaluator's limits cannot be defeated by swallowing them.\n *\n * @param {Array} args - Argument expressions\n * @param {import('../../xpath/evaluator.js').XPathContext} ctx - Evaluation context\n * @returns {*} The value of the expression\n * @throws {Error} When dynamic evaluation is disabled\n */\n const evaluate = (args, ctx) => {\n if (!isEnabled()) {\n throw new Error(\n \"dyn:evaluate() is disabled; set enableDynamicEvaluate on the engine to allow it\",\n );\n }\n checkArity(\"dyn:evaluate\", args, 1);\n const expression = evaluator.toString(evaluator.evaluate(args[0], ctx));\n if (expression === \"\") return [];\n let ast;\n try {\n ast = parse(expression);\n } catch {\n return [];\n }\n return evaluator.evaluate(ast, ctx);\n };\n evaluate.isAvailable = isEnabled;\n\n return { [expandedFunctionName(EXSLT_DYNAMIC, \"evaluate\")]: evaluate };\n}\n", "/**\n * EXSLT math module (http://exslt.org/math), following libexslt `math.c`.\n *\n * - `min()` / `max()` are NaN for an empty node-set or when any node is NaN.\n * - `highest()` / `lowest()` are empty in the same cases.\n * - `constant(name, precision)` truncates the constant's decimal text to\n * `precision` characters (the leading \"3.\" of PI counts), NaN otherwise.\n * - Every numeric function returns NaN for a NaN argument.\n */\n\n\"use strict\";\n\nimport { expandedFunctionName } from \"../../xpath/evaluator.js\";\nimport { parseXPathNumber } from \"../../xpath/strings.js\";\nimport {\n EXSLT_MATH,\n checkArity,\n inDocumentOrder,\n toNodeSet,\n} from \"./arguments.js\";\n\n/** Decimal text of the constants known to `math:constant()`. */\nconst CONSTANTS = Object.freeze({\n PI: \"3.1415926535897932384626433832795028841971693993751\",\n E: \"2.71828182845904523536028747135266249775724709369996\",\n SQRRT2: \"1.41421356237309504880168872420969807856967187537694\",\n LN2: \"0.69314718055994530941723212145817656807550013436025\",\n LN10: \"2.30258509299404568402\",\n LOG2E: \"1.4426950408889634074\",\n SQRT1_2: \"0.70710678118654752440\",\n});\n\n/**\n * `math:constant(name, precision)`.\n *\n * @param {string} name - Constant name, case-sensitive\n * @param {number} precision - Number of characters of the decimal text\n * @returns {number} The truncated constant, NaN for an unknown name\n */\nexport function mathConstant(name, precision) {\n if (Number.isNaN(precision) || precision < 1) return Number.NaN;\n if (!Object.hasOwn(CONSTANTS, name)) return Number.NaN;\n const text = CONSTANTS[name];\n return parseXPathNumber(\n text.substring(0, Math.min(text.length, Math.trunc(precision))),\n );\n}\n\n/**\n * `math:power(base, power)` with C `pow()` semantics: 1 raised to anything,\n * and -1 raised to an infinity, are 1 (JavaScript gives NaN).\n *\n * @param {number} base - The base\n * @param {number} power - The exponent\n * @returns {number} The power, NaN when either argument is NaN\n */\nexport function mathPower(base, power) {\n if (Number.isNaN(base) || Number.isNaN(power)) return Number.NaN;\n if (base === 1 || (base === -1 && !Number.isFinite(power))) return 1;\n return Math.pow(base, power);\n}\n\n/**\n * Extreme nodes of a node-set: those whose number is the best one.\n *\n * @param {number[]} values - Numbers of the nodes, in node order\n * @param {(a: number, b: number) => boolean} better - Whether a beats b\n * @returns {number[]} Indexes of the extreme nodes, empty when any is NaN\n */\nfunction extremeIndexes(values, better) {\n if (values.length === 0 || values.some(Number.isNaN)) return [];\n let best = values[0];\n let indexes = [];\n values.forEach((value, index) => {\n if (better(value, best)) {\n best = value;\n indexes = [index];\n } else if (value === best) {\n indexes.push(index);\n }\n });\n return indexes;\n}\n\n/** One-argument numeric functions and their implementation. */\nconst UNARY = Object.freeze({\n abs: Math.abs,\n sqrt: Math.sqrt,\n log: Math.log,\n sin: Math.sin,\n cos: Math.cos,\n tan: Math.tan,\n asin: Math.asin,\n acos: Math.acos,\n atan: Math.atan,\n exp: Math.exp,\n});\n\n/**\n * Build the EXSLT math functions.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluates the arguments\n * @param {{random?: () => number}} [options] - `random` replaces `Math.random` (tests)\n * @returns {Object<string, Function>} Functions keyed by expanded name\n */\nexport function createMathFunctions(evaluator, options = {}) {\n const random = options.random ?? Math.random;\n const number = (arg, ctx) => evaluator.toNumber(evaluator.evaluate(arg, ctx));\n\n /**\n * Numbers of the nodes of a node-set argument, in document order.\n *\n * @param {string} name - Function name, for errors\n * @param {Array} args - Argument expressions\n * @param {object} ctx - Evaluation context\n * @returns {{nodes: Node[], values: number[]}} The nodes and their numbers\n */\n const numbered = (name, args, ctx) => {\n checkArity(name, args, 1);\n const nodes = inDocumentOrder(\n evaluator,\n toNodeSet(name, evaluator.evaluate(args[0], ctx)),\n );\n const values = nodes.map((node) =>\n evaluator.toNumber(evaluator.getStringValue(node)),\n );\n return { nodes, values };\n };\n\n const extremeValue = (name, better) => (args, ctx) => {\n const { values } = numbered(name, args, ctx);\n const indexes = extremeIndexes(values, better);\n return indexes.length === 0 ? Number.NaN : values[indexes[0]];\n };\n\n const extremeNodes = (name, better) => (args, ctx) => {\n const { nodes, values } = numbered(name, args, ctx);\n return extremeIndexes(values, better).map((index) => nodes[index]);\n };\n\n const less = (a, b) => a < b;\n const greater = (a, b) => a > b;\n const key = (local) => expandedFunctionName(EXSLT_MATH, local);\n\n const functions = {\n [key(\"min\")]: extremeValue(\"math:min\", less),\n [key(\"max\")]: extremeValue(\"math:max\", greater),\n [key(\"lowest\")]: extremeNodes(\"math:lowest\", less),\n [key(\"highest\")]: extremeNodes(\"math:highest\", greater),\n [key(\"constant\")]: (args, ctx) => {\n checkArity(\"math:constant\", args, 2);\n const name = evaluator.toString(evaluator.evaluate(args[0], ctx));\n return mathConstant(name, number(args[1], ctx));\n },\n [key(\"random\")]: (args) => {\n checkArity(\"math:random\", args, 0);\n return random();\n },\n [key(\"power\")]: (args, ctx) => {\n checkArity(\"math:power\", args, 2);\n return mathPower(number(args[0], ctx), number(args[1], ctx));\n },\n [key(\"atan2\")]: (args, ctx) => {\n checkArity(\"math:atan2\", args, 2);\n return Math.atan2(number(args[0], ctx), number(args[1], ctx));\n },\n };\n\n for (const [local, fn] of Object.entries(UNARY)) {\n functions[key(local)] = (args, ctx) => {\n checkArity(`math:${local}`, args, 1);\n return fn(number(args[0], ctx));\n };\n }\n\n return functions;\n}\n", "/**\n * EXSLT sets module (http://exslt.org/sets), following libexslt `sets.c` and\n * the libxml2 node-set primitives it calls.\n *\n * Every argument must be a node-set and every node-set result is in document\n * order. `leading()` / `trailing()` return the first node-set unchanged when\n * the second is empty, and an empty node-set when the first node of the\n * second is not in the first.\n */\n\n\"use strict\";\n\nimport { expandedFunctionName } from \"../../xpath/evaluator.js\";\nimport {\n EXSLT_SETS,\n checkArity,\n inDocumentOrder,\n toNodeSet,\n} from \"./arguments.js\";\n\n/**\n * Build the EXSLT sets functions.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluates the arguments\n * @returns {Object<string, Function>} Functions keyed by expanded name\n */\nexport function createSetsFunctions(evaluator) {\n /**\n * Evaluate the node-set arguments of a call, each in document order.\n *\n * @param {string} name - Function name, for errors\n * @param {Array} args - Argument expressions\n * @param {object} ctx - Evaluation context\n * @param {number} count - Required number of arguments\n * @returns {Node[][]} The node-sets\n */\n const nodeSets = (name, args, ctx, count) => {\n checkArity(name, args, count);\n return args.map((arg) =>\n inDocumentOrder(evaluator, toNodeSet(name, evaluator.evaluate(arg, ctx))),\n );\n };\n\n /**\n * `leading()` / `trailing()`: the nodes of the first node-set before or\n * after the first node of the second one.\n *\n * @param {string} name - Function name, for errors\n * @param {boolean} before - True for leading, false for trailing\n * @returns {Function} The XPath function\n */\n const around = (name, before) => (args, ctx) => {\n const [nodes, others] = nodeSets(name, args, ctx, 2);\n if (others.length === 0) return nodes;\n\n const index = nodes.indexOf(others[0]);\n if (index === -1) return [];\n return before ? nodes.slice(0, index) : nodes.slice(index + 1);\n };\n\n const key = (local) => expandedFunctionName(EXSLT_SETS, local);\n\n return {\n [key(\"difference\")]: (args, ctx) => {\n const [nodes, others] = nodeSets(\"set:difference\", args, ctx, 2);\n const excluded = new Set(others);\n return nodes.filter((node) => !excluded.has(node));\n },\n\n [key(\"intersection\")]: (args, ctx) => {\n const [nodes, others] = nodeSets(\"set:intersection\", args, ctx, 2);\n const included = new Set(others);\n return nodes.filter((node) => included.has(node));\n },\n\n [key(\"distinct\")]: (args, ctx) => {\n const [nodes] = nodeSets(\"set:distinct\", args, ctx, 1);\n const seen = new Set();\n return nodes.filter((node) => {\n const value = evaluator.getStringValue(node);\n if (seen.has(value)) return false;\n seen.add(value);\n return true;\n });\n },\n\n [key(\"has-same-node\")]: (args, ctx) => {\n const [nodes, others] = nodeSets(\"set:has-same-node\", args, ctx, 2);\n const included = new Set(others);\n return nodes.some((node) => included.has(node));\n },\n\n [key(\"leading\")]: around(\"set:leading\", true),\n [key(\"trailing\")]: around(\"set:trailing\", false),\n };\n}\n", "/**\n * String algorithms of the EXSLT strings module, ported from libexslt\n * `strings.c`. They work on plain strings; `strings.js` binds them to XPath.\n * Lengths and positions count characters (Unicode code points).\n */\n\n\"use strict\";\n\nimport { characters } from \"./arguments.js\";\n\n/** Delimiters `str:tokenize()` uses without a second argument. */\nexport const DEFAULT_TOKENIZE_DELIMITERS = \"\\t\\r\\n \";\n\n/** Longest string `str:padding()` builds (libexslt's limit). */\nexport const MAX_PADDING = 100000;\n\n/**\n * `str:tokenize()`: split on any of the delimiter characters, dropping empty\n * tokens; an empty delimiter string makes every character a token.\n *\n * @param {string} str - The string to split\n * @param {string} delimiters - Delimiter characters\n * @returns {string[]} The tokens\n */\nexport function tokenizeString(str, delimiters) {\n const chars = characters(str);\n if (delimiters === \"\") return chars;\n\n const separators = new Set(characters(delimiters));\n const tokens = [];\n let token = \"\";\n for (const char of chars) {\n if (!separators.has(char)) {\n token += char;\n } else if (token !== \"\") {\n tokens.push(token);\n token = \"\";\n }\n }\n if (token !== \"\") tokens.push(token);\n return tokens;\n}\n\n/**\n * Lower-case the ASCII letters of a string, as libxml2 `xmlStrncasecmp`.\n *\n * @param {string} str - Any string\n * @returns {string} The string with A-Z lower-cased\n */\nfunction asciiLowerCase(str) {\n return str.replace(/[A-Z]/g, (letter) => letter.toLowerCase());\n}\n\n/**\n * `str:split()`: split on a delimiter string, dropping empty tokens. As in\n * libexslt the delimiter matches ASCII letters case-insensitively, and an\n * empty delimiter makes every character a token.\n *\n * @param {string} str - The string to split\n * @param {string} delimiter - The delimiter\n * @returns {string[]} The tokens\n */\nexport function splitString(str, delimiter) {\n if (delimiter === \"\") return characters(str);\n\n const haystack = asciiLowerCase(str);\n const needle = asciiLowerCase(delimiter);\n const tokens = [];\n let start = 0;\n let at = haystack.indexOf(needle);\n while (at !== -1) {\n if (at > start) tokens.push(str.substring(start, at));\n start = at + needle.length;\n at = haystack.indexOf(needle, start);\n }\n if (start < str.length) tokens.push(str.substring(start));\n return tokens;\n}\n\n/**\n * `str:padding(length, chars)`: repeat `chars` (a space when empty) and\n * truncate to `length` characters, capped at {@link MAX_PADDING}.\n *\n * @param {number} length - Requested length\n * @param {string} chars - Padding characters\n * @returns {string} The padding\n */\nexport function paddingString(length, chars) {\n if (Number.isNaN(length) || length < 1) return \"\";\n const count = Math.min(Math.trunc(length), MAX_PADDING);\n const pattern = characters(chars === \"\" ? \" \" : chars);\n const whole = Math.floor(count / pattern.length);\n return (\n pattern.join(\"\").repeat(whole) +\n pattern.slice(0, count - whole * pattern.length).join(\"\")\n );\n}\n\n/**\n * `str:align(string, padding, alignment)`: overlay the string on the padding\n * (\"left\" unless \"right\" or \"center\"), truncating a longer string.\n *\n * @param {string} str - The string to align\n * @param {string} padding - The padding it is placed on\n * @param {string|null} alignment - \"left\", \"right\" or \"center\"\n * @returns {string} The aligned string\n */\nexport function alignString(str, padding, alignment) {\n const text = characters(str);\n const pad = characters(padding);\n if (text.length >= pad.length) return text.slice(0, pad.length).join(\"\");\n\n const free = pad.length - text.length;\n let left = 0;\n if (alignment === \"right\") left = free;\n else if (alignment === \"center\") left = Math.floor(free / 2);\n\n return (\n pad.slice(0, left).join(\"\") + str + pad.slice(left + text.length).join(\"\")\n );\n}\n\n/**\n * `str:replace()`: replace every occurrence of the search strings, longest\n * match first (the earliest search string on ties). Search string `i` is\n * replaced by replacement `i`, or removed when there is none. The first empty\n * search string with a non-empty replacement inserts that replacement between\n * the characters that no search string matches.\n *\n * @param {string} str - The string to process\n * @param {string[]} searches - Search strings\n * @param {Array<string|null>} replacements - Replacements by search index\n * @returns {string} The processed string\n */\nexport function replaceStrings(str, searches, replacements) {\n const replacementOf = (index) => replacements[index] ?? \"\";\n let emptyIndex = searches.indexOf(\"\");\n if (emptyIndex !== -1 && replacementOf(emptyIndex) === \"\") emptyIndex = -1;\n\n let result = \"\";\n let start = 0;\n let at = 0;\n while (at < str.length) {\n let match = -1;\n searches.forEach((search, index) => {\n const longer = match === -1 || search.length > searches[match].length;\n if (search !== \"\" && longer && str.startsWith(search, at)) match = index;\n });\n\n if (match === -1) {\n if (emptyIndex !== -1 && start < at) {\n result += str.substring(start, at) + replacementOf(emptyIndex);\n start = at;\n }\n at += str.codePointAt(at) > 0xffff ? 2 : 1;\n } else {\n result += str.substring(start, at) + replacementOf(match);\n at += searches[match].length;\n start = at;\n }\n }\n return result + str.substring(start);\n}\n", "/**\n * `str:encode-uri()` / `str:decode-uri()` algorithms, following libexslt\n * `strings.c` and libxml2 `xmlURIEscapeStr()` / `xmlURIUnescapeString()`.\n *\n * Only UTF-8 is supported: any other encoding argument (the name is compared\n * case-sensitively, as libexslt does) yields the empty string, as does a\n * string that is not well-formed Unicode or decodes to malformed UTF-8.\n */\n\n\"use strict\";\n\n/** The only encoding name the functions accept. */\nexport const URI_ENCODING = \"UTF-8\";\n\n/** Characters never escaped: RFC 2396 \"mark\" characters (letters and digits aside). */\nconst MARKS = \"-_.!~*'()\";\n\n/** Reserved characters kept when `escape-reserved` is false. */\nconst RESERVED = \";/?:@&=+$,[]\";\n\n/**\n * Whether a string contains an unpaired surrogate, which has no UTF-8 form.\n *\n * @param {string} str - Any string\n * @returns {boolean} True when the string is not well-formed\n */\nfunction hasLoneSurrogate(str) {\n return /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/.test(\n str,\n );\n}\n\n/**\n * Percent-encode the UTF-8 bytes of one character, in upper case hex.\n *\n * @param {string} char - One character (code point)\n * @returns {string} The escaped bytes\n */\nfunction escapeBytes(char) {\n const code = char.codePointAt(0);\n if (code < 0x80) {\n return `%${code.toString(16).toUpperCase().padStart(2, \"0\")}`;\n }\n return encodeURIComponent(char);\n}\n\n/**\n * `str:encode-uri(string, escape-reserved, encoding?)`.\n *\n * @param {string} str - The string to escape\n * @param {boolean} escapeReserved - Whether reserved characters are escaped too\n * @param {string} [encoding] - Must be \"UTF-8\" when given\n * @returns {string} The escaped string, \"\" on failure\n */\nexport function encodeUri(str, escapeReserved, encoding = URI_ENCODING) {\n if (encoding !== URI_ENCODING || hasLoneSurrogate(str)) return \"\";\n\n const kept = escapeReserved ? MARKS : MARKS + RESERVED;\n let result = \"\";\n for (const char of str) {\n const unescaped = /^[A-Za-z0-9]$/.test(char) || kept.includes(char);\n result += unescaped ? char : escapeBytes(char);\n }\n return result;\n}\n\n/**\n * `str:decode-uri(string, encoding?)`: decode every `%XX` escape (a `%` not\n * followed by two hex digits stays as is); the decoded bytes must be UTF-8.\n * As the result is a C string in libexslt, it ends at a decoded NUL byte.\n *\n * @param {string} str - The string to unescape\n * @param {string} [encoding] - Must be \"UTF-8\" when given\n * @returns {string} The unescaped string, \"\" on failure\n */\nexport function decodeUri(str, encoding = URI_ENCODING) {\n if (encoding !== URI_ENCODING || hasLoneSurrogate(str)) return \"\";\n\n // Re-escape everything but valid escapes, then let the platform decode the\n // bytes: decodeURIComponent throws on malformed UTF-8.\n const escaped = str.replace(/%(?![0-9A-Fa-f]{2})|[^%]+/gu, (text) =>\n text === \"%\" ? \"%25\" : encodeURIComponent(text),\n );\n\n try {\n const decoded = decodeURIComponent(escaped);\n const nul = decoded.indexOf(\"\\0\");\n return nul === -1 ? decoded : decoded.substring(0, nul);\n } catch {\n return \"\";\n }\n}\n", "/**\n * EXSLT strings module (http://exslt.org/strings), following libexslt\n * `strings.c`: tokenize, split, replace, padding, align, concat, encode-uri\n * and decode-uri.\n *\n * `tokenize()` / `split()` return `token` elements (no namespace) and\n * `replace()` returns one text node; like libexslt's result tree fragments,\n * the nodes of one call are siblings in a new DocumentFragment.\n */\n\n\"use strict\";\n\nimport { expandedFunctionName } from \"../../xpath/evaluator.js\";\nimport {\n EXSLT_STRINGS,\n checkArity,\n createContainer,\n isNodeSetValue,\n toNodeSet,\n} from \"./arguments.js\";\nimport {\n DEFAULT_TOKENIZE_DELIMITERS,\n alignString,\n paddingString,\n replaceStrings,\n splitString,\n tokenizeString,\n} from \"./stringOps.js\";\nimport { decodeUri, encodeUri } from \"./uri.js\";\n\n/**\n * Build the EXSLT strings functions.\n *\n * @param {import('../../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluates the arguments\n * @returns {Object<string, Function>} Functions keyed by expanded name\n */\nexport function createStringsFunctions(evaluator) {\n const value = (arg, ctx) => evaluator.evaluate(arg, ctx);\n const string = (arg, ctx) => evaluator.toString(value(arg, ctx));\n const optionalString = (args, index, ctx, fallback) =>\n args.length > index ? string(args[index], ctx) : fallback;\n\n /**\n * Turn tokens into `token` elements of a new fragment.\n *\n * @param {string[]} tokens - The tokens\n * @param {object} ctx - Evaluation context, provides the owner document\n * @returns {Element[]} The token elements\n */\n const tokenElements = (tokens, ctx) => {\n const container = createContainer(ctx);\n const doc = container.ownerDocument;\n return tokens.map((token) => {\n const element = doc.createElementNS(null, \"token\");\n element.appendChild(doc.createTextNode(token));\n return container.appendChild(element);\n });\n };\n\n /**\n * String values of a node-set argument, or the string of any other value.\n *\n * @param {*} argValue - An evaluated argument\n * @returns {string[]} The strings\n */\n const stringList = (argValue) =>\n isNodeSetValue(argValue)\n ? toNodeSet(\"str:replace\", argValue).map((node) =>\n evaluator.getStringValue(node),\n )\n : [evaluator.toString(argValue)];\n\n const key = (local) => expandedFunctionName(EXSLT_STRINGS, local);\n\n return {\n [key(\"tokenize\")]: (args, ctx) => {\n checkArity(\"str:tokenize\", args, 1, 2);\n const delimiters = optionalString(\n args,\n 1,\n ctx,\n DEFAULT_TOKENIZE_DELIMITERS,\n );\n return tokenElements(\n tokenizeString(string(args[0], ctx), delimiters),\n ctx,\n );\n },\n\n [key(\"split\")]: (args, ctx) => {\n checkArity(\"str:split\", args, 1, 2);\n const delimiter = optionalString(args, 1, ctx, \" \");\n return tokenElements(splitString(string(args[0], ctx), delimiter), ctx);\n },\n\n [key(\"replace\")]: (args, ctx) => {\n checkArity(\"str:replace\", args, 3);\n const str = string(args[0], ctx);\n const searches = stringList(value(args[1], ctx));\n const replacements = stringList(value(args[2], ctx));\n const container = createContainer(ctx);\n const text = container.ownerDocument.createTextNode(\n replaceStrings(str, searches, replacements),\n );\n return [container.appendChild(text)];\n },\n\n [key(\"padding\")]: (args, ctx) => {\n checkArity(\"str:padding\", args, 1, 2);\n const length = evaluator.toNumber(value(args[0], ctx));\n return paddingString(length, optionalString(args, 1, ctx, \"\"));\n },\n\n [key(\"align\")]: (args, ctx) => {\n checkArity(\"str:align\", args, 2, 3);\n return alignString(\n string(args[0], ctx),\n string(args[1], ctx),\n optionalString(args, 2, ctx, null),\n );\n },\n\n [key(\"concat\")]: (args, ctx) => {\n checkArity(\"str:concat\", args, 1);\n return toNodeSet(\"str:concat\", value(args[0], ctx))\n .map((node) => evaluator.getStringValue(node))\n .join(\"\");\n },\n\n [key(\"encode-uri\")]: (args, ctx) => {\n checkArity(\"str:encode-uri\", args, 2, 3);\n return encodeUri(\n string(args[0], ctx),\n evaluator.toBoolean(value(args[1], ctx)),\n optionalString(args, 2, ctx, undefined),\n );\n },\n\n [key(\"decode-uri\")]: (args, ctx) => {\n checkArity(\"str:decode-uri\", args, 1, 2);\n return decodeUri(\n string(args[0], ctx),\n optionalString(args, 1, ctx, undefined),\n );\n },\n };\n}\n", "/**\n * EXSLT extension functions (https://exslt.org/), the set libexslt provides\n * to libxslt and so to Chrome's native XSLTProcessor: common, math, sets,\n * strings, dates-and-times and dynamic.\n *\n * `../functions.js` merges this map into the XSLT function library, so the\n * functions are found by expanded name through any prefix bound to their\n * namespace and are reported by `function-available()`.\n *\n * Engine properties read at call time (all optional):\n * - `clock()`: returns the current instant as a Date (or any object with\n * `getTime()` and `getTimezoneOffset()`), for deterministic dates;\n * - `enableDynamicEvaluate`: `true` enables `dyn:evaluate()`.\n */\n\n\"use strict\";\n\nimport { createCommonFunctions } from \"./common.js\";\nimport { createDatesFunctions, systemClock } from \"./dates.js\";\nimport { createDynamicFunctions } from \"./dynamic.js\";\nimport { createMathFunctions } from \"./math.js\";\nimport { createSetsFunctions } from \"./sets.js\";\nimport { createStringsFunctions } from \"./strings.js\";\n\nexport {\n EXSLT_COMMON,\n EXSLT_DATES,\n EXSLT_DYNAMIC,\n EXSLT_MATH,\n EXSLT_SETS,\n EXSLT_STRINGS,\n} from \"./arguments.js\";\n\n/**\n * Build the EXSLT function map of an engine.\n *\n * @param {{xpathEvaluator: import('../../xpath/evaluator.js').XPathEvaluator, clock?: Function, enableDynamicEvaluate?: boolean}} engine - The engine\n * @returns {Object<string, Function>} Functions keyed by expanded name\n *\n * @example\n * evaluator.registerFunctions(createExsltFunctions(engine));\n */\nexport function createExsltFunctions(engine) {\n const evaluator = engine.xpathEvaluator;\n const clock = () =>\n typeof engine.clock === \"function\" ? engine.clock() : systemClock();\n\n return {\n ...createCommonFunctions(evaluator),\n ...createMathFunctions(evaluator),\n ...createSetsFunctions(evaluator),\n ...createStringsFunctions(evaluator),\n ...createDatesFunctions(evaluator, clock),\n ...createDynamicFunctions(\n evaluator,\n () => engine.enableDynamicEvaluate === true,\n ),\n };\n}\n", "/**\n * XSLT-defined XPath functions.\n *\n * XSLT 1.0 section 12 adds functions to the XPath function library, and the\n * EXSLT `node-set()` extension (also under the msxsl namespace) is registered\n * by expanded name next to them, together with the other EXSLT functions of\n * `./exslt/index.js`. They live here rather than in `src/xpath` so\n * that module stays a pure XPath 1.0 implementation; the engine registers this\n * map on its evaluator through\n * {@link XPathEvaluator#registerFunctions}.\n */\n\n\"use strict\";\n\nimport { formatNumber, DEFAULT_DECIMAL_FORMAT } from \"./formatNumber.js\";\nimport { isXsltElementAvailable, XSLT_NAMESPACE } from \"./elements.js\";\nimport {\n expandedFunctionName,\n resolveNamespacePrefix,\n} from \"../xpath/evaluator.js\";\nimport { rootNodeOf } from \"../xpath/axes.js\";\nimport { EXSLT_COMMON, createExsltFunctions } from \"./exslt/index.js\";\n\n/** Namespace of the EXSLT common module (`exsl:node-set()`). */\nexport const EXSLT_COMMON_NAMESPACE = EXSLT_COMMON;\n\n/** Namespace of the MSXML extension functions (`msxsl:node-set()`). */\nexport const MSXSL_NAMESPACE = \"urn:schemas-microsoft-com:xslt\";\n\n/** Vendor identification reported by `system-property()`. */\nexport const VENDOR = \"@tradik/xslt-processor\";\n\n/** Vendor URL reported by `system-property()`. */\nexport const VENDOR_URL = \"https://github.com/spagu/XSLT-Processor\";\n\n/**\n * Values reported by `system-property()`, keyed by property name.\n *\n * The XSLT version is reported as the string `\"1\"`; XPath 1.0 converts it to\n * the number 1 wherever a numeric comparison or arithmetic is used.\n */\nconst SYSTEM_PROPERTIES = Object.freeze({\n \"xsl:version\": \"1\",\n \"xsl:vendor\": VENDOR,\n \"xsl:vendor-url\": VENDOR_URL,\n});\n\n/**\n * Get the document that owns a node.\n *\n * @param {Node} node - Any node\n * @returns {Document} The owning document, or the node when it is a document\n */\nfunction ownerDocumentOf(node) {\n return node.ownerDocument || node;\n}\n\n/**\n * Convert an evaluated argument to the list of strings it denotes.\n *\n * Node-sets yield the string value of every node, other types yield one string.\n *\n * @param {XPathEvaluator} evaluator - The evaluator providing the conversions\n * @param {(value: *) => string} stringify - The XPath `string()` conversion\n * @param {*} value - An evaluated XPath value\n * @returns {string[]} The string values\n */\nfunction toStringList(evaluator, stringify, value) {\n if (Array.isArray(value)) {\n return value.map((node) => evaluator.getStringValue(node));\n }\n return [stringify(value)];\n}\n\n/**\n * Split a QName into its prefix and local part.\n *\n * @param {string} qname - A possibly prefixed name\n * @returns {{prefix: (string|null), localName: string}} The parts of the name\n */\nfunction splitQName(qname) {\n const colon = qname.indexOf(\":\");\n if (colon === -1) return { prefix: null, localName: qname };\n return {\n prefix: qname.substring(0, colon),\n localName: qname.substring(colon + 1),\n };\n}\n\n/**\n * Expanded name key of the decimal format named by the third argument of\n * `format-number()`, with the prefix resolved in the expression's scope\n * (XSLT 1.0 section 12.3); the table is keyed the same way (see\n * declarationNames.js).\n *\n * @param {string} qname - The decimal format QName\n * @param {{namespaces: Object<string, string>}} ctx - The XPath context\n * @returns {string} `{uri}local`, or the local name in no namespace\n * @throws {Error} When the prefix is not declared\n */\nfunction decimalFormatKey(qname, ctx) {\n const { prefix, localName } = splitQName(qname);\n if (prefix === null) return localName;\n const namespaceUri = resolveNamespacePrefix(prefix, ctx.namespaces);\n if (!namespaceUri) {\n throw new Error(\n `format-number(): undeclared namespace prefix \"${prefix}\" in \"${qname}\"`,\n );\n }\n return `{${namespaceUri}}${localName}`;\n}\n\n/**\n * Build the XSLT function map for an engine.\n *\n * @param {import('./engine.js').XsltEngine} engine - The engine providing loaders, keys and formats\n * @returns {Object<string, Function>} Functions ready for `registerFunctions`\n *\n * @example\n * evaluator.registerFunctions(createXsltFunctions(engine));\n */\nexport function createXsltFunctions(engine) {\n const evaluator = engine.xpathEvaluator;\n\n /**\n * The XPath `string()` conversion of the evaluator.\n *\n * `XPathEvaluator#toString` shadows `Object#toString` and takes the value to\n * convert as its argument, so it is bound once under an unambiguous name.\n *\n * @type {(value: *) => string}\n */\n const stringify = evaluator.toString.bind(evaluator);\n const evaluate = (arg, ctx) => evaluator.evaluate(arg, ctx);\n const asString = (arg, ctx) => stringify(evaluate(arg, ctx));\n\n /**\n * `exsl:node-set(object)` - EXSLT common, also known as `msxsl:node-set()`.\n *\n * A result tree fragment (a DocumentFragment in this engine) becomes a\n * node-set holding its root node, so `exsl:node-set($rtf)/item` selects the\n * fragment's top-level `item` elements. A node-set is returned unchanged; any\n * other value becomes a node-set holding one text node with its string value.\n *\n * @param {Array} args - Argument expressions\n * @param {import('../xpath/evaluator.js').XPathContext} ctx - Evaluation context\n * @returns {Node[]} The node-set\n */\n const nodeSet = (args, ctx) => {\n const value = evaluate(args[0], ctx);\n if (Array.isArray(value)) return value;\n if (value?.nodeType) return [value];\n return [ownerDocumentOf(ctx.node).createTextNode(stringify(value))];\n };\n\n return {\n ...createExsltFunctions(engine),\n [expandedFunctionName(EXSLT_COMMON_NAMESPACE, \"node-set\")]: nodeSet,\n [expandedFunctionName(MSXSL_NAMESPACE, \"node-set\")]: nodeSet,\n\n /**\n * `document(object, base?)` - load external XML documents.\n *\n * An empty URI denotes the stylesheet itself. Without a document loader, or\n * when the loader returns null, the result is an empty node-set. The\n * optional second argument is read as a base URI string.\n */\n document: (args, ctx) => {\n const baseUri = args.length > 1 ? asString(args[1], ctx) : engine.baseUri;\n const uris = toStringList(evaluator, stringify, evaluate(args[0], ctx));\n const result = [];\n\n for (const uri of uris) {\n const doc = engine.loadDocument(uri, baseUri || engine.baseUri);\n if (doc && !result.includes(doc)) result.push(doc);\n }\n\n return result;\n },\n\n /**\n * `key(name, value)` - look up nodes through an `xsl:key` index of the\n * tree containing the context node: its document, or the fragment of a\n * result tree fragment converted with `exsl:node-set()`.\n */\n key: (args, ctx) => {\n const name = asString(args[0], ctx);\n const values = toStringList(evaluator, stringify, evaluate(args[1], ctx));\n return engine.keyRegistry.lookup(name, values, rootNodeOf(ctx.node));\n },\n\n /** `format-number(number, pattern, decimalFormat?)`. */\n \"format-number\": (args, ctx) => {\n const value = evaluator.toNumber(evaluate(args[0], ctx));\n const pattern = asString(args[1], ctx);\n const formatName =\n args.length > 2 ? decimalFormatKey(asString(args[2], ctx), ctx) : \"\";\n const format =\n engine.decimalFormats[formatName] || DEFAULT_DECIMAL_FORMAT;\n return formatNumber(value, pattern, format);\n },\n\n /** `current()` - the XSLT current node, not the XPath context node. */\n current: (args, ctx) => {\n const currentNode = ctx.hostContext?.currentNode;\n return currentNode ? [currentNode] : [ctx.node];\n },\n\n /** `generate-id(node-set?)` - a stable id for the life of the transform. */\n \"generate-id\": (args, ctx) => {\n let node = ctx.node;\n\n if (args.length > 0) {\n const nodeSet = evaluate(args[0], ctx);\n node = Array.isArray(nodeSet) ? nodeSet[0] : nodeSet;\n }\n\n return node ? engine.generateId(node) : \"\";\n },\n\n /** `system-property(name)` - XSLT version and vendor information. */\n \"system-property\": (args, ctx) => {\n const name = asString(args[0], ctx);\n return Object.hasOwn(SYSTEM_PROPERTIES, name)\n ? SYSTEM_PROPERTIES[name]\n : \"\";\n },\n\n /**\n * `function-available(name)` - reflects the evaluator function table. A\n * prefixed name is resolved through the stylesheet's namespace bindings,\n * just as a call of that function would be. A function can report itself\n * unavailable through an `isAvailable()` property (`dyn:evaluate()` does\n * until the engine enables it).\n */\n \"function-available\": (args, ctx) => {\n const { prefix, localName } = splitQName(asString(args[0], ctx));\n const fn = evaluator.resolveFunction(localName, prefix, ctx.namespaces);\n return fn !== null && fn.isAvailable?.() !== false;\n },\n\n /** `element-available(name)` - reflects the XSLT elements the engine runs. */\n \"element-available\": (args, ctx) => {\n const { prefix, localName } = splitQName(asString(args[0], ctx));\n // An unprefixed name is in the default namespace (XSLT 1.0 section\n // 15), which may be the XSLT namespace itself (libxslt bug-200)\n const namespaceUri = prefix\n ? (ctx.namespaces[prefix] ?? (prefix === \"xsl\" ? XSLT_NAMESPACE : null))\n : ctx.namespaces[\"\"] || null;\n if (!namespaceUri) return false;\n\n if (namespaceUri === XSLT_NAMESPACE) {\n return isXsltElementAvailable(localName);\n }\n // Extension elements with an implementation (registerExtensionElement)\n return Boolean(\n engine.extensionElements?.has(`{${namespaceUri}}${localName}`),\n );\n },\n\n /**\n * `unparsed-entity-uri(name)` - always empty.\n *\n * Unparsed entity declarations are not exposed by the DOM, so this\n * processor cannot resolve them; returning the empty string keeps\n * stylesheets that call the function working.\n */\n \"unparsed-entity-uri\": () => \"\",\n };\n}\n", "/**\n * `xsl:key` indexing for the XSLT `key()` function.\n *\n * Indexes are built lazily, once per (root node, key name) pair, and cached in\n * a `WeakMap` so source documents stay garbage collectable. The root node is\n * the document of the context node, or the DocumentFragment of a result tree\n * fragment converted with `exsl:node-set()` (see `rootNodeOf` in xpath/axes). The registry is\n * deliberately decoupled from the engine: pattern matching and `use` evaluation\n * are injected as callbacks.\n */\n\n\"use strict\";\n\n/**\n * @typedef {Object} KeyDefinition\n * @property {string} match - Pattern of the nodes to index\n * @property {string} use - Expression computing the key values\n * @property {Object<string, string>} [namespaces] - Prefixes in scope on the xsl:key element\n */\n\n/**\n * @typedef {Object} KeyIndex\n * @property {Map<string, Node[]>} buckets - Key value to nodes, in document order\n * @property {Map<Node, number>} order - Document order position of every node\n */\n\n/**\n * Lazily built, per-tree indexes for all declared keys.\n */\nexport class KeyIndexRegistry {\n /**\n * @param {Object} options - Registry configuration\n * @param {Object<string, (KeyDefinition|KeyDefinition[])>} options.keys - Declared keys by name; several xsl:key elements may share a name\n * @param {(node: Node, pattern: string, definition: KeyDefinition) => boolean} options.matchesPattern - XSLT pattern matcher\n * @param {(node: Node, expression: string, definition: KeyDefinition) => string[]} options.evaluateUse - `use` evaluator returning key values\n */\n constructor({ keys, matchesPattern, evaluateUse }) {\n this.keys = keys;\n this.matchesPattern = matchesPattern;\n this.evaluateUse = evaluateUse;\n this.cache = new WeakMap();\n }\n\n /**\n * Drop every cached index, for example after the key declarations changed.\n *\n * @returns {void}\n *\n * @example\n * registry.clear();\n */\n clear() {\n this.cache = new WeakMap();\n }\n\n /**\n * Look up the nodes indexed under one or more key values.\n *\n * @param {string} name - The key name\n * @param {string|string[]} values - One key value, or several to union\n * @param {Node} doc - Root of the tree to search (Document or DocumentFragment)\n * @returns {Node[]} Matching nodes in document order, without duplicates\n * @throws {Error} When the key name was never declared\n *\n * @example\n * registry.lookup('byId', 'a1', xmlDoc);\n */\n lookup(name, values, doc) {\n if (!Object.hasOwn(this.keys, name)) {\n throw new Error(`Undefined key: ${name}`);\n }\n\n const { buckets, order } = this.getIndex(name, doc);\n const wanted = Array.isArray(values) ? values : [values];\n if (wanted.length === 1) return [...(buckets.get(wanted[0]) || [])];\n\n const found = new Set();\n for (const value of wanted) {\n for (const node of buckets.get(value) || []) found.add(node);\n }\n return [...found].sort((a, b) => order.get(a) - order.get(b));\n }\n\n /**\n * Get (building if needed) the index of one key for one document.\n *\n * @param {string} name - The key name\n * @param {Node} doc - Root of the tree being indexed\n * @returns {KeyIndex} The index\n */\n getIndex(name, doc) {\n let byName = this.cache.get(doc);\n if (!byName) {\n byName = new Map();\n this.cache.set(doc, byName);\n }\n\n let index = byName.get(name);\n if (!index) {\n index = this.buildIndex(name, doc);\n byName.set(name, index);\n }\n\n return index;\n }\n\n /**\n * Build the index of one key for one document, merging every declaration\n * of that key name.\n *\n * @param {string} name - The key name\n * @param {Node} doc - Root of the tree being indexed\n * @returns {KeyIndex} The index\n */\n buildIndex(name, doc) {\n const definitions = [this.keys[name]].flat();\n const buckets = new Map();\n const order = new Map();\n\n for (const node of documentOrderNodes(doc)) {\n order.set(node, order.size);\n\n for (const definition of definitions) {\n if (!this.matchesPattern(node, definition.match, definition)) continue;\n\n for (const value of this.evaluateUse(\n node,\n definition.use,\n definition,\n )) {\n const bucket = buckets.get(value);\n if (!bucket) buckets.set(value, [node]);\n else if (bucket[bucket.length - 1] !== node) bucket.push(node);\n }\n }\n }\n\n return { buckets, order };\n }\n}\n\n/**\n * Walk a document in document order, including attribute nodes.\n *\n * @param {Node} root - The document or subtree root\n * @yields {Node} Every node of the subtree\n */\nfunction* documentOrderNodes(root) {\n const stack = [root];\n\n while (stack.length > 0) {\n const current = stack.pop();\n yield current;\n\n if (current.nodeType === 1 && current.attributes) {\n for (const attribute of current.attributes) yield attribute;\n }\n\n const children = current.childNodes;\n if (children) {\n for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]);\n }\n }\n}\n", "/**\n * Literal result element support: namespace aliasing and attribute filtering.\n *\n * `xsl:namespace-alias` rewrites the namespace of literal result elements and\n * attributes, which is what makes it possible for a stylesheet to generate\n * another stylesheet. Attribute filtering keeps XSLT-only attributes such as\n * `xsl:use-attribute-sets` out of the result tree.\n */\n\n\"use strict\";\n\n/**\n * Resolve a namespace prefix against the declarations in scope of a node.\n *\n * Falls back to walking `xmlns` attributes when the DOM implementation does not\n * provide `lookupNamespaceURI`.\n *\n * @param {Element} node - The element whose scope is searched\n * @param {string|null} prefix - The prefix, or null for the default namespace\n * @returns {string|null} The namespace URI, or null when undeclared\n *\n * @example\n * lookupNamespaceUri(stylesheetElement, 'xsl');\n */\nexport function lookupNamespaceUri(node, prefix) {\n if (typeof node.lookupNamespaceURI === \"function\") {\n const found = node.lookupNamespaceURI(prefix);\n if (found) return found;\n }\n\n const attributeName = prefix ? `xmlns:${prefix}` : \"xmlns\";\n let current = node;\n\n while (current?.nodeType === 1) {\n const value = current.getAttribute(attributeName);\n if (value) return value;\n current = current.parentNode;\n }\n\n return null;\n}\n\n/**\n * The `xsl:namespace-alias` declarations of a stylesheet.\n *\n * Literal result names are aliased as libxslt (and so Chrome) does, see\n * {@link NamespaceAliasMap#resolveLiteral}: the namespace URI is replaced and\n * the prefix written in the stylesheet is kept (`axsl:stylesheet` with\n * `xmlns:axsl` bound to the XSLT namespace); `result-prefix=\"#default\"`\n * without a default namespace in scope gives names in no namespace, and\n * `stylesheet-prefix=\"#default\"` without a default namespace in scope\n * aliases the elements in no namespace, which then take the result prefix.\n */\nexport class NamespaceAliasMap {\n constructor() {\n this.byUri = new Map();\n /** Alias of elements in no namespace (`#default` stylesheet prefix). */\n this.noNamespaceAlias = null;\n }\n\n /**\n * Record one `xsl:namespace-alias` declaration.\n *\n * @param {Element} node - The `xsl:namespace-alias` element\n * @returns {void}\n *\n * @example\n * aliases.add(namespaceAliasElement);\n */\n add(node) {\n const stylesheetPrefix = node.getAttribute(\"stylesheet-prefix\");\n const resultPrefix = node.getAttribute(\"result-prefix\");\n if (!stylesheetPrefix || !resultPrefix) return;\n\n const isDefaultSource = stylesheetPrefix === \"#default\";\n const fromUri = lookupNamespaceUri(\n node,\n isDefaultSource ? null : stylesheetPrefix,\n );\n if (!fromUri && !isDefaultSource) return;\n\n const isDefaultResult = resultPrefix === \"#default\";\n const toUri = lookupNamespaceUri(\n node,\n isDefaultResult ? null : resultPrefix,\n );\n const alias = { uri: toUri, prefix: isDefaultResult ? null : resultPrefix };\n\n if (fromUri) this.byUri.set(fromUri, alias);\n else if (toUri) this.noNamespaceAlias = alias;\n }\n\n /**\n * Whether any alias was declared.\n *\n * @returns {boolean} True when at least one alias is known\n *\n * @example\n * aliases.isEmpty();\n */\n isEmpty() {\n return this.byUri.size === 0 && this.noNamespaceAlias === null;\n }\n\n /**\n * Whether a namespace is the stylesheet side of an alias.\n *\n * @param {string} uri - A namespace URI\n * @returns {boolean} True when literal result names in it are aliased\n *\n * @example\n * aliases.isAliased('http://www.w3.org/1999/XSL/TransformAlias'); // true\n */\n isAliased(uri) {\n return this.byUri.has(uri);\n }\n\n /**\n * Apply aliasing to a literal result name.\n *\n * @param {string|null} namespaceUri - The namespace of the stylesheet node\n * @param {string} localName - The local name of the stylesheet node\n * @returns {{namespaceUri: (string|null), qname: string}|null} The aliased name, or null when no alias applies\n *\n * @example\n * aliases.resolve('http://www.w3.org/1999/XSL/TransformAlias', 'stylesheet');\n * // { namespaceUri: 'http://www.w3.org/1999/XSL/Transform', qname: 'xsl:stylesheet' }\n */\n resolve(namespaceUri, localName) {\n const alias = namespaceUri ? this.byUri.get(namespaceUri) : undefined;\n if (!alias) return null;\n\n return {\n namespaceUri: alias.uri,\n qname: alias.prefix ? `${alias.prefix}:${localName}` : localName,\n };\n }\n\n /**\n * Apply aliasing to the name of a literal result element or attribute as\n * libxslt does: the namespace URI is replaced and the stylesheet prefix\n * kept. An element in no namespace takes the `#default` stylesheet-prefix\n * alias with its result prefix; an alias to no namespace drops the prefix.\n *\n * @param {Element|Attr} node - The literal result element or attribute\n * @returns {{namespaceUri: (string|null), qname: string}|null} The aliased\n * name, or null when no alias applies\n *\n * @example\n * // xmlns:axsl=\"urn:alias\", <xsl:namespace-alias stylesheet-prefix=\"axsl\"\n * // result-prefix=\"xsl\"/>\n * aliases.resolveLiteral(axslStylesheetElement);\n * // { namespaceUri: 'http://www.w3.org/1999/XSL/Transform', qname: 'axsl:stylesheet' }\n */\n resolveLiteral(node) {\n const { localName } = node;\n if (!node.namespaceURI) {\n const alias = node.nodeType === 1 ? this.noNamespaceAlias : null;\n return alias\n ? { namespaceUri: alias.uri, qname: `${alias.prefix}:${localName}` }\n : null;\n }\n const alias = this.byUri.get(node.namespaceURI);\n if (!alias) return null;\n if (!alias.uri) return { namespaceUri: null, qname: localName };\n return {\n namespaceUri: alias.uri,\n qname: node.prefix ? `${node.prefix}:${localName}` : localName,\n };\n }\n}\n\n/**\n * Whether an attribute of a literal result element is copied to the output.\n *\n * Namespace declarations are re-created from the element namespaces themselves,\n * and every XSLT attribute (`xsl:use-attribute-sets`, `xsl:version`,\n * `xsl:exclude-result-prefixes`, `xsl:extension-element-prefixes`) is an\n * instruction to the processor rather than result tree content.\n *\n * @param {Attr} attribute - The attribute of the stylesheet element\n * @param {string} xsltNamespace - The XSLT namespace URI\n * @returns {boolean} True when the attribute belongs in the result\n *\n * @example\n * shouldCopyAttribute(attr, 'http://www.w3.org/1999/XSL/Transform');\n */\nexport function shouldCopyAttribute(attribute, xsltNamespace) {\n if (attribute.namespaceURI === xsltNamespace) return false;\n if (attribute.name === \"xmlns\" || attribute.name.startsWith(\"xmlns:\")) {\n return false;\n }\n return !attribute.name.startsWith(\"xsl:\");\n}\n\n/**\n * Read an XSLT attribute from a literal result element.\n *\n * Works both for namespace aware DOMs and for documents where the attribute is\n * only known by its `xsl:` qualified name.\n *\n * @param {Element} node - The literal result element\n * @param {string} localName - The XSLT attribute local name\n * @param {string} xsltNamespace - The XSLT namespace URI\n * @returns {string|null} The attribute value, or null when absent\n *\n * @example\n * getXsltAttribute(element, 'use-attribute-sets', XSLT_NS);\n */\nexport function getXsltAttribute(node, localName, xsltNamespace) {\n if (!node.attributes) return null;\n\n for (const attribute of node.attributes) {\n const matchesNamespace =\n attribute.namespaceURI === xsltNamespace &&\n (attribute.localName || attribute.name) === localName;\n if (matchesNamespace || attribute.name === `xsl:${localName}`) {\n return attribute.value;\n }\n }\n\n return null;\n}\n", "/**\n * Compilation of XSLT 1.0 patterns (section 5.2).\n *\n * A pattern is parsed with the XPath parser and turned into a list of\n * alternatives (one per union member). Each alternative has an anchor (the\n * root for absolute paths, an `id()`/`key()` call, or none) and a list of\n * child or attribute steps, each remembering the separator (`/` or `//`)\n * that links it to the step on its left.\n *\n * @module xslt/patternCompiler\n */\n\nimport { NodeType, parse } from \"../xpath/parser.js\";\n\n/** Number of (literal) arguments of the anchor functions of patterns. */\nconst ANCHOR_ARITY = Object.freeze({ id: 1, key: 2 });\nconst POSITIONAL_FUNCTIONS = new Set([\"position\", \"last\"]);\n\n/** Marker anchor of absolute location path patterns. */\nexport const ROOT = Symbol(\"root\");\n\n/**\n * Whether an expression calls `position()` or `last()` anywhere.\n *\n * @param {*} ast - XPath AST node (or any nested value)\n * @returns {boolean} True when the expression may depend on the position\n */\nfunction usesPosition(ast) {\n if (Array.isArray(ast)) return ast.some(usesPosition);\n if (!ast || typeof ast !== \"object\") return false;\n if (\n ast.type === NodeType.FUNCTION_CALL &&\n !ast.prefix &&\n POSITIONAL_FUNCTIONS.has(ast.name)\n ) {\n return true;\n }\n return Object.values(ast).some(usesPosition);\n}\n\n/**\n * Whether a step is the `descendant-or-self::node()` step that `//` expands to.\n *\n * @param {object} step - Step AST node\n * @returns {boolean} True for the abbreviated `//` step\n */\nfunction isDescendantSeparator(step) {\n return (\n step.axis === \"descendant-or-self\" &&\n step.nodeTest.type === NodeType.NODE_TYPE_TEST &&\n step.nodeTest.nodeType === \"node\" &&\n step.predicates.length === 0\n );\n}\n\n/**\n * Split a parsed union into its alternatives.\n *\n * @param {object} ast - XPath AST\n * @param {object[]} [result] - Array to append to\n * @returns {object[]} The alternatives in pattern order\n */\nfunction unionAlternatives(ast, result = []) {\n if (ast.type === NodeType.UNION_EXPR) {\n unionAlternatives(ast.left, result);\n unionAlternatives(ast.right, result);\n } else {\n result.push(ast);\n }\n return result;\n}\n\n/**\n * Whether an AST node is an `id()` or `key()` call.\n *\n * @param {object} ast - XPath AST node\n * @returns {boolean} True for an anchor function call\n */\nfunction isAnchorCall(ast) {\n return (\n ast?.type === NodeType.FUNCTION_CALL &&\n !ast.prefix &&\n Object.hasOwn(ANCHOR_ARITY, ast.name)\n );\n}\n\n/**\n * Check the arguments of an `id()`/`key()` pattern anchor: XSLT 1.0\n * (section 5.2, production IdKeyPattern) only allows string literals, as\n * libxslt enforces.\n *\n * @param {object} call - Function call AST of the anchor\n * @returns {object} The call\n * @throws {Error} When the arguments are not the right number of literals\n */\nfunction checkAnchorArguments(call) {\n const arity = ANCHOR_ARITY[call.name];\n const literals = call.args.every((arg) => arg.type === NodeType.LITERAL);\n if (call.args.length !== arity || !literals) {\n const noun = arity === 1 ? \"literal\" : \"literals\";\n throw new Error(\n `${call.name}() expects ${arity} ${noun} in a pattern (XSLT 1.0 section 5.2)`,\n );\n }\n return call;\n}\n\n/**\n * Compile one location path pattern.\n *\n * @param {object} ast - AST of one union alternative\n * @returns {{anchor: (symbol|object|null), steps: object[]}} Compiled alternative\n * @throws {Error} When the expression is not a valid pattern\n */\nfunction compileAlternative(ast) {\n let anchor;\n let steps;\n\n if (ast.type === NodeType.LOCATION_PATH) {\n anchor = ast.absolute ? ROOT : null;\n steps = ast.steps;\n } else if (isAnchorCall(ast)) {\n anchor = checkAnchorArguments(ast);\n steps = [];\n } else if (\n ast.type === NodeType.PATH_EXPR &&\n isAnchorCall(ast.filter) &&\n !ast.predicates\n ) {\n anchor = checkAnchorArguments(ast.filter);\n steps = ast.steps;\n } else {\n throw new Error(`Unsupported pattern expression: ${ast.type}`);\n }\n\n const compiled = [];\n let separator = anchor ? \"/\" : null;\n\n for (const step of steps) {\n if (isDescendantSeparator(step)) {\n separator = \"//\";\n continue;\n }\n if (step.axis !== \"child\" && step.axis !== \"attribute\") {\n throw new Error(`Axis not allowed in a pattern: ${step.axis}`);\n }\n compiled.push({\n axis: step.axis,\n nodeTest: step.nodeTest,\n separator,\n predicates: step.predicates.map((predicate) => ({\n expr: predicate.expr,\n positional: usesPosition(predicate.expr),\n })),\n });\n separator = \"/\";\n }\n\n if (separator === \"//\") throw new Error(\"Pattern cannot end with //\");\n return { anchor, steps: compiled };\n}\n\n/**\n * Parse and compile a pattern string.\n *\n * @param {string} pattern - The XSLT pattern\n * @returns {object[]} The compiled alternatives\n * @throws {Error} When the pattern is not valid\n *\n * @example\n * compilePattern('chapter/title | appendix//title');\n */\nexport function compilePattern(pattern) {\n return unionAlternatives(parse(pattern)).map(compileAlternative);\n}\n", "/**\n * Helpers of the XSLT pattern matcher (see patterns.js): node relationships\n * in the XPath data model and the per-call {@link MatchScope} that builds the\n * XPath contexts predicates and `id()`/`key()` anchors are evaluated in.\n *\n * @module xslt/matchScope\n */\n\n\"use strict\";\n\nimport { XPathContext } from \"../xpath/evaluator.js\";\nimport { parentOf } from \"../xpath/axes.js\";\n\nconst XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\nconst EMPTY_VARIABLES = Object.freeze({});\nconst EMPTY_NAMESPACES = Object.freeze({});\n\nexport { parentOf };\n\n/**\n * The root of the tree holding a node (its document, or the top of a\n * detached subtree or result tree fragment).\n *\n * @param {Node} node - Any node\n * @returns {Node} The outermost ancestor\n */\nexport function rootOf(node) {\n let root = node;\n for (let parent = parentOf(root); parent; parent = parentOf(parent)) {\n root = parent;\n }\n return root;\n}\n\n/**\n * Whether a node is a root node (a document or a result tree fragment).\n *\n * @param {Node|null} node - Any node\n * @returns {boolean} True for document and document fragment nodes\n */\nexport function isRoot(node) {\n return node !== null && (node.nodeType === 9 || node.nodeType === 11);\n}\n\n/**\n * Whether an attribute is a namespace declaration, which XPath does not\n * expose on the attribute axis.\n *\n * @param {Attr} attribute - An attribute node\n * @returns {boolean} True for `xmlns` and `xmlns:*` attributes\n */\nexport function isNamespaceDeclaration(attribute) {\n return (\n attribute.namespaceURI === XMLNS_NAMESPACE ||\n attribute.name === \"xmlns\" ||\n attribute.name.startsWith(\"xmlns:\")\n );\n}\n\n/**\n * State of a single match call: lazily merges the XSLT variables once.\n */\nexport class MatchScope {\n /**\n * @param {object|null} host - XSLT context (variables, parameters, namespaces)\n * @param {Object<string, string>} [namespaces] - Prefix bindings, when they\n * differ from the host's (e.g. those in scope on an xsl:template)\n */\n constructor(host, namespaces) {\n this.host = host;\n this.namespaces = namespaces ?? host?.namespaces ?? EMPTY_NAMESPACES;\n this.variables = null;\n }\n\n /**\n * Build an XPath context for evaluating a predicate or anchor call.\n *\n * @param {Node} node - Context node\n * @param {number} position - Context position\n * @param {number} size - Context size\n * @returns {XPathContext} The evaluation context\n */\n context(node, position, size) {\n if (!this.variables) {\n this.variables = this.host?.xpathVariables ?? {\n ...this.host?.variables,\n ...this.host?.parameters,\n };\n }\n return new XPathContext(\n node,\n position,\n size,\n this.variables,\n this.namespaces,\n this.host,\n );\n }\n\n /**\n * Build a cheap XPath context for node tests (namespaces only).\n *\n * @param {Node} node - Context node\n * @returns {XPathContext} The evaluation context\n */\n testContext(node) {\n return new XPathContext(\n node,\n 1,\n 1,\n EMPTY_VARIABLES,\n this.namespaces,\n this.host,\n );\n }\n}\n", "/**\n * XSLT 1.0 pattern matching (section 5.2).\n *\n * A pattern is a union of location path patterns. Each alternative is an\n * absolute or relative location path that only uses the child and attribute\n * axes and the `/` and `//` separators, optionally anchored on an `id()` or\n * `key()` call. Patterns are parsed once with the XPath parser and the\n * compiled form is cached per pattern string.\n *\n * Matching runs right to left: the node is tested against the last step, then\n * its parent (for `/`) or any ancestor (for `//`) against the previous step.\n * This costs O(depth) per node instead of evaluating the pattern as an\n * expression from the parent, which is O(siblings) and made\n * `xsl:apply-templates` quadratic in the number of children.\n *\n * Predicates follow the \"position in the context of the parent\" rule: a\n * predicate is evaluated with the node's position among its siblings that\n * pass the step's node test and the preceding predicates. That sibling list is\n * only built when the predicate uses `position()`/`last()` or evaluates to a\n * number, and it is cached per parent until {@link PatternMatcher#reset}.\n *\n * @module xslt/patterns\n */\n\nimport { childAxis } from \"../xpath/axes.js\";\nimport { ROOT, compilePattern } from \"./patternCompiler.js\";\nimport {\n MatchScope,\n isNamespaceDeclaration,\n isRoot,\n parentOf,\n rootOf,\n} from \"./matchScope.js\";\n\nexport { compilePattern };\n\n/**\n * Matches nodes against XSLT patterns with an XPath evaluator.\n */\nexport class PatternMatcher {\n /**\n * @param {import('../xpath/evaluator.js').XPathEvaluator} evaluator - Evaluator used for node tests, predicates and anchors\n */\n constructor(evaluator) {\n this.evaluator = evaluator;\n this.compiled = new Map();\n this.positions = new WeakMap();\n this.anchors = new WeakMap();\n }\n\n /**\n * Forget cached sibling positions and anchor node-sets, e.g. before a new\n * transformation (the source tree may have been modified in between).\n *\n * @returns {void}\n */\n reset() {\n this.positions = new WeakMap();\n this.anchors = new WeakMap();\n }\n\n /**\n * Compile a pattern, reusing the cached form.\n *\n * @param {string} pattern - The XSLT pattern\n * @returns {object[]} The compiled alternatives\n * @throws {Error} When the string is not a valid pattern (XSLT 1.0\n * section 5.2); the message names the pattern\n */\n compile(pattern) {\n let compiled = this.compiled.get(pattern);\n if (!compiled) {\n try {\n compiled = compilePattern(pattern);\n } catch (error) {\n throw new Error(`Invalid pattern \"${pattern}\": ${error.message}`, {\n cause: error,\n });\n }\n this.compiled.set(pattern, compiled);\n }\n return compiled;\n }\n\n /**\n * Test whether a node matches a pattern.\n *\n * @param {Node} node - The candidate node\n * @param {string} pattern - The XSLT pattern\n * @param {object|null} [host] - XSLT context supplying variables and namespaces\n * @param {Object<string, string>} [namespaces] - Prefix bindings overriding the host's\n * @returns {boolean} True when the node matches any alternative\n *\n * @example\n * matcher.matches(titleElement, 'chapter/title', xsltContext); // true\n */\n matches(node, pattern, host = null, namespaces = undefined) {\n const scope = new MatchScope(host, namespaces);\n for (const alternative of this.compile(pattern)) {\n if (this.matchesAlternative(node, alternative, scope)) return true;\n }\n return false;\n }\n\n /**\n * @param {Node} node - Candidate node\n * @param {object} alternative - Compiled alternative\n * @param {MatchScope} scope - Match state\n * @returns {boolean} Whether the node matches the alternative\n */\n matchesAlternative(node, alternative, scope) {\n const { anchor, steps } = alternative;\n if (steps.length > 0) {\n return this.matchesStep(node, alternative, steps.length - 1, scope);\n }\n if (anchor === ROOT) return isRoot(node);\n return this.anchorNodes(anchor, node, scope).has(node);\n }\n\n /**\n * Match a node against step `index`, then the rest of the path leftwards.\n *\n * @param {Node} node - Candidate node\n * @param {object} alternative - Compiled alternative\n * @param {number} index - Index of the step to test\n * @param {MatchScope} scope - Match state\n * @returns {boolean} Whether the node matches steps 0..index\n */\n matchesStep(node, alternative, index, scope) {\n const step = alternative.steps[index];\n if (!this.testStep(node, step, scope)) return false;\n\n const parent = parentOf(node);\n if (step.separator === null) return true;\n\n let accepts;\n if (index > 0) {\n accepts = (candidate) =>\n this.matchesStep(candidate, alternative, index - 1, scope);\n } else if (alternative.anchor === ROOT) {\n accepts = isRoot;\n } else {\n const anchors = this.anchorNodes(alternative.anchor, node, scope);\n accepts = (candidate) => anchors.has(candidate);\n }\n\n if (step.separator === \"/\") return parent !== null && accepts(parent);\n for (let ancestor = parent; ancestor; ancestor = parentOf(ancestor)) {\n if (accepts(ancestor)) return true;\n }\n return false;\n }\n\n /**\n * Test a node against the axis, node test and predicates of one step.\n *\n * @param {Node} node - Candidate node\n * @param {object} step - Compiled step\n * @param {MatchScope} scope - Match state\n * @returns {boolean} Whether the node satisfies the step\n */\n testStep(node, step, scope) {\n const type = node.nodeType;\n if (step.axis === \"attribute\") {\n if (type !== 2 || isNamespaceDeclaration(node)) return false;\n } else if (type === 2 || type === 9 || type === 11 || type === 13) {\n // Patterns only use the child and attribute axes: roots, attributes\n // and namespace nodes are never children\n return false;\n }\n if (\n !this.evaluator.matchNodeTest(\n step.nodeTest,\n node,\n scope.testContext(node),\n )\n ) {\n return false;\n }\n\n for (let k = 0; k < step.predicates.length; k++) {\n if (!this.testPredicate(node, step, k, scope)) return false;\n }\n return true;\n }\n\n /**\n * Evaluate predicate `k` of a step for a node.\n *\n * @param {Node} node - Candidate node\n * @param {object} step - Compiled step\n * @param {number} k - Predicate index\n * @param {MatchScope} scope - Match state\n * @returns {boolean} Whether the predicate holds\n */\n testPredicate(node, step, k, scope) {\n const predicate = step.predicates[k];\n let position = 1;\n let size = 1;\n\n if (predicate.positional) {\n ({ position, size } = this.siblingPosition(node, step, k, scope));\n }\n\n const value = this.evaluator.evaluate(\n predicate.expr,\n scope.context(node, position, size),\n );\n if (typeof value !== \"number\") return this.evaluator.toBoolean(value);\n if (!predicate.positional) {\n position = this.siblingPosition(node, step, k, scope).position;\n }\n return value === position;\n }\n\n /**\n * Position and size of a node among its siblings that pass the step's node\n * test and its predicates before `k`. Cached per parent and predicate.\n *\n * @param {Node} node - Candidate node\n * @param {object} step - Compiled step\n * @param {number} k - Predicate index\n * @param {MatchScope} scope - Match state\n * @returns {{position: number, size: number}} Context position and size\n */\n siblingPosition(node, step, k, scope) {\n const parent = parentOf(node);\n if (!parent) return { position: 1, size: 1 };\n\n let byPredicate = this.positions.get(parent);\n if (!byPredicate) {\n byPredicate = new Map();\n this.positions.set(parent, byPredicate);\n }\n\n const predicate = step.predicates[k];\n let entry = byPredicate.get(predicate);\n if (!entry) {\n const nodes = this.candidateSiblings(parent, step, k, scope);\n const index = new Map();\n nodes.forEach((sibling, i) => index.set(sibling, i + 1));\n entry = { index, size: nodes.length };\n byPredicate.set(predicate, entry);\n }\n\n return { position: entry.index.get(node) ?? 0, size: entry.size };\n }\n\n /**\n * Siblings selected by a step before predicate `k` is applied.\n *\n * @param {Node} parent - The common parent\n * @param {object} step - Compiled step\n * @param {number} k - Predicate index\n * @param {MatchScope} scope - Match state\n * @returns {Node[]} The candidate siblings in document order\n */\n candidateSiblings(parent, step, k, scope) {\n const all =\n step.axis === \"attribute\"\n ? Array.from(parent.attributes || [])\n : childAxis(parent);\n let nodes = all.filter(\n (sibling) =>\n (sibling.nodeType === 2) === (step.axis === \"attribute\") &&\n !(sibling.nodeType === 2 && isNamespaceDeclaration(sibling)) &&\n this.evaluator.matchNodeTest(\n step.nodeTest,\n sibling,\n scope.testContext(sibling),\n ),\n );\n const base = scope.context(parent, 1, 1);\n for (let i = 0; i < k; i++) {\n nodes = this.evaluator.filterByPredicate(nodes, step.predicates[i], base);\n }\n return nodes;\n }\n\n /**\n * The nodes selected by the `id()`/`key()` anchor of a pattern relative to\n * a node. Anchors only have literal arguments (see patternCompiler.js), so\n * the set only depends on the node's tree and the prefixes in scope: it is\n * computed once per root until {@link PatternMatcher#reset}, instead of\n * once per candidate node.\n *\n * @param {object} anchor - Function call AST\n * @param {Node} node - Node providing the document\n * @param {MatchScope} scope - Match state\n * @returns {Set<Node>} The anchor nodes\n */\n anchorNodes(anchor, node, scope) {\n const root = rootOf(node);\n let byAnchor = this.anchors.get(root);\n if (!byAnchor) {\n byAnchor = new Map();\n this.anchors.set(root, byAnchor);\n }\n let byScope = byAnchor.get(anchor);\n if (!byScope) {\n byScope = new Map();\n byAnchor.set(anchor, byScope);\n }\n let nodes = byScope.get(scope.namespaces);\n if (!nodes) {\n nodes = this.evaluateAnchor(anchor, node, scope);\n byScope.set(scope.namespaces, nodes);\n }\n return nodes;\n }\n\n /**\n * Evaluate the `id()`/`key()` anchor of a pattern relative to a node.\n *\n * @param {object} anchor - Function call AST\n * @param {Node} node - Node providing the document\n * @param {MatchScope} scope - Match state\n * @returns {Set<Node>} The anchor nodes\n */\n evaluateAnchor(anchor, node, scope) {\n const result = this.evaluator.evaluate(anchor, scope.context(node, 1, 1));\n return new Set(Array.isArray(result) ? result : []);\n }\n}\n", "/**\n * Installation of the XsltEngine method groups.\n *\n * The engine is split by concern into modules that each export a plain\n * object of methods (`this` is the engine). They are installed on\n * `XsltEngine.prototype`, so every method stays callable on the engine under\n * its old name and the instruction dispatch (`this[method](...)`) costs no\n * extra stack frame per recursion level.\n */\n\n/**\n * Define the methods (and accessors) of each group on a prototype, as\n * non-enumerable properties like class methods.\n *\n * @param {object} prototype - The class prototype receiving the methods\n * @param {...object} groups - Objects of methods, getters included\n * @returns {void}\n * @throws {Error} When two groups define the same name\n */\nexport function installMethods(prototype, ...groups) {\n for (const group of groups) {\n const descriptors = Object.getOwnPropertyDescriptors(group);\n for (const [name, descriptor] of Object.entries(descriptors)) {\n if (Object.hasOwn(prototype, name)) {\n throw new Error(`Engine method defined twice: ${name}`);\n }\n Object.defineProperty(prototype, name, {\n ...descriptor,\n enumerable: false,\n });\n }\n }\n}\n", "/**\n * XML names (XML 1.0 fifth edition, section 2.3) and qualified names\n * (Namespaces in XML 1.0, section 4).\n *\n * Used to validate names computed at run time by `xsl:element` and\n * `xsl:attribute` (XSLT 1.0 sections 7.1.2 and 7.1.3) before they reach the\n * DOM, so an invalid name is reported instead of producing malformed output.\n *\n * @module xslt/qname\n */\n\n\"use strict\";\n\n/** NameStartChar code point ranges, without \":\" (production [4]). */\nconst NAME_START_RANGES = [\n [0x41, 0x5a], // A-Z\n [0x5f, 0x5f], // _\n [0x61, 0x7a], // a-z\n [0xc0, 0xd6],\n [0xd8, 0xf6],\n [0xf8, 0x2ff],\n [0x370, 0x37d],\n [0x37f, 0x1fff],\n [0x200c, 0x200d],\n [0x2070, 0x218f],\n [0x2c00, 0x2fef],\n [0x3001, 0xd7ff],\n [0xf900, 0xfdcf],\n [0xfdf0, 0xfffd],\n [0x10000, 0xeffff],\n];\n\n/** Extra NameChar code point ranges (production [4a]). */\nconst NAME_CHAR_RANGES = [\n [0x2d, 0x2e], // - .\n [0x30, 0x39], // 0-9\n [0xb7, 0xb7],\n [0x300, 0x36f],\n [0x203f, 0x2040],\n];\n\n/**\n * Whether a code point lies in one of the ranges.\n *\n * @param {number} code - A Unicode code point\n * @param {number[][]} ranges - Inclusive `[first, last]` ranges\n * @returns {boolean} True when the code point is in a range\n */\nfunction inRanges(code, ranges) {\n return ranges.some(([first, last]) => code >= first && code <= last);\n}\n\n/**\n * Whether a string is an NCName (a name without a colon).\n *\n * @param {string} name - The candidate name\n * @returns {boolean} True for a valid NCName\n *\n * @example\n * isNcName(\"item-1\"); // true\n * isNcName(\"1item\"); // false\n */\nexport function isNcName(name) {\n let first = true;\n for (const char of name) {\n const code = char.codePointAt(0);\n const valid =\n inRanges(code, NAME_START_RANGES) ||\n (!first && inRanges(code, NAME_CHAR_RANGES));\n if (!valid) return false;\n first = false;\n }\n return !first;\n}\n\n/**\n * Whether a string is a QName: an NCName, optionally prefixed by another\n * NCName and a single colon.\n *\n * @param {string} name - The candidate name\n * @returns {boolean} True for a valid QName\n *\n * @example\n * isQName(\"xl:href\"); // true\n * isQName(\"a:b:c\"); // false\n */\nexport function isQName(name) {\n const parts = name.split(\":\");\n return parts.length <= 2 && parts.every(isNcName);\n}\n", "/**\n * In-scope namespaces of stylesheet elements.\n *\n * Prefixes in XPath expressions, patterns and QName-valued attributes resolve\n * against the namespace declarations in scope on the element that carries\n * them (XSLT 1.0 section 2.4), not against one stylesheet-wide table: a\n * declaration on `xsl:template` or on a literal result element applies inside\n * it only, and an included stylesheet may bind a prefix differently from the\n * including one. The same bindings are the namespace nodes that literal\n * result elements copy to the result tree (section 7.1.1), minus the XSLT\n * namespace and the excluded and extension prefixes.\n *\n * Every map is computed once per element and cached; an element without\n * declarations of its own shares its parent's (frozen) map, so identical\n * scopes can be recognised by identity.\n *\n * @module xslt/stylesheetNamespaces\n */\n\n\"use strict\";\n\nimport { XSLT_NAMESPACE } from \"./elements.js\";\n\n/** Namespace of `xmlns` attributes. */\nexport const XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\n\n/** Namespace bound to the `xml` prefix. */\nexport const XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\n\n/** The scope above the stylesheet document element. */\nconst EMPTY_SCOPE = Object.freeze({});\n\n/** Namespaces excluded above the stylesheet document element. */\nconst BASE_EXCLUSIONS = new Set([XSLT_NAMESPACE]);\n\n/** No extension namespaces, above the stylesheet document element. */\nconst NO_EXTENSIONS = new Set();\n\nconst scopes = new WeakMap();\nconst exclusions = new WeakMap();\nconst extensions = new WeakMap();\nconst namespaceNodes = new WeakMap();\n\n/**\n * The prefix a namespace declaration attribute declares, or null when the\n * attribute is not a declaration.\n *\n * @param {Attr} attribute - Any attribute\n * @returns {string|null} The prefix, \"\" for a default namespace declaration\n */\nexport function declaredPrefix(attribute) {\n const name = attribute.name;\n if (name === \"xmlns\") return \"\";\n if (name.startsWith(\"xmlns:\")) return name.slice(6);\n return null;\n}\n\n/**\n * The namespace bindings in scope on a stylesheet element.\n *\n * @param {Node|null} node - A stylesheet element (other nodes have no scope)\n * @returns {Readonly<Object<string, string>>} URIs by prefix; \"\" holds the\n * default namespace, an empty URI means \"undeclared\"\n *\n * @example\n * inScopeNamespaces(templateElement).f; // \"urn:f\"\n */\nexport function inScopeNamespaces(node) {\n if (node?.nodeType !== 1) return EMPTY_SCOPE;\n\n let scope = scopes.get(node);\n if (scope) return scope;\n\n const parentScope = inScopeNamespaces(node.parentNode);\n let own = null;\n for (const attribute of node.attributes) {\n const prefix = declaredPrefix(attribute);\n if (prefix === null) continue;\n own ??= {};\n own[prefix] = attribute.value;\n }\n\n scope = own ? Object.freeze({ ...parentScope, ...own }) : parentScope;\n scopes.set(node, scope);\n return scope;\n}\n\n/**\n * Split an XSLT attribute holding whitespace separated prefixes.\n *\n * @param {string|null} value - e.g. `\"a b #default\"`\n * @returns {string[]} The prefixes, \"\" standing for `#default`\n */\nfunction prefixList(value) {\n if (!value) return [];\n return value\n .split(/[ \\t\\r\\n]+/)\n .filter(Boolean)\n .map((prefix) => (prefix === \"#default\" ? \"\" : prefix));\n}\n\n/** Attributes whose prefixes are excluded from the result tree. */\nconst EXCLUSION_ATTRIBUTES = [\n \"exclude-result-prefixes\",\n \"extension-element-prefixes\",\n];\n\n/** Attributes declaring extension namespaces (XSLT 1.0 section 14.1). */\nconst EXTENSION_ATTRIBUTES = [\"extension-element-prefixes\"];\n\n/**\n * Read prefix list attributes of one stylesheet element: unqualified on\n * `xsl:stylesheet`, `xsl:`-qualified on literal result elements.\n *\n * @param {Element} element - A stylesheet element\n * @param {string[]} attributes - Local names of the attributes to read\n * @returns {Array<{prefix: string, attribute: string}>} Prefixes declared on\n * this element, with the attribute declaring each\n */\nfunction ownPrefixes(element, attributes) {\n const isXslt = element.namespaceURI === XSLT_NAMESPACE;\n const read = (localName) =>\n isXslt\n ? element.getAttribute(localName)\n : element.getAttributeNS(XSLT_NAMESPACE, localName);\n return attributes.flatMap((attribute) =>\n prefixList(read(attribute)).map((prefix) => ({ prefix, attribute })),\n );\n}\n\n/**\n * Namespace URIs named by prefix list attributes on a stylesheet element or\n * its ancestors, cached per element.\n *\n * @param {Node|null} node - A stylesheet element\n * @param {object} kind - What to collect\n * @param {string[]} kind.attributes - The prefix list attributes\n * @param {WeakMap<Element, Set<string>>} kind.cache - Results by element\n * @param {Set<string>} kind.base - The set above the document element\n * @param {boolean} kind.report - Whether undeclared prefixes are reported\n * @returns {Set<string>} The namespace URIs\n */\nfunction declaredNamespaces(node, kind) {\n if (node?.nodeType !== 1) return kind.base;\n\n let found = kind.cache.get(node);\n if (found) return found;\n\n found = declaredNamespaces(node.parentNode, kind);\n const prefixes = ownPrefixes(node, kind.attributes);\n if (prefixes.length > 0) {\n const scope = inScopeNamespaces(node);\n found = new Set(found);\n for (const { prefix, attribute } of prefixes) {\n const uri = resolvePrefix(scope, prefix);\n if (uri) {\n found.add(uri);\n } else if (kind.report) {\n // An error in XSLT 1.0 (section 7.1.1) that libxslt reports and\n // recovers from; reported once, as the result is cached per element\n console.warn(\n `XSLT: ${attribute}: undefined namespace prefix \"${prefix || \"#default\"}\" is ignored`,\n );\n }\n }\n }\n kind.cache.set(node, found);\n return found;\n}\n\n/** Excluded namespaces: excluded and extension prefixes, plus XSLT. */\nconst EXCLUDED = {\n attributes: EXCLUSION_ATTRIBUTES,\n cache: exclusions,\n base: BASE_EXCLUSIONS,\n report: true,\n};\n\n/** Extension namespaces (reported through EXCLUDED already). */\nconst EXTENSIONS = {\n attributes: EXTENSION_ATTRIBUTES,\n cache: extensions,\n base: NO_EXTENSIONS,\n report: false,\n};\n\n/**\n * Namespace URIs excluded from the result tree around a stylesheet element:\n * the XSLT namespace, plus the namespaces of every excluded or extension\n * prefix declared on the element or its ancestors. A prefix that is not\n * declared (including `#all`, which XSLT 1.0 does not know) is reported with\n * console.warn and ignored.\n *\n * @param {Node|null} node - A stylesheet element\n * @returns {Set<string>} Excluded namespace URIs\n */\nfunction excludedNamespaces(node) {\n return declaredNamespaces(node, EXCLUDED);\n}\n\n/**\n * Whether a stylesheet element is an extension element: an element in a\n * namespace that an `extension-element-prefixes` attribute on it or on an\n * ancestor declares as an extension namespace (XSLT 1.0 section 14.1).\n *\n * @param {Element} element - A stylesheet element that is not in the XSLT namespace\n * @returns {boolean} True for extension elements\n *\n * @example\n * // <xsl:stylesheet xmlns:e=\"urn:e\" extension-element-prefixes=\"e\">\n * isExtensionElement(eElement); // true\n */\nexport function isExtensionElement(element) {\n const uri = element.namespaceURI;\n if (!uri) return false;\n // Resolving the exclusions first reports undeclared prefixes once\n excludedNamespaces(element);\n return declaredNamespaces(element, EXTENSIONS).has(uri);\n}\n\n/**\n * The namespace nodes a literal result element copies to the result tree\n * (XSLT 1.0 section 7.1.1).\n *\n * @param {Element} node - The literal result element\n * The list is shared by every element with the same scope and exclusions,\n * so equal lists can be compared by identity.\n *\n * @param {Element} node - The literal result element\n * @returns {Array<[string, string]>} `[prefix, uri]` pairs, \"\" for the default namespace\n *\n * @example\n * resultNamespaceNodes(literalElement); // [[\"q\", \"urn:q\"]]\n */\nexport function resultNamespaceNodes(node) {\n const scope = inScopeNamespaces(node);\n const excluded = excludedNamespaces(node);\n\n let byExclusions = namespaceNodes.get(scope);\n if (!byExclusions) {\n byExclusions = new WeakMap();\n namespaceNodes.set(scope, byExclusions);\n }\n let nodes = byExclusions.get(excluded);\n if (!nodes) {\n nodes = Object.entries(scope).filter(\n ([, uri]) => uri !== \"\" && !excluded.has(uri),\n );\n byExclusions.set(excluded, nodes);\n }\n return nodes;\n}\n\n/**\n * Resolve a QName prefix against a scope.\n *\n * @param {Object<string, string>} scope - Bindings from {@link inScopeNamespaces}\n * @param {string} prefix - The prefix, \"\" for the default namespace\n * @returns {string|null} The namespace URI, or null when unbound\n */\nexport function resolvePrefix(scope, prefix) {\n if (prefix === \"xml\") return XML_NAMESPACE;\n return Object.hasOwn(scope, prefix) && scope[prefix] !== \"\"\n ? scope[prefix]\n : null;\n}\n", "/**\n * Namespaces of result tree elements and attributes.\n *\n * - `xsl:element` and `xsl:attribute` resolve the prefix of their computed\n * name against the namespaces in scope on the instruction, and an\n * unprefixed `xsl:element` name takes the default namespace (XSLT 1.0\n * sections 7.1.2 and 7.1.3); a `namespace` attribute wins over both.\n * - An attribute in a namespace needs a prefix, so one is generated (`ns_1`,\n * `ns_2`, ..., the names libxslt uses) when the name has none, its prefix\n * is `xmlns` or already bound to another namespace on the element. The XML\n * namespace always gets the `xml` prefix.\n * - Literal result elements copy the namespace nodes in scope in the\n * stylesheet (section 7.1.1) as `xmlns` attributes; declarations the parent\n * result element already carries are not repeated.\n *\n * @module xslt/resultNamespaces\n */\n\n\"use strict\";\n\nimport {\n XMLNS_NAMESPACE,\n XML_NAMESPACE,\n resolvePrefix,\n resultNamespaceNodes,\n} from \"./stylesheetNamespaces.js\";\n\n/** Stylesheet scope each literal result element was created in. */\nconst createdInScope = new WeakMap();\n\n/**\n * Split a QName into prefix and local part.\n *\n * @param {string} qname - e.g. `xl:href` or `p`\n * @returns {{prefix: string, localName: string}} The parts, prefix \"\" when absent\n */\nexport function splitQName(qname) {\n const colon = qname.indexOf(\":\");\n return colon < 0\n ? { prefix: \"\", localName: qname }\n : { prefix: qname.slice(0, colon), localName: qname.slice(colon + 1) };\n}\n\n/**\n * Compute the expanded name of an element created by `xsl:element`.\n *\n * @param {string} qname - The evaluated `name` attribute\n * @param {string|null} namespace - The evaluated `namespace` attribute, null when absent\n * @param {Object<string, string>} scope - Namespaces in scope on the instruction\n * @returns {{namespaceUri: (string|null), qname: string}} The element name\n *\n * @example\n * elementName(\"p\", null, { \"\": \"http://www.w3.org/1999/xhtml\" });\n * // { namespaceUri: \"http://www.w3.org/1999/xhtml\", qname: \"p\" }\n */\nexport function elementName(qname, namespace, scope) {\n const { prefix, localName } = splitQName(qname);\n if (namespace !== null) {\n // An element in no namespace cannot keep a prefix, as for attributes\n return namespace\n ? { namespaceUri: namespace, qname }\n : { namespaceUri: null, qname: localName };\n }\n return { namespaceUri: resolvePrefix(scope, prefix), qname };\n}\n\n/**\n * Compute the expanded name of an attribute created by `xsl:attribute`.\n * Unprefixed attribute names are in no namespace unless `namespace` says so.\n *\n * @param {string} qname - The evaluated `name` attribute\n * @param {string|null} namespace - The evaluated `namespace` attribute, null when absent\n * @param {Object<string, string>} scope - Namespaces in scope on the instruction\n * @returns {{namespaceUri: (string|null), qname: string}} The attribute name\n */\nexport function attributeName(qname, namespace, scope) {\n const { prefix, localName } = splitQName(qname);\n if (namespace !== null) {\n return namespace\n ? { namespaceUri: namespace, qname }\n : { namespaceUri: null, qname: localName };\n }\n return { namespaceUri: prefix ? resolvePrefix(scope, prefix) : null, qname };\n}\n\n/**\n * Whether a prefix may be used on an element for a namespace: it must not be\n * bound to another namespace by the element name or by another attribute.\n *\n * @param {Element} element - The result element\n * @param {string} prefix - A candidate prefix\n * @param {string} uri - The namespace the prefix should denote\n * @returns {boolean} True when the prefix is free or already bound to `uri`\n */\nfunction prefixAvailable(element, prefix, uri) {\n if (element.prefix === prefix && element.namespaceURI !== uri) return false;\n for (const attribute of element.attributes) {\n if (attribute.prefix === prefix && attribute.namespaceURI !== uri) {\n return false;\n }\n if (\n attribute.namespaceURI === XMLNS_NAMESPACE &&\n attribute.localName === prefix &&\n attribute.value !== uri\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Pick the prefix of a namespaced attribute on an element.\n *\n * @param {Element} element - The result element\n * @param {string} prefix - The prefix of the requested name, \"\" when none\n * @param {string} uri - The attribute namespace\n * @returns {string} A prefix bound to nothing else on the element\n */\nfunction attributePrefix(element, prefix, uri) {\n if (uri === XML_NAMESPACE) return \"xml\";\n const reserved = prefix === \"xmlns\" || prefix === \"xml\";\n if (prefix && !reserved && prefixAvailable(element, prefix, uri)) {\n return prefix;\n }\n let index = 1;\n while (!prefixAvailable(element, `ns_${index}`, uri)) index++;\n return `ns_${index}`;\n}\n\n/**\n * Add (or replace) an attribute of a result element.\n *\n * @param {Element} element - The result element\n * @param {{namespaceUri: (string|null), qname: string}} name - Expanded name\n * @param {string} value - The attribute value\n * @returns {void}\n *\n * @example\n * setResultAttribute(el, { namespaceUri: \"urn:x\", qname: \"a\" }, \"1\"); // ns_1:a=\"1\"\n */\nexport function setResultAttribute(element, name, value) {\n const { prefix, localName } = splitQName(name.qname);\n if (!name.namespaceUri) {\n if (localName === \"xmlns\") return;\n element.setAttribute(localName, value);\n return;\n }\n // Namespace declarations are not attributes\n if (name.qname === \"xmlns\" || name.namespaceUri === XMLNS_NAMESPACE) return;\n\n const existing = element.getAttributeNodeNS(name.namespaceUri, localName);\n if (existing) {\n existing.value = value;\n return;\n }\n const chosen = attributePrefix(element, prefix, name.namespaceUri);\n element.setAttributeNS(name.namespaceUri, `${chosen}:${localName}`, value);\n}\n\n/**\n * Copy the namespace nodes of a literal result element onto its result\n * element, skipping the declarations already in effect on the parent.\n *\n * @param {Element} element - The new result element\n * @param {Element} stylesheetNode - The literal result element\n * @param {Node} parent - The result node receiving `element`\n * @param {(uri: string) => boolean} isAliased - Whether a URI is the\n * stylesheet side of an `xsl:namespace-alias` (such namespaces are replaced,\n * never copied)\n * @returns {void}\n */\nexport function copyLiteralNamespaces(\n element,\n stylesheetNode,\n parent,\n isAliased,\n) {\n const nodes = resultNamespaceNodes(stylesheetNode);\n if (nodes.length === 0) return;\n createdInScope.set(element, nodes);\n if (createdInScope.get(parent) === nodes) return;\n\n const parentElement = parent.nodeType === 1 ? parent : null;\n for (const [prefix, uri] of nodes) {\n if (isAliased(uri)) continue;\n if (parentElement?.lookupNamespaceURI(prefix || null) === uri) continue;\n if ((element.prefix ?? \"\") === prefix && element.namespaceURI !== uri) {\n continue;\n }\n element.setAttributeNS(\n XMLNS_NAMESPACE,\n prefix ? `xmlns:${prefix}` : \"xmlns\",\n uri,\n );\n }\n}\n\n/**\n * Copy the namespace declarations of a source element (its own `xmlns`\n * attributes) onto a copy, as `xsl:copy` and `xsl:copy-of` do.\n *\n * @param {Element} source - The copied element\n * @param {Element} copy - The result element\n * @returns {void}\n */\nexport function copyNamespaceDeclarations(source, copy) {\n for (const attribute of source.attributes) {\n if (attribute.namespaceURI !== XMLNS_NAMESPACE) continue;\n const prefix = attribute.prefix ? attribute.localName : \"\";\n if (\n (copy.prefix ?? \"\") === prefix &&\n copy.namespaceURI !== attribute.value\n ) {\n continue;\n }\n copy.setAttributeNS(XMLNS_NAMESPACE, attribute.name, attribute.value);\n }\n}\n", "/**\n * QName-valued attributes of `xsl:output` (XSLT 1.0 section 16).\n *\n * `cdata-section-elements` lists QNames that are expanded with the namespace\n * declarations in scope on the `xsl:output` element, the default namespace\n * included for unprefixed names (section 16.1). The serializer then compares\n * expanded names, so the prefixes used in the result do not matter.\n *\n * @module xslt/outputNames\n */\n\n\"use strict\";\n\nimport { isQName } from \"./qname.js\";\nimport { splitQName } from \"./resultNamespaces.js\";\nimport { resolvePrefix } from \"./stylesheetNamespaces.js\";\n\n/**\n * @typedef {{namespaceUri: (string|null), localName: string}} ExpandedName\n */\n\n/**\n * Expand the QNames of a `cdata-section-elements` attribute and add them to\n * the names already declared (several xsl:output elements are merged, so the\n * lists are united). Invalid names and undeclared prefixes are reported and\n * skipped.\n *\n * @param {string} value - Whitespace separated QNames\n * @param {Object<string, string>} scope - Namespaces in scope on xsl:output\n * @param {ExpandedName[]} declared - Names declared by earlier xsl:output elements\n * @param {(message: string) => void} warn - Reports a name that is skipped\n * @returns {ExpandedName[]} The union, without duplicates\n *\n * @example\n * cdataSectionNames(\"p:c d\", { p: \"urn:p\" }, [], console.warn);\n * // [{ namespaceUri: \"urn:p\", localName: \"c\" },\n * // { namespaceUri: null, localName: \"d\" }]\n */\nexport function cdataSectionNames(value, scope, declared, warn) {\n const names = [...declared];\n const seen = new Set(names.map((n) => `{${n.namespaceUri}}${n.localName}`));\n\n for (const qname of value.split(/[ \\t\\r\\n]+/).filter(Boolean)) {\n const { prefix, localName } = splitQName(qname);\n const namespaceUri = resolvePrefix(scope, prefix);\n if (!isQName(qname) || (prefix && !namespaceUri)) {\n warn(\n `xsl:output cdata-section-elements: \"${qname}\" is not a QName with a declared prefix and is ignored`,\n );\n continue;\n }\n const key = `{${namespaceUri}}${localName}`;\n if (seen.has(key)) continue;\n seen.add(key);\n names.push({ namespaceUri, localName });\n }\n return names;\n}\n", "/**\n * The xsl:output declaration and the engine's output settings\n * (XSLT 1.0 section 16).\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { cdataSectionNames } from \"../outputNames.js\";\nimport { inScopeNamespaces } from \"../stylesheetNamespaces.js\";\n\n/**\n * The xsl:output attributes copied as they are, with their setting names.\n * A later non-empty attribute replaces the setting.\n */\nconst OUTPUT_ATTRIBUTES = Object.freeze([\n [\"method\", \"method\"],\n [\"version\", \"version\"],\n [\"encoding\", \"encoding\"],\n [\"standalone\", \"standalone\"],\n [\"indent\", \"indent\"],\n [\"omit-xml-declaration\", \"omitXmlDeclaration\"],\n [\"doctype-public\", \"doctypePublic\"],\n [\"doctype-system\", \"doctypeSystem\"],\n [\"media-type\", \"mediaType\"],\n]);\n\n/**\n * The output settings of a stylesheet without xsl:output.\n *\n * A null method means \"not declared\": the serializer then picks html or xml\n * from the result tree (XSLT 1.0 section 16). An undefined indent is \"no\"\n * too, except for the line breaks libxslt writes between comments and the\n * document element (see serializer/settings.js).\n *\n * @returns {object} New default output settings\n */\nexport function createOutputSettings() {\n return {\n method: null,\n version: \"1.0\",\n encoding: \"UTF-8\",\n standalone: null,\n indent: undefined,\n omitXmlDeclaration: \"no\",\n doctypePublic: null,\n doctypeSystem: null,\n mediaType: null,\n cdataSectionElements: [],\n };\n}\n\nexport const outputDeclarationMethods = {\n /**\n * Merge an xsl:output element into the output settings (XSLT 1.0\n * section 16): a later attribute wins, except cdata-section-elements whose\n * expanded names are united.\n *\n * @param {Element} node - The xsl:output element\n * @returns {void}\n */\n processOutput(node) {\n for (const [attribute, setting] of OUTPUT_ATTRIBUTES) {\n const value = node.getAttribute(attribute);\n if (value) this.outputSettings[setting] = value;\n }\n\n const cdataElements = node.getAttribute(\"cdata-section-elements\");\n if (cdataElements) {\n this.outputSettings.cdataSectionElements = cdataSectionNames(\n cdataElements,\n inScopeNamespaces(node),\n this.outputSettings.cdataSectionElements,\n (message) => this.warnOnce(message),\n );\n }\n },\n};\n", "/**\n * URI helpers for XSLT stylesheet and document resolution.\n *\n * Kept deliberately small and dependency free: the engine only needs enough\n * URI arithmetic to turn a relative `href` into something a host supplied\n * loader can resolve, plus fragment removal for the `document()` function.\n */\n\n\"use strict\";\n\n/** Matches an absolute URI such as `http://`, `https://` or `file://`. */\nconst ABSOLUTE_URI_PATTERN = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;\n\n/**\n * Resolve a possibly relative URI against a base URI.\n *\n * Absolute URIs (with a scheme) and root relative URIs (starting with `/`)\n * are returned untouched, as is any URI when no base is available.\n *\n * @param {string} href - The URI to resolve\n * @param {string} [baseUri] - The base URI, typically the stylesheet location\n * @returns {string} The resolved URI\n *\n * @example\n * resolveUri('common.xsl', '/styles/main.xsl'); // '/styles/common.xsl'\n */\nexport function resolveUri(href, baseUri) {\n if (!href) return href;\n if (!baseUri || isAbsoluteUri(href) || href.startsWith(\"/\")) {\n return href;\n }\n\n const lastSlash = baseUri.lastIndexOf(\"/\");\n const baseDir = lastSlash >= 0 ? baseUri.substring(0, lastSlash + 1) : \"\";\n\n return baseDir + href;\n}\n\n/**\n * Check whether a URI is absolute (has a scheme).\n *\n * @param {string} uri - The URI to inspect\n * @returns {boolean} True when the URI carries a scheme\n *\n * @example\n * isAbsoluteUri('https://example.com/a.xml'); // true\n */\nexport function isAbsoluteUri(uri) {\n return ABSOLUTE_URI_PATTERN.test(uri);\n}\n\n/**\n * Remove a fragment identifier from a URI.\n *\n * XSLT 1.0 leaves the meaning of fragment identifiers passed to `document()`\n * implementation defined; this processor ignores them.\n *\n * @param {string} uri - The URI, possibly carrying a `#fragment`\n * @returns {string} The URI without its fragment\n *\n * @example\n * stripFragment('data.xml#section'); // 'data.xml'\n */\nexport function stripFragment(uri) {\n if (typeof uri !== \"string\") return \"\";\n const hash = uri.indexOf(\"#\");\n return hash === -1 ? uri : uri.substring(0, hash);\n}\n", "/**\n * XML parsing through whatever DOM implementation is available.\n *\n * Stylesheets pulled in by xsl:import/xsl:include and documents returned by a\n * `document()` loader may be XML strings. They are parsed with, in order: a\n * DOMParser given to the engine (`domParser` option), the global\n * `DOMParser` (browsers, or a jsdom/xmldom global installed by the host), or\n * the DOMParser of the window owning the stylesheet document. Parse errors are\n * detected through `getElementsByTagName`, which every DOM implementation\n * has (xmldom, for one, has no `querySelector`).\n *\n * @module xslt/domParsing\n */\n\n\"use strict\";\n\n/**\n * Namespace Gecko puts its `parsererror` element in. A namespace name is an\n * identifier compared as a string, never fetched, so http is correct here.\n */\nconst GECKO_PARSER_ERROR_NS =\n \"http://www.mozilla.org/newlayout/xml/parsererror.xml\"; // NOSONAR\n\n/**\n * @typedef {{parseFromString: (text: string, type: string) => Document}} DomParserLike\n */\n\n/**\n * The first `parsererror` element of a document parsed by a DOMParser, if\n * any. Browsers and jsdom report malformed XML this way instead of throwing\n * (xmldom throws, see {@link parseXml}).\n *\n * @param {Node|null|undefined} doc - A parsed document (or element)\n * @returns {Element|null} The error element, or null when parsing succeeded\n *\n * @example\n * findParseError(new DOMParser().parseFromString(\"<a>\", \"application/xml\"));\n * // <parsererror>\u2026</parsererror>\n */\nexport function findParseError(doc) {\n if (!doc?.getElementsByTagName) return null;\n const plain = doc.getElementsByTagName(\"parsererror\");\n if (plain.length > 0) return plain[0];\n const gecko = doc.getElementsByTagNameNS?.(\n GECKO_PARSER_ERROR_NS,\n \"parsererror\",\n );\n return gecko?.length > 0 ? gecko[0] : null;\n}\n\n/**\n * Pick the DOMParser to use.\n *\n * @param {DomParserLike|null|undefined} configured - The engine's `domParser` option\n * @param {Document|null|undefined} referenceDoc - A document whose window may\n * provide a DOMParser (usually the stylesheet)\n * @returns {DomParserLike|null} A parser, or null when none is available\n */\nexport function resolveDomParser(configured, referenceDoc) {\n if (configured) return configured;\n const Parser =\n globalThis.DOMParser ?? referenceDoc?.defaultView?.DOMParser ?? null;\n return Parser ? new Parser() : null;\n}\n\n/**\n * Parse an XML string into a document.\n *\n * @param {string} xml - The markup\n * @param {DomParserLike|null} parser - The parser (see {@link resolveDomParser})\n * @returns {Document} The parsed document\n * @throws {Error} When no parser is available or the markup is not well formed\n *\n * @example\n * parseXml(\"<a/>\", new DOMParser()).documentElement.nodeName; // \"a\"\n */\nexport function parseXml(xml, parser) {\n if (!parser) {\n throw new Error(\n \"XML parsing not available in this environment: pass a domParser option or install a global DOMParser\",\n );\n }\n let doc;\n try {\n doc = parser.parseFromString(xml, \"application/xml\");\n } catch (thrown) {\n // xmldom's own DOMParser throws a ParseError instead\n throw new Error(`XML parse error: ${thrown.message}`, {\n cause: thrown,\n });\n }\n const error = findParseError(doc);\n if (error) throw new Error(`XML parse error: ${error.textContent}`);\n return doc;\n}\n", "/**\n * Stylesheet loading: the main stylesheet and the xsl:import and\n * xsl:include modules (the top-level elements are in topLevel.js).\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { resolveUri } from \"../uri.js\";\nimport { parseXml, resolveDomParser } from \"../domParsing.js\";\n\n/**\n * Whether an element is an xsl:stylesheet or xsl:transform element.\n *\n * @param {object} engine - The engine\n * @param {Element} root - The document element of a stylesheet module\n * @returns {boolean} True for a stylesheet element\n */\nfunction isStylesheetElement(engine, root) {\n return (\n engine.isXsltElement(root, \"stylesheet\") ||\n engine.isXsltElement(root, \"transform\")\n );\n}\n\nexport const stylesheetLoadingMethods = {\n /**\n * Set the loader used by xsl:import and xsl:include.\n *\n * @param {((href: string, baseUri?: string) => (Document|string))|null} loader - The loader, or null to remove it\n * @returns {XsltEngine} This engine, to allow chaining\n *\n * @example\n * engine.setStylesheetLoader((href) => readFileSync(href, 'utf8'));\n */\n setStylesheetLoader(loader) {\n this.stylesheetLoader = loader ?? null;\n return this;\n },\n\n /**\n * Resolve a relative URI against a base URI\n *\n * @param {string} href - The URI to resolve\n * @param {string} [baseUri] - The base URI\n * @returns {string} The resolved URI\n */\n resolveUri(href, baseUri) {\n return resolveUri(href, baseUri);\n },\n\n /**\n * Load an external stylesheet document with the stylesheet loader.\n *\n * @param {string} href - The referenced URI\n * @param {string} [baseUri] - Base URI of the referencing stylesheet\n * @returns {{document: (Document|string), uri: string}} What the loader\n * returned (a string is parsed by the caller) and the resolved URI\n * @throws {Error} When no stylesheet loader is configured\n */\n loadStylesheet(href, baseUri) {\n if (!this.stylesheetLoader) {\n throw new Error(\n `Cannot load stylesheet \"${href}\": no stylesheetLoader configured. ` +\n \"Use engine.setStylesheetLoader(fn) to provide a loader function.\",\n );\n }\n\n const resolvedUri = this.resolveUri(href, baseUri);\n const result = this.stylesheetLoader(resolvedUri, baseUri);\n return { document: result, uri: resolvedUri };\n },\n\n /**\n * Parse an XML string returned by a stylesheet or document loader, with\n * the `domParser` option, else the global DOMParser, else the DOMParser of\n * the stylesheet's window (see domParsing.js).\n *\n * @param {string} xmlString - The markup\n * @returns {Document} The parsed document\n * @throws {Error} When no parser is available or the markup is malformed\n */\n parseXmlString(xmlString) {\n return parseXml(\n xmlString,\n resolveDomParser(this.domParser, this.stylesheetDoc),\n );\n },\n\n /**\n * Import and compile an XSLT stylesheet\n * @param {Document|Element} stylesheetNode - The stylesheet document or root element\n * @param {string} [stylesheetUri] - Optional URI of the stylesheet for resolving imports\n */\n importStylesheet(stylesheetNode, stylesheetUri) {\n const isMainStylesheet = this.stylesheetDoc === null;\n\n if (isMainStylesheet) {\n this.stylesheetDoc = stylesheetNode.ownerDocument || stylesheetNode;\n if (stylesheetUri) this.baseUri = stylesheetUri;\n if (this.baseUri) this.stylesheetStack.push(this.baseUri);\n }\n\n const root = stylesheetNode.documentElement || stylesheetNode;\n\n if (!isStylesheetElement(this, root)) {\n // A literal result element as document element: simplified stylesheet\n if (root.getAttribute && root.getAttribute(\"xsl:version\")) {\n this.processLiteralResultStylesheet(root);\n return;\n }\n throw new Error(\n \"Invalid XSLT stylesheet: root element must be xsl:stylesheet or xsl:transform\",\n );\n }\n\n this.processTopLevelElements(root, stylesheetUri || this.baseUri);\n\n // Increment import precedence after processing this stylesheet\n if (isMainStylesheet) {\n this.currentImportPrecedence++;\n }\n },\n\n /**\n * Process an xsl:include element: the included stylesheet is merged at the\n * import precedence of the including stylesheet.\n *\n * @param {Element} node - The xsl:include element\n * @param {string} baseUri - URI of the including stylesheet\n * @returns {void}\n */\n processInclude(node, baseUri) {\n const savedPrecedence = this.currentImportPrecedence;\n this.loadStylesheetModule(node, baseUri, \"include\");\n this.currentImportPrecedence = savedPrecedence;\n },\n\n /**\n * Process an xsl:import element: the imported stylesheet gets a lower import\n * precedence than everything processed after it.\n *\n * @param {Element} node - The xsl:import element\n * @param {string} baseUri - URI of the importing stylesheet\n * @returns {void}\n */\n processImport(node, baseUri) {\n this.loadStylesheetModule(node, baseUri, \"import\");\n this.currentImportPrecedence++;\n },\n\n /**\n * Load and process the stylesheet referenced by xsl:import or xsl:include.\n *\n * Only a stylesheet that (directly or indirectly) references itself is an\n * error; the same stylesheet may be reached through several branches of the\n * import tree (\"diamond\" imports), as in libxslt.\n *\n * @param {Element} node - The xsl:import or xsl:include element\n * @param {string} baseUri - URI of the referencing stylesheet\n * @param {\"import\"|\"include\"} kind - The referencing instruction\n * @returns {void}\n * @throws {Error} When href is missing, loading fails or a cycle is found\n */\n loadStylesheetModule(node, baseUri, kind) {\n const href = node.getAttribute(\"href\");\n if (!href) {\n throw new Error(`xsl:${kind} requires an href attribute`);\n }\n\n const resolvedUri = this.resolveUri(href, baseUri);\n if (this.stylesheetStack.includes(resolvedUri)) {\n throw new Error(`Circular stylesheet reference detected: ${resolvedUri}`);\n }\n\n this.stylesheetStack.push(resolvedUri);\n try {\n const { document: loaded } = this.loadStylesheet(href, baseUri);\n const doc =\n typeof loaded === \"string\" ? this.parseXmlString(loaded) : loaded;\n this.processIncludedStylesheet(doc, resolvedUri);\n } catch (error) {\n throw new Error(\n `Failed to ${kind} stylesheet \"${href}\": ${error.message}`,\n { cause: error },\n );\n } finally {\n this.stylesheetStack.pop();\n }\n },\n\n /**\n * Process an included/imported stylesheet document.\n *\n * @param {Document|Element} stylesheetDoc - The loaded stylesheet module\n * @param {string} stylesheetUri - Its resolved URI\n * @returns {void}\n * @throws {Error} When the document is not an XSLT stylesheet\n */\n processIncludedStylesheet(stylesheetDoc, stylesheetUri) {\n const root = stylesheetDoc.documentElement || stylesheetDoc;\n if (!isStylesheetElement(this, root)) {\n throw new Error(\n \"Included/imported document is not a valid XSLT stylesheet\",\n );\n }\n this.processTopLevelElements(root, stylesheetUri);\n },\n};\n", "/**\n * Static checks run while a stylesheet is compiled.\n *\n * - Patterns (XSLT 1.0 section 5.2) of `xsl:template match`, `xsl:key match`\n * and `xsl:number count`/`from` are compiled at import time, so an invalid\n * pattern makes `importStylesheet` fail with an error naming it, as libxslt\n * (and so the browsers' XSLTProcessor) rejects such a stylesheet.\n * - Two global xsl:variable elements of the same name and import precedence\n * (section 11.4) and text at the top level of a stylesheet (section 2.2)\n * make `importStylesheet` fail, as libxslt rejects such a stylesheet.\n * - Two local variables or parameters of the same name where one is in the\n * scope of the other (section 11.5), and a global xsl:param clashing with\n * another global binding of the same import precedence (section 11.4),\n * are errors libxslt only reports; they are warned about here, and the\n * binding used so far keeps being used.\n *\n * @module xslt/stylesheetChecks\n */\n\n\"use strict\";\n\nimport { XSLT_NAMESPACE } from \"./elements.js\";\n\n/**\n * The local name of an XSLT element, or null for any other node.\n *\n * @param {Node} node - A stylesheet node\n * @returns {string|null} e.g. \"number\" for xsl:number\n */\nexport function xsltLocalName(node) {\n if (node.nodeType !== 1) return null;\n if (node.namespaceURI === XSLT_NAMESPACE) return node.localName;\n return node.nodeName.startsWith(\"xsl:\") ? node.nodeName.slice(4) : null;\n}\n\n/**\n * Visit every element below a node, in document order.\n *\n * @param {Node} root - The subtree root (not visited itself)\n * @param {(element: Element) => void} visit - Called for each element\n * @returns {void}\n */\nfunction forEachDescendant(root, visit) {\n for (let child = root.firstChild; child; child = child.nextSibling) {\n if (child.nodeType !== 1) continue;\n visit(child);\n forEachDescendant(child, visit);\n }\n}\n\n/**\n * Compile a pattern of the stylesheet, reporting where it comes from when\n * it is invalid.\n *\n * @param {{compile: (pattern: string) => object[]}} matcher - The pattern matcher\n * @param {string} pattern - The pattern\n * @param {string} where - The attribute holding it, e.g. \"xsl:template match\"\n * @returns {void}\n * @throws {Error} When the pattern is invalid\n *\n * @example\n * checkPattern(matcher, \"a/..\", \"xsl:template match\");\n * // Error: xsl:template match: Invalid pattern \"a/..\": Axis not allowed ...\n */\nexport function checkPattern(matcher, pattern, where) {\n try {\n matcher.compile(pattern);\n } catch (error) {\n throw new Error(`${where}: ${error.message}`, { cause: error });\n }\n}\n\n/**\n * Compile the `count` and `from` patterns of every `xsl:number` below a\n * stylesheet element (they are not attribute value templates, so they are\n * known at compile time).\n *\n * @param {{compile: (pattern: string) => object[]}} matcher - The pattern matcher\n * @param {Element} root - The stylesheet (or simplified stylesheet) element\n * @returns {void}\n * @throws {Error} When one of the patterns is invalid\n */\nexport function checkNumberPatterns(matcher, root) {\n forEachDescendant(root, (element) => {\n if (xsltLocalName(element) !== \"number\") return;\n for (const attribute of [\"count\", \"from\"]) {\n const pattern = element.getAttribute(attribute);\n if (pattern) checkPattern(matcher, pattern, `xsl:number ${attribute}`);\n }\n });\n}\n\n/**\n * A short description of the declaration holding local bindings.\n *\n * @param {Element} declaration - xsl:template, xsl:variable, ...\n * @returns {string} e.g. `template match=\"/\"`\n */\nfunction describeDeclaration(declaration) {\n const kind = xsltLocalName(declaration) ?? declaration.nodeName;\n for (const attribute of [\"match\", \"name\"]) {\n const value = declaration.getAttribute(attribute);\n if (value !== null) return `${kind} ${attribute}=\"${value}\"`;\n }\n return kind;\n}\n\n/**\n * Walk a sequence constructor, reporting bindings that shadow another local\n * binding in scope. A binding is in scope for its following siblings and\n * their descendants, not for its own content.\n *\n * @param {Element} parent - The element whose children are walked\n * @param {Set<string>} inScope - Local names bound around `parent`\n * @param {(name: string) => void} report - Called for each duplicate\n * @returns {void}\n */\nfunction walkBindings(parent, inScope, report) {\n let scope = inScope;\n for (let child = parent.firstChild; child; child = child.nextSibling) {\n if (child.nodeType !== 1) continue;\n const kind = xsltLocalName(child);\n walkBindings(child, scope, report);\n if (kind !== \"variable\" && kind !== \"param\") continue;\n\n const name = child.getAttribute(\"name\");\n if (scope.has(name)) report(name);\n scope = new Set(scope).add(name);\n }\n}\n\n/**\n * Warn about local variables and parameters that shadow another local\n * binding of the same declaration (XSLT 1.0 section 11.5). A local binding\n * shadowing a global one is allowed and not reported.\n *\n * @param {Element} declaration - A top-level element (xsl:template,\n * xsl:variable, xsl:param, xsl:attribute-set)\n * @param {(message: string) => void} warn - Reports one duplicate\n * @returns {void}\n *\n * @example\n * checkLocalBindings(templateElement, (m) => console.warn(m));\n */\nexport function checkLocalBindings(declaration, warn) {\n walkBindings(declaration, new Set(), (name) =>\n warn(\n `duplicate binding of variable $${name} in ${describeDeclaration(declaration)}; the later one is used (XSLT 1.0 section 11.5)`,\n ),\n );\n}\n\n/**\n * Check a global variable or parameter repeating the name of an earlier one\n * with the same import precedence (XSLT 1.0 section 11.4). Two\n * xsl:variable elements are an error, as in libxslt; a clash involving an\n * xsl:param is warned about, naming the binding the engine uses: the later\n * declaration, except that a global xsl:variable wins over an xsl:param.\n *\n * @param {{name: string, kind: string, precedence: number}} declaration - The\n * new declaration: its name, \"variable\" or \"param\", and import precedence\n * @param {{variable?: object, param?: object}} earlier - The definitions\n * registered so far under that name (with `node` and `importPrecedence`)\n * @param {(message: string) => void} warn - Reports the duplicate\n * @returns {void}\n * @throws {Error} When an xsl:variable repeats an xsl:variable\n *\n * @example\n * checkGlobalDuplicate({ name: \"v\", kind: \"param\", precedence: 1 },\n * { variable: { node, importPrecedence: 1 } }, console.warn);\n */\nexport function checkGlobalDuplicate(declaration, earlier, warn) {\n const { name, kind, precedence } = declaration;\n const clashes = (definition) =>\n Boolean(definition?.node) && definition.importPrecedence === precedence;\n if (kind === \"variable\" && clashes(earlier.variable)) {\n throw new Error(\n `redefinition of global variable $${name} at the same import precedence (XSLT 1.0 section 11.4)`,\n );\n }\n if (!clashes(earlier.variable) && !clashes(earlier.param)) return;\n const used =\n kind === \"param\" && earlier.variable ? \"the xsl:variable\" : \"the later one\";\n warn(\n `duplicate global binding of variable $${name} at the same import precedence; ${used} is used (XSLT 1.0 section 11.4)`,\n );\n}\n\n/**\n * Reject text other than whitespace among the top-level elements of a\n * stylesheet (XSLT 1.0 section 2.2), as libxslt does.\n *\n * @param {Element} root - The xsl:stylesheet or xsl:transform element\n * @returns {void}\n * @throws {Error} When a text node holds non-whitespace characters\n */\nexport function checkTopLevelText(root) {\n for (let child = root.firstChild; child; child = child.nextSibling) {\n const isText = child.nodeType === 3 || child.nodeType === 4;\n if (isText && /[^ \\t\\r\\n]/.test(child.nodeValue)) {\n throw new Error(\n `misplaced text at the top level of the stylesheet: \"${child.nodeValue.trim()}\" (XSLT 1.0 section 2.2)`,\n );\n }\n }\n}\n", "/**\n * Forwards-compatible processing and xsl:fallback (XSLT 1.0 sections 2.5\n * and 15).\n *\n * An element is processed in forwards-compatible mode when the nearest\n * enclosing `version` declaration (the `version` attribute of\n * `xsl:stylesheet`/`xsl:transform`, or the `xsl:version` attribute of a\n * literal result element) is not \"1.0\". In that mode unknown top-level XSLT\n * elements are ignored. An unknown XSLT instruction is replaced by its\n * `xsl:fallback` children when it has some (in any mode); otherwise it is an\n * error only if it is actually instantiated.\n *\n * @module xslt/forwardsCompatible\n */\n\n\"use strict\";\n\nimport { XSLT_NAMESPACE } from \"./elements.js\";\nimport { xsltLocalName } from \"./stylesheetChecks.js\";\n\nconst modes = new WeakMap();\n\n/**\n * The version declared on one stylesheet element, if any.\n *\n * @param {Element} element - A stylesheet element\n * @returns {string|null} The declared version, null when none\n */\nexport function declaredVersion(element) {\n const localName = xsltLocalName(element);\n if (localName === \"stylesheet\" || localName === \"transform\") {\n return element.getAttribute(\"version\");\n }\n if (localName !== null) return null;\n return element.getAttributeNS?.(XSLT_NAMESPACE, \"version\") ?? null;\n}\n\n/**\n * Whether a stylesheet element is processed in forwards-compatible mode.\n * Cached per element.\n *\n * @param {Node|null} node - A stylesheet node\n * @returns {boolean} True when the version in effect is not \"1.0\"\n *\n * @example\n * isForwardsCompatible(instruction); // true under version=\"2.0\"\n */\nexport function isForwardsCompatible(node) {\n if (node?.nodeType !== 1) return false;\n\n let forwards = modes.get(node);\n if (forwards === undefined) {\n const version = declaredVersion(node);\n forwards =\n version === null || version === \"\"\n ? isForwardsCompatible(node.parentNode)\n : version.trim() !== \"1.0\";\n modes.set(node, forwards);\n }\n return forwards;\n}\n\n/**\n * The `xsl:fallback` children of an instruction, in document order.\n *\n * @param {Element} instruction - An XSLT instruction\n * @returns {Element[]} The fallback elements\n */\nexport function fallbackChildren(instruction) {\n const fallbacks = [];\n for (let child = instruction.firstChild; child; child = child.nextSibling) {\n if (xsltLocalName(child) === \"fallback\") fallbacks.push(child);\n }\n return fallbacks;\n}\n", "/**\n * Top-level elements of a stylesheet module: their dispatch to the\n * declaration handlers, simplified stylesheets and the stylesheet-wide\n * namespace table.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { XSLT_NAMESPACE } from \"../elements.js\";\nimport { inScopeNamespaces } from \"../stylesheetNamespaces.js\";\nimport {\n checkLocalBindings,\n checkNumberPatterns,\n checkTopLevelText,\n} from \"../stylesheetChecks.js\";\nimport { isForwardsCompatible } from \"../forwardsCompatible.js\";\n\n/**\n * Engine method handling each top-level XSLT element (xsl:import is handled\n * first, separately, because imports must precede everything else).\n */\nconst TOP_LEVEL_HANDLERS = Object.freeze({\n template: \"registerTemplate\",\n output: \"processOutput\",\n variable: \"processGlobalVariable\",\n param: \"processGlobalParam\",\n key: \"processKey\",\n \"decimal-format\": \"processDecimalFormat\",\n \"namespace-alias\": \"processNamespaceAlias\",\n \"attribute-set\": \"processAttributeSet\",\n \"strip-space\": \"processStripSpace\",\n \"preserve-space\": \"processPreserveSpace\",\n include: \"processInclude\",\n});\n\nexport const topLevelMethods = {\n /**\n * Process the top-level elements of a stylesheet module.\n *\n * xsl:import elements are processed first, so imported declarations get a\n * lower import precedence than the ones of the importing stylesheet.\n *\n * @param {Element} root - The xsl:stylesheet element\n * @param {string} stylesheetUri - URI used to resolve imports and includes\n * @returns {void}\n */\n processTopLevelElements(root, stylesheetUri) {\n checkTopLevelText(root);\n this.collectNamespaces(root);\n\n const imports = [];\n const otherElements = [];\n for (const child of root.childNodes) {\n if (child.nodeType !== 1) continue;\n if (this.isXsltElement(child, \"import\")) imports.push(child);\n else otherElements.push(child);\n }\n\n for (const importNode of imports) {\n this.processImport(importNode, stylesheetUri);\n }\n\n for (const child of otherElements) {\n if (!this.isXsltNamespace(child)) continue;\n const method = TOP_LEVEL_HANDLERS[child.localName];\n if (method) this[method](child, stylesheetUri);\n else this.unknownTopLevelElement(child);\n }\n checkNumberPatterns(this.patternMatcher, root);\n },\n\n /**\n * Ignore an unknown top-level XSLT element: silently in forwards-compatible\n * mode (XSLT 1.0 section 2.5), with a warning otherwise.\n *\n * @param {Element} node - The unknown element\n * @returns {void}\n */\n unknownTopLevelElement(node) {\n if (isForwardsCompatible(node)) return;\n this.warnOnce(`unknown top-level element xsl:${node.localName} is ignored`);\n },\n\n /**\n * Register a simplified stylesheet (XSLT 1.0 section 2.3): the literal result\n * root element is the body of a template rule matching \"/\", so the root\n * element itself is instantiated, not only its children.\n *\n * @param {Element} root - The literal result root element\n * @returns {void}\n */\n processLiteralResultStylesheet(root) {\n this.collectNamespaces(root);\n checkNumberPatterns(this.patternMatcher, root);\n checkLocalBindings(root, (message) => this.warnOnce(message));\n this.templates.push({\n match: \"/\",\n name: null,\n mode: null,\n priority: 0.5,\n importPrecedence: this.currentImportPrecedence,\n namespaces: inScopeNamespaces(root),\n node: { firstChild: root, childNodes: [root] },\n });\n },\n\n /**\n * Record the namespace declarations of a stylesheet document element in\n * the stylesheet-wide fallback table. Instructions resolve prefixes against\n * their own in-scope namespaces; this table only serves contexts without a\n * stylesheet element. The first binding of a prefix wins, so a module\n * loaded later cannot rebind the main stylesheet's prefixes.\n *\n * @param {Element} node - The stylesheet element\n * @returns {void}\n */\n collectNamespaces(node) {\n if (!node.attributes) return;\n\n for (const attr of node.attributes) {\n let prefix = null;\n if (attr.name.startsWith(\"xmlns:\")) prefix = attr.name.substring(6);\n else if (attr.name === \"xmlns\") prefix = \"\";\n\n if (prefix !== null && attr.value !== XSLT_NAMESPACE) {\n this.namespaces[prefix] ??= attr.value;\n }\n }\n },\n};\n", "/**\n * Name tests of `xsl:strip-space` and `xsl:preserve-space` (XSLT 1.0\n * section 3.4).\n *\n * The `elements` attribute lists XPath name tests: `*`, `prefix:*` or a\n * QName. The prefixes are expanded with the namespace declarations in scope\n * on the declaring element, and an unprefixed name only matches elements in\n * no namespace (XPath 1.0 section 2.3), so `p:*` matches by namespace URI\n * whatever prefix the source document uses. Name tests given as plain\n * strings (the {@link WhitespaceFilter} API before 1.2.0) are still matched\n * by their lexical name.\n *\n * @module xslt/spaceNameTests\n */\n\n\"use strict\";\n\nimport { isQName } from \"./qname.js\";\nimport { splitQName } from \"./resultNamespaces.js\";\nimport { inScopeNamespaces, resolvePrefix } from \"./stylesheetNamespaces.js\";\n\n/**\n * @typedef {Object} ElementNameTest\n * @property {string|null|undefined} namespaceUri - The namespace to match,\n * null for no namespace, undefined for any (the `*` test)\n * @property {string} localName - The local name, `*` for any\n */\n\n/**\n * Expand the name tests of an `elements` attribute.\n *\n * @param {string|null} value - Whitespace separated name tests\n * @param {Element} element - The xsl:strip-space or xsl:preserve-space element\n * @param {(message: string) => void} warn - Reports a skipped name test\n * @returns {ElementNameTest[]} The expanded name tests\n *\n * @example\n * // <xsl:strip-space xmlns:m=\"urn:m\" elements=\"m:* p *\"/>\n * compileSpaceNameTests(\"m:* p *\", element, console.warn);\n * // [{ namespaceUri: \"urn:m\", localName: \"*\" },\n * // { namespaceUri: null, localName: \"p\" },\n * // { namespaceUri: undefined, localName: \"*\" }]\n */\nexport function compileSpaceNameTests(value, element, warn) {\n const tests = [];\n for (const token of (value ?? \"\").split(/[ \\t\\r\\n]+/).filter(Boolean)) {\n if (token === \"*\") {\n tests.push({ namespaceUri: undefined, localName: \"*\" });\n continue;\n }\n const { prefix, localName } = splitQName(token);\n const qname = localName === \"*\" ? `${prefix}:x` : token;\n const namespaceUri = prefix\n ? resolvePrefix(inScopeNamespaces(element), prefix)\n : null;\n if (!isQName(qname) || (prefix && !namespaceUri)) {\n warn(\n `xsl:${element.localName} elements: \"${token}\" is not a name test with a declared prefix and is ignored`,\n );\n continue;\n }\n tests.push({ namespaceUri, localName });\n }\n return tests;\n}\n\n/**\n * The XSLT default priority of an element name test (section 5.5).\n *\n * @param {string|ElementNameTest} nameTest - A name test\n * @returns {number} -0.5 for `*`, -0.25 for `prefix:*`, 0 for a name\n */\nexport function nameTestPriority(nameTest) {\n if (typeof nameTest === \"string\") {\n if (nameTest === \"*\") return -0.5;\n return nameTest.endsWith(\":*\") ? -0.25 : 0;\n }\n if (nameTest.namespaceUri === undefined) return -0.5;\n return nameTest.localName === \"*\" ? -0.25 : 0;\n}\n\n/**\n * Whether an element matches a lexical name test (the string API).\n *\n * @param {Element} element - The element to test\n * @param {string} nameTest - `*`, `prefix:*` or a name\n * @returns {boolean} True when the element matches\n */\nfunction matchesLexicalTest(element, nameTest) {\n if (nameTest === \"*\") return true;\n if (nameTest.endsWith(\":*\")) {\n return element.nodeName.startsWith(`${nameTest.slice(0, -2)}:`);\n }\n return element.nodeName === nameTest || element.localName === nameTest;\n}\n\n/**\n * Whether an element matches a name test.\n *\n * @param {Element} element - The element to test\n * @param {string|ElementNameTest} nameTest - A name test\n * @returns {boolean} True when the element matches\n *\n * @example\n * matchesNameTest(pElement, { namespaceUri: null, localName: \"p\" }); // true\n */\nexport function matchesNameTest(element, nameTest) {\n if (typeof nameTest === \"string\") {\n return matchesLexicalTest(element, nameTest);\n }\n const { namespaceUri, localName } = nameTest;\n if (namespaceUri === undefined) return true;\n if ((element.namespaceURI || null) !== namespaceUri) return false;\n return localName === \"*\" || element.localName === localName;\n}\n", "/**\n * Serializer Constants\n *\n * Shared node type codes, namespace URIs and HTML element tables used by the\n * XSLT 1.0 output serializers (XSLT 1.0 section 16).\n */\n\n/**\n * DOM node type codes used by the serializers.\n */\nexport const NODE_TYPE = {\n ELEMENT: 1,\n TEXT: 3,\n CDATA_SECTION: 4,\n PROCESSING_INSTRUCTION: 7,\n COMMENT: 8,\n DOCUMENT: 9,\n DOCUMENT_FRAGMENT: 11,\n};\n\n/**\n * Namespace URI reserved for namespace declaration attributes.\n */\nexport const XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\n\n/**\n * Namespace URI bound to the reserved `xml` prefix.\n */\nexport const XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\n\n/**\n * How the text children of an element have to be written out.\n */\nexport const TEXT_MODE = {\n ESCAPE: \"escape\",\n CDATA: \"cdata\",\n RAW: \"raw\",\n};\n\n/** Namespace of XHTML elements. */\nexport const XHTML_NAMESPACE = \"http://www.w3.org/1999/xhtml\";\n\n/**\n * HTML elements that never have an end tag.\n */\nexport const VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/**\n * HTML attributes holding URIs, which the html output method %-escapes\n * (XSLT 1.0 section 16.2): the attributes libxml2 (and so Chrome) escapes,\n * on any element. `name` is a URI attribute on `a` only (see\n * {@link URI_ATTRIBUTES_OF_A}).\n */\nexport const URI_ATTRIBUTES = new Set([\"action\", \"href\", \"src\"]);\n\n/** Further URI attributes of the `a` element (libxml2). */\nexport const URI_ATTRIBUTES_OF_A = new Set([\"name\"]);\n\n/**\n * HTML elements whose character data must not be escaped.\n */\nexport const RAW_TEXT_ELEMENTS = new Set([\"script\", \"style\"]);\n\n/**\n * HTML elements whose content must never be re-indented.\n */\nexport const PRESERVE_SPACE_ELEMENTS = new Set([\n \"pre\",\n \"script\",\n \"style\",\n \"textarea\",\n]);\n\n/**\n * Indentation unit used when `indent=\"yes\"` is requested.\n */\nexport const INDENT_UNIT = \" \";\n", "/**\n * Output Settings Resolution\n *\n * Normalizes the `xsl:output` settings collected by the XSLT engine into the\n * shape the serializers consume (XSLT 1.0 section 16).\n */\n\nimport { NODE_TYPE } from \"./constants.js\";\n\n/**\n * Test whether an `xsl:output` yes/no attribute is enabled.\n *\n * @param {string|boolean|undefined} value - Raw attribute value\n * @returns {boolean} True when the value means \"yes\"\n */\nfunction isYes(value) {\n return value === true || String(value).toLowerCase() === \"yes\";\n}\n\n/**\n * Lookup key of an expanded name, in Clark notation: `{uri}local`, or the\n * bare local name for a name in no namespace.\n *\n * @param {string|null|undefined} namespaceUri - Namespace URI, empty for none\n * @param {string} localName - Local name\n * @returns {string} The key\n *\n * @example\n * expandedNameKey(\"urn:p\", \"c\"); // \"{urn:p}c\"\n * expandedNameKey(null, \"c\"); // \"c\"\n */\nexport function expandedNameKey(namespaceUri, localName) {\n return namespaceUri ? `{${namespaceUri}}${localName}` : localName;\n}\n\n/**\n * @typedef {Object} CdataNames\n * @property {Set<string>} expanded - Expanded name keys ({@link expandedNameKey})\n * @property {Array<{prefix: string, localName: string}>} qnames - Prefixed\n * names whose prefix is resolved against the result element\n */\n\n/**\n * Normalize a `cdata-section-elements` value.\n *\n * Entries resolved by the engine, `{namespaceUri, localName}`, are exact\n * expanded names. A plain string QName carries no namespace bindings: an\n * unprefixed name is taken to be in no namespace, and a prefixed one is kept\n * aside to be resolved with the in-scope namespaces of each result element.\n *\n * @param {string|Array<string|{namespaceUri: ?string, localName: string}>|undefined} value -\n * Whitespace separated QNames, or an array of QNames and expanded names\n * @returns {CdataNames} The names\n */\nfunction toCdataNames(value) {\n const entries =\n typeof value === \"string\" ? value.split(/\\s+/) : [value ?? []].flat();\n const expanded = new Set();\n const qnames = [];\n\n for (const entry of entries) {\n if (typeof entry !== \"string\") {\n expanded.add(expandedNameKey(entry.namespaceUri, entry.localName));\n continue;\n }\n const colon = entry.indexOf(\":\");\n if (colon === -1) {\n if (entry) expanded.add(entry);\n } else {\n qnames.push({\n prefix: entry.slice(0, colon),\n localName: entry.slice(colon + 1),\n });\n }\n }\n\n return { expanded, qnames };\n}\n\n/**\n * Find the first element node of a result tree.\n *\n * @param {Node|null} node - Document, fragment or element\n * @returns {Element|null} The result document element, when there is one\n */\nexport function findRootElement(node) {\n if (!node) {\n return null;\n }\n if (node.nodeType === NODE_TYPE.ELEMENT) {\n return node;\n }\n for (const child of node.childNodes || []) {\n if (child.nodeType === NODE_TYPE.ELEMENT) {\n return child;\n }\n }\n return null;\n}\n\n/** Text made only of XML whitespace (#x20 #x9 #xD #xA). */\nconst XML_WHITESPACE_ONLY = /^[ \\t\\r\\n]*$/;\n\n/**\n * Whether text other than XML whitespace precedes the first element child.\n *\n * @param {Node} node - Document or fragment that has an element child\n * @returns {boolean} True when a non-whitespace text node comes first\n */\nfunction hasLeadingText(node) {\n for (\n let child = node.firstChild;\n child.nodeType !== NODE_TYPE.ELEMENT;\n child = child.nextSibling\n ) {\n const isText =\n child.nodeType === NODE_TYPE.TEXT ||\n child.nodeType === NODE_TYPE.CDATA_SECTION;\n if (isText && !XML_WHITESPACE_ONLY.test(child.nodeValue)) return true;\n }\n return false;\n}\n\n/**\n * Derive the default output method from the result tree.\n *\n * XSLT 1.0 section 16 defaults to `html` when the document element is `html`\n * in no namespace and no text other than whitespace precedes it, and to\n * `xml` otherwise.\n *\n * @param {Node|null} node - Result tree root\n * @returns {string} Either \"html\" or \"xml\"\n */\nexport function detectOutputMethod(node) {\n const root = findRootElement(node);\n const isHtmlRoot =\n root &&\n !root.namespaceURI &&\n root.localName.toLowerCase() === \"html\" &&\n (root === node || !hasLeadingText(node));\n return isHtmlRoot ? \"html\" : \"xml\";\n}\n\n/**\n * Normalize an `xsl:output` settings object.\n *\n * An absent, empty or \"auto\" method triggers the XSLT 1.0 default method\n * detection based on the result tree.\n *\n * @param {object|null} outputSettings - Raw settings from the XSLT engine\n * @param {Node|null} node - Result tree used for default method detection\n * @returns {object} Normalized settings consumed by the serializers\n */\nexport function resolveOutputSettings(outputSettings, node) {\n const raw = outputSettings || {};\n const declared = typeof raw.method === \"string\" ? raw.method.trim() : \"\";\n const method =\n declared && declared !== \"auto\"\n ? declared.toLowerCase()\n : detectOutputMethod(node);\n const cdata = toCdataNames(raw.cdataSectionElements);\n\n return {\n method,\n version: raw.version || \"1.0\",\n encoding: raw.encoding || \"UTF-8\",\n standalone: raw.standalone || null,\n indent: isYes(raw.indent),\n // libxslt writes a line break after a top-level comment followed by\n // another node unless indent=\"no\" is declared (xsltSaveResultTo)\n topLevelLineBreaks: raw.indent == null || isYes(raw.indent),\n omitXmlDeclaration: isYes(raw.omitXmlDeclaration),\n doctypePublic: raw.doctypePublic || null,\n doctypeSystem: raw.doctypeSystem || null,\n mediaType: raw.mediaType || null,\n cdataSectionElements: cdata.expanded,\n cdataSectionQNames: cdata.qnames,\n };\n}\n", "/**\n * Names of named stylesheet objects (XSLT 1.0 section 2.4).\n *\n * Named templates, attribute sets and decimal formats are named by QNames\n * that are expanded with the namespace declarations in scope on the element\n * carrying the name; the default namespace is not used for unprefixed names.\n * Two names are the same when their expanded names are, whatever prefixes\n * they use, so every table of such objects is keyed by the expanded name in\n * Clark notation (`{uri}local`, or the bare local name in no namespace).\n *\n * @module xslt/declarationNames\n */\n\n\"use strict\";\n\nimport { isQName } from \"./qname.js\";\nimport { splitQName } from \"./resultNamespaces.js\";\nimport { inScopeNamespaces, resolvePrefix } from \"./stylesheetNamespaces.js\";\nimport { expandedNameKey } from \"./serializer/settings.js\";\n\n/**\n * Expand a QName-valued attribute of a stylesheet element.\n *\n * @param {string} qname - The QName, e.g. `p:format` or `common`\n * @param {Element} element - The element in whose scope the prefix resolves\n * @returns {{key: string}|{error: string}} The expanded name key, or why the\n * value is not a QName with a declared prefix\n *\n * @example\n * // <xsl:decimal-format xmlns:p=\"urn:p\" name=\"p:f\"/>\n * expandName(\"p:f\", element); // { key: \"{urn:p}f\" }\n * expandName(\"q:f\", element); // { error: 'undeclared namespace prefix \"q\" in \"q:f\"' }\n */\nexport function expandName(qname, element) {\n if (!isQName(qname)) return { error: `invalid QName \"${qname}\"` };\n const { prefix, localName } = splitQName(qname);\n if (!prefix) return { key: localName };\n const namespaceUri = resolvePrefix(inScopeNamespaces(element), prefix);\n if (!namespaceUri) {\n return { error: `undeclared namespace prefix \"${prefix}\" in \"${qname}\"` };\n }\n return { key: expandedNameKey(namespaceUri, localName) };\n}\n\n/**\n * Expand a QName that must be valid, failing with a message naming where it\n * comes from.\n *\n * @param {string} qname - The QName\n * @param {Element} element - The element in whose scope the prefix resolves\n * @param {string} where - The attribute holding it, e.g. \"xsl:template name\"\n * @returns {string} The expanded name key\n * @throws {Error} When the value is not a QName or its prefix is undeclared\n *\n * @example\n * requireExpandedName(\"p:t\", templateElement, \"xsl:template name\"); // \"{urn:p}t\"\n */\nexport function requireExpandedName(qname, element, where) {\n const expanded = expandName(qname, element);\n if (expanded.error) throw new Error(`${where}: ${expanded.error}`);\n return expanded.key;\n}\n\n/**\n * Expand the whitespace separated QNames of an attribute such as\n * `use-attribute-sets`.\n *\n * @param {string|null} value - The attribute value\n * @param {Element} element - The element carrying the attribute\n * @param {string} where - Attribute description for error messages\n * @returns {string[]} The expanded name keys, in order\n * @throws {Error} When one of the names is not a QName with a declared prefix\n */\nexport function requireExpandedNames(value, element, where) {\n if (!value) return [];\n return value\n .split(/[ \\t\\r\\n]+/)\n .filter(Boolean)\n .map((qname) => requireExpandedName(qname, element, where));\n}\n", "/**\n * Named attribute sets (XSLT 1.0 section 7.1.4).\n *\n * Every `xsl:attribute-set` declaration is kept: declarations with the same\n * expanded name are merged into one set. Applying a set applies its\n * declarations from the lowest import precedence to the highest (stylesheet\n * order within one precedence), each one its `use-attribute-sets` first and\n * then its own `xsl:attribute` children. A later attribute of the same name\n * replaces an earlier one, so attributes of a higher import precedence win\n * over imported ones and a declaration's own attributes win over the sets it\n * uses, as in libxslt.\n *\n * @module xslt/attributeSets\n */\n\n\"use strict\";\n\nimport {\n requireExpandedName,\n requireExpandedNames,\n} from \"./declarationNames.js\";\n\n/**\n * @typedef {Object} AttributeSetDeclaration\n * @property {Element} node - The xsl:attribute-set element\n * @property {string[]} uses - Expanded names of its use-attribute-sets\n * @property {number} importPrecedence - Import precedence of its stylesheet\n */\n\n/**\n * Register an `xsl:attribute-set` declaration.\n *\n * @param {Object<string, AttributeSetDeclaration[]>} sets - Declarations by\n * expanded name; updated in place\n * @param {Element} node - The xsl:attribute-set element\n * @param {number} importPrecedence - Import precedence of its stylesheet\n * @returns {void}\n * @throws {Error} When the name or a used name is not a QName with a\n * declared prefix (libxslt rejects such a stylesheet)\n */\nexport function registerAttributeSet(sets, node, importPrecedence) {\n const key = requireExpandedName(\n node.getAttribute(\"name\") ?? \"\",\n node,\n \"xsl:attribute-set name\",\n );\n const uses = requireExpandedNames(\n node.getAttribute(\"use-attribute-sets\"),\n node,\n \"xsl:attribute-set use-attribute-sets\",\n );\n const declarations = Object.hasOwn(sets, key) ? sets[key] : [];\n declarations.push({ node, uses, importPrecedence });\n // Stable sort: stylesheet order is kept within one import precedence\n declarations.sort((a, b) => a.importPrecedence - b.importPrecedence);\n sets[key] = declarations;\n}\n\n/**\n * Apply attribute sets to a result element.\n *\n * @param {Object<string, AttributeSetDeclaration[]>} sets - Declarations by expanded name\n * @param {string[]} keys - Expanded names of the sets to apply, in order\n * @param {(node: Element) => void} applyDeclaration - Instantiates the\n * xsl:attribute children of one declaration\n * @param {Set<string>} [active] - Sets being applied (recursion guard)\n * @returns {void}\n * @throws {Error} When a set uses itself, directly or indirectly (an error\n * in XSLT 1.0 section 7.1.4)\n *\n * @example\n * applyAttributeSets(engine.attributeSets, [\"common\"], (node) =>\n * engine.processChildren(node, context, element));\n */\nexport function applyAttributeSets(\n sets,\n keys,\n applyDeclaration,\n active = new Set(),\n) {\n for (const key of keys) {\n if (!Object.hasOwn(sets, key)) continue;\n if (active.has(key)) {\n throw new Error(\n `xsl:attribute-set ${key} uses itself (XSLT 1.0 section 7.1.4)`,\n );\n }\n active.add(key);\n for (const declaration of sets[key]) {\n applyAttributeSets(sets, declaration.uses, applyDeclaration, active);\n applyDeclaration(declaration.node);\n }\n active.delete(key);\n }\n}\n", "/**\n * Top-level declarations other than templates and xsl:output: global\n * variables and parameters, keys, decimal formats, namespace aliases,\n * attribute sets and whitespace stripping.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { inScopeNamespaces } from \"../stylesheetNamespaces.js\";\nimport { compileSpaceNameTests } from \"../spaceNameTests.js\";\nimport { registerAttributeSet } from \"../attributeSets.js\";\nimport { expandName } from \"../declarationNames.js\";\nimport {\n checkGlobalDuplicate,\n checkLocalBindings,\n checkPattern,\n xsltLocalName,\n} from \"../stylesheetChecks.js\";\n\n/**\n * The properties of an xsl:decimal-format declaration, with their defaults\n * (XSLT 1.0 section 12.3).\n *\n * @param {Element} node - The xsl:decimal-format element\n * @param {number} importPrecedence - Its import precedence\n * @returns {object} The decimal format\n */\nfunction readDecimalFormat(node, importPrecedence) {\n return {\n importPrecedence,\n decimalSeparator: node.getAttribute(\"decimal-separator\") || \".\",\n groupingSeparator: node.getAttribute(\"grouping-separator\") || \",\",\n percent: node.getAttribute(\"percent\") || \"%\",\n perMille: node.getAttribute(\"per-mille\") || \"\u2030\",\n zeroDigit: node.getAttribute(\"zero-digit\") || \"0\",\n digit: node.getAttribute(\"digit\") || \"#\",\n patternSeparator: node.getAttribute(\"pattern-separator\") || \";\",\n infinity: node.getAttribute(\"infinity\") || \"Infinity\",\n nan: node.getAttribute(\"NaN\") || \"NaN\",\n minusSign: node.getAttribute(\"minus-sign\") || \"-\",\n };\n}\n\nexport const declarationMethods = {\n /**\n * Register an `xsl:variable` top level declaration.\n *\n * @param {Element} node - The `xsl:variable` element\n * @returns {void}\n */\n processGlobalVariable(node) {\n const name = node.getAttribute(\"name\");\n this.checkGlobalBinding(name, node);\n this.globalVariables[name] = {\n node,\n select: node.getAttribute(\"select\"),\n importPrecedence: this.currentImportPrecedence,\n };\n },\n\n /**\n * Warn about a global variable or parameter declared twice at the same\n * import precedence (an error in XSLT 1.0 section 11.4 that libxslt\n * reports) and about duplicate local bindings in its content. The later\n * declaration is used, or the xsl:variable when a parameter has the same\n * name and import precedence.\n *\n * @param {string} name - The declared name\n * @param {Element} node - The xsl:variable or xsl:param element\n * @returns {void}\n */\n checkGlobalBinding(name, node) {\n const warn = (message) => this.warnOnce(message);\n checkLocalBindings(node, warn);\n checkGlobalDuplicate(\n {\n name,\n kind: xsltLocalName(node),\n precedence: this.currentImportPrecedence,\n },\n {\n variable: this.globalVariables[name],\n param: this.globalParameters[name],\n },\n warn,\n );\n },\n\n /**\n * Register an `xsl:param` top level declaration.\n *\n * A value supplied from outside (through `setParameter`) has precedence over\n * the declared default, so it survives compilation of the stylesheet.\n *\n * @param {Element} node - The `xsl:param` element\n * @returns {void}\n */\n processGlobalParam(node) {\n const name = node.getAttribute(\"name\");\n this.checkGlobalBinding(name, node);\n const existing = this.globalParameters[name];\n const definition = {\n node,\n select: node.getAttribute(\"select\"),\n importPrecedence: this.currentImportPrecedence,\n };\n\n if (existing && \"value\" in existing) {\n definition.value = existing.value;\n }\n\n this.globalParameters[name] = definition;\n },\n\n /**\n * Register an xsl:key declaration. Declarations sharing a name all\n * contribute to the same key (XSLT 1.0 section 12.2); a declaration seen\n * again through another import branch is only kept once.\n *\n * @param {Element} node - The xsl:key element\n * @returns {void}\n */\n processKey(node) {\n const name = node.getAttribute(\"name\");\n const match = node.getAttribute(\"match\");\n const use = node.getAttribute(\"use\");\n if (match !== null) {\n checkPattern(this.patternMatcher, match, \"xsl:key match\");\n }\n const definitions = (this.keys[name] ??= []);\n\n if (!definitions.some((d) => d.match === match && d.use === use)) {\n definitions.push({ match, use, namespaces: inScopeNamespaces(node) });\n }\n this.keyRegistry.clear();\n },\n\n /**\n * Register an xsl:decimal-format declaration under the expanded name of\n * its `name` (XSLT 1.0 section 12.3). Like libxslt, an invalid name or an\n * undeclared prefix is reported and the declaration ignored, and a second\n * declaration of the same name and import precedence is reported and\n * ignored; one of a higher import precedence replaces an imported one.\n *\n * @param {Element} node - The xsl:decimal-format element\n * @returns {void}\n */\n processDecimalFormat(node) {\n const name = node.getAttribute(\"name\");\n let key = \"\";\n if (name !== null) {\n const expanded = expandName(name, node);\n if (expanded.error) {\n this.warnOnce(\n `xsl:decimal-format: ${expanded.error}; the declaration is ignored`,\n );\n return;\n }\n key = expanded.key;\n const existing = this.decimalFormats[key];\n if (existing?.importPrecedence === this.currentImportPrecedence) {\n this.warnOnce(\n `xsl:decimal-format: \"${name}\" is already declared; the first declaration is used`,\n );\n return;\n }\n }\n\n this.decimalFormats[key] = readDecimalFormat(\n node,\n this.currentImportPrecedence,\n );\n },\n\n /**\n * Register an xsl:namespace-alias declaration.\n *\n * @param {Element} node - The xsl:namespace-alias element\n * @returns {void}\n */\n processNamespaceAlias(node) {\n this.namespaceAliases.add(node);\n },\n\n /**\n * Register an xsl:attribute-set declaration; declarations of the same\n * expanded name are merged (see attributeSets.js).\n *\n * @param {Element} node - The xsl:attribute-set element\n * @returns {void}\n */\n processAttributeSet(node) {\n checkLocalBindings(node, (message) => this.warnOnce(message));\n registerAttributeSet(\n this.attributeSets,\n node,\n this.currentImportPrecedence,\n );\n },\n\n /**\n * Register the name tests of an xsl:strip-space element, expanded with\n * its namespace declarations (see spaceNameTests.js).\n *\n * @param {Element} node - The xsl:strip-space element\n * @returns {void}\n */\n processStripSpace(node) {\n this.stripSpace.push(...this.spaceNameTests(node));\n },\n\n /**\n * Register the name tests of an xsl:preserve-space element.\n *\n * @param {Element} node - The xsl:preserve-space element\n * @returns {void}\n */\n processPreserveSpace(node) {\n this.preserveSpace.push(...this.spaceNameTests(node));\n },\n\n /**\n * Expand the `elements` name tests of xsl:strip-space/preserve-space.\n *\n * @param {Element} node - The declaring element\n * @returns {object[]} The expanded name tests\n */\n spaceNameTests(node) {\n return compileSpaceNameTests(node.getAttribute(\"elements\"), node, (m) =>\n this.warnOnce(m),\n );\n },\n};\n", "/**\n * Default template priorities (XSLT 1.0 section 5.5).\n *\n * A template rule without an explicit `priority` attribute gets a default\n * priority derived from the shape of its match pattern. A union pattern is\n * treated as a set of template rules, one per alternative, so each\n * alternative must be assigned its own priority by the caller.\n *\n * @module xslt/templatePriority\n */\n\nconst NAME = String.raw`[A-Za-z_][\\w.-]*`;\nconst QNAME = `(?:${NAME}:)?${NAME}`;\n\n/** Patterns of the form `name`, `prefix:name`, `@name`, `@prefix:name`. */\nconst QNAME_PATTERN = new RegExp(`^(?:child::|attribute::|@)?${QNAME}$`);\n\n/** Patterns of the form `prefix:*` or `@prefix:*`. */\nconst PREFIX_WILDCARD_PATTERN = new RegExp(\n String.raw`^(?:child::|attribute::|@)?${NAME}:\\*$`,\n);\n\n/** Patterns of the form `*`, `@*`, `node()`, `text()`, `comment()`, `processing-instruction()`. */\nconst NODE_TEST_PATTERN =\n /^(?:child::|attribute::|@)?(?:\\*|node\\(\\)|text\\(\\)|comment\\(\\)|processing-instruction\\(\\))$/;\n\n/** `processing-instruction('literal')` patterns. */\nconst PI_LITERAL_PATTERN =\n /^(?:child::)?processing-instruction\\(\\s*(?:\"[^\"]*\"|'[^']*')\\s*\\)$/;\n\n/**\n * Compute the default priority of a single (non-union) match pattern.\n *\n * @param {string|null|undefined} pattern - The match pattern, already trimmed\n * @returns {number} -0.5, -0.25, 0 or 0.5 as defined by the specification\n */\nexport function calculatePriority(pattern) {\n if (!pattern) return 0.5;\n\n if (NODE_TEST_PATTERN.test(pattern)) return -0.5;\n if (PREFIX_WILDCARD_PATTERN.test(pattern)) return -0.25;\n if (QNAME_PATTERN.test(pattern) || PI_LITERAL_PATTERN.test(pattern)) return 0;\n\n return 0.5;\n}\n", "/**\n * The template registry: registration of xsl:template, default priorities,\n * and the choice of the template rule or named template to instantiate.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { calculatePriority } from \"../templatePriority.js\";\nimport { inScopeNamespaces } from \"../stylesheetNamespaces.js\";\nimport { requireExpandedName } from \"../declarationNames.js\";\nimport { checkLocalBindings, checkPattern } from \"../stylesheetChecks.js\";\n\n/**\n * Split a pattern on the `|` operators that are not inside a predicate or a\n * string literal.\n *\n * @param {string} pattern - The match pattern\n * @returns {string[]} The alternatives, untrimmed; a trailing empty one is\n * dropped\n */\nexport function splitUnionPattern(pattern) {\n const parts = [];\n let start = 0;\n let depth = 0;\n let quote = \"\";\n\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (quote) {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \"[\") {\n depth++;\n } else if (char === \"]\") {\n depth--;\n } else if (char === \"|\" && depth === 0) {\n parts.push(pattern.slice(start, i));\n start = i + 1;\n }\n }\n\n if (start < pattern.length) parts.push(pattern.slice(start));\n return parts;\n}\n\n/**\n * Whether a template rule may be chosen for a mode below an import\n * precedence limit.\n *\n * @param {object} template - The template record\n * @param {string|null} mode - The mode\n * @param {number} maxImportPrecedence - Exclusive import precedence limit\n * @returns {boolean} True when the template is a candidate\n */\nfunction isCandidateRule(template, mode, maxImportPrecedence) {\n return (\n template.mode === mode &&\n Boolean(template.match) &&\n (template.importPrecedence || 0) < maxImportPrecedence\n );\n}\n\n/**\n * Whether a matching template rule wins over the best one so far: a higher\n * import precedence wins; on equal precedence a priority that is not lower\n * wins, so the last template in stylesheet order wins ties (the XSLT 1.0\n * section 5.5 recovery, as in libxslt).\n *\n * @param {object} template - The matching template\n * @param {object|null} best - The best template so far\n * @returns {boolean} True when `template` becomes the best one\n */\nfunction outranks(template, best) {\n if (!best) return true;\n const precedence = template.importPrecedence || 0;\n const bestPrecedence = best.importPrecedence || 0;\n return (\n precedence > bestPrecedence ||\n (precedence === bestPrecedence && template.priority >= best.priority)\n );\n}\n\nexport const templateRuleMethods = {\n /**\n * Register a template rule.\n *\n * A union match pattern is equivalent to a set of template rules, one per\n * alternative (XSLT 1.0 section 5.5), so each alternative is registered\n * separately with its own default priority.\n *\n * @param {Element} node - The xsl:template element\n * @returns {void}\n */\n registerTemplate(node) {\n const match = node.getAttribute(\"match\");\n if (match !== null) {\n checkPattern(this.patternMatcher, match, \"xsl:template match\");\n }\n checkLocalBindings(node, (message) => this.warnOnce(message));\n const name = node.getAttribute(\"name\");\n const nameKey = name === null ? null : this.namedTemplateKey(node, name);\n const mode = node.getAttribute(\"mode\") || null;\n const priorityAttr = node.getAttribute(\"priority\");\n const alternatives = match\n ? this.splitUnionPattern(match).map((p) => p.trim())\n : [null];\n\n const namespaces = inScopeNamespaces(node);\n for (const alternative of alternatives) {\n this.templates.push({\n match: alternative,\n name,\n nameKey,\n mode,\n namespaces,\n priority: priorityAttr\n ? parseFloat(priorityAttr)\n : this.calculatePriority(alternative),\n importPrecedence: this.currentImportPrecedence,\n node,\n });\n }\n },\n\n /**\n * Expand the name of a named template, rejecting a second template of the\n * same expanded name and import precedence (XSLT 1.0 section 6), as\n * libxslt does.\n *\n * @param {Element} node - The xsl:template element\n * @param {string} name - Its name attribute\n * @returns {string} The expanded name key\n * @throws {Error} When the name is invalid or already used\n */\n namedTemplateKey(node, name) {\n const key = requireExpandedName(name, node, \"xsl:template name\");\n const duplicate = this.templates.some(\n (template) =>\n template.nameKey === key &&\n template.importPrecedence === this.currentImportPrecedence,\n );\n if (duplicate) {\n throw new Error(\n `xsl:template: duplicate template name \"${name}\" at the same import precedence (XSLT 1.0 section 6)`,\n );\n }\n return key;\n },\n\n /**\n * Default priority of a single match pattern (see templatePriority.js).\n *\n * @param {string|null} matchPattern - The match pattern\n * @returns {number} The default priority\n */\n calculatePriority(matchPattern) {\n return calculatePriority(matchPattern ? matchPattern.trim() : matchPattern);\n },\n\n /**\n * Split a union pattern into its alternatives (see splitUnionPattern).\n *\n * @param {string} pattern - The match pattern\n * @returns {string[]} The alternatives\n */\n splitUnionPattern(pattern) {\n return splitUnionPattern(pattern);\n },\n\n /**\n * Find the best matching template rule for a node (XSLT 1.0 section 5.5).\n * Every candidate's pattern is tested, in stylesheet order.\n *\n * @param {Node} node - The node to process\n * @param {string|null} mode - The mode\n * @param {XsltContext} context - Context supplying variables\n * @param {number} [maxImportPrecedence] - Only templates of a lower import\n * precedence are considered (xsl:apply-imports)\n * @returns {object|null} The template, or null for the built-in rules\n */\n findMatchingTemplate(node, mode, context, maxImportPrecedence = Infinity) {\n let best = null;\n for (const template of this.templates) {\n if (\n isCandidateRule(template, mode, maxImportPrecedence) &&\n this.matchesPattern(\n node,\n template.match,\n context,\n template.namespaces,\n ) &&\n outranks(template, best)\n ) {\n best = template;\n }\n }\n return best;\n },\n\n /**\n * Find the named template with the highest import precedence; among equal\n * precedences the last one in stylesheet order wins.\n *\n * @param {string} key - Expanded name of the template (see\n * declarationNames.js)\n * @returns {object|null} The template, or null when none has that name\n */\n findNamedTemplate(key) {\n let best = null;\n for (const template of this.templates) {\n if (\n template.nameKey === key &&\n (!best ||\n (template.importPrecedence || 0) >= (best.importPrecedence || 0))\n ) {\n best = template;\n }\n }\n return best;\n },\n\n /**\n * Check whether a node matches an XSLT pattern (see patterns.js).\n *\n * Errors raised while evaluating a predicate make the pattern not match,\n * as before the compiled matcher existed.\n *\n * @param {Node} node - The candidate node\n * @param {string} pattern - The XSLT pattern\n * @param {XsltContext|null} context - Context supplying variables and namespaces\n * @param {Object<string, string>} [namespaces] - Prefixes in scope on the\n * element holding the pattern, when they differ from the context's\n * @returns {boolean} Whether the node matches\n */\n matchesPattern(node, pattern, context, namespaces) {\n try {\n return this.patternMatcher.matches(node, pattern, context, namespaces);\n } catch {\n return false;\n }\n },\n};\n", "/**\n * xsl:sort (XSLT 1.0 section 10).\n *\n * Sort keys are computed once per node (decorate, sort, undecorate) instead of\n * once per comparison, and the attributes `order`, `lang`, `data-type` and\n * `case-order` are evaluated as attribute value templates.\n *\n * Text keys are compared by Unicode code point unless `lang` or `case-order`\n * is given. That matches libxslt, the engine behind the native XSLTProcessor\n * in Chromium browsers, so a stylesheet sorts the same way with this library\n * as it did natively. With `lang` or `case-order` an `Intl.Collator` is used.\n *\n * @module xslt/sort\n */\n\n/**\n * Compare two strings by Unicode code point (not by UTF-16 code unit).\n *\n * @param {string} a - First string\n * @param {string} b - Second string\n * @returns {number} Negative, zero or positive\n */\nexport function compareCodePoints(a, b) {\n const left = a[Symbol.iterator]();\n const right = b[Symbol.iterator]();\n\n for (;;) {\n const x = left.next();\n const y = right.next();\n if (x.done || y.done) return Number(y.done) - Number(x.done) || 0;\n const diff = x.value.codePointAt(0) - y.value.codePointAt(0);\n if (diff !== 0) return diff;\n }\n}\n\n/**\n * Compare two numeric sort keys; NaN precedes every number (section 10).\n *\n * @param {number} a - First key\n * @param {number} b - Second key\n * @returns {number} Negative, zero or positive\n */\nexport function compareNumbers(a, b) {\n const aNaN = Number.isNaN(a);\n const bNaN = Number.isNaN(b);\n if (aNaN || bNaN) return Number(bNaN) - Number(aNaN) || 0;\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\n/**\n * Build the text comparator for one sort key.\n *\n * @param {string} lang - Evaluated `lang` attribute (may be empty)\n * @param {string} caseOrder - Evaluated `case-order` attribute (may be empty)\n * @returns {(a: string, b: string) => number} The comparator\n */\nfunction textComparator(lang, caseOrder) {\n if (!lang && !caseOrder) return compareCodePoints;\n\n let collator;\n try {\n collator = new Intl.Collator(lang || undefined, {\n caseFirst: caseOrder === \"lower-first\" ? \"lower\" : \"upper\",\n sensitivity: \"variant\",\n });\n } catch {\n collator = new Intl.Collator(undefined, {\n caseFirst: caseOrder === \"lower-first\" ? \"lower\" : \"upper\",\n sensitivity: \"variant\",\n });\n }\n return collator.compare;\n}\n\n/**\n * @typedef {object} SortHost\n * @property {(expr: string, context: object) => *} evaluate - Evaluate an XPath expression\n * @property {(value: string, context: object) => string} avt - Evaluate an attribute value template\n * @property {(value: *) => string} toString - XPath string() conversion\n * @property {(value: *) => number} toNumber - XPath number() conversion\n */\n\n/**\n * Resolve one xsl:sort element into a key specification.\n *\n * @param {Element} element - The xsl:sort element\n * @param {object} context - Context of the sorting instruction (for AVTs)\n * @param {SortHost} host - Engine callbacks\n * @returns {{select: string, descending: boolean, numeric: boolean, compare: Function}} Specification\n */\nexport function resolveSortSpec(element, context, host) {\n const attribute = (name) => {\n const raw = element.getAttribute(name);\n return raw ? host.avt(raw, context).trim() : \"\";\n };\n\n const dataType = attribute(\"data-type\");\n const numeric = dataType === \"number\";\n\n return {\n select: element.getAttribute(\"select\") || \".\",\n descending: attribute(\"order\") === \"descending\",\n numeric,\n compare: numeric\n ? compareNumbers\n : textComparator(attribute(\"lang\"), attribute(\"case-order\")),\n };\n}\n\n/**\n * Sort a node list by the given xsl:sort elements.\n *\n * Each key is evaluated with the node as current node, the unsorted list as\n * current node list and the node's position in that list, as the\n * specification requires. Ties keep the original order.\n *\n * @param {Node[]} nodes - Nodes in their original (document) order\n * @param {Element[]} sortElements - The xsl:sort children, in order\n * @param {object} context - XSLT context of the sorting instruction\n * @param {SortHost} host - Engine callbacks\n * @returns {Node[]} A new, sorted array\n */\nexport function sortNodes(nodes, sortElements, context, host) {\n if (sortElements.length === 0 || nodes.length < 2) return [...nodes];\n\n const specs = sortElements.map((el) => resolveSortSpec(el, context, host));\n\n const rows = nodes.map((node, index) => {\n const nodeContext = context.clone({\n currentNode: node,\n currentNodeList: nodes,\n position: index + 1,\n });\n const keys = specs.map((spec) => {\n const text = host.toString(host.evaluate(spec.select, nodeContext));\n return spec.numeric ? host.toNumber(text) : text;\n });\n return { node, index, keys };\n });\n\n rows.sort((a, b) => {\n for (let k = 0; k < specs.length; k++) {\n const cmp = specs[k].compare(a.keys[k], b.keys[k]);\n if (cmp !== 0) return specs[k].descending ? -cmp : cmp;\n }\n return a.index - b.index;\n });\n\n return rows.map((row) => row.node);\n}\n", "/**\n * Explicit work stack for template instantiation.\n *\n * Recursive stylesheets nest template invocations thousands of levels deep\n * (libxslt allows 3000). Instantiating each level with JavaScript recursion\n * costs several native frames per level and overflows the call stack of\n * browsers and Node long before that, so the engine keeps the pending work\n * in frames on an explicit stack instead:\n *\n * - a SequenceFrame walks the children of a stylesheet element (a sequence\n * constructor: a template body, the content of xsl:if, a literal result\n * element, ...);\n * - a LoopFrame visits the items of xsl:apply-templates or xsl:for-each.\n *\n * An instruction whose content comes last (xsl:if, xsl:choose,\n * xsl:call-template, literal result elements, ...) schedules that content\n * with {@link workStackMethods.continueWith} and returns; the driver loop\n * runs it before the next sibling of the instruction. The native stack then\n * stays flat however deep the templates nest. Instructions that need the\n * result at once (xsl:attribute, xsl:with-param content, ...) run a nested\n * driver with {@link workStackMethods.runFrame}.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { inScopeNamespaces } from \"../stylesheetNamespaces.js\";\n\n/**\n * Deepest nesting of template instantiations in a transformation, the\n * default of libxslt's `xsltMaxDepth`. Deeper recursion is reported as a\n * potential infinite recursion. Override it with the `maxTemplateDepth`\n * engine option.\n */\nexport const XSLT_MAX_TEMPLATE_DEPTH = 3000;\n\n/**\n * Pending instantiation of the children of a stylesheet element.\n */\nexport class SequenceFrame {\n /**\n * A body declaring variables gets its own copy of the local bindings: a\n * variable is visible to its following siblings and their descendants only.\n *\n * @param {object} engine - The engine\n * @param {Element|object} node - The parent stylesheet element\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @param {(() => void)|null} [onDone] - Called once the children are done\n */\n constructor(engine, node, context, output, onDone = null) {\n this.scope = engine.declaresVariables(node) ? context.clone() : context;\n this.saved = this.scope.namespaces;\n this.next = node.firstChild;\n this.output = output;\n // Not named `then`: an object with a `then` method is treated as a promise\n this.onDone = onDone;\n // Whether the frame is a template instantiation (counted in the depth)\n this.template = false;\n }\n\n /**\n * Instantiate children until one schedules further frames or none is left.\n *\n * @param {object} engine - The engine\n * @param {object[]} frames - The work stack\n * @returns {boolean} False when every child is done\n */\n advance(engine, frames) {\n const height = frames.length;\n const scope = this.scope;\n for (let child = this.next; child; child = this.next) {\n this.next = child.nextSibling;\n const type = child.nodeType;\n if (type === 1) {\n // Prefixes resolve against the namespaces in scope on the element\n scope.namespaces = inScopeNamespaces(child);\n const method = engine.instructionMethod(child);\n if (method) engine[method](child, scope, this.output);\n } else if (type === 3 || type === 4) {\n engine.processText(child, scope, this.output);\n }\n if (frames.length !== height) return true;\n }\n return false;\n }\n\n /**\n * Leave the frame, completed or abandoned by an error.\n *\n * @param {object} engine - The engine\n * @returns {void}\n */\n release(engine) {\n this.scope.namespaces = this.saved;\n if (this.template) engine.templateDepth--;\n }\n\n /**\n * Complete the frame.\n *\n * @param {object} engine - The engine\n * @returns {void}\n */\n finish(engine) {\n this.release(engine);\n if (this.onDone) this.onDone();\n }\n}\n\n/**\n * Pending visits of the items of a list (the nodes of xsl:apply-templates\n * or xsl:for-each), one at a time.\n */\nexport class LoopFrame {\n /**\n * @param {number} count - Number of items\n * @param {(index: number) => void} visit - Instantiates one item; it may\n * schedule frames, which run before the next item\n */\n constructor(count, visit) {\n this.count = count;\n this.index = 0;\n this.visit = visit;\n this.template = false;\n }\n\n /**\n * Visit items until one schedules further frames or none is left.\n *\n * @param {object} _engine - The engine\n * @param {object[]} frames - The work stack\n * @returns {boolean} False when every item is done\n */\n advance(_engine, frames) {\n const height = frames.length;\n while (this.index < this.count) {\n this.visit(this.index++);\n if (frames.length !== height) return true;\n }\n return false;\n }\n\n /**\n * Leave the frame, completed or abandoned by an error.\n *\n * @param {object} engine - The engine\n * @returns {void}\n */\n release(engine) {\n if (this.template) engine.templateDepth--;\n }\n\n /**\n * Complete the frame.\n *\n * @param {object} engine - The engine\n * @returns {void}\n */\n finish(engine) {\n this.release(engine);\n }\n}\n\nexport const workStackMethods = {\n /**\n * Run a frame, and the frames it schedules, to completion.\n *\n * The outermost call owns the work stack of the transformation; nested\n * calls (content whose result is needed at once) run on top of it.\n *\n * @param {SequenceFrame|LoopFrame} frame - The frame\n * @returns {void}\n */\n runFrame(frame) {\n const outermost = this.frames === null;\n if (outermost) {\n this.frames = [];\n this.templateDepth = 0;\n }\n const frames = this.frames;\n const base = frames.length;\n try {\n this.pushFrame(frame);\n while (frames.length > base) {\n const top = frames[frames.length - 1];\n if (!top.advance(this, frames)) {\n frames.pop();\n top.finish(this);\n }\n }\n } catch (error) {\n this.unwindFrames(base);\n throw error;\n } finally {\n if (outermost) this.frames = null;\n }\n },\n\n /**\n * Schedule a frame to run once the current instruction returns, before\n * its next sibling; without a running work stack, run it now.\n *\n * The instruction must not use the output of the frame afterwards.\n *\n * @param {SequenceFrame|LoopFrame} frame - The frame\n * @returns {void}\n */\n continueWith(frame) {\n if (this.frames === null) this.runFrame(frame);\n else this.pushFrame(frame);\n },\n\n /**\n * Push a frame on the work stack, counting template instantiations.\n *\n * @param {SequenceFrame|LoopFrame} frame - The frame\n * @returns {void}\n * @throws {Error} When the frame would nest templates deeper than\n * `maxTemplateDepth`\n */\n pushFrame(frame) {\n if (frame.template) {\n if (this.templateDepth >= this.maxTemplateDepth) {\n throw new Error(\n `Template recursion too deep: more than ${this.maxTemplateDepth} ` +\n \"nested template invocations, a potential infinite recursion \" +\n \"(raise the maxTemplateDepth option to allow deeper recursion)\",\n );\n }\n this.templateDepth++;\n }\n this.frames.push(frame);\n },\n\n /**\n * Drop the frames above a height after an error.\n *\n * @param {number} base - The height to return to\n * @returns {void}\n */\n unwindFrames(base) {\n const frames = this.frames;\n while (frames.length > base) frames.pop().release(this);\n },\n};\n", "/**\n * Conditional and repetition instructions: xsl:if, xsl:choose,\n * xsl:for-each, and the xsl:sort glue shared with xsl:apply-templates.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { sortNodes } from \"../sort.js\";\nimport { LoopFrame } from \"./workStack.js\";\n\n/**\n * Evaluate the `select` expression of xsl:for-each or xsl:apply-templates\n * as a node list.\n *\n * @param {object} engine - The engine\n * @param {string} select - The expression\n * @param {XsltContext} context - The current context\n * @returns {Node[]} The selected nodes (a single value becomes a list of\n * one, an empty value an empty list)\n */\nexport function selectNodes(engine, select, context) {\n const nodes = engine.evaluateXPath(select, context);\n if (Array.isArray(nodes)) return nodes;\n return nodes ? [nodes] : [];\n}\n\nexport const controlFlowMethods = {\n /**\n * Instantiate `xsl:if`: the content when the test is true.\n *\n * @param {Element} node - The xsl:if instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n xslIf(node, context, output) {\n const test = node.getAttribute(\"test\");\n const result = this.evaluateXPath(test, context);\n\n if (this.xpathEvaluator.toBoolean(result)) {\n this.scheduleChildren(node, context, output);\n }\n },\n\n /**\n * Instantiate `xsl:choose`: the first xsl:when whose test is true, else\n * the xsl:otherwise.\n *\n * @param {Element} node - The xsl:choose instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n xslChoose(node, context, output) {\n for (const child of node.childNodes) {\n if (child.nodeType !== 1) continue;\n\n if (this.isXsltElement(child, \"when\")) {\n const test = child.getAttribute(\"test\");\n const result = this.evaluateXPath(test, context);\n\n if (this.xpathEvaluator.toBoolean(result)) {\n this.scheduleChildren(child, context, output);\n return;\n }\n } else if (this.isXsltElement(child, \"otherwise\")) {\n this.scheduleChildren(child, context, output);\n return;\n }\n }\n },\n\n /**\n * Instantiate `xsl:for-each`: the content once per selected node, in\n * xsl:sort order, with that node as current node.\n *\n * @param {Element} node - The xsl:for-each instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n xslForEach(node, context, output) {\n const select = node.getAttribute(\"select\");\n const nodes = this.sortNodes(\n selectNodes(this, select, context),\n this.sortElementsOf(node),\n context,\n );\n\n if (nodes.length === 0) return;\n\n // One node at a time from the work stack (see workStack.js)\n this.continueWith(\n new LoopFrame(nodes.length, (i) => {\n const newContext = context.clone({\n currentNode: nodes[i],\n currentNodeList: nodes,\n position: i + 1,\n });\n this.scheduleChildren(node, newContext, output);\n }),\n );\n },\n\n /**\n * The xsl:sort children of a sorting instruction, in document order.\n *\n * @param {Element} instruction - xsl:for-each or xsl:apply-templates\n * @returns {Element[]} The xsl:sort elements\n */\n sortElementsOf(instruction) {\n return Array.from(instruction.childNodes).filter((child) =>\n this.isXsltElement(child, \"sort\"),\n );\n },\n\n /**\n * Sort a node list by xsl:sort elements (see sort.js).\n *\n * @param {Node[]} nodes - Nodes in document order\n * @param {Element[]} sortElements - The xsl:sort elements\n * @param {XsltContext} context - Context of the sorting instruction\n * @returns {Node[]} The sorted nodes\n */\n sortNodes(nodes, sortElements, context) {\n return sortNodes(nodes, sortElements, context, this.sortHost);\n },\n\n /**\n * Engine callbacks used by the sort module, created once per engine.\n *\n * @returns {import('../sort.js').SortHost} The callbacks\n */\n get sortHost() {\n if (!this._sortHost) {\n this._sortHost = {\n evaluate: (expr, ctx) => this.evaluateXPath(expr, ctx),\n avt: (value, ctx) => this.processAttributeValueTemplate(value, ctx),\n toString: (value) => this.xpathEvaluator.toString(value),\n toNumber: (value) => this.xpathEvaluator.toNumber(value),\n };\n }\n return this._sortHost;\n },\n};\n", "/**\n * Template invocation: xsl:apply-templates, xsl:apply-imports,\n * xsl:call-template, the built-in template rules and template parameters.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { childAxis } from \"../../xpath/axes.js\";\nimport { requireExpandedName } from \"../declarationNames.js\";\nimport { selectNodes } from \"./controlFlow.js\";\nimport { LoopFrame, SequenceFrame } from \"./workStack.js\";\n\nexport const templateInvocationMethods = {\n /**\n * Apply templates to a node list. The nodes are processed one at a time\n * from the work stack (see workStack.js).\n *\n * @param {Node|Node[]} nodes - The nodes to process, in order\n * @param {string|null} mode - The mode\n * @param {XsltContext} context - Context of the invoking instruction\n * @param {Node} output - The result node receiving the output\n * @param {Object<string, *>|null} [params] - Values of xsl:with-param by name\n * @param {boolean} [builtin] - Whether a built-in template rule applies\n * them, which counts as a template instantiation (as in libxslt)\n * @returns {void}\n */\n applyTemplates(nodes, mode, context, output, params = null, builtin = false) {\n const nodeList = Array.isArray(nodes) ? nodes : [nodes];\n if (nodeList.length === 0) return;\n\n const frame = new LoopFrame(nodeList.length, (index) =>\n this.applyTemplateRule(nodeList, index, mode, context, output, params),\n );\n frame.template = builtin;\n this.continueWith(frame);\n },\n\n /**\n * Apply the best template rule to one node of a list, else the built-in\n * rule.\n *\n * @param {Node[]} nodeList - The current node list\n * @param {number} index - Index of the node in the list\n * @param {string|null} mode - The mode\n * @param {XsltContext} context - Context of the invoking instruction\n * @param {Node} output - The result node receiving the output\n * @param {Object<string, *>|null} params - Values of xsl:with-param by name\n * @returns {void}\n */\n applyTemplateRule(nodeList, index, mode, context, output, params) {\n const node = nodeList[index];\n const template = this.findMatchingTemplate(node, mode, context);\n\n if (template) {\n const newContext = this.invocationContext(context, template, {\n currentNode: node,\n currentNodeList: nodeList,\n position: index + 1,\n currentMode: mode,\n });\n\n this.processTemplate(template.node, newContext, output, params);\n } else {\n this.applyBuiltinTemplate(node, mode, context, output, params);\n }\n },\n\n /**\n * Context of a template invocation: no local bindings, the template as\n * current template and the prefixes in scope on the xsl:template element.\n *\n * @param {XsltContext} context - Context of the invoking instruction\n * @param {object} template - The template record\n * @param {object} [overrides] - Further properties to change\n * @returns {XsltContext} The invocation context\n */\n invocationContext(context, template, overrides = {}) {\n const invocation = context.clone({\n currentTemplate: template,\n ...overrides,\n fresh: true,\n });\n invocation.namespaces = template.namespaces ?? context.namespaces;\n return invocation;\n },\n\n /**\n * Apply the built-in template rules (XSLT 1.0 section 5.8). Parameters are\n * passed on to the templates applied to the children, as libxslt does.\n *\n * @param {Node} node - The node without a matching template\n * @param {string|null} mode - The mode\n * @param {XsltContext} context - Context of the invoking instruction\n * @param {Node} output - The result node receiving the output\n * @param {Object<string, *>|null} [params] - Values of xsl:with-param by name\n * @returns {void}\n */\n applyBuiltinTemplate(node, mode, context, output, params = null) {\n switch (node.nodeType) {\n case 1: // Element\n case 9: // Document\n case 11: // Document Fragment\n this.applyTemplates(\n childAxis(node),\n mode,\n context,\n output,\n params,\n true,\n );\n break;\n\n case 2: // Attribute\n case 3: // Text\n case 4: // CDATA\n // Copy the string value; a text node stands for its whole text run\n output.appendChild(\n context.outputDocument.createTextNode(\n this.xpathEvaluator.getStringValue(node),\n ),\n );\n break;\n\n // Comments and PIs have no built-in template\n }\n },\n\n /**\n * Instantiate a template. Each `xsl:param` takes the value of the\n * `xsl:with-param` of the same name, else its default, evaluated after the\n * preceding parameters were bound (XSLT 1.0 section 11.6). The body runs\n * from the work stack once the invoking instruction returns.\n *\n * @param {Element|object} templateNode - The xsl:template element\n * @param {XsltContext} context - A fresh invocation context\n * @param {Node} output - The result node receiving the output\n * @param {Object<string, *>|null} [params] - Values of xsl:with-param by name\n * @returns {void}\n */\n processTemplate(templateNode, context, output, params = null) {\n for (\n let child = templateNode.firstChild;\n child;\n child = child.nextSibling\n ) {\n if (child.nodeType !== 1 || !this.isXsltElement(child, \"param\")) continue;\n\n const name = child.getAttribute(\"name\");\n context.parameters[name] =\n params && Object.hasOwn(params, name)\n ? params[name]\n : this.evaluateVariable(\n { node: child, select: child.getAttribute(\"select\") },\n context,\n );\n }\n\n const frame = new SequenceFrame(this, templateNode, context, output);\n frame.template = true;\n this.continueWith(frame);\n },\n\n /**\n * Instantiate `xsl:apply-templates`: the selected nodes (default the\n * children), sorted by the xsl:sort children, with the xsl:with-param\n * values.\n *\n * @param {Element} node - The xsl:apply-templates instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n xslApplyTemplates(node, context, output) {\n const select = node.getAttribute(\"select\") || \"node()\";\n const mode = node.getAttribute(\"mode\") || null;\n const nodes = this.sortNodes(\n selectNodes(this, select, context),\n this.sortElementsOf(node),\n context,\n );\n const params = this.withParams(node, context);\n this.applyTemplates(nodes, mode, context, output, params);\n },\n\n /**\n * Instantiate `xsl:apply-imports`.\n *\n * Only templates with a lower import precedence than the template being\n * instantiated are considered; when none matches, the built-in template rules\n * apply, exactly as for `xsl:apply-templates`.\n *\n * @param {Element} node - The `xsl:apply-imports` element\n * @param {XsltContext} context - The current XSLT context\n * @param {Node} output - The result tree node receiving the output\n * @returns {void}\n */\n xslApplyImports(node, context, output) {\n const currentNode = context.currentNode;\n const mode = context.currentMode ?? null;\n const precedence = context.currentTemplate\n ? context.currentTemplate.importPrecedence || 0\n : 0;\n\n const template = this.findMatchingTemplate(\n currentNode,\n mode,\n context,\n precedence,\n );\n\n if (!template) {\n this.applyBuiltinTemplate(currentNode, mode, context, output);\n return;\n }\n\n // xsl:apply-imports passes no parameters (XSLT 1.0 section 5.6)\n this.processTemplate(\n template.node,\n this.invocationContext(context, template),\n output,\n );\n },\n\n /**\n * Instantiate `xsl:call-template` with its xsl:with-param values.\n *\n * @param {Element} node - The xsl:call-template instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n * @throws {Error} When no template has that name\n */\n xslCallTemplate(node, context, output) {\n const name = node.getAttribute(\"name\");\n const template = this.findNamedTemplate(\n requireExpandedName(name ?? \"\", node, \"xsl:call-template name\"),\n );\n if (!template) {\n throw new Error(`Template not found: ${name}`);\n }\n\n // A named template does not become the current template rule\n const invocation = this.invocationContext(context, template, {\n currentTemplate: context.currentTemplate,\n });\n this.processTemplate(\n template.node,\n invocation,\n output,\n this.withParams(node, context),\n );\n },\n};\n", "/**\n * `xsl:strip-space` and `xsl:preserve-space` support.\n *\n * XSLT 1.0 removes whitespace-only text nodes from the source tree before the\n * transformation starts. This module builds a stripped copy of the source so\n * the caller's document is never mutated, and resolves the usual conflict rules\n * between the two declarations.\n */\n\n\"use strict\";\n\nimport { isTextContinuation, isTextNode } from \"../xpath/axes.js\";\nimport { matchesNameTest, nameTestPriority } from \"./spaceNameTests.js\";\n\n/** Node type of a document type declaration, which cannot be imported. */\nconst DOCUMENT_TYPE_NODE = 10;\n\n/** Text made only of XML whitespace: #x20, #x9, #xD and #xA (not NBSP). */\nconst XML_WHITESPACE_ONLY = /^[ \\t\\r\\n]*$/;\n\n/**\n * Whether a string consists of XML whitespace only (XML 1.0 production S).\n * Unlike `trim()` and `\\s`, a no-break space is not whitespace.\n *\n * @param {string} text - Any string\n * @returns {boolean} True for \"\" and strings of #x20 #x9 #xD #xA\n *\n * @example\n * isXmlWhitespace(\" \\n\"); // true\n * isXmlWhitespace(\"\\u00a0\"); // false\n */\nexport function isXmlWhitespace(text) {\n return XML_WHITESPACE_ONLY.test(text);\n}\n\n/**\n * The DOM nodes of the text run starting at a node: the node and every\n * directly following Text/CDATA sibling (one XPath text node).\n *\n * @param {Node} first - The first node of the run\n * @returns {Node[]} The nodes of the run\n */\nexport function textRun(first) {\n const run = [first];\n for (\n let next = first.nextSibling;\n isTextNode(next);\n next = next.nextSibling\n ) {\n run.push(next);\n }\n return run;\n}\n\n/**\n * Decides which whitespace-only text nodes of the source tree are removed.\n */\nexport class WhitespaceFilter {\n /**\n * @param {Array<string|import('./spaceNameTests.js').ElementNameTest>} [stripSpace] -\n * Name tests from `xsl:strip-space`: expanded (see spaceNameTests.js),\n * or strings matched by their lexical name\n * @param {Array<string|import('./spaceNameTests.js').ElementNameTest>} [preserveSpace] -\n * Name tests from `xsl:preserve-space`\n */\n constructor(stripSpace = [], preserveSpace = []) {\n this.stripSpace = stripSpace;\n this.preserveSpace = preserveSpace;\n }\n\n /**\n * Whether the filter can remove anything at all.\n *\n * @returns {boolean} True when at least one `xsl:strip-space` was declared\n *\n * @example\n * new WhitespaceFilter(['*']).isActive(); // true\n */\n isActive() {\n return this.stripSpace.length > 0;\n }\n\n /**\n * Whether whitespace-only children of an element are stripped.\n *\n * The most specific name test wins; `xsl:preserve-space` wins ties.\n *\n * @param {Element} element - The parent element\n * @returns {boolean} True when whitespace-only text children are removed\n *\n * @example\n * new WhitespaceFilter(['*'], ['pre']).isStripped(preElement); // false\n */\n isStripped(element) {\n let stripPriority = -Infinity;\n let preservePriority = -Infinity;\n\n for (const nameTest of this.stripSpace) {\n if (matchesNameTest(element, nameTest)) {\n stripPriority = Math.max(stripPriority, nameTestPriority(nameTest));\n }\n }\n\n for (const nameTest of this.preserveSpace) {\n if (matchesNameTest(element, nameTest)) {\n preservePriority = Math.max(\n preservePriority,\n nameTestPriority(nameTest),\n );\n }\n }\n\n return stripPriority > -Infinity && stripPriority > preservePriority;\n }\n}\n\n/**\n * Check whether `xml:space=\"preserve\"` is in scope for a node.\n *\n * @param {Node} node - The node to inspect\n * @returns {boolean} True when whitespace must be preserved\n */\nfunction hasXmlSpacePreserve(node) {\n let current = node;\n\n while (current?.nodeType === 1) {\n const value = current.getAttribute(\"xml:space\");\n if (value === \"preserve\") return true;\n if (value === \"default\") return false;\n current = current.parentNode;\n }\n\n return false;\n}\n\n/**\n * Remove whitespace-only text nodes from a subtree. Adjacent Text/CDATA\n * nodes form one text node and are only removed together.\n *\n * @param {Node} root - The root of the subtree to prune\n * @param {WhitespaceFilter} filter - The configured filter\n * @returns {void}\n */\nfunction pruneWhitespace(root, filter) {\n const doomed = [];\n const stack = [root];\n\n while (stack.length > 0) {\n const current = stack.pop();\n\n if (\n isTextNode(current) &&\n !isTextContinuation(current) &&\n current.parentNode?.nodeType === 1 &&\n filter.isStripped(current.parentNode) &&\n !hasXmlSpacePreserve(current.parentNode)\n ) {\n const run = textRun(current);\n if (run.every((node) => isXmlWhitespace(node.nodeValue))) {\n doomed.push(...run);\n }\n }\n\n const children = current.childNodes;\n if (children) {\n for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]);\n }\n }\n\n for (const node of doomed) node.parentNode.removeChild(node);\n}\n\n/**\n * Build a copy of the source tree with stripped whitespace removed.\n *\n * @param {Node} sourceNode - The source document or element\n * @param {WhitespaceFilter} filter - The configured filter\n * @param {Document} targetDoc - An empty document owning the copy\n * @returns {Node} The stripped copy, a document when the source was a document\n *\n * @example\n * const stripped = stripWhitespaceNodes(xmlDoc, filter, emptyDoc);\n */\nexport function stripWhitespaceNodes(sourceNode, filter, targetDoc) {\n let root;\n\n if (sourceNode.nodeType === 9) {\n root = targetDoc;\n for (const child of Array.from(sourceNode.childNodes)) {\n if (child.nodeType === DOCUMENT_TYPE_NODE) continue;\n targetDoc.appendChild(targetDoc.importNode(child, true));\n }\n } else {\n root = targetDoc.importNode(sourceNode, true);\n targetDoc.appendChild(root);\n }\n\n pruneWhitespace(root, filter);\n return root;\n}\n", "/**\n * Instantiation of sequence constructors: the dispatch of each child of a\n * template body to its instruction, stylesheet text, unknown XSLT elements,\n * xsl:fallback and extension elements.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { isTextContinuation } from \"../../xpath/axes.js\";\nimport { isXmlWhitespace } from \"../whitespace.js\";\nimport { isExtensionElement } from \"../stylesheetNamespaces.js\";\nimport { xsltLocalName } from \"../stylesheetChecks.js\";\nimport { fallbackChildren } from \"../forwardsCompatible.js\";\nimport { SequenceFrame } from \"./workStack.js\";\n\n/**\n * Engine method instantiating each XSLT element that may occur in a sequence\n * constructor; null marks elements that produce nothing there.\n */\nconst INSTRUCTION_METHODS = Object.freeze({\n \"apply-templates\": \"xslApplyTemplates\",\n \"apply-imports\": \"xslApplyImports\",\n \"call-template\": \"xslCallTemplate\",\n \"value-of\": \"xslValueOf\",\n text: \"xslText\",\n element: \"xslElement\",\n attribute: \"xslAttribute\",\n if: \"xslIf\",\n choose: \"xslChoose\",\n \"for-each\": \"xslForEach\",\n copy: \"xslCopy\",\n \"copy-of\": \"xslCopyOf\",\n variable: \"xslVariable\",\n comment: \"xslComment\",\n \"processing-instruction\": \"xslProcessingInstruction\",\n number: \"xslNumber\",\n message: \"xslMessage\",\n // Handled by their parent instruction, or at template start\n param: null,\n sort: null,\n \"with-param\": null,\n // Used for forward compatibility\n fallback: null,\n});\n\nexport const sequenceConstructorMethods = {\n /**\n * Instantiate the children of a stylesheet element (a sequence\n * constructor) now, for instructions that use the result at once.\n *\n * @param {Element|object} node - The parent stylesheet element\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n processChildren(node, context, output) {\n this.runFrame(new SequenceFrame(this, node, context, output));\n },\n\n /**\n * Instantiate the children of a stylesheet element once the current\n * instruction returns (see workStack.js), keeping the JavaScript stack flat\n * in deep recursion. For content that comes last in an instruction.\n *\n * @param {Element|object} node - The parent stylesheet element\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @param {(() => void)|null} [then] - Called once the children are done\n * @returns {void}\n */\n scheduleChildren(node, context, output, then = null) {\n this.continueWith(new SequenceFrame(this, node, context, output, then));\n },\n\n /**\n * Whether an element has an xsl:variable child. Cached per element.\n *\n * @param {Element|object} node - A stylesheet element\n * @returns {boolean} True when a child declares a variable\n */\n declaresVariables(node) {\n this.variableDeclarations ??= new WeakMap();\n let declares = this.variableDeclarations.get(node);\n if (declares === undefined) {\n declares = false;\n for (let child = node.firstChild; child; child = child.nextSibling) {\n if (this.isXsltElement(child, \"variable\")) declares = true;\n }\n this.variableDeclarations.set(node, declares);\n }\n return declares;\n },\n\n /**\n * Instantiate a stylesheet text node. Adjacent text and CDATA nodes form\n * one text node, which is dropped when it only holds XML whitespace (unless\n * xml:space=\"preserve\" is in scope, XSLT 1.0 section 3.4).\n *\n * @param {Text} node - A text or CDATA node of the stylesheet\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n processText(node, context, output) {\n if (isTextContinuation(node)) return;\n const text = this.xpathEvaluator.getStringValue(node);\n if (text && (!isXmlWhitespace(text) || this.shouldPreserveSpace(node))) {\n output.appendChild(context.outputDocument.createTextNode(text));\n }\n },\n\n /**\n * Whether xml:space=\"preserve\" is in scope on a stylesheet text node.\n *\n * @param {Node} node - The text node\n * @returns {boolean} True when the nearest xml:space says preserve\n */\n shouldPreserveSpace(node) {\n let current = node.parentNode;\n while (current && current.nodeType === 1) {\n const space = current.getAttribute(\"xml:space\");\n if (space === \"preserve\") return true;\n if (space === \"default\") return false;\n current = current.parentNode;\n }\n return false;\n },\n\n /**\n * Name of the engine method instantiating a stylesheet element: the\n * handler of an XSLT instruction, processLiteralResultElement, or\n * instantiateUnknown for an XSLT element the engine does not implement.\n * Returns null for elements that are not instructions (xsl:param,\n * xsl:sort, xsl:with-param, xsl:fallback).\n *\n * @param {Element} node - A stylesheet element in a sequence constructor\n * @returns {string|null} The method name\n */\n instructionMethod(node) {\n if (!this.isXsltNamespace(node)) {\n return isExtensionElement(node)\n ? \"instantiateExtension\"\n : \"processLiteralResultElement\";\n }\n\n const localName = node.localName || node.nodeName.replace(/^xsl:/, \"\");\n if (Object.hasOwn(INSTRUCTION_METHODS, localName)) {\n return INSTRUCTION_METHODS[localName];\n }\n return \"instantiateUnknown\";\n },\n\n /**\n * Instantiate an XSLT element the engine does not implement (XSLT 1.0\n * section 15): its xsl:fallback children are instantiated in order; without\n * any, the error is reported and nothing is produced.\n *\n * @param {Element} node - The unknown XSLT element\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n instantiateUnknown(node, context, output) {\n if (!this.instantiateFallbacks(node, context, output)) {\n console.warn(`Unknown XSLT element: ${xsltLocalName(node)}`);\n }\n },\n\n /**\n * Instantiate the xsl:fallback children of an element in order.\n *\n * @param {Element} node - An unknown XSLT element or extension element\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {boolean} Whether the element had any xsl:fallback child\n */\n instantiateFallbacks(node, context, output) {\n const fallbacks = fallbackChildren(node);\n for (const fallback of fallbacks) {\n this.processChildren(fallback, context, output);\n }\n return fallbacks.length > 0;\n },\n\n /**\n * Register the implementation of an extension element (XSLT 1.0 section\n * 14.1). It is called as `handler(node, context, output, engine)` where\n * an element of that name is instantiated in a namespace declared with\n * `extension-element-prefixes`.\n *\n * @param {string} namespaceUri - The extension namespace\n * @param {string} localName - The element's local name\n * @param {(node: Element, context: XsltContext, output: Node, engine: XsltEngine) => void} handler - The implementation\n * @returns {XsltEngine} This engine, to allow chaining\n *\n * @example\n * engine.registerExtensionElement(\"urn:my\", \"log\", (node) => console.log(node.textContent));\n */\n registerExtensionElement(namespaceUri, localName, handler) {\n this.extensionElements.set(`{${namespaceUri}}${localName}`, handler);\n return this;\n },\n\n /**\n * Instantiate an extension element: its registered implementation, else\n * its xsl:fallback children (XSLT 1.0 sections 14.1 and 15); without\n * either, the error is reported once and nothing is produced, as libxslt\n * does. An extension element is never copied to the result.\n *\n * @param {Element} node - The extension element\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the output\n * @returns {void}\n */\n instantiateExtension(node, context, output) {\n const name = `{${node.namespaceURI}}${node.localName}`;\n const handler = this.extensionElements.get(name);\n if (handler) {\n handler(node, context, output, this);\n return;\n }\n if (!this.instantiateFallbacks(node, context, output)) {\n this.warnOnce(\n `extension element ${node.nodeName} (${name}) is not supported and has no xsl:fallback`,\n );\n }\n },\n};\n", "/**\n * Variable and parameter bindings (XSLT 1.0 section 11).\n *\n * Local bindings live in the `variables` and `parameters` objects of an\n * XSLT context; the engine gives every template invocation empty ones and a\n * new copy to every sequence constructor that declares a variable, which\n * makes local variables lexically scoped. Global variables and parameters are\n * kept in a {@link GlobalBindings} table shared by all contexts of one\n * transformation and are evaluated lazily, so they may refer to each other in\n * any order (section 11.4).\n *\n * @module xslt/variables\n */\n\n\"use strict\";\n\n/** Evaluation states of a global binding. */\nconst PENDING = 0;\nconst EVALUATING = 1;\nconst DONE = 2;\n\n/**\n * The global variables and parameters of one transformation.\n */\nexport class GlobalBindings {\n /**\n * @param {(definition: object) => *} evaluate - Computes the value of a\n * definition; called at most once per name\n */\n constructor(evaluate) {\n this.evaluate = evaluate;\n this.entries = new Map();\n }\n\n /**\n * Declare a global binding. A later declaration of the same name replaces\n * an earlier one.\n *\n * @param {string} name - The variable or parameter name\n * @param {object} definition - Passed to the evaluate callback\n * @returns {void}\n *\n * @example\n * globals.define('title', { select: \"'Report'\" });\n */\n define(name, definition) {\n this.entries.set(name, { definition, state: PENDING, value: undefined });\n }\n\n /**\n * Whether a global binding with that name exists.\n *\n * @param {string} name - The variable name\n * @returns {boolean} True when declared\n */\n has(name) {\n return this.entries.has(name);\n }\n\n /**\n * The value of a global binding, evaluating it on first use.\n *\n * @param {string} name - The variable name\n * @returns {*} The value, undefined when the name is not declared\n * @throws {Error} When the definition (indirectly) refers to itself\n *\n * @example\n * globals.get('title'); // \"Report\"\n */\n get(name) {\n const entry = this.entries.get(name);\n if (!entry) return undefined;\n if (entry.state === DONE) return entry.value;\n if (entry.state === EVALUATING) {\n throw new Error(\n `Circular definition of global variable $${name} (XSLT 1.0 section 11.4)`,\n );\n }\n\n entry.state = EVALUATING;\n try {\n entry.value = this.evaluate(entry.definition);\n } catch (error) {\n entry.state = PENDING;\n throw error;\n }\n entry.state = DONE;\n return entry.value;\n }\n\n /**\n * Evaluate every binding, in declaration order, so that errors and\n * `xsl:message` side effects of unused globals still surface.\n *\n * @returns {void}\n */\n evaluateAll() {\n for (const name of this.entries.keys()) this.get(name);\n }\n}\n\n/**\n * Look a variable up in an XSLT context: local variables, then local\n * parameters, then the globals.\n *\n * @param {{variables: object, parameters: object, globals?: GlobalBindings|null}} context - The XSLT context\n * @param {string} name - The variable name\n * @returns {{found: boolean, value: *}} Whether it is bound, and its value\n */\nexport function lookupVariable(context, name) {\n if (Object.hasOwn(context.variables, name)) {\n return { found: true, value: context.variables[name] };\n }\n if (Object.hasOwn(context.parameters, name)) {\n return { found: true, value: context.parameters[name] };\n }\n const globals = context.globals;\n if (globals?.has(name)) return { found: true, value: globals.get(name) };\n return { found: false, value: undefined };\n}\n\n/**\n * Read-only object view of the variables in scope of an XSLT context, in the\n * shape the XPath evaluator expects (`hasOwnProperty` + property access).\n * Nothing is copied: lookups read the context live, and globals are only\n * evaluated when an expression actually refers to them.\n *\n * @param {object} context - The XSLT context\n * @returns {object} A proxy mapping variable names to values\n *\n * @example\n * new XPathContext(node, 1, 1, createVariableView(xsltContext), namespaces);\n */\nexport function createVariableView(context) {\n const binding = (name) =>\n typeof name === \"string\" ? lookupVariable(context, name) : null;\n\n return new Proxy(Object.create(null), {\n has: (_target, name) => binding(name)?.found === true,\n get: (_target, name) => binding(name)?.value,\n getOwnPropertyDescriptor: (_target, name) => {\n const found = binding(name);\n if (!found?.found) return undefined;\n return {\n value: found.value,\n writable: false,\n enumerable: true,\n configurable: true,\n };\n },\n });\n}\n", "/**\n * Variables and parameters: external parameter values, the global bindings\n * of a transformation, variable values, xsl:variable and xsl:with-param.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { trimXmlSpace } from \"../../xpath/strings.js\";\nimport { inScopeNamespaces } from \"../stylesheetNamespaces.js\";\nimport { GlobalBindings } from \"../variables.js\";\n\n/**\n * Whether a variable-binding element has content (XSLT 1.0 section 11.2).\n *\n * Whitespace-only text is stripped from stylesheets, and comments and\n * processing instructions are not part of a template, so they do not count.\n *\n * @param {Element|undefined} node - xsl:variable, xsl:param or xsl:with-param\n * @returns {boolean} True when instantiating the element produces a fragment\n */\nfunction hasTemplateContent(node) {\n for (let child = node?.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1) return true;\n const isText = child.nodeType === 3 || child.nodeType === 4;\n if (isText && trimXmlSpace(child.nodeValue) !== \"\") return true;\n }\n return false;\n}\n\nexport const bindingMethods = {\n /**\n * Supply the value of a global parameter from outside the stylesheet.\n *\n * The value is merged into the `xsl:param` declaration when there is one, so\n * removing the value later restores the declared default.\n *\n * @param {string} name - The parameter name, `{uri}local` when namespaced\n * @param {*} value - The value to use\n * @returns {void}\n *\n * @example\n * engine.setParameterValue('sortOrder', 'ascending');\n */\n setParameterValue(name, value) {\n const definition = this.globalParameters[name];\n\n if (definition) definition.value = value;\n else this.globalParameters[name] = { value };\n },\n\n /**\n * Remove an externally supplied parameter value.\n *\n * The `xsl:param` declaration of the stylesheet is kept, so the parameter\n * falls back to its declared default instead of becoming undefined.\n *\n * @param {string} name - The parameter name, `{uri}local` when namespaced\n * @returns {void}\n *\n * @example\n * engine.clearParameterValue('sortOrder');\n */\n clearParameterValue(name) {\n const definition = this.globalParameters[name];\n if (!definition) return;\n\n if (definition.node) delete definition.value;\n else delete this.globalParameters[name];\n },\n\n /**\n * Remove every externally supplied parameter value.\n *\n * @returns {void}\n *\n * @example\n * engine.clearParameterValues();\n */\n clearParameterValues() {\n for (const name of Object.keys(this.globalParameters)) {\n this.clearParameterValue(name);\n }\n },\n\n /**\n * Declare the global variables and parameters of the stylesheet for one\n * transformation. They are evaluated lazily with the root node as context\n * node (XSLT 1.0 section 11.4), so they may refer to each other in any\n * order. Of a variable and a parameter of the same name, the one with the\n * higher import precedence wins (section 11.4), the variable when the\n * precedences are equal.\n *\n * @param {XsltContext} rootContext - The initial context\n * @returns {GlobalBindings} The global bindings\n */\n createGlobals(rootContext) {\n const globals = new GlobalBindings((def) => {\n const context = rootContext.clone();\n if (def.node) context.namespaces = inScopeNamespaces(def.node);\n return this.evaluateVariable(def, context);\n });\n\n for (const [name, def] of Object.entries(this.globalParameters)) {\n globals.define(name, def);\n }\n for (const [name, def] of Object.entries(this.globalVariables)) {\n const param = this.globalParameters[name];\n if (param?.node && param.importPrecedence > def.importPrecedence) {\n continue;\n }\n globals.define(name, def);\n }\n return globals;\n },\n\n /**\n * Compute the value of a variable or parameter definition.\n *\n * A value supplied from outside (`setParameter`) wins over the `select`\n * expression and over the instantiated content of the declaration.\n *\n * @param {{value?: *, select?: string, node?: Element}} def - The definition\n * @param {XsltContext} context - The context used for evaluation\n * @returns {*} The variable value\n */\n evaluateVariable(def, context) {\n if (\"value\" in def) {\n return def.value;\n }\n\n if (def.select) {\n return this.evaluateXPath(def.select, context);\n }\n\n // Empty content and no select: the value is an empty string (XSLT 11.2),\n // which is false in a boolean test, unlike an (always true) fragment.\n if (!hasTemplateContent(def.node)) {\n return \"\";\n }\n\n // Otherwise the content is instantiated as a result tree fragment\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(def.node, context, fragment);\n return fragment;\n },\n\n /**\n * Evaluate the xsl:with-param children of an apply-templates or\n * call-template instruction.\n *\n * @param {Element} node - The invoking instruction\n * @param {XsltContext} context - Its context\n * @returns {Object<string, *>} Values by parameter name\n */\n withParams(node, context) {\n const params = {};\n for (let child = node.firstChild; child; child = child.nextSibling) {\n if (this.isXsltElement(child, \"with-param\")) {\n params[child.getAttribute(\"name\")] = this.evaluateVariable(\n { node: child, select: child.getAttribute(\"select\") },\n context,\n );\n }\n }\n return params;\n },\n\n /**\n * Instantiate xsl:variable: bind the variable for the following siblings.\n * Content is instantiated from the work stack (see workStack.js), so\n * recursion inside a variable keeps the JavaScript stack flat, and the\n * fragment is bound once it is complete.\n *\n * @param {Element} node - The xsl:variable element\n * @param {XsltContext} context - The current context\n * @param {Node} _output - Unused: a variable produces no output\n * @returns {void}\n */\n xslVariable(node, context, _output) {\n const name = node.getAttribute(\"name\");\n const select = node.getAttribute(\"select\");\n if (select || !hasTemplateContent(node)) {\n context.setVariable(\n name,\n this.evaluateVariable({ node, select }, context),\n );\n return;\n }\n\n const fragment = context.outputDocument.createDocumentFragment();\n this.scheduleChildren(node, context, fragment, () =>\n context.setVariable(name, fragment),\n );\n },\n};\n", "/**\n * Attribute value templates (XSLT 1.0 section 7.6.2).\n *\n * An AVT is literal text with XPath expressions in curly braces. A brace\n * inside a string literal of an expression is part of the literal, so the\n * template is split with a small scanner that knows '...' and \"...\" literals;\n * `{{` and `}}` outside expressions stand for single braces. A lone `}` in the\n * literal text is an error in the recommendation; it is kept as a character\n * instead, like browsers do. Parsed templates are cached per string.\n *\n * @module xslt/avt\n */\n\n\"use strict\";\n\n/**\n * @typedef {string | {expr: string}} AvtPart\n * A literal text part, or an expression part.\n */\n\nconst cache = new Map();\n\n/**\n * Find the `}` closing an expression that starts at `start`.\n *\n * @param {string} value - The whole template\n * @param {number} start - Index just after the opening `{`\n * @returns {number} Index of the closing `}`\n * @throws {Error} When the expression is not closed\n */\nfunction closingBrace(value, start) {\n let quote = null;\n for (let i = start; i < value.length; i++) {\n const char = value[i];\n if (quote) {\n if (char === quote) quote = null;\n } else if (char === \"'\" || char === '\"') {\n quote = char;\n } else if (char === \"}\") {\n return i;\n }\n }\n throw new Error(`Unclosed expression in attribute value template: ${value}`);\n}\n\n/**\n * Split an attribute value template into literal and expression parts.\n *\n * @param {string} value - The attribute value\n * @returns {AvtPart[]} The parts, adjacent literals merged\n * @throws {Error} When an expression is not closed\n *\n * @example\n * parseAvt(\"a{@b}c\"); // [\"a\", { expr: \"@b\" }, \"c\"]\n */\nexport function parseAvt(value) {\n let parts = cache.get(value);\n if (parts) return parts;\n\n parts = [];\n let text = \"\";\n let i = 0;\n while (i < value.length) {\n const char = value[i];\n if ((char === \"{\" || char === \"}\") && value[i + 1] === char) {\n text += char;\n i += 2;\n } else if (char === \"{\") {\n const end = closingBrace(value, i + 1);\n if (text) parts.push(text);\n text = \"\";\n parts.push({ expr: value.slice(i + 1, end) });\n i = end + 1;\n } else {\n text += char;\n i++;\n }\n }\n if (text) parts.push(text);\n\n cache.set(value, parts);\n return parts;\n}\n\n/**\n * Evaluate an attribute value template.\n *\n * @param {string} value - The attribute value\n * @param {(expr: string) => string} evaluate - Evaluates one expression to a string\n * @returns {string} The resulting text\n *\n * @example\n * evaluateAvt(\"{1+1}px\", (e) => String(eval(e))); // \"2px\"\n */\nexport function evaluateAvt(value, evaluate) {\n if (!value.includes(\"{\") && !value.includes(\"}\")) return value;\n\n let result = \"\";\n for (const part of parseAvt(value)) {\n result += typeof part === \"string\" ? part : evaluate(part.expr);\n }\n return result;\n}\n", "/**\n * Instructions producing text: xsl:value-of, xsl:text, xsl:comment,\n * xsl:processing-instruction and xsl:message, and attribute value templates.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { evaluateAvt } from \"../avt.js\";\n\n/**\n * Append a text node to the result unless the text is empty.\n *\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the text\n * @param {string} text - The text\n * @param {boolean} disableOutputEscaping - Whether the serializer must write\n * the text without escaping\n * @returns {void}\n */\nfunction appendText(context, output, text, disableOutputEscaping) {\n if (!text) return;\n const textNode = context.outputDocument.createTextNode(text);\n if (disableOutputEscaping) {\n textNode._disableOutputEscaping = true;\n }\n output.appendChild(textNode);\n}\n\n/**\n * Whether an instruction has disable-output-escaping=\"yes\".\n *\n * @param {Element} node - xsl:value-of or xsl:text\n * @returns {boolean} True when output escaping is disabled\n */\nfunction disablesOutputEscaping(node) {\n return node.getAttribute(\"disable-output-escaping\") === \"yes\";\n}\n\nexport const textInstructionMethods = {\n /**\n * Instantiate `xsl:value-of`: the string value of the expression.\n *\n * @param {Element} node - The xsl:value-of instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the text\n * @returns {void}\n */\n xslValueOf(node, context, output) {\n const result = this.evaluateXPath(node.getAttribute(\"select\"), context);\n appendText(\n context,\n output,\n this.xpathEvaluator.toString(result),\n disablesOutputEscaping(node),\n );\n },\n\n /**\n * Instantiate `xsl:text`: its text and CDATA children.\n *\n * @param {Element} node - The xsl:text instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the text\n * @returns {void}\n */\n xslText(node, context, output) {\n let text = \"\";\n for (const child of node.childNodes) {\n if (child.nodeType === 3 || child.nodeType === 4) {\n text += child.nodeValue || \"\";\n }\n }\n appendText(context, output, text, disablesOutputEscaping(node));\n },\n\n /**\n * Instantiate the content of an instruction and return its string value,\n * for instructions whose result is text (attribute, comment, PI, message).\n *\n * @param {Element} node - The instruction\n * @param {XsltContext} context - The current context\n * @returns {string} The text of the instantiated content\n */\n instantiateText(node, context) {\n const fragment = context.outputDocument.createDocumentFragment();\n this.processChildren(node, context, fragment);\n return this.xpathEvaluator.getStringValue(fragment);\n },\n\n /**\n * Instantiate `xsl:comment`. \"--\" and a trailing \"-\" are made safe by the\n * serializer (XSLT 1.0 section 7.4).\n *\n * @param {Element} node - The xsl:comment instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the comment\n * @returns {void}\n */\n xslComment(node, context, output) {\n const text = this.instantiateText(node, context);\n output.appendChild(context.outputDocument.createComment(text));\n },\n\n /**\n * Instantiate `xsl:processing-instruction`, with the error recovery of\n * XSLT 1.0 section 7.3: \"?>\" cannot end the data early.\n *\n * @param {Element} node - The xsl:processing-instruction instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the PI\n * @returns {void}\n */\n xslProcessingInstruction(node, context, output) {\n const name = this.processAttributeValueTemplate(\n node.getAttribute(\"name\"),\n context,\n );\n const data = this.instantiateText(node, context).replaceAll(\"?>\", \"? >\");\n const pi = context.outputDocument.createProcessingInstruction(name, data);\n output.appendChild(pi);\n },\n\n /**\n * Instantiate `xsl:message`: log the text, and stop the transformation\n * with terminate=\"yes\".\n *\n * @param {Element} node - The xsl:message instruction\n * @param {XsltContext} context - The current context\n * @param {Node} _output - Unused: a message produces no output\n * @returns {void}\n * @throws {Error} With terminate=\"yes\"\n */\n xslMessage(node, context, _output) {\n const terminate = node.getAttribute(\"terminate\") === \"yes\";\n const text = this.instantiateText(node, context);\n\n console.log(\"XSLT Message:\", text);\n\n if (terminate) {\n throw new Error(`XSLT terminated: ${text}`);\n }\n },\n\n /**\n * Evaluate an attribute value template (see avt.js).\n *\n * @param {string} value - The attribute value\n * @param {XsltContext} context - The current context\n * @returns {string} The resulting text\n */\n processAttributeValueTemplate(value, context) {\n return evaluateAvt(value, (expr) =>\n this.xpathEvaluator.toString(this.evaluateXPath(expr, context)),\n );\n },\n\n /**\n * Evaluate an optional attribute value template attribute.\n *\n * @param {Element} node - The instruction\n * @param {string} name - The attribute name\n * @param {XsltContext} context - The current context\n * @returns {string|null} The value, or null when the attribute is absent\n */\n optionalAvt(node, name, context) {\n const raw = node.getAttribute(name);\n return raw === null\n ? null\n : this.processAttributeValueTemplate(raw, context);\n },\n};\n", "/**\n * `xsl:number` counting (XSLT 1.0 section 7.7).\n *\n * Counting is kept independent from the engine: callers pass a `matcher`\n * callback that answers \"does this node match this XSLT pattern\", which keeps\n * this module free of the XPath evaluator and easy to test in isolation.\n *\n * Numbering every node of a long list would be quadratic if each call counted\n * from scratch, so a call may be given a memo (one per instruction and\n * transformation, see {@link isMemoizable}) remembering the numbers already\n * computed: a later call stops at the nearest numbered node. The tree is\n * walked with previousSibling/lastChild/parentNode only.\n */\n\n\"use strict\";\n\nimport { isParserArtifact } from \"../xpath/axes.js\";\n\n/** Node types that participate in `xsl:number` counting. */\nconst COUNTABLE_NODE_TYPES = new Set([1, 3, 4, 7, 8]);\n\n/**\n * Whether a node takes part in counting: an element, text, processing\n * instruction or comment of the data model (not a parser artifact, see\n * axes.js).\n *\n * @param {Node} node - Any node\n * @returns {boolean} True for countable nodes\n */\nfunction isCountable(node) {\n return COUNTABLE_NODE_TYPES.has(node.nodeType) && !isParserArtifact(node);\n}\n\n/**\n * The XPath node kind of a DOM node: CDATA sections are text nodes.\n *\n * @param {Node} node - Any node\n * @returns {number} The DOM node type, 3 for CDATA sections\n */\nfunction nodeKind(node) {\n return node.nodeType === 4 ? 3 : node.nodeType;\n}\n\n/**\n * Default `count` pattern: nodes of the same kind as the numbered node and,\n * for elements and attributes, the same expanded name; for processing\n * instructions, the same target.\n *\n * @param {Node} candidate - The node being considered\n * @param {Node} node - The node `xsl:number` is numbering\n * @returns {boolean} True when the candidate is counted\n */\nfunction matchesDefaultCount(candidate, node) {\n if (nodeKind(candidate) !== nodeKind(node)) return false;\n switch (node.nodeType) {\n case 1:\n case 2:\n return (\n candidate.localName === node.localName &&\n (candidate.namespaceURI ?? null) === (node.namespaceURI ?? null)\n );\n case 7:\n return candidate.target === node.target;\n default:\n return true;\n }\n}\n\n/**\n * Key telling apart the node kinds the default `count` pattern selects, so\n * memoized numbers are only reused for the same kind.\n *\n * @param {Node} node - The numbered node\n * @returns {string} e.g. `1|urn:x|item`\n */\nfunction defaultCountKey(node) {\n if (node.nodeType === 7) return `7|${node.target}`;\n if (node.nodeType === 1 || node.nodeType === 2) {\n return `${node.nodeType}|${node.namespaceURI ?? \"\"}|${node.localName}`;\n }\n return String(nodeKind(node));\n}\n\n/**\n * Whether the numbers of an instruction may be memoized: its patterns must\n * not depend on variables or on the current node, whose values may differ\n * between invocations of the same instruction.\n *\n * @param {string|null} count - The `count` pattern\n * @param {string|null} from - The `from` pattern\n * @returns {boolean} True when counting only depends on the source tree\n *\n * @example\n * isMemoizable(\"item\", null); // true\n * isMemoizable(\"item[@k=$k]\", null); // false\n */\nexport function isMemoizable(count, from) {\n return !/\\$|current\\s*\\(/.test(`${count ?? \"\"} ${from ?? \"\"}`);\n}\n\n/**\n * Count a node's preceding siblings satisfying the predicate, stopping at the\n * nearest one whose position is memoized.\n *\n * @param {Node} node - The (counted) node whose position is computed\n * @param {(candidate: Node) => boolean} isCounted - Counting predicate\n * @param {WeakMap<Node, number>|null} positions - Memoized positions\n * @returns {number} The 1-based position\n */\nfunction siblingPosition(node, isCounted, positions) {\n const own = positions?.get(node);\n if (own !== undefined) return own;\n\n let position = 1;\n for (let sibling = node.previousSibling; sibling;) {\n const known = positions?.get(sibling);\n if (known !== undefined) {\n position += known;\n break;\n }\n if (isCountable(sibling) && isCounted(sibling)) {\n position++;\n }\n sibling = sibling.previousSibling;\n }\n positions?.set(node, position);\n return position;\n}\n\n/**\n * Whether a node hangs off an element without being its child: an\n * attribute or a namespace node, whose parent is `ownerElement`.\n *\n * @param {Node} node - Any node\n * @returns {boolean} True for attribute and namespace nodes\n */\nfunction isAttachedNode(node) {\n return node.nodeType === 2 || node.nodeType === 13;\n}\n\n/**\n * The node before another one in document order (its preceding node or its\n * parent).\n *\n * @param {Node} node - A child node\n * @returns {Node|null} The previous node, null at the root\n */\nfunction previousInDocumentOrder(node) {\n let previous = node.previousSibling;\n if (!previous) return node.parentNode;\n while (previous.lastChild) previous = previous.lastChild;\n return previous;\n}\n\n/**\n * Count the ancestors-or-self of a node according to `level=\"single\"` or\n * `level=\"multiple\"`.\n *\n * @param {Node} node - The node being numbered\n * @param {boolean} multiple - Whether every counted ancestor is numbered\n * @param {(candidate: Node) => boolean} isCounted - Counting predicate\n * @param {(candidate: Node) => boolean} isFrom - Boundary predicate\n * @param {WeakMap<Node, number>|null} positions - Memoized positions\n * @returns {number[]} Numbers from the outermost ancestor inwards\n */\nfunction countAncestors(node, multiple, isCounted, isFrom, positions) {\n const numbers = [];\n let current = node;\n\n while (current && current.nodeType !== 9) {\n if (isFrom(current)) break;\n if (isCounted(current)) {\n numbers.unshift(siblingPosition(current, isCounted, positions));\n if (!multiple) break;\n }\n current = isAttachedNode(current)\n ? current.ownerElement\n : current.parentNode;\n }\n\n return numbers;\n}\n\n/**\n * Count a node according to `level=\"any\"`: walk backwards in document order\n * until a `from` node, the root, or a node whose total is memoized. An\n * attribute or namespace node counts itself, then its element and the nodes\n * before it: other attributes are neither preceding nor ancestor nodes (as\n * in libxslt).\n *\n * @param {Node} node - The node being numbered\n * @param {(candidate: Node) => boolean} isCounted - Counting predicate\n * @param {(candidate: Node) => boolean} isFrom - Boundary predicate\n * @param {WeakMap<Node, number>|null} totals - Memoized totals\n * @returns {number[]} A single number, or an empty list when nothing matches\n */\nfunction countAny(node, isCounted, isFrom, totals) {\n let total = 0;\n let current = node;\n if (isAttachedNode(node)) {\n if (isFrom(node)) return [];\n if (isCounted(node)) total++;\n current = node.ownerElement;\n }\n\n while (current && current.nodeType !== 9) {\n const known = totals?.get(current);\n if (known !== undefined) {\n total += known;\n break;\n }\n if (isCountable(current)) {\n if (isFrom(current)) break;\n if (isCounted(current)) total++;\n }\n current = previousInDocumentOrder(current);\n }\n\n totals?.set(node, total);\n return total > 0 ? [total] : [];\n}\n\n/**\n * The memo tables of one kind of counted node.\n *\n * @param {Map<string, {positions: WeakMap, totals: WeakMap}>|null} memo - The instruction's memo\n * @param {string} key - The counted kind\n * @returns {{positions: WeakMap, totals: WeakMap}|null} The tables, null without memo\n */\nfunction memoTables(memo, key) {\n if (!memo) return null;\n let tables = memo.get(key);\n if (!tables) {\n tables = { positions: new WeakMap(), totals: new WeakMap() };\n memo.set(key, tables);\n }\n return tables;\n}\n\n/**\n * Compute the number sequence for an `xsl:number` instruction.\n *\n * @param {Node} node - The current node\n * @param {{level?: string, count?: string|null, from?: string|null}} options - Instruction attributes\n * @param {(node: Node, pattern: string) => boolean} matcher - XSLT pattern matcher\n * @param {Map|null} [memo] - Memo of the instruction for the current\n * transformation (a Map owned by the caller), or null to count from scratch\n * @returns {number[]} The computed numbers, outermost first\n *\n * @example\n * countXsltNumber(item, { level: 'any' }, matcher); // [2]\n */\nexport function countXsltNumber(node, options, matcher, memo = null) {\n const { level = \"single\", count = null, from = null } = options;\n const isCounted = count\n ? (candidate) => matcher(candidate, count)\n : (candidate) => matchesDefaultCount(candidate, node);\n const isFrom = from ? (candidate) => matcher(candidate, from) : () => false;\n const tables = memoTables(memo, count ? \"\" : defaultCountKey(node));\n\n if (level === \"any\") {\n return countAny(node, isCounted, isFrom, tables?.totals ?? null);\n }\n return countAncestors(\n node,\n level === \"multiple\",\n isCounted,\n isFrom,\n tables?.positions ?? null,\n );\n}\n", "/**\n * `xsl:number` number-to-string conversion.\n *\n * Renders the number sequence produced by {@link countXsltNumber} using the\n * `format` attribute of `xsl:number`: numeric tokens (`1`, `01`, and the\n * same in any Unicode digit family, e.g. `\u0660\u0661`), alphabetic tokens (`a`, `A`)\n * and Roman numerals (`i`, `I`), together with the prefix, separators and\n * suffix taken from the format string itself.\n *\n * Extreme values follow libxslt: a negative number is formatted as 0, NaN\n * and Infinity as by `string()`, alphabetic and Roman tokens use decimals\n * below 1 (and Roman ones above 5000), and every conversion takes O(log n)\n * steps, so a huge value cannot stall the transformation.\n */\n\n\"use strict\";\n\n/**\n * Convert a positive integer to a bijective base-26 alphabetic sequence.\n *\n * @param {number} value - The number to convert\n * @param {boolean} upperCase - Whether to emit upper case letters\n * @returns {string} The alphabetic representation, e.g. `27` becomes `aa`\n */\nfunction toAlphabetic(value, upperCase) {\n let remaining = value;\n let result = \"\";\n\n while (remaining > 0) {\n const index = (remaining - 1) % 26;\n result = String.fromCodePoint((upperCase ? 65 : 97) + index) + result;\n remaining = Math.floor((remaining - 1) / 26);\n }\n\n return result;\n}\n\n/** Roman numeral building blocks, largest first. */\nconst ROMAN_NUMERALS = Object.freeze([\n [\"M\", 1000],\n [\"CM\", 900],\n [\"D\", 500],\n [\"CD\", 400],\n [\"C\", 100],\n [\"XC\", 90],\n [\"L\", 50],\n [\"XL\", 40],\n [\"X\", 10],\n [\"IX\", 9],\n [\"V\", 5],\n [\"IV\", 4],\n [\"I\", 1],\n]);\n\n/** Largest number written with Roman numerals, as in libxslt. */\nconst MAX_ROMAN = 5000;\n\n/**\n * Convert a positive integer to a Roman numeral.\n *\n * @param {number} value - The number to convert\n * @returns {string} The upper case Roman numeral\n *\n * @example\n * toRoman(2004); // 'MMIV'\n */\nexport function toRoman(value) {\n let remaining = value;\n let result = \"\";\n\n for (const [numeral, amount] of ROMAN_NUMERALS) {\n result += numeral.repeat(Math.floor(remaining / amount));\n remaining %= amount;\n }\n\n return result;\n}\n\n/**\n * Insert a grouping separator every `size` digits, counting from the right.\n *\n * @param {string} digits - The decimal digits\n * @param {{separator?: string, size?: number}} grouping - The grouping settings\n * @returns {string} The grouped digits\n */\nfunction groupDigits(digits, { separator, size }) {\n if (!separator || Number.isNaN(size) || size <= 0) return digits;\n\n let result = \"\";\n for (let end = digits.length; end > 0; end -= size) {\n const group = digits.slice(Math.max(0, end - size), end);\n result = result ? `${group}${separator}${result}` : group;\n }\n return result;\n}\n\n/** A Unicode decimal digit (general category Nd). */\nconst DECIMAL_DIGIT = /^\\p{Nd}$/u;\n\n/**\n * Whether a code point is a Unicode decimal digit.\n *\n * @param {number} codePoint - Any code point\n * @returns {boolean} True for characters of category Nd\n */\nfunction isDecimalDigit(codePoint) {\n return DECIMAL_DIGIT.test(String.fromCodePoint(codePoint));\n}\n\n/**\n * The zero of the digit family of a decimal format token: a token whose\n * last character has the digit value 1 and whose other characters are the\n * zero of that family (XSLT 1.0 section 7.7.1), e.g. `1`, `01`, `\u0660\u0661`.\n * Digit families are runs of ten code points, which may follow each other\n * (the mathematical digits), so the value is counted from the run start.\n *\n * @param {string} token - A format token\n * @returns {number|null} The code point of the family's zero, or null\n */\nfunction decimalTokenZero(token) {\n const digits = Array.from(token, (char) => char.codePointAt(0));\n const one = digits.at(-1);\n if (!isDecimalDigit(one)) return null;\n let start = one;\n while (isDecimalDigit(start - 1)) start--;\n const zero = one - 1;\n if ((one - start) % 10 !== 1) return null;\n return digits.slice(0, -1).every((digit) => digit === zero) ? zero : null;\n}\n\n/**\n * The decimal digits of a non-negative integer, without exponent notation.\n *\n * @param {number} value - A finite, non-negative integer\n * @returns {string} Its ASCII decimal digits\n */\nfunction decimalDigits(value) {\n return Number.isSafeInteger(value) ? String(value) : BigInt(value).toString();\n}\n\n/**\n * Write a number with decimal digits of a family, padded with zeros to a\n * minimum width and grouped.\n *\n * @param {number} value - A finite, non-negative integer\n * @param {number} zero - Code point of the family's zero\n * @param {number} width - Minimum number of digits\n * @param {{separator?: string, size?: number}} grouping - Digit grouping\n * @returns {string} The rendered number\n */\nfunction formatDecimal(value, zero, width, grouping) {\n const ascii = decimalDigits(value).padStart(width, \"0\");\n const digits =\n zero === 0x30\n ? ascii\n : Array.from(ascii, (digit) =>\n String.fromCodePoint(zero + Number(digit)),\n ).join(\"\");\n return groupDigits(digits, grouping);\n}\n\n/**\n * Render one number with a single `xsl:number` format token.\n *\n * @param {number} value - The number to render\n * @param {string} token - The format token, e.g. `1`, `01`, `a`, `I`\n * @param {{separator?: string, size?: number}} grouping - Digit grouping\n * @returns {string} The rendered number\n */\nfunction formatToken(value, token, grouping) {\n if (Number.isNaN(value) || value === Infinity) return String(value);\n // Negative numbers are an error that libxslt recovers from with 0\n const number = value < 0 ? 0 : Math.round(value);\n\n if (/^\\d+$/.test(token)) {\n return formatDecimal(number, 0x30, token.length, grouping);\n }\n const zero = decimalTokenZero(token);\n if (zero !== null) {\n return formatDecimal(number, zero, Array.from(token).length, grouping);\n }\n\n const alphabetic = token === \"a\" || token === \"A\";\n const roman = token === \"i\" || token === \"I\";\n if (number < 1 || (roman && number > MAX_ROMAN) || (!alphabetic && !roman)) {\n return decimalDigits(number);\n }\n if (alphabetic) return toAlphabetic(number, token === \"A\");\n return token === \"I\" ? toRoman(number) : toRoman(number).toLowerCase();\n}\n\n/**\n * Split an `xsl:number` format string into prefix, tokens, separators, suffix.\n *\n * @param {string} format - The format attribute value\n * @returns {{prefix: string, suffix: string, tokens: string[], separators: string[]}} The parsed format\n */\nfunction parseFormat(format) {\n const parts = format.match(/[\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+/gu) || [];\n const isToken = (part) => /^[\\p{L}\\p{N}]+$/u.test(part);\n\n const tokens = [];\n const separators = [];\n let prefix = \"\";\n let suffix = \"\";\n\n for (const part of parts) {\n if (isToken(part)) tokens.push(part);\n else if (tokens.length === 0) prefix = part;\n else separators.push(part);\n }\n\n if (parts.length > 0 && tokens.length > 0 && !isToken(parts.at(-1))) {\n suffix = separators.pop();\n }\n\n if (tokens.length === 0) tokens.push(\"1\");\n\n return { prefix, suffix, tokens, separators };\n}\n\n/**\n * Format a number sequence produced by {@link countXsltNumber}.\n *\n * Decimal tokens are grouped when both `grouping.separator` and a positive\n * `grouping.size` are given (the `grouping-separator` and `grouping-size`\n * attributes).\n *\n * @param {number[]} numbers - The numbers, outermost first\n * @param {string} [format] - The `format` attribute value\n * @param {{separator?: string, size?: number}} [grouping] - Digit grouping\n * @returns {string} The formatted string, empty when there is nothing to number\n *\n * @example\n * formatXsltNumber([2, 3], '1.1'); // '2.3'\n * formatXsltNumber([1234567], '1', { separator: ',', size: 3 }); // '1,234,567'\n */\nexport function formatXsltNumber(numbers, format = \"1\", grouping = {}) {\n if (numbers.length === 0) return \"\";\n\n const { prefix, suffix, tokens, separators } = parseFormat(format);\n let result = prefix;\n\n numbers.forEach((value, index) => {\n if (index > 0) {\n const separator = separators[index - 1] ?? separators.at(-1) ?? \".\";\n result += separator;\n }\n result += formatToken(value, tokens[index] ?? tokens.at(-1), grouping);\n });\n\n return result + suffix;\n}\n", "/**\n * xsl:number (XSLT 1.0 section 7.7) and the number formatting helpers.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { countXsltNumber, isMemoizable } from \"../number.js\";\nimport { formatXsltNumber, toRoman } from \"../numberFormat.js\";\n\n/**\n * The numbers an xsl:number instruction formats: its rounded `value`, else\n * the position of the current node counted by level, count and from.\n *\n * @param {object} engine - The engine\n * @param {Element} node - The xsl:number instruction\n * @param {XsltContext} context - The current context\n * @returns {number[]} The numbers\n */\nfunction numberValues(engine, node, context) {\n const value = node.getAttribute(\"value\");\n if (value) {\n const number = Math.round(\n engine.xpathEvaluator.toNumber(engine.evaluateXPath(value, context)),\n );\n // An error that libxslt reports and recovers from by numbering 0\n if (number < 0) {\n engine.warnOnce(\"xsl:number: negative value, 0 is used\");\n }\n return [number];\n }\n\n const count = node.getAttribute(\"count\");\n const from = node.getAttribute(\"from\");\n return countXsltNumber(\n context.currentNode,\n { level: node.getAttribute(\"level\") || \"single\", count, from },\n (candidate, pattern) => engine.matchesPattern(candidate, pattern, context),\n isMemoizable(count, from) ? engine.numberMemo(node) : null,\n );\n}\n\nexport const numberingMethods = {\n /**\n * Instantiate `xsl:number` (XSLT 1.0 section 7.7). The formatting\n * attributes format, grouping-separator and grouping-size are attribute\n * value templates; lang and letter-value have no effect.\n *\n * @param {Element} node - The xsl:number instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the number\n * @returns {void}\n */\n xslNumber(node, context, output) {\n const format = this.optionalAvt(node, \"format\", context) || \"1\";\n const grouping = {\n separator: this.optionalAvt(node, \"grouping-separator\", context),\n size: Number(this.optionalAvt(node, \"grouping-size\", context)),\n };\n const numbers = numberValues(this, node, context);\n\n const text = context.outputDocument.createTextNode(\n formatXsltNumber(numbers, format, grouping),\n );\n output.appendChild(text);\n },\n\n /**\n * The memo of an xsl:number instruction for the current transformation\n * (see number.js), so numbering a long list stays linear.\n *\n * @param {Element} node - The xsl:number instruction\n * @returns {Map} The instruction's memo\n */\n numberMemo(node) {\n this.numberMemos ??= new WeakMap();\n let memo = this.numberMemos.get(node);\n if (!memo) {\n memo = new Map();\n this.numberMemos.set(node, memo);\n }\n return memo;\n },\n\n /**\n * Format a single number with an `xsl:number` format token.\n *\n * @param {number} number - The number to format\n * @param {string} format - The format token, e.g. `1`, `01`, `a`, `I`\n * @returns {string} The formatted number\n */\n formatNumber(number, format) {\n return formatXsltNumber([number], format);\n },\n\n /**\n * Convert a number to an upper case Roman numeral.\n *\n * @param {number} num - The number to convert\n * @returns {string} The Roman numeral\n */\n toRoman(num) {\n return toRoman(num);\n },\n};\n", "/**\n * Validation of the names computed by `xsl:element` and `xsl:attribute`\n * (XSLT 1.0 sections 7.1.2 and 7.1.3).\n *\n * The `name` attribute is an attribute value template, so its value is only\n * known at run time. It must be a QName whose prefix (when there is no\n * `namespace` attribute) is declared in scope on the instruction, and an\n * attribute may not be called `xmlns` (nor use the `xmlns` prefix). Like\n * libxslt, the processor recovers from these errors by reporting them and not\n * creating the element (with its content) or the attribute.\n *\n * @module xslt/computedNames\n */\n\n\"use strict\";\n\nimport { isQName } from \"./qname.js\";\nimport { attributeName, elementName, splitQName } from \"./resultNamespaces.js\";\nimport { resolvePrefix } from \"./stylesheetNamespaces.js\";\n\n/**\n * @typedef {object} ComputedName\n * @property {{namespaceUri: (string|null), qname: string}} [name] - The\n * expanded name, when valid\n * @property {string} [error] - Why no node can be created, when invalid\n */\n\n/**\n * Check the parts shared by element and attribute names.\n *\n * @param {string} kind - \"element\" or \"attribute\", used in messages\n * @param {string} qname - The evaluated `name` attribute\n * @param {string|null} namespace - The evaluated `namespace` attribute, null when absent\n * @param {Object<string, string>} scope - Namespaces in scope on the instruction\n * @returns {string|null} The error message, or null when the name is usable\n */\nfunction nameError(kind, qname, namespace, scope) {\n if (!isQName(qname)) {\n return `xsl:${kind}: \"${qname}\" is not a valid ${kind} name (QName), the ${kind} is not created`;\n }\n const { prefix } = splitQName(qname);\n if (namespace === null && prefix && !resolvePrefix(scope, prefix)) {\n return `xsl:${kind}: undefined namespace prefix \"${prefix}\" in \"${qname}\", the ${kind} is not created`;\n }\n return null;\n}\n\n/**\n * Resolve the name computed by `xsl:element`.\n *\n * @param {string} qname - The evaluated `name` attribute\n * @param {string|null} namespace - The evaluated `namespace` attribute, null when absent\n * @param {Object<string, string>} scope - Namespaces in scope on the instruction\n * @returns {ComputedName} The expanded name, or the error to report\n *\n * @example\n * computedElementName(\"p:e\", null, { p: \"urn:p\" }).name;\n * // { namespaceUri: \"urn:p\", qname: \"p:e\" }\n * computedElementName(\"x{\", null, {}).error; // 'xsl:element: \"x{\" is not ...'\n */\nexport function computedElementName(qname, namespace, scope) {\n const error = nameError(\"element\", qname, namespace, scope);\n return error ? { error } : { name: elementName(qname, namespace, scope) };\n}\n\n/**\n * Resolve the name computed by `xsl:attribute`; `xmlns` and `xmlns:*` are\n * rejected because namespace declarations are not attributes.\n *\n * @param {string} qname - The evaluated `name` attribute\n * @param {string|null} namespace - The evaluated `namespace` attribute, null when absent\n * @param {Object<string, string>} scope - Namespaces in scope on the instruction\n * @returns {ComputedName} The expanded name, or the error to report\n *\n * @example\n * computedAttributeName(\"xmlns\", null, {}).error;\n * // 'xsl:attribute: \"xmlns\" cannot be used as an attribute name ...'\n */\nexport function computedAttributeName(qname, namespace, scope) {\n // With a namespace attribute, the prefix of `xmlns:a` is only a hint and\n // is replaced (libxslt REC/test-7.1.3)\n const xmlnsName =\n qname === \"xmlns\" || (namespace === null && qname.startsWith(\"xmlns:\"));\n if (xmlnsName) {\n return {\n error: `xsl:attribute: \"${qname}\" cannot be used as an attribute name (XSLT 1.0 section 7.1.3), the attribute is not created`,\n };\n }\n const error = nameError(\"attribute\", qname, namespace, scope);\n return error ? { error } : { name: attributeName(qname, namespace, scope) };\n}\n", "/**\n * Creation of result elements and attributes: literal result elements,\n * xsl:element, xsl:attribute and attribute sets.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { XSLT_NAMESPACE } from \"../elements.js\";\nimport { getXsltAttribute, shouldCopyAttribute } from \"../literalResult.js\";\nimport {\n copyLiteralNamespaces,\n setResultAttribute,\n} from \"../resultNamespaces.js\";\nimport {\n computedAttributeName,\n computedElementName,\n} from \"../computedNames.js\";\nimport { applyAttributeSets } from \"../attributeSets.js\";\nimport { requireExpandedNames } from \"../declarationNames.js\";\n\nexport const nodeConstructionMethods = {\n /**\n * Copy one attribute of a literal result element to the result, evaluating\n * it as an attribute value template and applying xsl:namespace-alias.\n *\n * @param {Attr} attr - Attribute of the literal result element\n * @param {XsltContext} context - The current XSLT context\n * @param {Element} outputElement - The result element\n * @returns {void}\n */\n copyLiteralAttribute(attr, context, outputElement) {\n const value = this.processAttributeValueTemplate(attr.value, context);\n const alias = this.namespaceAliases.resolveLiteral(attr);\n\n if (alias) {\n outputElement.setAttributeNS(alias.namespaceUri, alias.qname, value);\n } else if (attr.namespaceURI) {\n outputElement.setAttributeNS(attr.namespaceURI, attr.name, value);\n } else {\n outputElement.setAttribute(attr.name, value);\n }\n },\n\n /**\n * Process a literal result element (non-XSLT)\n *\n * Applies `xsl:namespace-alias` to the element and its attributes, honours\n * `xsl:use-attribute-sets` and keeps XSLT-only attributes and namespace\n * declarations out of the result tree.\n *\n * @param {Element} node - The literal result element in the stylesheet\n * @param {XsltContext} context - The current XSLT context\n * @param {Node} output - The result tree node receiving the element\n * @returns {void}\n */\n processLiteralResultElement(node, context, output) {\n const alias = this.namespaceAliases.resolveLiteral(node);\n const namespaceUri = alias ? alias.namespaceUri : node.namespaceURI;\n const qname = alias ? alias.qname : node.nodeName;\n\n const outputElement =\n namespaceUri && context.outputDocument.createElementNS\n ? context.outputDocument.createElementNS(namespaceUri, qname)\n : context.outputDocument.createElement(qname);\n // Attached first, so namespace lookups see the result ancestors\n output.appendChild(outputElement);\n copyLiteralNamespaces(outputElement, node, output, (uri) =>\n this.namespaceAliases.isAliased(uri),\n );\n\n // Attribute sets come first so literal attributes take precedence\n const useAttributeSets = getXsltAttribute(\n node,\n \"use-attribute-sets\",\n XSLT_NAMESPACE,\n );\n if (useAttributeSets) {\n this.applyAttributeSets(useAttributeSets, context, outputElement, node);\n }\n\n for (const attr of node.attributes) {\n if (shouldCopyAttribute(attr, XSLT_NAMESPACE)) {\n this.copyLiteralAttribute(attr, context, outputElement);\n }\n }\n\n this.scheduleChildren(node, context, outputElement);\n },\n\n /**\n * Instantiate `xsl:element`. The name's prefix, or the default namespace\n * for an unprefixed name, resolves against the namespaces in scope on the\n * instruction; a `namespace` attribute wins (XSLT 1.0 section 7.1.2).\n * An invalid name or an undeclared prefix is reported and, as in libxslt,\n * neither the element nor its content is created.\n *\n * @param {Element} node - The xsl:element instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the element\n * @returns {void}\n */\n xslElement(node, context, output) {\n const { name, error } = computedElementName(\n this.processAttributeValueTemplate(node.getAttribute(\"name\"), context),\n this.optionalAvt(node, \"namespace\", context),\n context.namespaces,\n );\n if (error) {\n this.warnOnce(error);\n return;\n }\n const { namespaceUri, qname } = name;\n const element = namespaceUri\n ? context.outputDocument.createElementNS(namespaceUri, qname)\n : context.outputDocument.createElement(qname);\n output.appendChild(element);\n\n const useAttributeSets = node.getAttribute(\"use-attribute-sets\");\n if (useAttributeSets) {\n this.applyAttributeSets(useAttributeSets, context, element, node);\n }\n\n this.scheduleChildren(node, context, element);\n },\n\n /**\n * Instantiate `xsl:attribute` (XSLT 1.0 section 7.1.3): a prefixed name\n * uses the namespace bound in scope, `namespace` wins, and a namespaced\n * attribute without a usable prefix gets a generated one. An invalid name,\n * an undeclared prefix or `xmlns` is reported and the attribute skipped.\n *\n * @param {Element} node - The xsl:attribute instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result element receiving the attribute\n * @returns {void}\n */\n xslAttribute(node, context, output) {\n if (!this.canAddAttribute(output)) return;\n\n const { name, error } = computedAttributeName(\n this.processAttributeValueTemplate(node.getAttribute(\"name\"), context),\n this.optionalAvt(node, \"namespace\", context),\n context.namespaces,\n );\n if (error) {\n this.warnOnce(error);\n return;\n }\n setResultAttribute(output, name, this.instantiateText(node, context));\n },\n\n /**\n * Whether an attribute may still be added to a result node: it must be an\n * element without children. Attributes added after children are ignored\n * (as libxslt does), with a single warning per engine.\n *\n * @param {Node} target - The result node\n * @returns {boolean} True when the attribute can be added\n */\n canAddAttribute(target) {\n if (target.nodeType !== 1) return false;\n if (!target.firstChild) return true;\n this.warnOnce(\n \"an attribute created after the children of an element is ignored (XSLT 1.0 section 7.1.3)\",\n );\n return false;\n },\n\n /**\n * Apply the attribute sets named by a `use-attribute-sets` attribute (see\n * attributeSets.js). The xsl:attribute children of each declaration are\n * instantiated with the prefixes in scope there.\n *\n * @param {string} names - Whitespace separated QNames\n * @param {XsltContext} context - Context of the instruction\n * @param {Element} element - The result element receiving the attributes\n * @param {Element} instruction - The element carrying the attribute, whose\n * namespace declarations expand the names\n * @returns {void}\n */\n applyAttributeSets(names, context, element, instruction) {\n const keys = requireExpandedNames(names, instruction, \"use-attribute-sets\");\n applyAttributeSets(this.attributeSets, keys, (declaration) =>\n this.processChildren(declaration, context, element),\n );\n },\n};\n", "/**\n * Copying source nodes to the result tree: `xsl:copy-of` (XSLT 1.0 section\n * 11.3) and the node kinds of `xsl:copy` (section 7.5).\n *\n * Copies follow the XPath data model rather than the raw DOM: a run of\n * adjacent Text/CDATA nodes is one text node (its first DOM node stands for\n * the run), copying a root node copies its children, and copying an attribute\n * or a namespace node adds it to the result element being built. Names keep their namespace and\n * elements keep their namespace declarations.\n *\n * @module xslt/copying\n */\n\n\"use strict\";\n\nimport { childAxis } from \"../xpath/axes.js\";\nimport { NAMESPACE_NODE, inScopeBindings } from \"../xpath/namespaceNodes.js\";\nimport { copyNamespaceDeclarations } from \"./resultNamespaces.js\";\nimport { XMLNS_NAMESPACE } from \"./stylesheetNamespaces.js\";\n\n/**\n * Copy an attribute node onto a result element. A namespace declaration or a\n * target that is not an element is ignored; so is an attribute added after\n * the element got children (see {@link canAddAttribute}).\n *\n * @param {Attr} attribute - The source attribute\n * @param {Node} target - The result node receiving it\n * @param {(element: Node) => boolean} canAddAttribute - Guard for late attributes\n * @returns {void}\n */\nexport function copyAttribute(attribute, target, canAddAttribute) {\n if (attribute.namespaceURI === XMLNS_NAMESPACE) return;\n if (!canAddAttribute(target)) return;\n if (attribute.namespaceURI) {\n target.setAttributeNS(\n attribute.namespaceURI,\n attribute.name,\n attribute.value,\n );\n } else {\n target.setAttribute(attribute.name, attribute.value);\n }\n}\n\n/**\n * Copy a namespace node onto a result element as a namespace declaration\n * (XSLT 1.0 sections 7.5 and 11.3). As in libxslt, nothing is declared for\n * the implicit `xml` binding, for a prefix the element's own name binds to\n * another namespace, for a prefix the element already declares differently,\n * or when the element already has children (see `canAddAttribute`).\n *\n * @param {import('../xpath/namespaceNodes.js').NamespaceNode} namespace - The namespace node\n * @param {Node} target - The result node receiving it\n * @param {(element: Node) => boolean} canAddNamespace - Guard for late nodes\n * @returns {void}\n *\n * @example\n * copyNamespaceNode(nsNode, resultElement, () => true); // xmlns:a=\"urn:a\"\n */\nexport function copyNamespaceNode(namespace, target, canAddNamespace) {\n const prefix = namespace.localName;\n if (prefix === \"xml\" || !canAddNamespace(target)) return;\n const uri = namespace.nodeValue;\n if ((target.prefix ?? \"\") === prefix && (target.namespaceURI ?? \"\") !== uri) {\n return;\n }\n const declared = target.getAttributeNS(XMLNS_NAMESPACE, prefix || \"xmlns\");\n if (declared !== null && declared !== uri) return;\n target.setAttributeNS(\n XMLNS_NAMESPACE,\n prefix ? `xmlns:${prefix}` : \"xmlns\",\n uri,\n );\n}\n\n/**\n * Create a shallow copy of an element: same expanded name and prefix, and the\n * same namespace declarations.\n *\n * @param {Element} element - The source element\n * @param {Document} doc - The result document\n * @returns {Element} The empty copy\n */\nexport function shallowCopyElement(element, doc) {\n const copy = element.namespaceURI\n ? doc.createElementNS(element.namespaceURI, element.nodeName)\n : doc.createElement(element.nodeName);\n copyNamespaceDeclarations(element, copy);\n return copy;\n}\n\n/**\n * Deep copy of a node that can be a child in the result tree.\n *\n * @param {Node} node - Element, text, CDATA, comment, PI or document fragment\n * @param {Document} doc - The result document\n * @param {(node: Node) => string} stringValue - XPath string value (text runs)\n * @returns {Node|null} The copy, or null for nodes that cannot be children\n *\n * @example\n * cloneNode(sourceElement, resultDocument, (n) => evaluator.getStringValue(n));\n */\nexport function cloneNode(node, doc, stringValue) {\n switch (node.nodeType) {\n case 1: {\n const copy = shallowCopyElement(node, doc);\n for (const attribute of node.attributes) {\n copyAttribute(attribute, copy, () => true);\n }\n appendChildCopies(node, copy, doc, stringValue);\n return copy;\n }\n case 3:\n case 4:\n return doc.createTextNode(stringValue(node));\n case 7:\n return doc.createProcessingInstruction(node.target, node.data);\n case 8:\n return doc.createComment(node.nodeValue);\n case 11: {\n const fragment = doc.createDocumentFragment();\n appendChildCopies(node, fragment, doc, stringValue);\n return fragment;\n }\n default:\n return null;\n }\n}\n\n/**\n * Append deep copies of the (XPath) children of a node.\n *\n * @param {Node} node - The source parent\n * @param {Node} target - The result parent\n * @param {Document} doc - The result document\n * @param {(node: Node) => string} stringValue - XPath string value\n * @returns {void}\n */\nfunction appendChildCopies(node, target, doc, stringValue) {\n for (const child of childAxis(node)) {\n const copy = cloneNode(child, doc, stringValue);\n if (copy) target.appendChild(copy);\n }\n}\n\n/**\n * Declare on the copy of an element every namespace in scope on the source\n * element that is not in scope on the result parent already: `xsl:copy-of`\n * copies the namespace nodes of an element (XSLT 1.0 section 11.3), those\n * declared on its ancestors included, as libxslt does for the top element of\n * a copied tree (its descendants inherit them in the result).\n *\n * @param {Element} source - The copied source element\n * @param {Element} copy - Its copy, not yet attached\n * @param {Node} output - The result node receiving the copy\n * @returns {void}\n */\nfunction copyInScopeNamespaces(source, copy, output) {\n const inOutput = (prefix, uri) =>\n output.nodeType === 1 && output.lookupNamespaceURI(prefix || null) === uri;\n for (const [prefix, uri] of inScopeBindings(source)) {\n if (!inOutput(prefix, uri)) {\n copyNamespaceNode(\n { localName: prefix, nodeValue: uri },\n copy,\n () => true,\n );\n }\n }\n}\n\n/**\n * Copy the result of an `xsl:copy-of` select expression to the result tree.\n *\n * Node-sets are copied node by node (roots as their children, attributes onto\n * the current result element); any other value is written as text.\n *\n * @param {*} value - The evaluated expression\n * @param {Node} output - The result node receiving the copy\n * @param {object} host - Engine services\n * @param {Document} host.doc - The result document\n * @param {(node: Node) => string} host.stringValue - XPath string value\n * @param {(value: *) => string} host.toString - XPath string() conversion\n * @param {(element: Node) => boolean} host.canAddAttribute - Guard for attributes\n * @returns {void}\n */\nexport function copyOf(value, output, host) {\n if (Array.isArray(value)) {\n for (const item of value) copyOf(item, output, host);\n return;\n }\n\n if (value === null || value === undefined) return;\n if (!value.nodeType) {\n const text = host.toString(value);\n if (text) output.appendChild(host.doc.createTextNode(text));\n return;\n }\n\n if (value.nodeType === 2) {\n copyAttribute(value, output, host.canAddAttribute);\n } else if (value.nodeType === NAMESPACE_NODE) {\n copyNamespaceNode(value, output, host.canAddAttribute);\n } else if (value.nodeType === 9 || value.nodeType === 11) {\n // Children one by one: xmldom mishandles appending a DocumentFragment\n appendChildCopies(value, output, host.doc, host.stringValue);\n } else {\n const copy = cloneNode(value, host.doc, host.stringValue);\n if (value.nodeType === 1) copyInScopeNamespaces(value, copy, output);\n if (copy) output.appendChild(copy);\n }\n}\n", "/**\n * Copying source nodes to the result: xsl:copy and xsl:copy-of.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport {\n cloneNode,\n copyAttribute,\n copyNamespaceNode,\n copyOf,\n shallowCopyElement,\n} from \"../copying.js\";\n\nexport const copyInstructionMethods = {\n /**\n * Instantiate `xsl:copy`: a shallow copy of the current node; the content\n * is instantiated into a copied element, or directly for a root node.\n *\n * @param {Element} node - The xsl:copy instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the copy\n * @returns {void}\n */\n xslCopy(node, context, output) {\n const currentNode = context.currentNode;\n const useAttributeSets = node.getAttribute(\"use-attribute-sets\");\n\n switch (currentNode.nodeType) {\n case 1: {\n // Element, with its namespace declarations (XSLT 1.0 section 7.5)\n const copy = shallowCopyElement(currentNode, context.outputDocument);\n output.appendChild(copy);\n\n if (useAttributeSets) {\n this.applyAttributeSets(useAttributeSets, context, copy, node);\n }\n\n this.scheduleChildren(node, context, copy);\n break;\n }\n\n case 2: // Attribute\n copyAttribute(currentNode, output, (target) =>\n this.canAddAttribute(target),\n );\n break;\n\n case 13: // Namespace node: a namespace declaration\n copyNamespaceNode(currentNode, output, (target) =>\n this.canAddAttribute(target),\n );\n break;\n\n case 3: // Text\n case 4: // CDATA; a text node stands for its whole text run\n output.appendChild(\n context.outputDocument.createTextNode(\n this.xpathEvaluator.getStringValue(currentNode),\n ),\n );\n break;\n\n case 7: // Processing Instruction\n output.appendChild(\n context.outputDocument.createProcessingInstruction(\n currentNode.target,\n currentNode.data,\n ),\n );\n break;\n\n case 8: // Comment\n output.appendChild(\n context.outputDocument.createComment(currentNode.nodeValue || \"\"),\n );\n break;\n\n case 9: // Document\n case 11: // Document Fragment\n this.scheduleChildren(node, context, output);\n break;\n }\n },\n\n /**\n * Instantiate `xsl:copy-of`: a deep copy of the selected value.\n *\n * @param {Element} node - The xsl:copy-of instruction\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the copy\n * @returns {void}\n */\n xslCopyOf(node, context, output) {\n const select = node.getAttribute(\"select\");\n const result = this.evaluateXPath(select, context);\n\n this.copyToOutput(result, context, output);\n },\n\n /**\n * Copy a value to the result tree as `xsl:copy-of` does (see copying.js).\n *\n * @param {*} value - The value to copy\n * @param {XsltContext} context - The current context\n * @param {Node} output - The result node receiving the copy\n * @returns {void}\n */\n copyToOutput(value, context, output) {\n copyOf(value, output, {\n doc: context.outputDocument,\n stringValue: (node) => this.xpathEvaluator.getStringValue(node),\n toString: (item) => this.xpathEvaluator.toString(item),\n canAddAttribute: (target) => this.canAddAttribute(target),\n });\n },\n\n /**\n * Deep copy of a node for the result tree (see copying.js); nodes that\n * cannot be children become an empty text node.\n *\n * @param {Node} node - The node to copy\n * @param {Document} targetDoc - The result document\n * @returns {Node} The copy\n */\n deepCloneNode(node, targetDoc) {\n return (\n cloneNode(node, targetDoc, (text) =>\n this.xpathEvaluator.getStringValue(text),\n ) ?? targetDoc.createTextNode(\"\")\n );\n },\n};\n", "/**\n * Result tree construction helpers.\n *\n * XSLT builds its result tree in a neutral XML document: building directly in\n * an HTML owner document would lower case element names and force the XHTML\n * namespace on every created element. The finished tree is imported into the\n * caller's document only at the very end, which keeps names, namespaces and the\n * `disable-output-escaping` markers intact.\n */\n\n\"use strict\";\n\n/**\n * Create an empty, namespace neutral XML document.\n *\n * @param {Document} ownerDocument - Any document, used for its DOM implementation\n * @returns {Document} A fresh empty XML document\n *\n * @example\n * const resultDoc = createResultDocument(window.document);\n */\nexport function createResultDocument(ownerDocument) {\n return ownerDocument.implementation.createDocument(null, null, null);\n}\n\n/**\n * Copy an element in no namespace into an HTML document as an element of the\n * XHTML namespace, as Chrome and Firefox do when they insert XML output into\n * an HTML document: `<ul><li>` become HTMLElements that render as a list.\n * The name is kept as written (no case folding).\n *\n * @param {Element} element - Element in no namespace\n * @param {Document} targetDoc - The HTML document that will own the copy\n * @returns {Element} The shallow copy, with the attributes\n */\nfunction importAsHtmlElement(element, targetDoc) {\n const copy = targetDoc.createElementNS(XHTML_NAMESPACE, element.localName);\n for (const attribute of element.attributes) {\n copy.setAttributeNS(\n attribute.namespaceURI,\n attribute.name,\n attribute.value,\n );\n }\n return copy;\n}\n\n/**\n * Deep-import a result tree node into another document.\n *\n * Unlike `Document.importNode` this preserves the internal\n * `_disableOutputEscaping` marker set by `disable-output-escaping`. With\n * `htmlElements` and an HTML target document, elements in no namespace\n * become XHTML elements (see importAsHtmlElement), as in the fragments\n * browsers return; elements of other namespaces are kept.\n *\n * @param {Node} node - The node to import\n * @param {Document} targetDoc - The document that will own the copy\n * @param {{htmlElements?: boolean}} [options] - Import options\n * @returns {Node} The imported copy\n *\n * @example\n * const copy = importResultNode(element, window.document);\n */\nexport function importResultNode(node, targetDoc, options = {}) {\n const asHtml =\n options.htmlElements === true &&\n node.nodeType === 1 &&\n !node.namespaceURI &&\n isHtmlDocument(targetDoc);\n const copy = asHtml\n ? importAsHtmlElement(node, targetDoc)\n : targetDoc.importNode(node, false);\n\n if (node._disableOutputEscaping) {\n copy._disableOutputEscaping = true;\n }\n\n if (node.childNodes) {\n for (const child of node.childNodes) {\n copy.appendChild(importResultNode(child, targetDoc, options));\n }\n }\n\n return copy;\n}\n\n/**\n * Move a finished result fragment into the caller's output document.\n *\n * @param {DocumentFragment} fragment - The fragment built in the neutral document\n * @param {Document} targetDoc - The document that will own the result\n * @param {{htmlElements?: boolean}} [options] - See {@link importResultNode}\n * @returns {DocumentFragment} A fragment owned by `targetDoc`\n *\n * @example\n * const result = importResultFragment(fragment, window.document);\n */\nexport function importResultFragment(fragment, targetDoc, options = {}) {\n if (fragment.ownerDocument === targetDoc) return fragment;\n\n const imported = targetDoc.createDocumentFragment();\n for (const child of fragment.childNodes) {\n imported.appendChild(importResultNode(child, targetDoc, options));\n }\n\n return imported;\n}\n\n/** The XHTML namespace. */\nexport const XHTML_NAMESPACE = \"http://www.w3.org/1999/xhtml\";\n\n/** Public and system identifiers of the XHTML 1.0 Strict DTD. */\nconst XHTML_STRICT_DOCTYPE = [\n \"-//W3C//DTD XHTML 1.0 Strict//EN\",\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\",\n];\n\n/**\n * Turn an empty document into the one Chrome's `XSLTProcessor` returns from\n * `transformToDocument` for `method=\"text\"`: the text in a `pre` element of\n * the XHTML 1.0 Strict page Blink builds, with its line breaks:\n * `<!DOCTYPE html PUBLIC ...>` then\n * `<html>\\n<head><title/></head>\\n<body>\\n<pre>text</pre>\\n</body>\\n</html>`.\n * A text result has no element to be the document element of an XML\n * document.\n *\n * @param {Document} doc - An empty document\n * @param {string} text - The serialized text output\n * @returns {Document} The same document, filled in\n *\n * @example\n * wrapTextResult(emptyDoc, \"hello\").documentElement.textContent;\n * // \"\\n\\n\\nhello\\n\\n\"\n */\nexport function wrapTextResult(doc, text) {\n // appendChild, not append: xmldom has no ParentNode.append\n const create = (name, ...children) => {\n const element = doc.createElementNS(XHTML_NAMESPACE, name);\n for (const child of children) {\n element.appendChild(\n typeof child === \"string\" ? doc.createTextNode(child) : child,\n );\n }\n return element;\n };\n const pre = create(\"pre\");\n if (text) pre.appendChild(doc.createTextNode(text));\n const head = create(\"head\", create(\"title\"));\n const body = create(\"body\", \"\\n\", pre, \"\\n\");\n // One node at a time: a doctype cannot pass through a fragment\n appendDoctype(doc, \"html\", ...XHTML_STRICT_DOCTYPE);\n doc.appendChild(create(\"html\", \"\\n\", head, \"\\n\", body, \"\\n\"));\n return doc;\n}\n\n/**\n * Append a document type node to a document.\n *\n * @param {Document} doc - A document without a doctype\n * @param {string} name - The root element name\n * @param {string} publicId - Public identifier (\"\" for none)\n * @param {string} systemId - System identifier (\"\" for none)\n * @returns {DocumentType} The appended node\n *\n * @example\n * appendDoctype(doc, \"html\", \"\", \"about:legacy-compat\");\n */\nexport function appendDoctype(doc, name, publicId, systemId) {\n const doctype = doc.implementation.createDocumentType(\n name,\n publicId,\n systemId,\n );\n doc.appendChild(doctype);\n // xmldom leaves Document.doctype null when a doctype node is appended\n doc.doctype ??= doctype;\n return doctype;\n}\n\n/**\n * Whether a document is an HTML document (as opposed to an XML one).\n *\n * @param {Document} doc - Any document\n * @returns {boolean} True for documents of content type text/html\n */\nexport function isHtmlDocument(doc) {\n return doc.contentType === \"text/html\";\n}\n\n/**\n * Parse serialized `html` output into a fragment of an HTML document, as\n * Chrome's `XSLTProcessor.transformToFragment` does: the elements are\n * created by the HTML parser, so `<a>` is an `HTMLAnchorElement` and\n * `<script>` elements run when inserted. Like Blink, the markup is parsed\n * in the context of a (detached) `body` element, that is in the \"in body\"\n * insertion mode: `<html>`, `<head>` and `<body>` tags are dropped and their\n * content becomes children of the fragment.\n *\n * @param {string} markup - HTML markup\n * @param {Document} doc - The HTML document that will own the fragment\n * @returns {DocumentFragment} The parsed fragment\n *\n * @example\n * parseHtmlFragment('<a href=\"u\">x</a>', document).firstChild; // HTMLAnchorElement\n */\nexport function parseHtmlFragment(markup, doc) {\n const range = doc.createRange();\n range.selectNodeContents(doc.createElement(\"body\"));\n return range.createContextualFragment(markup);\n}\n", "/**\n * Output Escaping Helpers\n *\n * Character escaping rules for the xml, xhtml and html output methods\n * (XSLT 1.0 section 16).\n */\n\nconst XML_TEXT_ESCAPES = { \"&\": \"&\", \"<\": \"<\", \"\\r\": \" \" };\n\nconst HTML_TEXT_ESCAPES = { \"&\": \"&\", \"<\": \"<\", \">\": \">\" };\n\nconst XML_ATTRIBUTE_ESCAPES = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"\\t\": \"	\",\n \"\\n\": \" \",\n \"\\r\": \" \",\n};\n\nconst HTML_ATTRIBUTE_ESCAPES = { \"&\": \"&\", '\"': \""\" };\n\n/**\n * Replace every character matched by a pattern using a lookup table.\n *\n * @param {string} value - Text to escape\n * @param {RegExp} pattern - Global pattern selecting the characters to replace\n * @param {Record<string, string>} escapes - Character to replacement mapping\n * @returns {string} Escaped text\n */\nfunction escapeWith(value, pattern, escapes) {\n return String(value).replaceAll(pattern, (character) => escapes[character]);\n}\n\n/**\n * Escape character data for the xml output method.\n *\n * `>` is only escaped where it would close a CDATA section, matching the\n * \"minimal escaping\" rule of XSLT 1.0 section 16.1. A carriage return is\n * written as ` `, as libxml2 does, since an XML parser would turn a\n * literal one into a line feed.\n *\n * @param {string} value - Text content\n * @returns {string} Escaped text\n *\n * @example\n * escapeXmlText(\"a<b\\r\"); // \"a<b \"\n */\nexport function escapeXmlText(value) {\n return escapeWith(value, /[&<\\r]/g, XML_TEXT_ESCAPES).replaceAll(\n \"]]>\",\n \"]]>\",\n );\n}\n\n/**\n * Escape an attribute value for the xml output method.\n *\n * @param {string} value - Attribute value\n * @returns {string} Escaped value\n */\nexport function escapeXmlAttribute(value) {\n return escapeWith(value, /[&<>\"\\t\\n\\r]/g, XML_ATTRIBUTE_ESCAPES);\n}\n\n/**\n * Escape character data for the html output method.\n *\n * @param {string} value - Text content\n * @returns {string} Escaped text\n */\nexport function escapeHtmlText(value) {\n return escapeWith(value, /[&<>]/g, HTML_TEXT_ESCAPES);\n}\n\n/**\n * Escape an attribute value for the html output method.\n *\n * Only `&` and `\"` are escaped: XSLT 1.0 section 16.2 keeps `<` unescaped\n * and `&` unescaped before `{` (HTML 4.0 script macros), as libxslt does.\n *\n * @param {string} value - Attribute value\n * @returns {string} Escaped value\n *\n * @example\n * escapeHtmlAttribute('&{x} & <b> \"'); // '&{x} & <b> "'\n */\nexport function escapeHtmlAttribute(value) {\n return escapeWith(value, /&(?!\\{)|\"/g, HTML_ATTRIBUTE_ESCAPES);\n}\n\n/** Leading HTML whitespace, which libxml2 writes unescaped. */\nconst LEADING_HTML_SPACE = /^[ \\t\\n\\f\\r]*/;\n\n/** Runs of spaces, control characters, DEL and characters outside ASCII. */\nconst URI_UNSAFE_RUN = /[^!-~]+/gu;\n\n/**\n * %-escape a URI attribute value as libxml2's HTML serializer does (and so\n * Chrome's XSLTProcessor): after any leading HTML whitespace, which is kept,\n * spaces, control characters, DEL and non-ASCII characters become the\n * %-escaped bytes of their UTF-8 encoding (XSLT 1.0 section 16.2, HTML 4.01\n * appendix B.2.1). Printable ASCII, `%` included, is kept as it is.\n *\n * @param {string} value - Attribute value\n * @returns {string} The escaped value\n *\n * @example\n * escapeUriAttribute(\"/caf\u00E9?q=a b\"); // \"/caf%C3%A9?q=a%20b\"\n */\nexport function escapeUriAttribute(value) {\n const text = String(value);\n const leading = LEADING_HTML_SPACE.exec(text)[0];\n const encoder = new globalThis.TextEncoder();\n const rest = text\n .slice(leading.length)\n .replaceAll(URI_UNSAFE_RUN, (run) =>\n Array.from(\n encoder.encode(run),\n (byte) => `%${byte.toString(16).toUpperCase().padStart(2, \"0\")}`,\n ).join(\"\"),\n );\n return leading + rest;\n}\n\n/**\n * Wrap text in a CDATA section, splitting it around any `]]>` terminator.\n *\n * @param {string} value - Text content\n * @returns {string} One or more CDATA sections\n */\nexport function wrapCdata(value) {\n return `<![CDATA[${String(value).replaceAll(\"]]>\", \"]]]]><![CDATA[>\")}]]>`;\n}\n", "/**\n * Output Encodings\n *\n * The `encoding` attribute of `xsl:output` names the character encoding of the\n * serialized result. A character the encoding cannot represent is written as\n * a character reference (XSLT 1.0 section 16.1: `€` in ISO-8859-1), so\n * the serialized string only holds characters the declared encoding has, and\n * turning it into bytes (see {@link encodeOutput}, used by the CLI) is\n * lossless.\n *\n * Supported encodings:\n * - UTF-8 and UTF-16 (every label TextDecoder maps to them) represent every\n * character; UTF-16 output starts with a byte order mark;\n * - ISO-8859-1 / latin1 (up to U+00FF) and US-ASCII (up to U+007F), handled\n * here because the WHATWG Encoding Standard aliases both to windows-1252;\n * - every other single-byte encoding known to TextDecoder (windows-125x,\n * ISO-8859-x, KOI8-R/U, IBM866, macintosh, ...): its repertoire is read\n * lazily by decoding the 256 byte values once;\n * - multi-byte encodings other than UTF (Shift_JIS, EUC-JP, GBK, Big5, ...) and\n * unknown labels are treated as able to represent every character: no\n * character reference is written, and {@link encodeOutput} falls back to\n * UTF-8 bytes (`isExact` is false so callers can warn).\n *\n * @module xslt/serializer/encoding\n */\n\n/** Labels of US-ASCII (IANA names and aliases). */\nconst ASCII_LABELS = new Set([\n \"ascii\",\n \"us-ascii\",\n \"ansi_x3.4-1968\",\n \"iso646-us\",\n \"iso-ir-6\",\n \"csascii\",\n \"us\",\n]);\n\n/** Labels of ISO-8859-1 (IANA names and aliases). */\nconst LATIN1_LABELS = new Set([\n \"iso-8859-1\",\n \"iso8859-1\",\n \"iso88591\",\n \"iso_8859-1\",\n \"iso_8859-1:1987\",\n \"latin1\",\n \"l1\",\n \"cp819\",\n \"ibm819\",\n \"csisolatin1\",\n \"iso-ir-100\",\n]);\n\n/** Canonical WHATWG names of the single-byte encodings. */\nconst SINGLE_BYTE_ENCODINGS = new Set([\n \"ibm866\",\n \"iso-8859-2\",\n \"iso-8859-3\",\n \"iso-8859-4\",\n \"iso-8859-5\",\n \"iso-8859-6\",\n \"iso-8859-7\",\n \"iso-8859-8\",\n \"iso-8859-8-i\",\n \"iso-8859-10\",\n \"iso-8859-13\",\n \"iso-8859-14\",\n \"iso-8859-15\",\n \"iso-8859-16\",\n \"koi8-r\",\n \"koi8-u\",\n \"macintosh\",\n \"windows-874\",\n \"windows-1250\",\n \"windows-1251\",\n \"windows-1252\",\n \"windows-1253\",\n \"windows-1254\",\n \"windows-1255\",\n \"windows-1256\",\n \"windows-1257\",\n \"windows-1258\",\n \"x-mac-cyrillic\",\n]);\n\n/**\n * @typedef {Object} OutputEncoding\n * @property {string} name - Canonical name (\"utf-8\", \"utf-16le\", \"iso-8859-1\"...)\n * @property {boolean} isUnicode - True when every character is representable\n * @property {boolean} isExact - False when bytes fall back to UTF-8\n * @property {Map<number, number>|null} bytes - Byte of every representable\n * code point, for single-byte encodings\n */\n\n/** Encodings already resolved, by lower-cased label. */\nconst cache = new Map();\n\n/**\n * Build a single-byte encoding whose bytes map to the same code points.\n *\n * @param {string} name - Canonical name\n * @param {number} last - Highest byte value (0x7F or 0xFF)\n * @returns {OutputEncoding} The encoding\n */\nfunction identityEncoding(name, last) {\n const bytes = new Map();\n for (let byte = 0; byte <= last; byte++) bytes.set(byte, byte);\n return { name, isUnicode: false, isExact: true, bytes };\n}\n\n/**\n * Build a single-byte encoding from the repertoire TextDecoder reports.\n *\n * @param {TextDecoder} decoder - Decoder of the encoding\n * @returns {OutputEncoding} The encoding\n */\nfunction tableEncoding(decoder) {\n const bytes = new Map();\n for (let byte = 0; byte <= 0xff; byte++) {\n const codePoint = decoder.decode(Uint8Array.of(byte)).codePointAt(0);\n if (codePoint !== 0xfffd && !bytes.has(codePoint)) {\n bytes.set(codePoint, byte);\n }\n }\n return { name: decoder.encoding, isUnicode: false, isExact: true, bytes };\n}\n\n/**\n * Resolve an encoding label that is not ASCII or ISO-8859-1.\n *\n * @param {string} label - Lower-cased, trimmed label\n * @returns {OutputEncoding} The encoding\n */\nfunction resolveWithDecoder(label) {\n let decoder;\n try {\n decoder = new globalThis.TextDecoder(label);\n } catch {\n return { name: label, isUnicode: true, isExact: false, bytes: null };\n }\n const name = decoder.encoding;\n if (SINGLE_BYTE_ENCODINGS.has(name)) return tableEncoding(decoder);\n const isExact = name === \"utf-8\" || name.startsWith(\"utf-16\");\n return { name, isUnicode: true, isExact, bytes: null };\n}\n\n/**\n * Resolve the `encoding` of `xsl:output`.\n *\n * @param {string} [label] - Encoding label, UTF-8 when absent\n * @returns {OutputEncoding} The encoding\n *\n * @example\n * getOutputEncoding(\"ISO-8859-1\").bytes.has(0x20ac); // false\n */\nexport function getOutputEncoding(label = \"UTF-8\") {\n const key = String(label).trim().toLowerCase();\n let encoding = cache.get(key);\n if (!encoding) {\n if (ASCII_LABELS.has(key)) encoding = identityEncoding(\"us-ascii\", 0x7f);\n else if (LATIN1_LABELS.has(key)) {\n encoding = identityEncoding(\"iso-8859-1\", 0xff);\n } else encoding = resolveWithDecoder(key);\n cache.set(key, encoding);\n }\n return encoding;\n}\n\n/**\n * Numeric character reference of a code point.\n *\n * @param {number} codePoint - The code point\n * @returns {string} `&#N;`\n */\nexport function characterReference(codePoint) {\n return `&#${codePoint};`;\n}\n\n/** Characters outside ASCII, as whole code points. */\nconst NON_ASCII = /[\\u{80}-\\u{10FFFF}]/gu;\n\n/**\n * Replace every character an encoding cannot represent.\n *\n * Every supported encoding is a superset of ASCII, so only non-ASCII\n * characters are checked.\n *\n * @param {string} text - Text to write\n * @param {OutputEncoding} encoding - The output encoding\n * @param {(codePoint: number) => string} [reference] - Replacement of an\n * unrepresentable code point; a numeric character reference by default\n * @returns {string} Text holding only representable characters\n *\n * @example\n * replaceUnencodable(\"\u20AC\u00E9\", getOutputEncoding(\"latin1\")); // \"€\u00E9\"\n */\nexport function replaceUnencodable(\n text,\n encoding,\n reference = characterReference,\n) {\n if (encoding.isUnicode) return text;\n return text.replace(NON_ASCII, (character) => {\n const codePoint = character.codePointAt(0);\n return encoding.bytes.has(codePoint) ? character : reference(codePoint);\n });\n}\n\n/**\n * Split text into runs an encoding can and cannot represent, as needed to\n * write a CDATA section, which cannot hold character references.\n *\n * @param {string} text - Text to write\n * @param {OutputEncoding} encoding - The output encoding\n * @returns {Array<{text: string, representable: boolean}>} The runs, in order;\n * an unrepresentable run holds one code point\n */\nexport function splitUnencodable(text, encoding) {\n if (encoding.isUnicode) return [{ text, representable: true }];\n const runs = [];\n let start = 0;\n for (const match of text.matchAll(NON_ASCII)) {\n if (encoding.bytes.has(match[0].codePointAt(0))) continue;\n if (match.index > start) {\n runs.push({ text: text.slice(start, match.index), representable: true });\n }\n runs.push({ text: match[0], representable: false });\n start = match.index + match[0].length;\n }\n if (start < text.length || runs.length === 0) {\n runs.push({ text: text.slice(start), representable: true });\n }\n return runs;\n}\n\n/**\n * Encode UTF-16 code units, after a byte order mark when requested.\n *\n * @param {string} text - Text to encode\n * @param {boolean} bigEndian - Byte order\n * @param {boolean} bom - Whether to start with a byte order mark\n * @returns {Uint8Array} The bytes\n */\nfunction encodeUtf16(text, bigEndian, bom) {\n const offset = bom ? 2 : 0;\n const bytes = new Uint8Array(offset + text.length * 2);\n const view = new DataView(bytes.buffer);\n if (bom) view.setUint16(0, 0xfeff, !bigEndian);\n for (let i = 0; i < text.length; i++) {\n view.setUint16(offset + i * 2, text.charCodeAt(i), !bigEndian);\n }\n return bytes;\n}\n\n/**\n * Encode text with a single-byte encoding; a character without a byte\n * (possible only in comments and processing instructions, which cannot hold\n * references) becomes a character reference, as libxml2 does.\n *\n * @param {string} text - Text to encode\n * @param {Map<number, number>} table - Byte of every representable code point\n * @returns {Uint8Array} The bytes\n */\nfunction encodeSingleByte(text, table) {\n const bytes = [];\n for (const character of text) {\n const codePoint = character.codePointAt(0);\n const byte = table.get(codePoint);\n if (byte === undefined) {\n for (const unit of characterReference(codePoint)) {\n bytes.push(unit.charCodeAt(0));\n }\n } else {\n bytes.push(byte);\n }\n }\n return Uint8Array.from(bytes);\n}\n\n/**\n * Create an encoder turning serialized output, chunk after chunk, into the\n * bytes of its declared encoding: the concatenated bytes equal\n * {@link encodeOutput} of the concatenated text, since only the first chunk\n * gets the UTF-16 byte order mark (chunks never split a surrogate pair, see\n * chunks.js).\n *\n * @param {string} [label] - The `xsl:output` encoding, UTF-8 when absent\n * @returns {(text: string) => Uint8Array} The stateful encoder\n *\n * @example\n * const encode = createOutputEncoder(\"UTF-16\");\n * encode(\"a\"); // Uint8Array [0xff, 0xfe, 0x61, 0x00]\n * encode(\"b\"); // Uint8Array [0x62, 0x00]\n */\nexport function createOutputEncoder(label) {\n const encoding = getOutputEncoding(label);\n if (encoding.bytes) return (text) => encodeSingleByte(text, encoding.bytes);\n if (encoding.name.startsWith(\"utf-16\")) {\n const bigEndian = encoding.name === \"utf-16be\";\n let bom = true;\n return (text) => {\n const bytes = encodeUtf16(text, bigEndian, bom);\n bom = false;\n return bytes;\n };\n }\n const encoder = new globalThis.TextEncoder();\n return (text) => encoder.encode(text);\n}\n\n/**\n * Turn serialized output into the bytes of its declared encoding.\n *\n * UTF-8 is written without a byte order mark, UTF-16 with one. Encodings\n * without an encoder here (multi-byte encodings other than UTF, unknown\n * labels) are written as UTF-8; `getOutputEncoding(label).isExact` is false\n * for them.\n *\n * @param {string} text - Serialized output\n * @param {string} [label] - The `xsl:output` encoding, UTF-8 when absent\n * @returns {Uint8Array} The encoded bytes\n *\n * @example\n * encodeOutput(\"\u00E9\", \"ISO-8859-1\"); // Uint8Array [0xe9]\n */\nexport function encodeOutput(text, label) {\n return createOutputEncoder(label)(text);\n}\n", "/**\n * Namespace Declaration Tracking\n *\n * Computes the `xmlns` declarations an element has to carry so that every\n * namespace is declared where it is first used and never twice.\n */\n\nimport { XMLNS_NAMESPACE, XML_NAMESPACE } from \"./constants.js\";\n\n/**\n * Create the namespace scope in effect above the result tree root.\n *\n * @returns {Map<string, string>} Prefix (empty string for the default) to URI\n */\nexport function createNamespaceScope() {\n return new Map([\n [\"\", \"\"],\n [\"xml\", XML_NAMESPACE],\n ]);\n}\n\n/**\n * Collect the namespace declarations an element must emit.\n *\n * @param {Element} element - Element being serialized\n * @param {Map<string, string>} scope - Namespace scope inherited from the parent\n * @returns {{declarations: Array<{prefix: string, uri: string}>, scope: Map<string, string>}}\n * The declarations to write and the scope in effect for the children\n */\nexport function collectNamespaceDeclarations(element, scope) {\n const declarations = [];\n let next = scope;\n\n /**\n * Record a declaration when the binding is not already in scope.\n * @param {string} prefix - Namespace prefix, empty for the default namespace\n * @param {string} uri - Namespace URI\n * @returns {void}\n */\n const declare = (prefix, uri) => {\n if (next.get(prefix) === uri) {\n return;\n }\n if (next === scope) {\n next = new Map(scope);\n }\n next.set(prefix, uri);\n declarations.push({ prefix, uri });\n };\n\n declare(element.prefix || \"\", element.namespaceURI || \"\");\n\n const attributes = Array.from(element.attributes || []);\n\n for (const attribute of attributes) {\n if (attribute.namespaceURI !== XMLNS_NAMESPACE && attribute.prefix) {\n declare(attribute.prefix, attribute.namespaceURI || \"\");\n }\n }\n\n for (const attribute of attributes) {\n if (attribute.namespaceURI === XMLNS_NAMESPACE) {\n declare(attribute.prefix ? attribute.localName : \"\", attribute.value);\n }\n }\n\n return { declarations, scope: next };\n}\n", "/**\n * Indentation Rules\n *\n * Decides which elements may be pretty printed when `indent=\"yes\"` is set.\n * Only element-only content is indented; mixed content is left untouched so\n * that the transformation result stays character-for-character faithful.\n */\n\nimport { NODE_TYPE } from \"./constants.js\";\n\n/**\n * Test whether a character data node holds only whitespace.\n *\n * @param {Node} node - Text node to test\n * @returns {boolean} True when the node contains no non-whitespace character\n */\nexport function isWhitespaceOnlyText(node) {\n return !/\\S/.test(node.nodeValue || \"\");\n}\n\n/**\n * Collect the children to write when indenting an element.\n *\n * @param {Element} element - Element whose children are inspected\n * @returns {Node[]|null} Children to indent, or null when the element must be\n * serialized without any added whitespace\n */\nexport function getIndentableChildren(element) {\n const indentable = [];\n\n for (const child of element.childNodes) {\n if (child.nodeType === NODE_TYPE.TEXT) {\n if (isWhitespaceOnlyText(child)) {\n continue;\n }\n return null;\n }\n\n if (\n child.nodeType !== NODE_TYPE.ELEMENT &&\n child.nodeType !== NODE_TYPE.COMMENT &&\n child.nodeType !== NODE_TYPE.PROCESSING_INSTRUCTION\n ) {\n return null;\n }\n\n indentable.push(child);\n }\n\n return indentable.length > 0 ? indentable : null;\n}\n", "/**\n * Raw Text Registry\n *\n * Tracks the text nodes produced with `disable-output-escaping=\"yes\"`\n * (XSLT 1.0 section 16.4) so the serializers can emit them verbatim.\n */\n\n/**\n * Text nodes whose content must be written without escaping.\n * @type {WeakSet<Node>}\n */\nexport const rawTextNodes = new WeakSet();\n\n/**\n * Mark a text node as produced with `disable-output-escaping=\"yes\"`.\n *\n * @param {Node|null} node - Text node to mark\n * @returns {Node|null} The same node, for chaining\n */\nexport function markRawText(node) {\n if (node) {\n rawTextNodes.add(node);\n }\n return node;\n}\n\n/**\n * Check whether a node must be serialized without output escaping.\n *\n * Both the registry and the legacy `_disableOutputEscaping` flag set by the\n * XSLT engine are honored so that either marking mechanism works.\n *\n * @param {Node|null} node - Node to test\n * @returns {boolean} True when the node content must be emitted raw\n */\nexport function isRawText(node) {\n if (!node) {\n return false;\n }\n return rawTextNodes.has(node) || node._disableOutputEscaping === true;\n}\n", "/**\n * Output Chunking\n *\n * The serializers write markup into a {@link ChunkBuffer}, which hands it out\n * in chunks of a bounded size: the streaming API (`serializeChunks`,\n * `transformToStream`) yields each chunk as soon as it is full, while\n * `serializeResult` uses an unbounded buffer and joins everything once. One\n * writer implementation serves both.\n *\n * @module xslt/serializer/chunks\n */\n\n/** Default chunk size, in UTF-16 code units (16 KiB of ASCII). */\nexport const DEFAULT_CHUNK_SIZE = 16384;\n\n/**\n * Validate a chunk size.\n *\n * @param {number} [size] - Requested size, {@link DEFAULT_CHUNK_SIZE} when absent\n * @returns {number} A positive integer, or Infinity (one chunk)\n * @throws {RangeError} For anything else\n *\n * @example\n * toChunkSize(undefined); // 16384\n */\nexport function toChunkSize(size) {\n if (size === undefined) return DEFAULT_CHUNK_SIZE;\n if (size === Infinity || (Number.isInteger(size) && size > 0)) return size;\n throw new RangeError(\n `chunkSize must be a positive integer or Infinity, got ${size}`,\n );\n}\n\n/**\n * Whether a UTF-16 code unit is a high (leading) surrogate.\n *\n * @param {number} unit - The code unit\n * @returns {boolean} True for U+D800..U+DBFF\n */\nfunction isHighSurrogate(unit) {\n return unit >= 0xd800 && unit <= 0xdbff;\n}\n\n/**\n * End of the next chunk of `text` starting at `start`, moved so that a\n * surrogate pair is never split (a chunk encoded on its own, e.g. with\n * TextEncoder, would otherwise turn each half into U+FFFD).\n *\n * @param {string} text - The buffered text\n * @param {number} start - Start of the chunk\n * @param {number} size - Chunk size\n * @returns {number} End of the chunk (exclusive)\n */\nfunction chunkEnd(text, start, size) {\n const end = start + size;\n if (!isHighSurrogate(text.charCodeAt(end - 1))) return end;\n return end - 1 > start ? end - 1 : end + 1;\n}\n\nexport class ChunkBuffer {\n /**\n * @param {number} [chunkSize] - Chunk size in code units; Infinity keeps\n * everything for one final chunk\n */\n constructor(chunkSize = Infinity) {\n this.chunkSize = toChunkSize(chunkSize);\n this.parts = [];\n this.length = 0;\n }\n\n /**\n * Append text.\n *\n * @param {string} text - Markup or character data\n * @returns {void}\n */\n write(text) {\n this.parts.push(text);\n this.length += text.length;\n }\n\n /**\n * Whether at least one full chunk is buffered.\n *\n * @returns {boolean} True when {@link ChunkBuffer#take} would yield\n */\n get full() {\n return this.length >= this.chunkSize;\n }\n\n /**\n * Yield the buffered text as chunks of `chunkSize` code units (one more\n * when a surrogate pair straddles the boundary). The last partial chunk is\n * kept for later unless `final` is set.\n *\n * @param {boolean} [final] - Also yield the partial last chunk\n * @yields {string} Non-empty chunks\n * @returns {Generator<string, void, void>} The chunks\n *\n * @example\n * const buffer = new ChunkBuffer(2);\n * buffer.write(\"abcde\");\n * [...buffer.take(true)]; // [\"ab\", \"cd\", \"e\"]\n */\n *take(final = false) {\n const text = this.parts.length === 1 ? this.parts[0] : this.parts.join(\"\");\n this.parts = [];\n this.length = 0;\n let start = 0;\n while (text.length - start >= this.chunkSize) {\n const end = chunkEnd(text, start, this.chunkSize);\n yield text.slice(start, end);\n start = end;\n }\n const rest = text.slice(start);\n if (!rest) return;\n if (final) yield rest;\n else this.write(rest);\n }\n}\n", "/**\n * Open Node Frames\n *\n * The writer walks the result tree without recursion: every element (and\n * the result root) whose children are being written is a frame on an\n * explicit stack, so the depth of the tree is bounded by memory, not by the\n * JavaScript call stack. A frame hands out its children one at a time\n * ({@link ContentFrame#nextChild}) and knows the markup that closes it\n * (`end`), written when it has no child left.\n *\n * Three kinds of content exist, as in XSLT 1.0 section 16 output:\n * - {@link ContentFrame}: children written as they are, adjacent character\n * data joined into one CDATA section in `cdata-section-elements`;\n * - {@link TopLevelFrame}: the children of the result root (document or\n * fragment), with libxslt's line break after a top-level comment;\n * - {@link IndentFrame}: element-only content, each child on its own\n * indented line (`indent=\"yes\"`).\n *\n * @module xslt/serializer/frames\n */\n\nimport { INDENT_UNIT, NODE_TYPE, TEXT_MODE } from \"./constants.js\";\nimport { isRawText } from \"./rawText.js\";\n\n/**\n * Children of a node written without adding whitespace.\n *\n * In CDATA mode (`cdata-section-elements`), adjacent character data nodes\n * are one text node of the XPath data model, so they are written as one\n * CDATA section, as libxslt does, not one section per DOM node; text\n * written with `disable-output-escaping` ends the run.\n */\nexport class ContentFrame {\n /**\n * @param {Node} parent - Node whose children are written\n * @param {Map<string, string>} scope - Namespace scope for the children\n * @param {number} depth - Indentation depth of the children\n * @param {string} textMode - {@link TEXT_MODE} for character data children\n * @param {string} end - Markup written once every child is written\n */\n constructor(parent, scope, depth, textMode, end) {\n this.scope = scope;\n this.depth = depth;\n this.textMode = textMode;\n this.end = end;\n this.next = parent.firstChild;\n this.joinsText = textMode === TEXT_MODE.CDATA;\n }\n\n /**\n * Whether a child joins the pending CDATA run instead of being written.\n *\n * @param {Node} child - Child node\n * @returns {boolean} True for escaped character data in CDATA mode\n */\n joins(child) {\n const type = child.nodeType;\n return (\n (type === NODE_TYPE.TEXT || type === NODE_TYPE.CDATA_SECTION) &&\n !isRawText(child)\n );\n }\n\n /**\n * The next child to write. In CDATA mode the character data before it is\n * written first, as one CDATA section.\n *\n * @param {import('./baseWriter.js').BaseWriter} writer - The writer\n * @returns {Node|null} The child, or null when every child is written\n */\n nextChild(writer) {\n let child = this.next;\n if (this.joinsText) {\n let run = \"\";\n while (child && this.joins(child)) {\n run += child.nodeValue;\n child = child.nextSibling;\n }\n if (run) writer.write(writer.cdataMarkup(run));\n }\n this.next = child ? child.nextSibling : null;\n return child;\n }\n}\n\n/**\n * Children of the result root (document or fragment). A line break follows\n * a comment that another node follows when the dialect asks for it\n * (`topLevelLineBreaks`); comments are leaves, so the break is written just\n * before that next node.\n */\nexport class TopLevelFrame extends ContentFrame {\n /**\n * @param {Node} parent - The result root\n * @param {Map<string, string>} scope - Namespace scope for the children\n * @param {number} depth - Indentation depth of the children\n * @param {string} textMode - {@link TEXT_MODE} for character data children\n * @param {boolean} lineBreaks - Whether a top-level comment ends a line\n */\n constructor(parent, scope, depth, textMode, lineBreaks) {\n super(parent, scope, depth, textMode, \"\");\n this.lineBreaks = lineBreaks;\n this.afterComment = false;\n }\n\n /**\n * The next top-level node, preceded by a line break after a comment.\n *\n * @param {import('./baseWriter.js').BaseWriter} writer - The writer\n * @returns {Node|null} The child, or null when every child is written\n */\n nextChild(writer) {\n const child = super.nextChild(writer);\n if (child && this.afterComment) writer.write(\"\\n\");\n this.afterComment =\n this.lineBreaks && child?.nodeType === NODE_TYPE.COMMENT;\n return child;\n }\n}\n\n/**\n * Element-only content written with `indent=\"yes\"`: each child starts a new\n * line indented one level deeper than the parent, and the end tag of the\n * parent starts a line at the parent's own indentation.\n */\nexport class IndentFrame {\n /**\n * @param {Node[]} children - Children to indent (see indent.js)\n * @param {Map<string, string>} scope - Namespace scope for the children\n * @param {number} depth - Indentation depth of the parent element\n * @param {string} textMode - {@link TEXT_MODE} for character data children\n * @param {string} endTag - End tag of the parent element\n */\n constructor(children, scope, depth, textMode, endTag) {\n this.children = children;\n this.index = 0;\n this.scope = scope;\n this.depth = depth + 1;\n this.textMode = textMode;\n this.lineStart = IndentFrame.lineStart(this.depth);\n this.end = IndentFrame.lineStart(depth) + endTag;\n }\n\n /**\n * A line break followed by the indentation of a depth.\n *\n * @param {number} depth - Indentation depth\n * @returns {string} The line start\n *\n * @example\n * IndentFrame.lineStart(2); // \"\\n \"\n */\n static lineStart(depth) {\n return `\\n${INDENT_UNIT.repeat(depth)}`;\n }\n\n /**\n * The next child to write, on a new indented line.\n *\n * @param {import('./baseWriter.js').BaseWriter} writer - The writer\n * @returns {Node|null} The child, or null when every child is written\n */\n nextChild(writer) {\n if (this.index === this.children.length) return null;\n writer.write(this.lineStart);\n return this.children[this.index++];\n }\n}\n", "/**\n * Result Tree Writer\n *\n * Walks a result tree and turns it into markup. Everything that differs\n * between the xml, xhtml and html output methods of XSLT 1.0 section 16 is\n * delegated to the dialect hooks implemented by the concrete writers.\n *\n * The walk is iterative: the elements whose children are being written are\n * frames on an explicit stack (see frames.js), so a result tree nested\n * deeper than the JavaScript call stack allows (tens of thousands of\n * levels, as deep template recursion builds) is written like any other.\n */\n\nimport { NODE_TYPE, TEXT_MODE, XMLNS_NAMESPACE } from \"./constants.js\";\nimport { wrapCdata } from \"./escape.js\";\nimport {\n getOutputEncoding,\n replaceUnencodable,\n splitUnencodable,\n} from \"./encoding.js\";\nimport {\n collectNamespaceDeclarations,\n createNamespaceScope,\n} from \"./namespaces.js\";\nimport { getIndentableChildren } from \"./indent.js\";\nimport { isRawText } from \"./rawText.js\";\nimport { findRootElement } from \"./settings.js\";\nimport { ChunkBuffer } from \"./chunks.js\";\nimport { ContentFrame, IndentFrame, TopLevelFrame } from \"./frames.js\";\n\n/**\n * Make comment text well-formed: XSLT 1.0 section 7.4 recovery inserts a\n * space after any `-` followed by another `-` or ending the comment.\n *\n * @param {string} text - The comment text\n * @returns {string} Text without `--` and without a trailing `-`\n *\n * @example\n * safeCommentText(\"a--b-\"); // \"a- -b- \"\n */\nexport function safeCommentText(text) {\n return text.replace(/-(?=-|$)/g, \"- \");\n}\n\nexport class BaseWriter {\n /**\n * @param {object} settings - Normalized output settings\n * @param {{xhtml?: boolean}} [options] - Dialect options\n */\n constructor(settings, options = {}) {\n this.settings = settings;\n this.xhtml = options.xhtml === true;\n this.buffer = new ChunkBuffer();\n this.encoding = getOutputEncoding(settings.encoding);\n this.reference = (codePoint) => this.characterReference(codePoint);\n }\n\n /**\n * Replace the characters the output encoding cannot represent with\n * references (XSLT 1.0 section 16.1). Only escaped character data and\n * attribute values go through here: comments, processing instructions and\n * unescaped text cannot hold references and are written unchanged.\n *\n * @param {string} text - Escaped text or attribute value\n * @returns {string} Text holding only representable characters\n */\n encodeReferences(text) {\n return replaceUnencodable(text, this.encoding, this.reference);\n }\n\n /**\n * Write text as CDATA sections. A character the output encoding cannot\n * represent ends the section and is written as a reference between two\n * sections, since a CDATA section cannot hold references.\n *\n * @param {string} value - Text content\n * @returns {string} CDATA sections and references\n */\n cdataMarkup(value) {\n return splitUnencodable(value, this.encoding)\n .map(({ text, representable }) =>\n representable ? wrapCdata(text) : this.reference(text.codePointAt(0)),\n )\n .join(\"\");\n }\n\n /**\n * Serialize a result tree node.\n *\n * @param {Node} node - Document, fragment or element to serialize\n * @returns {string} Serialized output\n */\n serialize(node) {\n let output = \"\";\n for (const chunk of this.chunks(node, Infinity)) output += chunk;\n return output;\n }\n\n /**\n * Serialize a result tree node incrementally: a chunk is yielded as soon\n * as `chunkSize` code units are written, so the first bytes are available\n * before the whole tree has been written and the output is never held as\n * one string.\n *\n * @param {Node} node - Document, fragment or element to serialize\n * @param {number} [chunkSize] - Chunk size in UTF-16 code units (see\n * chunks.js); Infinity yields the whole output as one chunk\n * @yields {string} Non-empty chunks of at most `chunkSize` code units (one\n * more when a surrogate pair straddles the boundary)\n * @returns {Generator<string, void, void>} The chunks, in order\n */\n *chunks(node, chunkSize) {\n this.buffer = new ChunkBuffer(chunkSize);\n this.writeProlog(node);\n\n const open = [];\n const root = this.openNode(\n node,\n createNamespaceScope(),\n 0,\n TEXT_MODE.ESCAPE,\n );\n if (root) open.push(root);\n\n while (open.length > 0) {\n const frame = open[open.length - 1];\n const child = frame.nextChild(this);\n if (child) {\n const opened = this.openNode(\n child,\n frame.scope,\n frame.depth,\n frame.textMode,\n );\n if (opened) open.push(opened);\n } else {\n open.pop();\n this.write(frame.end);\n }\n if (this.buffer.full) yield* this.buffer.take();\n }\n yield* this.buffer.take(true);\n }\n\n /**\n * Append markup to the output.\n *\n * @param {string} text - Markup\n * @returns {void}\n */\n write(text) {\n this.buffer.write(text);\n }\n\n /**\n * Write the XML declaration and the document type declaration.\n *\n * @param {Node} node - Result tree root\n * @returns {void}\n */\n writeProlog(node) {\n if (this.emitsXmlDeclaration) {\n const { version, encoding, standalone } = this.settings;\n const standalonePart = standalone ? ` standalone=\"${standalone}\"` : \"\";\n this.write(\n `<?xml version=\"${version}\" encoding=\"${encoding}\"${standalonePart}?>\\n`,\n );\n }\n\n const doctype = this.doctypeMarkup(findRootElement(node));\n if (doctype) {\n this.write(`${doctype}\\n`);\n }\n }\n\n /**\n * Start writing any result tree node. Leaves (character data, comments,\n * processing instructions) are written at once; for an element with\n * children or a result root, the start is written and the frame of its\n * children is returned for the walk in {@link BaseWriter#chunks}.\n *\n * @param {Node} node - Node to write\n * @param {Map<string, string>} scope - Namespace scope in effect\n * @param {number} depth - Current indentation depth\n * @param {string} textMode - {@link TEXT_MODE} for character data children\n * @returns {object|null} The frame of the children (see frames.js), or\n * null when the node is written completely\n */\n openNode(node, scope, depth, textMode) {\n switch (node.nodeType) {\n case NODE_TYPE.ELEMENT:\n return this.openElement(node, scope, depth);\n case NODE_TYPE.TEXT:\n case NODE_TYPE.CDATA_SECTION:\n this.writeText(node, textMode);\n break;\n case NODE_TYPE.COMMENT:\n this.write(`<!--${safeCommentText(node.nodeValue)}-->`);\n break;\n case NODE_TYPE.PROCESSING_INSTRUCTION:\n this.writeProcessingInstruction(node);\n break;\n case NODE_TYPE.DOCUMENT:\n case NODE_TYPE.DOCUMENT_FRAGMENT:\n return new TopLevelFrame(\n node,\n scope,\n depth,\n textMode,\n this.topLevelLineBreaks === true,\n );\n default:\n break;\n }\n return null;\n }\n\n /**\n * Write the start tag of an element with its namespaces and attributes,\n * or the whole element when it is empty.\n *\n * @param {Element} element - Element to write\n * @param {Map<string, string>} scope - Namespace scope inherited from the parent\n * @param {number} depth - Current indentation depth\n * @returns {object|null} The frame of its children, null when empty\n */\n openElement(element, scope, depth) {\n const namespaces = collectNamespaceDeclarations(element, scope);\n const name = element.nodeName;\n\n this.write(\n `<${name}${this.namespaceMarkup(namespaces.declarations, element)}` +\n this.attributesMarkup(element),\n );\n\n const leading = this.leadingChildMarkup(element);\n if (!element.firstChild && !leading) {\n this.write(this.emptyElementMarkup(element, name));\n return null;\n }\n\n this.write(\">\");\n return this.childrenFrame(\n element,\n namespaces.scope,\n depth,\n leading,\n `</${name}>`,\n );\n }\n\n /**\n * Frame of the children of an element, indenting element-only content.\n *\n * @param {Element} element - Parent element\n * @param {Map<string, string>} scope - Namespace scope in effect\n * @param {number} depth - Depth of the parent element\n * @param {string} leading - Markup the serializer adds before the\n * children, indented like a child (see leadingChildMarkup)\n * @param {string} endTag - End tag of the element\n * @returns {ContentFrame|IndentFrame} The frame\n */\n childrenFrame(element, scope, depth, leading, endTag) {\n const textMode = this.childTextMode(element);\n const indentable = this.indentableChildren(element, textMode);\n\n if (!indentable) {\n this.write(leading);\n return new ContentFrame(element, scope, depth, textMode, endTag);\n }\n\n const frame = new IndentFrame(indentable, scope, depth, textMode, endTag);\n if (leading) this.write(frame.lineStart + leading);\n return frame;\n }\n\n /**\n * Determine the children to indent inside an element.\n *\n * @param {Element} element - Parent element\n * @param {string} textMode - {@link TEXT_MODE} for character data children\n * @returns {Node[]|null} Children to indent, or null when indenting is off\n */\n indentableChildren(element, textMode) {\n if (!this.settings.indent || textMode !== TEXT_MODE.ESCAPE) {\n return null;\n }\n if (!this.allowsIndentInside(element)) {\n return null;\n }\n return getIndentableChildren(element);\n }\n\n /**\n * Build the namespace declaration markup of an element.\n *\n * @param {Array<{prefix: string, uri: string}>} declarations - Declarations\n * @param {Element} [_element] - The element they are written on\n * @returns {string} Attribute markup, starting with a space when non-empty\n */\n namespaceMarkup(declarations, _element) {\n return declarations\n .map(({ prefix, uri }) => {\n const name = prefix ? `xmlns:${prefix}` : \"xmlns\";\n return ` ${name}=\"${this.escapeAttribute(uri)}\"`;\n })\n .join(\"\");\n }\n\n /**\n * Build the attribute markup of an element, skipping namespace declarations.\n *\n * @param {Element} element - Element being written\n * @returns {string} Attribute markup, starting with a space when non-empty\n */\n attributesMarkup(element) {\n let markup = \"\";\n for (const attribute of Array.from(element.attributes || [])) {\n if (attribute.namespaceURI !== XMLNS_NAMESPACE) {\n markup += this.attributeMarkup(attribute);\n }\n }\n return markup;\n }\n\n /**\n * Build the markup of a single attribute.\n *\n * @param {Attr} attribute - Attribute to write\n * @returns {string} Attribute markup, starting with a space\n */\n attributeMarkup(attribute) {\n return ` ${attribute.name}=\"${this.escapeAttribute(attribute.value)}\"`;\n }\n\n /**\n * Write a character data node.\n *\n * Nodes produced with `disable-output-escaping=\"yes\"` are written verbatim.\n *\n * @param {Node} node - Text or CDATA section node\n * @param {string} textMode - {@link TEXT_MODE} requested by the parent\n * @returns {void}\n */\n writeText(node, textMode) {\n const value = node.nodeValue || \"\";\n\n if (isRawText(node)) {\n this.write(value);\n return;\n }\n\n const mode = this.resolveTextMode(node, textMode);\n if (mode === TEXT_MODE.CDATA) {\n this.write(this.cdataMarkup(value));\n } else if (mode === TEXT_MODE.RAW) {\n this.write(value);\n } else {\n this.write(this.escapeText(value));\n }\n }\n\n /**\n * Resolve the effective text mode of a character data node.\n *\n * @param {Node} node - Text or CDATA section node\n * @param {string} textMode - {@link TEXT_MODE} requested by the parent\n * @returns {string} A {@link TEXT_MODE} value\n */\n resolveTextMode(node, textMode) {\n if (textMode !== TEXT_MODE.ESCAPE) {\n return textMode;\n }\n return node.nodeType === NODE_TYPE.CDATA_SECTION\n ? this.cdataNodeMode\n : TEXT_MODE.ESCAPE;\n }\n\n /**\n * Write a processing instruction node.\n *\n * @param {ProcessingInstruction} node - Node to write\n * @returns {void}\n */\n writeProcessingInstruction(node) {\n const data = node.nodeValue || \"\";\n const separator = data ? \" \" : \"\";\n this.write(`<?${node.target}${separator}${data}${this.piTerminator}`);\n }\n}\n", "/**\n * XHTML 1.0 documents in xml output, as libxml2 (and so Chrome's\n * XSLTProcessor) writes them.\n *\n * When the xml output declares one of the XHTML 1.0 document types\n * (`doctype-public` or `doctype-system` of XHTML 1.0 Strict, Transitional\n * or Frameset), libxml2 switches to its XHTML serializer, which follows the\n * compatibility guidelines of XHTML 1.0 appendix C:\n * - an `html` element in no namespace without namespace declarations gets\n * `xmlns=\"http://www.w3.org/1999/xhtml\"` (A.3.1.1);\n * - a `head` child of the `html` document element without a Content-Type\n * `meta` gets `<meta http-equiv=\"Content-Type\" content=\"text/html;\n * charset=...\" />` as its first child (C.9);\n * - elements in no namespace follow the empty element rules of XHTML\n * elements (C.2, C.3).\n *\n * @module xslt/serializer/xhtmlDocument\n */\n\nimport { NODE_TYPE, XHTML_NAMESPACE } from \"./constants.js\";\n\n/** Public identifiers of the XHTML 1.0 document types. */\nconst XHTML1_PUBLIC_IDS = new Set([\n \"-//W3C//DTD XHTML 1.0 Strict//EN\",\n \"-//W3C//DTD XHTML 1.0 Transitional//EN\",\n \"-//W3C//DTD XHTML 1.0 Frameset//EN\",\n]);\n\n/** System identifiers of the XHTML 1.0 document types. */\nconst XHTML1_SYSTEM_IDS = new Set([\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\",\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\",\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\",\n]);\n\n/**\n * Whether the output settings declare an XHTML 1.0 document type.\n *\n * @param {{doctypePublic?: string|null, doctypeSystem?: string|null}} settings -\n * Normalized output settings\n * @returns {boolean} True for the XHTML 1.0 public or system identifiers\n *\n * @example\n * isXhtml1Doctype({ doctypePublic: \"-//W3C//DTD XHTML 1.0 Strict//EN\" }); // true\n */\nexport function isXhtml1Doctype(settings) {\n return (\n XHTML1_PUBLIC_IDS.has(settings.doctypePublic) ||\n XHTML1_SYSTEM_IDS.has(settings.doctypeSystem)\n );\n}\n\n/**\n * The namespace declaration libxml2 adds to an `html` element in no\n * namespace that declares no namespace itself.\n *\n * @param {Element} element - Element being written\n * @param {Array<object>} declarations - Declarations written on it\n * @returns {string} ` xmlns=\"http://www.w3.org/1999/xhtml\"`, or \"\"\n */\nexport function xhtmlRootNamespace(element, declarations) {\n const needed =\n element.localName === \"html\" &&\n !element.namespaceURI &&\n declarations.length === 0;\n return needed ? ` xmlns=\"${XHTML_NAMESPACE}\"` : \"\";\n}\n\n/**\n * Whether a `head` element has a `meta` child with\n * `http-equiv=\"Content-Type\"` (compared case-insensitively).\n *\n * @param {Element} head - The head element\n * @returns {boolean} True when libxml2 adds no meta element\n */\nfunction hasContentTypeMeta(head) {\n for (const child of head.childNodes) {\n if (child.nodeType !== NODE_TYPE.ELEMENT || child.localName !== \"meta\") {\n continue;\n }\n const value = child.getAttribute(\"http-equiv\");\n if (value?.toLowerCase() === \"content-type\") return true;\n }\n return false;\n}\n\n/**\n * The Content-Type `meta` element libxml2 writes as the first child of the\n * `head` child of an `html` document element.\n *\n * @param {Element} element - Element being written\n * @param {string} encoding - The output encoding, as declared\n * @returns {string} The meta element markup, or \"\"\n */\nexport function xhtmlHeadMeta(element, encoding) {\n const parent = element.parentNode;\n const isHead =\n element.localName === \"head\" &&\n parent?.localName === \"html\" &&\n parent.parentNode?.nodeType !== NODE_TYPE.ELEMENT;\n if (!isHead || hasContentTypeMeta(element)) return \"\";\n return `<meta http-equiv=\"Content-Type\" content=\"text/html; charset=${encoding}\" />`;\n}\n", "/**\n * XML Output Serializer\n *\n * Implements the `xml` output method of XSLT 1.0 section 16.1 and, with the\n * `xhtml` option, the XHTML empty element convention. It is also the base of\n * the html serializer, which overrides the dialect hooks defined here.\n */\n\nimport { TEXT_MODE, VOID_ELEMENTS, XHTML_NAMESPACE } from \"./constants.js\";\nimport { escapeXmlAttribute, escapeXmlText } from \"./escape.js\";\nimport { characterReference } from \"./encoding.js\";\nimport { BaseWriter } from \"./baseWriter.js\";\nimport { expandedNameKey } from \"./settings.js\";\nimport {\n isXhtml1Doctype,\n xhtmlHeadMeta,\n xhtmlRootNamespace,\n} from \"./xhtmlDocument.js\";\n\nexport class XmlWriter extends BaseWriter {\n /**\n * Whether an XML declaration has to be written.\n * @returns {boolean} True when the declaration is not omitted\n */\n get emitsXmlDeclaration() {\n return !this.settings.omitXmlDeclaration;\n }\n\n /**\n * Whether the output is an XHTML 1.0 document (see xhtmlDocument.js).\n * @returns {boolean} True when an XHTML 1.0 doctype is declared\n */\n get isXhtmlDocument() {\n return isXhtml1Doctype(this.settings);\n }\n\n /**\n * Namespace declarations of an element, plus the XHTML namespace libxml2\n * adds to an `html` element in no namespace of an XHTML 1.0 document.\n *\n * @param {Array<{prefix: string, uri: string}>} declarations - Declarations\n * @param {Element} element - The element they are written on\n * @returns {string} Attribute markup, starting with a space when non-empty\n */\n namespaceMarkup(declarations, element) {\n const markup = super.namespaceMarkup(declarations);\n return this.isXhtmlDocument\n ? markup + xhtmlRootNamespace(element, declarations)\n : markup;\n }\n\n /**\n * Terminator of a processing instruction.\n * @returns {string} The XML processing instruction terminator\n */\n get piTerminator() {\n return \"?>\";\n }\n\n /**\n * How a source CDATA section node has to be written.\n * @returns {string} A {@link TEXT_MODE} value\n */\n get cdataNodeMode() {\n return TEXT_MODE.CDATA;\n }\n\n /**\n * Whether a line break follows a top-level comment that another node\n * follows, as libxslt (xsltSaveResultTo) writes unless `indent=\"no\"` is\n * declared.\n * @returns {boolean} True for xml output without `indent=\"no\"`\n */\n get topLevelLineBreaks() {\n return this.settings.topLevelLineBreaks === true;\n }\n\n /**\n * Build the document type declaration for the xml output method.\n *\n * @param {Element|null} rootElement - Result document element\n * @returns {string} Doctype markup, or an empty string when not applicable\n */\n doctypeMarkup(rootElement) {\n const { doctypePublic, doctypeSystem } = this.settings;\n if (!rootElement || !doctypeSystem) {\n return \"\";\n }\n\n const name = rootElement.nodeName;\n return doctypePublic\n ? `<!DOCTYPE ${name} PUBLIC \"${doctypePublic}\" \"${doctypeSystem}\">`\n : `<!DOCTYPE ${name} SYSTEM \"${doctypeSystem}\">`;\n }\n\n /**\n * Determine how the character data children of an element are written:\n * as CDATA sections when the expanded name of the element is listed in\n * `cdata-section-elements` (XSLT 1.0 section 16.1).\n *\n * @param {Element} element - Parent element\n * @returns {string} A {@link TEXT_MODE} value\n */\n childTextMode(element) {\n return this.isCdataSectionElement(element)\n ? TEXT_MODE.CDATA\n : TEXT_MODE.ESCAPE;\n }\n\n /**\n * Whether an element is listed in `cdata-section-elements`. Prefixed names\n * the engine passed unresolved are resolved with the element's in-scope\n * namespaces.\n *\n * @param {Element} element - Element to test\n * @returns {boolean} True when its text is written as CDATA sections\n */\n isCdataSectionElement(element) {\n const { cdataSectionElements, cdataSectionQNames = [] } = this.settings;\n const namespaceUri = element.namespaceURI || null;\n const { localName } = element;\n if (cdataSectionElements.has(expandedNameKey(namespaceUri, localName))) {\n return true;\n }\n return cdataSectionQNames.some(\n (qname) =>\n qname.localName === localName &&\n namespaceUri !== null &&\n element.lookupNamespaceURI(qname.prefix) === namespaceUri,\n );\n }\n\n /**\n * Markup the serializer itself adds as the first child of an element: the\n * Content-Type meta of an XHTML 1.0 document head, as libxml2 writes it.\n *\n * @param {Element} element - Element being written\n * @returns {string} The meta element, or an empty string\n */\n leadingChildMarkup(element) {\n return this.isXhtmlDocument\n ? xhtmlHeadMeta(element, this.settings.encoding)\n : \"\";\n }\n\n /**\n * Whether the content of an element may be re-indented.\n *\n * @param {Element} _element - Element being inspected\n * @returns {boolean} Always true for XML output\n */\n allowsIndentInside(_element) {\n return true;\n }\n\n /**\n * Build the markup closing an element that has no children.\n *\n * XHTML elements follow the XHTML compatibility guidelines, as libxml2\n * (Chrome) and the DOM serializer (Firefox) do: void elements become\n * `<br />` and every other empty element gets an explicit end tag, because\n * `<script/>` or `<div/>` break when XHTML reaches an HTML parser. Other\n * elements use the XML empty-element tag.\n *\n * @param {Element} element - Empty element\n * @param {string} name - Element name as written\n * @returns {string} Markup terminating the start tag\n */\n emptyElementMarkup(element, name) {\n if (!this.followsXhtmlConventions(element)) return \"/>\";\n return this.isVoidElement(element) ? \" />\" : `></${name}>`;\n }\n\n /**\n * Whether an element is written with the XHTML empty-element conventions:\n * elements in the XHTML namespace, and namespace-less elements when the\n * output method is `xhtml` or the document type is XHTML 1.0.\n *\n * @param {Element} element - Element to test\n * @returns {boolean} True for XHTML elements\n */\n followsXhtmlConventions(element) {\n const namespace = element.namespaceURI || null;\n if (namespace === XHTML_NAMESPACE) return true;\n return namespace === null && (this.xhtml || this.isXhtmlDocument);\n }\n\n /**\n * Test whether an element is an HTML void element.\n *\n * @param {Element} element - Element to test\n * @returns {boolean} True for void elements such as `br`\n */\n isVoidElement(element) {\n return VOID_ELEMENTS.has(String(element.localName).toLowerCase());\n }\n\n /**\n * Escape character data.\n *\n * @param {string} value - Text content\n * @returns {string} Escaped text\n */\n escapeText(value) {\n return this.encodeReferences(escapeXmlText(value));\n }\n\n /**\n * Escape an attribute value.\n *\n * @param {string} value - Attribute value\n * @returns {string} Escaped value\n */\n escapeAttribute(value) {\n return this.encodeReferences(escapeXmlAttribute(value));\n }\n\n /**\n * Reference to a character the output encoding cannot represent.\n *\n * @param {number} codePoint - The code point\n * @returns {string} A numeric character reference\n */\n characterReference(codePoint) {\n return characterReference(codePoint);\n }\n}\n", "/**\n * HTML 4.01 Character Entity References\n *\n * The html output method writes a character the output encoding cannot\n * represent as an entity reference when HTML 4.01 defines one (`€` in\n * ISO-8859-1 output) and as a numeric character reference otherwise, as\n * libxslt does (XSLT 1.0 section 16.2).\n *\n * @module xslt/serializer/htmlEntities\n */\n\nimport { characterReference } from \"./encoding.js\";\n\n/** Entity names of U+00A0 to U+00FF, in code point order. */\nconst LATIN1_NAMES =\n \"nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy \" +\n \"reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm \" +\n \"raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring \" +\n \"AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde \" +\n \"Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml \" +\n \"Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil \" +\n \"egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve \" +\n \"oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute \" +\n \"thorn yuml\";\n\n/** The other entities, as `name codePoint` pairs. */\nconst OTHER_ENTITIES =\n \"OElig 338 oelig 339 Scaron 352 scaron 353 Yuml 376 fnof 402 circ 710 \" +\n \"tilde 732 Alpha 913 Beta 914 Gamma 915 Delta 916 Epsilon 917 Zeta 918 \" +\n \"Eta 919 Theta 920 Iota 921 Kappa 922 Lambda 923 Mu 924 Nu 925 Xi 926 \" +\n \"Omicron 927 Pi 928 Rho 929 Sigma 931 Tau 932 Upsilon 933 Phi 934 Chi 935 \" +\n \"Psi 936 Omega 937 alpha 945 beta 946 gamma 947 delta 948 epsilon 949 \" +\n \"zeta 950 eta 951 theta 952 iota 953 kappa 954 lambda 955 mu 956 nu 957 \" +\n \"xi 958 omicron 959 pi 960 rho 961 sigmaf 962 sigma 963 tau 964 \" +\n \"upsilon 965 phi 966 chi 967 psi 968 omega 969 thetasym 977 upsih 978 \" +\n \"piv 982 ensp 8194 emsp 8195 thinsp 8201 zwnj 8204 zwj 8205 lrm 8206 \" +\n \"rlm 8207 ndash 8211 mdash 8212 lsquo 8216 rsquo 8217 sbquo 8218 \" +\n \"ldquo 8220 rdquo 8221 bdquo 8222 dagger 8224 Dagger 8225 bull 8226 \" +\n \"hellip 8230 permil 8240 prime 8242 Prime 8243 lsaquo 8249 rsaquo 8250 \" +\n \"oline 8254 frasl 8260 euro 8364 image 8465 weierp 8472 real 8476 \" +\n \"trade 8482 alefsym 8501 larr 8592 uarr 8593 rarr 8594 darr 8595 \" +\n \"harr 8596 crarr 8629 lArr 8656 uArr 8657 rArr 8658 dArr 8659 hArr 8660 \" +\n \"forall 8704 part 8706 exist 8707 empty 8709 nabla 8711 isin 8712 \" +\n \"notin 8713 ni 8715 prod 8719 sum 8721 minus 8722 lowast 8727 radic 8730 \" +\n \"prop 8733 infin 8734 ang 8736 and 8743 or 8744 cap 8745 cup 8746 \" +\n \"int 8747 there4 8756 sim 8764 cong 8773 asymp 8776 ne 8800 equiv 8801 \" +\n \"le 8804 ge 8805 sub 8834 sup 8835 nsub 8836 sube 8838 supe 8839 \" +\n \"oplus 8853 otimes 8855 perp 8869 sdot 8901 lceil 8968 rceil 8969 \" +\n \"lfloor 8970 rfloor 8971 lang 9001 rang 9002 loz 9674 spades 9824 \" +\n \"clubs 9827 hearts 9829 diams 9830\";\n\n/**\n * Entity name by code point.\n * @type {Map<number, string>}\n */\nconst ENTITY_NAMES = new Map(\n LATIN1_NAMES.split(\" \").map((name, index) => [0xa0 + index, name]),\n);\nconst otherParts = OTHER_ENTITIES.split(\" \");\nfor (let i = 0; i < otherParts.length; i += 2) {\n ENTITY_NAMES.set(Number(otherParts[i + 1]), otherParts[i]);\n}\n\n/**\n * Reference to a character the output encoding cannot represent: the HTML\n * 4.01 entity reference when there is one, a numeric reference otherwise.\n *\n * @param {number} codePoint - The code point\n * @returns {string} `&name;` or `&#N;`\n *\n * @example\n * htmlCharacterReference(0x20ac); // \"€\"\n */\nexport function htmlCharacterReference(codePoint) {\n const name = ENTITY_NAMES.get(codePoint);\n return name ? `&${name};` : characterReference(codePoint);\n}\n", "/**\n * Document type declaration of the html output method (XSLT 1.0 section\n * 16.2), as libxslt and libxml2 (and so Chrome) write it.\n *\n * Without `doctype-public` and `doctype-system`, libxslt derives the\n * identifiers from the `version` attribute of `xsl:output` (its table\n * below): `version=\"5\"` gives `<!DOCTYPE html>`, `version=\"4.01\"` the HTML\n * 4.01 Transitional DTD. The system identifier `about:legacy-compat` is not\n * written (HTML5's legacy doctype string).\n *\n * @module xslt/serializer/htmlDoctype\n */\n\n/** Doctype identifiers by html `version`, libxslt's xsltHTMLVersions. */\nconst HTML_VERSIONS = new Map([\n [\"5\", [null, \"about:legacy-compat\"]],\n [\n \"4.01frame\",\n [\n \"-//W3C//DTD HTML 4.01 Frameset//EN\",\n \"http://www.w3.org/TR/1999/REC-html401-19991224/frameset.dtd\",\n ],\n ],\n [\n \"4.01strict\",\n [\n \"-//W3C//DTD HTML 4.01//EN\",\n \"http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd\",\n ],\n ],\n [\n \"4.01trans\",\n [\n \"-//W3C//DTD HTML 4.01 Transitional//EN\",\n \"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\",\n ],\n ],\n [\n \"4.01\",\n [\n \"-//W3C//DTD HTML 4.01 Transitional//EN\",\n \"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\",\n ],\n ],\n [\n \"4.0strict\",\n [\"-//W3C//DTD HTML 4.01//EN\", \"http://www.w3.org/TR/html4/strict.dtd\"],\n ],\n [\n \"4.0trans\",\n [\n \"-//W3C//DTD HTML 4.01 Transitional//EN\",\n \"http://www.w3.org/TR/html4/loose.dtd\",\n ],\n ],\n [\n \"4.0frame\",\n [\n \"-//W3C//DTD HTML 4.01 Frameset//EN\",\n \"http://www.w3.org/TR/html4/frameset.dtd\",\n ],\n ],\n [\n \"4.0\",\n [\n \"-//W3C//DTD HTML 4.01 Transitional//EN\",\n \"http://www.w3.org/TR/html4/loose.dtd\",\n ],\n ],\n [\"3.2\", [\"-//W3C//DTD HTML 3.2//EN\", null]],\n]);\n\n/** System identifier libxml2 leaves out of an HTML doctype. */\nconst LEGACY_COMPAT = \"about:legacy-compat\";\n\n/**\n * Build the doctype of html output.\n *\n * @param {{doctypePublic?: string|null, doctypeSystem?: string|null,\n * version?: string|null}} settings - Normalized output settings\n * @param {string} name - Name of the document element\n * @returns {string} The doctype markup, or \"\" when there is none\n *\n * @example\n * htmlDoctypeMarkup({ version: \"5\" }, \"html\"); // \"<!DOCTYPE html>\"\n */\nexport function htmlDoctypeMarkup(settings, name) {\n let publicId = settings.doctypePublic || null;\n let systemId = settings.doctypeSystem || null;\n if (!publicId && !systemId) {\n const ids = HTML_VERSIONS.get(String(settings.version).toLowerCase());\n if (!ids) return \"\";\n [publicId, systemId] = ids;\n }\n if (publicId) {\n const system = systemId ? ` \"${systemId}\"` : \"\";\n return `<!DOCTYPE ${name} PUBLIC \"${publicId}\"${system}>`;\n }\n return systemId === LEGACY_COMPAT\n ? `<!DOCTYPE ${name}>`\n : `<!DOCTYPE ${name} SYSTEM \"${systemId}\">`;\n}\n", "/**\n * HTML Output Serializer\n *\n * Implements the `html` output method of XSLT 1.0 section 16.2 on top of the\n * XML writer: no XML declaration, void elements without a closing slash,\n * minimized boolean attributes and unescaped script/style content. Like\n * libxml2 (and so Chrome), namespace declarations of the result tree are\n * written, and an element in a namespace other than XHTML is not an HTML\n * element (`<s:img></s:img>`). Unlike libxml2, XHTML elements keep the HTML\n * rules, so `<br/>` in the XHTML namespace is not written as `<br></br>`\n * (which HTML parsers read as two line breaks).\n */\n\nimport {\n NODE_TYPE,\n PRESERVE_SPACE_ELEMENTS,\n RAW_TEXT_ELEMENTS,\n TEXT_MODE,\n URI_ATTRIBUTES,\n URI_ATTRIBUTES_OF_A,\n XHTML_NAMESPACE,\n} from \"./constants.js\";\nimport {\n escapeHtmlAttribute,\n escapeHtmlText,\n escapeUriAttribute,\n} from \"./escape.js\";\nimport { htmlCharacterReference } from \"./htmlEntities.js\";\nimport { htmlDoctypeMarkup } from \"./htmlDoctype.js\";\nimport { XmlWriter } from \"./xmlSerializer.js\";\n\n/**\n * Whether a `head` element already declares the content type or character\n * set: a `meta` child with `http-equiv=\"Content-Type\"` or a `charset`\n * attribute (names and the http-equiv value compared case-insensitively).\n *\n * @param {Element} head - The head element\n * @returns {boolean} True when no meta element has to be added\n */\nfunction hasContentTypeMeta(head) {\n for (const child of head.childNodes) {\n if (\n child.nodeType !== NODE_TYPE.ELEMENT ||\n child.localName.toLowerCase() !== \"meta\"\n ) {\n continue;\n }\n for (const { name, value } of child.attributes) {\n const lower = name.toLowerCase();\n if (lower === \"charset\") return true;\n if (lower === \"http-equiv\" && value.toLowerCase() === \"content-type\") {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Whether the html output method %-escapes an attribute, as libxml2 does:\n * `href`, `action` and `src`, and `name` on `a` (names compared\n * case-insensitively), when neither the attribute nor its element is in a\n * namespace.\n *\n * @param {Attr} attribute - Attribute being written\n * @returns {boolean} True for URI attributes\n */\nfunction isUriAttribute(attribute) {\n const element = attribute.ownerElement;\n if (attribute.namespaceURI || element.namespaceURI) return false;\n const name = attribute.localName.toLowerCase();\n return (\n URI_ATTRIBUTES.has(name) ||\n (URI_ATTRIBUTES_OF_A.has(name) && element.localName.toLowerCase() === \"a\")\n );\n}\n\nexport class HtmlWriter extends XmlWriter {\n /**\n * The html output method never writes an XML declaration.\n * @returns {boolean} Always false\n */\n get emitsXmlDeclaration() {\n return false;\n }\n\n /**\n * No line breaks are added between the top-level nodes of html output.\n * @returns {boolean} Always false\n */\n get topLevelLineBreaks() {\n return false;\n }\n\n /**\n * HTML output is never an XHTML document.\n * @returns {boolean} Always false\n */\n get isXhtmlDocument() {\n return false;\n }\n\n /**\n * HTML processing instructions are terminated by `>` alone.\n * @returns {string} The HTML processing instruction terminator\n */\n get piTerminator() {\n return \">\";\n }\n\n /**\n * HTML has no CDATA sections, so such nodes are escaped as text.\n * @returns {string} A {@link TEXT_MODE} value\n */\n get cdataNodeMode() {\n return TEXT_MODE.ESCAPE;\n }\n\n /**\n * Build the document type declaration for the html output method (see\n * htmlDoctype.js: declared identifiers, else derived from `version`).\n *\n * @param {Element|null} rootElement - Result document element\n * @returns {string} Doctype markup, or an empty string when not applicable\n */\n doctypeMarkup(rootElement) {\n return htmlDoctypeMarkup(\n this.settings,\n rootElement ? rootElement.nodeName : \"html\",\n );\n }\n\n /**\n * Script and style content is written verbatim.\n *\n * @param {Element} element - Parent element\n * @returns {string} A {@link TEXT_MODE} value\n */\n childTextMode(element) {\n return RAW_TEXT_ELEMENTS.has(String(element.localName).toLowerCase())\n ? TEXT_MODE.RAW\n : TEXT_MODE.ESCAPE;\n }\n\n /**\n * Content of `pre`, `script`, `style` and `textarea` is never re-indented.\n *\n * @param {Element} element - Element being inspected\n * @returns {boolean} True when the content may be indented\n */\n allowsIndentInside(element) {\n return !PRESERVE_SPACE_ELEMENTS.has(\n String(element.localName).toLowerCase(),\n );\n }\n\n /**\n * Void elements have no end tag; every other element gets one.\n *\n * @param {Element} element - Empty element\n * @param {string} name - Element name as written\n * @returns {string} Markup terminating the start tag\n */\n emptyElementMarkup(element, name) {\n const namespace = element.namespaceURI;\n const isHtml = !namespace || namespace === XHTML_NAMESPACE;\n return isHtml && this.isVoidElement(element) ? \">\" : `></${name}>`;\n }\n\n /**\n * Boolean attributes are minimized to their name alone; URI attributes\n * are %-escaped (see isUriAttribute).\n *\n * @param {Attr} attribute - Attribute to write\n * @returns {string} Attribute markup, starting with a space\n */\n attributeMarkup(attribute) {\n const { name, value } = attribute;\n if (String(value).toLowerCase() === name.toLowerCase()) {\n return ` ${name}`;\n }\n const written = isUriAttribute(attribute)\n ? escapeUriAttribute(value)\n : value;\n return ` ${name}=\"${this.escapeAttribute(written)}\"`;\n }\n\n /**\n * The content type `meta` element libxslt (and so Chrome) writes as the\n * first child of an HTML `head` element that does not already have one\n * (XSLT 1.0 section 16.2 recommends it). Firefox does not add it.\n *\n * @param {Element} element - Element being written\n * @returns {string} The meta element markup, or an empty string\n */\n leadingChildMarkup(element) {\n // libxml2 finds the head element by name, whatever its namespace\n if (\n element.localName.toLowerCase() !== \"head\" ||\n hasContentTypeMeta(element)\n ) {\n return \"\";\n }\n const { mediaType, encoding } = this.settings;\n const content = `${mediaType || \"text/html\"}; charset=${encoding}`;\n return `<meta http-equiv=\"Content-Type\" content=\"${this.escapeAttribute(content)}\">`;\n }\n\n /**\n * Escape character data for HTML.\n *\n * @param {string} value - Text content\n * @returns {string} Escaped text\n */\n escapeText(value) {\n return this.encodeReferences(escapeHtmlText(value));\n }\n\n /**\n * Escape an attribute value for HTML.\n *\n * @param {string} value - Attribute value\n * @returns {string} Escaped value\n */\n escapeAttribute(value) {\n return this.encodeReferences(escapeHtmlAttribute(value));\n }\n\n /**\n * Reference to a character the output encoding cannot represent: an HTML\n * entity reference where HTML 4.01 has one, as libxslt writes.\n *\n * @param {number} codePoint - The code point\n * @returns {string} An entity or numeric character reference\n */\n characterReference(codePoint) {\n return htmlCharacterReference(codePoint);\n }\n}\n", "/**\n * Text Output Serializer\n *\n * Implements the `text` output method of XSLT 1.0 section 16.3: the result is\n * the concatenation of every descendant character data node, unescaped.\n */\n\nimport { NODE_TYPE } from \"./constants.js\";\nimport { ChunkBuffer } from \"./chunks.js\";\n\n/**\n * Whether a node is character data (text or CDATA section).\n *\n * @param {Node} node - Node to test\n * @returns {boolean} True for character data\n */\nfunction isCharacterData(node) {\n return (\n node.nodeType === NODE_TYPE.TEXT ||\n node.nodeType === NODE_TYPE.CDATA_SECTION\n );\n}\n\n/**\n * The character data nodes under `root` in document order, found without\n * recursion (firstChild/nextSibling walk), so deep trees cannot overflow the\n * stack.\n *\n * @param {Node} root - Document, fragment, element or character data node\n * @yields {Node} Character data nodes\n * @returns {Generator<Node, void, void>} The nodes\n */\nfunction* characterDataNodes(root) {\n let node = root;\n while (node) {\n if (isCharacterData(node)) yield node;\n if (node.firstChild) {\n node = node.firstChild;\n continue;\n }\n while (node !== root && !node.nextSibling) node = node.parentNode;\n node = node === root ? null : node.nextSibling;\n }\n}\n\n/**\n * Serialize a result tree with the text output method, in chunks.\n *\n * @param {Node} node - Document, fragment, element or character data node\n * @param {number} [chunkSize] - Chunk size in UTF-16 code units; Infinity\n * yields the whole text as one chunk\n * @yields {string} Non-empty chunks of at most `chunkSize` code units\n * @returns {Generator<string, void, void>} The chunks, in order\n *\n * @example\n * [...textChunks(fragment, 16384)].join(\"\");\n */\nexport function* textChunks(node, chunkSize) {\n const buffer = new ChunkBuffer(chunkSize);\n for (const text of characterDataNodes(node)) {\n buffer.write(text.nodeValue || \"\");\n if (buffer.full) yield* buffer.take();\n }\n yield* buffer.take(true);\n}\n\n/**\n * Serialize a result tree with the text output method.\n *\n * @param {Node} node - Document, fragment, element or character data node\n * @returns {string} Concatenated character data\n */\nexport function serializeText(node) {\n let text = \"\";\n for (const chunk of textChunks(node, Infinity)) text += chunk;\n return text;\n}\n", "/**\n * XSLT Output Serializer\n *\n * Serializes a result tree to a string honoring the `xsl:output` settings of\n * the stylesheet (XSLT 1.0 section 16): output method, indentation, XML\n * declaration, document type declaration, CDATA sections and\n * `disable-output-escaping`.\n *\n * @example\n * import { serializeResult } from './serializer.js';\n *\n * serializeResult(resultDocument, { method: 'xml', indent: 'yes' });\n * // '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<BAR>\\n <QUX/>\\n</BAR>'\n */\n\nimport { resolveOutputSettings } from \"./serializer/settings.js\";\nimport { XmlWriter } from \"./serializer/xmlSerializer.js\";\nimport { HtmlWriter } from \"./serializer/htmlSerializer.js\";\nimport { textChunks } from \"./serializer/textSerializer.js\";\nimport { toChunkSize } from \"./serializer/chunks.js\";\n\nexport { markRawText, isRawText, rawTextNodes } from \"./serializer/rawText.js\";\nexport {\n resolveOutputSettings,\n detectOutputMethod,\n findRootElement,\n} from \"./serializer/settings.js\";\nexport { XmlWriter } from \"./serializer/xmlSerializer.js\";\nexport { HtmlWriter } from \"./serializer/htmlSerializer.js\";\nexport { serializeText, textChunks } from \"./serializer/textSerializer.js\";\nexport {\n ChunkBuffer,\n DEFAULT_CHUNK_SIZE,\n toChunkSize,\n} from \"./serializer/chunks.js\";\n\n/**\n * Serialize a transformation result incrementally, honoring the same\n * `xsl:output` settings as {@link serializeResult}. The result tree must be\n * complete (XSLT 1.0 builds it in memory); what is bounded is the output\n * text: chunks are yielded as soon as they are full, so a consumer can write\n * them out while the rest is being serialized.\n *\n * @param {Node|null} node - Result document, fragment or element\n * @param {object} [outputSettings] - `xsl:output` settings (see serializeResult)\n * @param {{chunkSize?: number}} [options] - `chunkSize` in UTF-16 code units,\n * {@link DEFAULT_CHUNK_SIZE} (16 KiB) by default, Infinity for one chunk\n * @yields {string} Non-empty chunks of at most `chunkSize` code units (one\n * more when a surrogate pair straddles the boundary)\n * @returns {Iterator<string>} The chunks; joined, they equal\n * `serializeResult(node, outputSettings)`\n * @throws {RangeError} When `chunkSize` is not a positive integer or Infinity\n *\n * @example\n * for (const chunk of serializeChunks(resultDocument, { method: \"xml\" })) {\n * stream.write(chunk);\n * }\n */\nexport function serializeChunks(node, outputSettings = {}, options = {}) {\n const chunkSize = toChunkSize(options.chunkSize);\n if (!node) return [][Symbol.iterator]();\n\n const settings = resolveOutputSettings(outputSettings, node);\n\n if (settings.method === \"text\") {\n return textChunks(node, chunkSize);\n }\n const writer =\n settings.method === \"html\"\n ? new HtmlWriter(settings)\n : new XmlWriter(settings, { xhtml: settings.method === \"xhtml\" });\n return writer.chunks(node, chunkSize);\n}\n\n/**\n * Serialize a transformation result to a string.\n *\n * @param {Node|null} node - Result document, fragment or element\n * @param {object} [outputSettings] - `xsl:output` settings, as collected by the\n * XSLT engine (`method`, `version`, `encoding`, `standalone`, `indent`,\n * `omitXmlDeclaration`, `doctypePublic`, `doctypeSystem`, `mediaType`,\n * `cdataSectionElements`)\n * @returns {string} The serialized result, or an empty string for a null node\n */\nexport function serializeResult(node, outputSettings = {}) {\n const chunks = serializeChunks(node, outputSettings, { chunkSize: Infinity });\n let output = \"\";\n for (const chunk of chunks) output += chunk;\n return output;\n}\n", "/**\n * The document returned by `transformToDocument`, built like Chrome's\n * `XSLTProcessor` builds it from the serialized output:\n *\n * - xml output: the result tree nodes, minus whitespace-only text at the\n * document level (the XML parser drops it, and a document cannot hold\n * text), with a document type node when `xsl:output` declares\n * `doctype-public` or `doctype-system` (as libxslt creates one);\n * - html output: an HTML document parsed from the serialized html output,\n * so it has `html`, `head` and `body` elements that are HTMLElements;\n * - text output: see wrapTextResult in resultTree.js.\n *\n * @module xslt/resultDocument\n */\n\n\"use strict\";\n\nimport { findRootElement } from \"./serializer/settings.js\";\nimport { appendDoctype } from \"./resultTree.js\";\nimport { findParseError } from \"./domParsing.js\";\n\n/** Text made only of XML whitespace (#x20 #x9 #xD #xA). */\nconst WHITESPACE_ONLY = /^[ \\t\\r\\n]*$/;\n\n/**\n * Whether a result node is whitespace-only character data.\n *\n * @param {Node} node - A child of the result fragment\n * @returns {boolean} True for text or CDATA holding only whitespace\n */\nfunction isWhitespaceText(node) {\n return (\n (node.nodeType === 3 || node.nodeType === 4) &&\n WHITESPACE_ONLY.test(node.nodeValue)\n );\n}\n\n/**\n * Move an xml result fragment into an empty document.\n *\n * @param {Document} doc - An empty XML document\n * @param {DocumentFragment} fragment - The result, owned by `doc`\n * @param {{doctypePublic?: string|null, doctypeSystem?: string|null}} settings -\n * The xsl:output settings\n * @returns {Document} The same document, filled in\n * @throws {Error} When the result cannot be a document (text or several\n * elements at the top level), as the DOM rejects it\n *\n * @example\n * fillXmlDocument(doc, fragment, { doctypeSystem: \"doc.dtd\" }).doctype.name;\n */\nexport function fillXmlDocument(doc, fragment, settings) {\n const { doctypePublic, doctypeSystem } = settings;\n const root = findRootElement(fragment);\n if (root && (doctypePublic || doctypeSystem)) {\n appendDoctype(doc, root.nodeName, doctypePublic ?? \"\", doctypeSystem ?? \"\");\n }\n for (const child of Array.from(fragment.childNodes)) {\n if (!isWhitespaceText(child)) doc.appendChild(child);\n }\n return doc;\n}\n\n/**\n * Parse serialized html output into an HTML document, as Chrome does for\n * `transformToDocument` with the html output method. The DOMParser of the\n * host (global, or the window of the source document) is used; without one,\n * an HTML document of the source's DOM implementation is filled through\n * `innerHTML` (without a doctype node).\n *\n * xmldom parses `text/html` too, into a document without the HTML\n * accessors (`body`, `head`, `title`); DOMs that can do neither, and markup\n * the HTML parser rejects, leave the XML result in place.\n *\n * @param {string} markup - The serialized html output\n * @param {Document} referenceDoc - A document of the DOM implementation to use\n * @returns {Document|null} The HTML document, or null when the DOM cannot\n * create HTML documents (the caller then keeps the XML result)\n *\n * @example\n * parseHtmlDocument(\"<html><body><p>x</p></body></html>\", xmlDoc).body;\n */\nexport function parseHtmlDocument(markup, referenceDoc) {\n const Parser =\n globalThis.DOMParser ?? referenceDoc.defaultView?.DOMParser ?? null;\n if (Parser) {\n const doc = new Parser().parseFromString(markup, \"text/html\");\n return findParseError(doc) ? null : doc;\n }\n\n const implementation = referenceDoc.implementation;\n if (typeof implementation?.createHTMLDocument !== \"function\") return null;\n const doc = implementation.createHTMLDocument(\"\");\n if (!(\"innerHTML\" in doc.documentElement)) return null;\n if (doc.doctype) doc.removeChild(doc.doctype);\n doc.documentElement.innerHTML = markup;\n return doc;\n}\n", "/**\n * XSLT processing context (the state of one instruction's evaluation).\n */\n\nimport { XPathEvaluator } from \"../../xpath/evaluator.js\";\nimport { createVariableView, lookupVariable } from \"../variables.js\";\n\n/**\n * XSLT Processing Context\n *\n * `variables` and `parameters` hold the local bindings in scope; the global\n * variables and parameters of the transformation are in `globals`. The engine\n * starts every template invocation with empty local bindings (and the\n * template's own parameters), so local variables are lexically scoped.\n * `namespaces` holds the prefixes in scope on the stylesheet element being\n * instantiated.\n */\nexport class XsltContext {\n constructor(options = {}) {\n this.currentNode = options.currentNode;\n this.currentNodeList = options.currentNodeList || [];\n this.position = options.position || 1;\n this.variables = { ...options.variables };\n this.parameters = { ...options.parameters };\n this.globals = options.globals ?? null;\n this.outputDocument = options.outputDocument;\n this.stylesheet = options.stylesheet;\n this.namespaces = options.namespaces ?? {};\n this.templates = options.templates || [];\n this.keys = options.keys || {};\n this.decimalFormats = options.decimalFormats || {};\n this.outputMethod = options.outputMethod || \"xml\";\n this.xpathEvaluator = options.xpathEvaluator || new XPathEvaluator();\n this.currentTemplate = options.currentTemplate || null;\n this.currentMode = options.currentMode ?? null;\n this.variableView = null;\n }\n\n /**\n * Copy the context, changing some of its properties.\n *\n * `variables`, `parameters` and `namespaces` overrides are merged into the\n * current ones; with `fresh: true` the copy starts without local bindings\n * (a new template invocation).\n *\n * @param {object} [overrides] - Properties to change\n * @returns {XsltContext} The copy\n */\n clone(overrides = {}) {\n const fresh = overrides.fresh === true;\n const merge = (own, extra) => (extra ? { ...own, ...extra } : own);\n return new XsltContext({\n currentNode: overrides.currentNode ?? this.currentNode,\n currentNodeList: overrides.currentNodeList ?? this.currentNodeList,\n position: overrides.position ?? this.position,\n variables: fresh ? null : merge(this.variables, overrides.variables),\n parameters: fresh ? null : merge(this.parameters, overrides.parameters),\n globals: this.globals,\n outputDocument: this.outputDocument,\n stylesheet: this.stylesheet,\n namespaces: merge(this.namespaces, overrides.namespaces),\n templates: this.templates,\n keys: this.keys,\n decimalFormats: this.decimalFormats,\n outputMethod: this.outputMethod,\n xpathEvaluator: this.xpathEvaluator,\n currentTemplate: overrides.currentTemplate ?? this.currentTemplate,\n currentMode: overrides.currentMode ?? this.currentMode,\n });\n }\n\n /**\n * The variables in scope, as the object view the XPath evaluator reads.\n *\n * @returns {object} A live, read-only view (see createVariableView)\n */\n get xpathVariables() {\n this.variableView ??= createVariableView(this);\n return this.variableView;\n }\n\n /**\n * The value of a variable or parameter in scope.\n *\n * @param {string} name - The variable name\n * @returns {*} The value\n * @throws {Error} When no such variable is in scope\n */\n getVariable(name) {\n const { found, value } = lookupVariable(this, name);\n if (!found) throw new Error(`Undefined variable: $${name}`);\n return value;\n }\n\n /**\n * Bind a local variable in this context.\n *\n * @param {string} name - The variable name\n * @param {*} value - Its value\n * @returns {void}\n */\n setVariable(name, value) {\n this.variables[name] = value;\n }\n}\n", "/**\n * Transformation entry points: building the result tree and shaping it as\n * a fragment, a document or a string.\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { WhitespaceFilter, stripWhitespaceNodes } from \"../whitespace.js\";\nimport {\n createResultDocument,\n importResultFragment,\n isHtmlDocument,\n parseHtmlFragment,\n wrapTextResult,\n} from \"../resultTree.js\";\nimport { resolveOutputSettings, serializeResult } from \"../serializer.js\";\nimport { fillXmlDocument, parseHtmlDocument } from \"../resultDocument.js\";\nimport { XsltContext } from \"./context.js\";\nimport {\n DocumentOrderIndex,\n hasNativePositionComparison,\n} from \"../../xpath/documentOrder.js\";\n\n/**\n * Turn a JavaScript stack overflow into a clear transformation error; any\n * other error is returned unchanged.\n *\n * @param {Error} error - The error thrown by a transformation\n * @returns {Error} The error to report\n */\nfunction recursionError(error) {\n const isStackOverflow =\n (error instanceof RangeError && /call stack/i.test(error.message)) ||\n // Firefox reports \"InternalError: too much recursion\"\n (error?.name === \"InternalError\" && /recursion/i.test(error.message));\n if (!isStackOverflow) return error;\n\n return new Error(\n \"Template recursion too deep: the transformation exceeded the JavaScript \" +\n \"call stack (infinite recursion, or recursion deeper than the runtime allows)\",\n { cause: error },\n );\n}\n\nexport const transformationMethods = {\n /**\n * Transform a source node into a fragment owned by `ownerDocument`, built\n * with the XML DOM (names and namespaces as in the result tree).\n *\n * @param {Node} sourceNode - Source document or element\n * @param {Document} [ownerDocument] - Output document, default the global one\n * @returns {DocumentFragment} The result\n */\n transform(sourceNode, ownerDocument) {\n const doc = this.outputDocumentOf(ownerDocument);\n return importResultFragment(this.buildResultTree(sourceNode, doc), doc);\n },\n\n /**\n * Transform a source node into a fragment of `ownerDocument` as Chrome's\n * `transformToFragment` does: into an HTML document, the output of the\n * html method (declared or detected) is serialized and parsed as HTML, so\n * it holds HTMLElements, and other output keeps its nodes except that\n * elements in no namespace become XHTML elements (as in Chrome and\n * Firefox); into an XML document the result nodes are kept.\n *\n * @param {Node} sourceNode - Source document or element\n * @param {Document} ownerDocument - Output document\n * @returns {DocumentFragment} The result\n */\n transformToFragment(sourceNode, ownerDocument) {\n const doc = this.outputDocumentOf(ownerDocument);\n const fragment = this.buildResultTree(sourceNode, doc);\n const settings = resolveOutputSettings(this.outputSettings, fragment);\n if (isHtmlDocument(doc) && settings.method === \"html\") {\n return parseHtmlFragment(\n serializeResult(fragment, this.outputSettings),\n doc,\n );\n }\n return importResultFragment(fragment, doc, { htmlElements: true });\n },\n\n /**\n * The document that owns a transformation result.\n *\n * @param {Document} [ownerDocument] - Requested owner\n * @returns {Document} The owner, else the global document\n * @throws {Error} When there is no document at all\n */\n outputDocumentOf(ownerDocument) {\n const doc =\n ownerDocument || (typeof document !== \"undefined\" ? document : null);\n\n if (!doc) {\n throw new Error(\"No output document available\");\n }\n return doc;\n },\n\n /**\n * Run the transformation and return the result tree, built in a neutral\n * XML document: creating nodes directly in an HTML owner document would\n * lower case names and force the XHTML namespace on every element.\n *\n * The templates are applied to the document node (not the document\n * element), so the \"/\" template has the document as context node and\n * paths such as \"RootElement/child\" work.\n *\n * @param {Node} sourceNode - Source document or element\n * @param {Document} doc - Document providing the DOM implementation\n * @returns {DocumentFragment} The result tree\n */\n buildResultTree(sourceNode, doc) {\n const resultDocument = createResultDocument(doc);\n const source = this.initialNode(this.prepareSource(sourceNode, doc));\n\n const context = new XsltContext({\n currentNode: source,\n currentNodeList: [source],\n position: 1,\n outputDocument: resultDocument,\n stylesheet: this.stylesheetDoc,\n namespaces: this.namespaces,\n templates: this.templates,\n keys: this.keys,\n decimalFormats: this.decimalFormats,\n outputMethod: this.outputSettings.method,\n xpathEvaluator: this.xpathEvaluator,\n });\n\n this.rootContext = context;\n // The source tree may have changed since the previous transformation\n this.keyRegistry.clear();\n this.patternMatcher.reset();\n this.xpathEvaluator.resetNamespaceNodes();\n // Document order from positions numbered once, unless the DOM compares\n // positions natively (see documentOrder.js)\n this.xpathEvaluator.resetDocumentOrder(\n hasNativePositionComparison(source) ? null : new DocumentOrderIndex(),\n );\n this.numberMemos = new WeakMap();\n\n const fragment = resultDocument.createDocumentFragment();\n try {\n context.globals = this.createGlobals(context);\n context.globals.evaluateAll();\n this.applyTemplates([source], null, context, fragment);\n } catch (error) {\n throw recursionError(error);\n }\n return fragment;\n },\n\n /**\n * Choose the node the transformation starts from.\n *\n * A document element is transformed through its document, so that the \"/\"\n * template rule applies as for a whole document (as browsers do); any other\n * node is transformed as is.\n *\n * @param {Node} source - The (prepared) source node\n * @returns {Node} The initial context node\n */\n initialNode(source) {\n const owner = source.ownerDocument;\n return source.nodeType === 1 && owner?.documentElement === source\n ? owner\n : source;\n },\n\n /**\n * Apply `xsl:strip-space` to the source tree.\n *\n * Stripping produces a copy so the caller's document is never modified; when\n * no `xsl:strip-space` is declared the original node is used unchanged.\n *\n * @param {Node} sourceNode - The source document or element\n * @param {Document} ownerDocument - Document providing the DOM implementation\n * @returns {Node} The source to transform\n */\n prepareSource(sourceNode, ownerDocument) {\n const filter = new WhitespaceFilter(this.stripSpace, this.preserveSpace);\n if (!filter.isActive()) return sourceNode;\n\n return stripWhitespaceNodes(\n sourceNode,\n filter,\n createResultDocument(ownerDocument),\n );\n },\n\n /**\n * Transform to a complete document, shaped as Chrome's XSLTProcessor\n * returns it (see resultDocument.js): with `method=\"text\"` an XHTML page\n * holding the text in a `pre` element (see wrapTextResult), with the html\n * method (declared or detected) an HTML document parsed from the html\n * output, otherwise an XML document of the result nodes.\n *\n * @param {Node} sourceNode - Source document or element to transform\n * @returns {Document} The result document\n */\n transformToDocument(sourceNode) {\n const doc = this.createDocument(sourceNode);\n const fragment = this.transform(sourceNode, doc);\n\n if (this.outputSettings.method === \"text\") {\n return wrapTextResult(doc, fragment.textContent);\n }\n const settings = resolveOutputSettings(this.outputSettings, fragment);\n if (settings.method === \"html\") {\n const markup = serializeResult(fragment, this.outputSettings);\n const htmlDoc = parseHtmlDocument(markup, doc);\n if (htmlDoc) return htmlDoc;\n }\n return fillXmlDocument(doc, fragment, settings);\n },\n\n /**\n * Transform a source document and serialize the result to a string.\n *\n * Non-W3C convenience method: the result tree is serialized honoring the\n * `xsl:output` settings of the stylesheet (XSLT 1.0 section 16).\n *\n * @param {Node} sourceNode - Source document or element to transform\n * @returns {string} The serialized transformation result\n */\n transformToString(sourceNode) {\n const fragment = this.buildResultTree(\n sourceNode,\n this.createDocument(sourceNode),\n );\n return serializeResult(fragment, this.outputSettings);\n },\n\n /**\n * Create an empty XML document to hold a transformation result.\n *\n * Uses the global `document` when running in a browser and otherwise falls\n * back to the DOM implementation owning `referenceNode` (e.g. a jsdom or\n * xmldom document in Node.js).\n *\n * @param {Node} [referenceNode] - Any node whose DOM implementation can be reused\n * @returns {Document} A new empty document\n * @throws {Error} When no DOM implementation is available\n */\n createDocument(referenceNode) {\n if (typeof document !== \"undefined\") {\n return document.implementation.createDocument(null, null, null);\n }\n\n const ownerDocument =\n referenceNode &&\n (referenceNode.nodeType === 9\n ? referenceNode\n : referenceNode.ownerDocument);\n if (ownerDocument?.implementation) {\n return ownerDocument.implementation.createDocument(null, null, null);\n }\n\n throw new Error(\"Document creation not available in this environment\");\n },\n};\n", "/**\n * Engine services behind the XSLT functions: document(), generate-id()\n * and key() (see functions.js).\n *\n * Methods installed on XsltEngine.prototype (`this` is the engine).\n */\n\nimport { resolveUri, stripFragment } from \"../uri.js\";\n\nexport const functionSupportMethods = {\n /**\n * Set the loader used by the XSLT `document()` function.\n *\n * The loader is synchronous and must return a `Document`, an XML string or\n * null. Returning null (or configuring no loader at all) makes `document()`\n * evaluate to an empty node-set instead of failing the transformation.\n *\n * @param {((uri: string, baseUri?: string) => (Document|string|null))|null} loader - The loader, or null to remove it\n * @returns {XsltEngine} This engine, to allow chaining\n *\n * @example\n * engine.setDocumentLoader((uri) => readFileSync(uri, 'utf8'));\n */\n setDocumentLoader(loader) {\n this.documentLoader = loader ?? null;\n this.loadedDocuments.clear();\n return this;\n },\n\n /**\n * Load an external document for the `document()` function.\n *\n * Results are cached per resolved URI for the life of the engine, so the same\n * URI always yields the identical node-set.\n *\n * @param {string} uri - The requested URI, fragment identifiers are ignored\n * @param {string} [baseUri] - Base URI used to resolve relative references\n * @returns {Document|null} The loaded document, or null when unavailable\n *\n * @example\n * engine.loadDocument('data.xml', '/styles/main.xsl');\n */\n loadDocument(uri, baseUri) {\n const target = stripFragment(uri);\n\n if (target === \"\") return this.stylesheetDoc;\n if (!this.documentLoader) return null;\n\n const resolved = resolveUri(target, baseUri);\n if (this.loadedDocuments.has(resolved)) {\n return this.loadedDocuments.get(resolved);\n }\n\n const loaded = this.documentLoader(resolved, baseUri);\n const doc =\n typeof loaded === \"string\" ? this.parseXmlString(loaded) : loaded || null;\n\n this.loadedDocuments.set(resolved, doc);\n return doc;\n },\n\n /**\n * Return the stable identifier of a node for `generate-id()`.\n *\n * @param {Node} node - The node to identify\n * @returns {string} An identifier starting with a letter\n *\n * @example\n * engine.generateId(element); // 'N1'\n */\n generateId(node) {\n let id = this.generatedIds.get(node);\n if (!id) {\n this.generatedIdCount++;\n id = `N${this.generatedIdCount}`;\n this.generatedIds.set(node, id);\n }\n return id;\n },\n\n /**\n * Evaluate the `use` expression of an `xsl:key` for one node.\n *\n * @param {Node} node - The node being indexed\n * @param {string} expression - The `use` expression\n * @param {Object<string, string>} [namespaces] - Prefixes in scope on the xsl:key\n * @returns {string[]} The key values contributed by the node\n */\n evaluateKeyValues(node, expression, namespaces) {\n const context = this.rootContext.clone({\n currentNode: node,\n currentNodeList: [node],\n position: 1,\n });\n if (namespaces) context.namespaces = namespaces;\n const value = this.evaluateXPath(expression, context);\n\n if (Array.isArray(value)) {\n return value.map((item) => this.xpathEvaluator.getStringValue(item));\n }\n return [this.xpathEvaluator.toString(value)];\n },\n};\n", "/**\n * XSLT 1.0 Processing Engine\n * Based on W3C XSLT 1.0 Specification: http://www.w3.org/TR/1999/REC-xslt-19991116\n *\n * Processes XSLT stylesheets and transforms XML documents.\n *\n * XsltEngine is a facade: it owns the engine state and the helpers every\n * part uses (XPath evaluation, XSLT element tests, warnings), while the\n * methods live in modules under ./engine/ by concern and are installed on\n * its prototype (see engine/methods.js):\n *\n * - stylesheetLoading.js: importStylesheet, xsl:import/xsl:include\n * - topLevel.js: dispatch of top-level elements, simplified stylesheets\n * - declarations.js, outputDeclaration.js: top-level declarations\n * - templateRules.js: template registry and matching\n * - templateInvocation.js: apply-templates, apply-imports, call-template\n * - sequenceConstructor.js: instruction dispatch, fallback, extensions\n * - workStack.js: the explicit stack instantiating templates and their\n * content without deep JavaScript recursion, and the template depth limit\n * - controlFlow.js: if, choose, for-each, sorting\n * - bindings.js: variables and parameters\n * - textInstructions.js, numbering.js: value-of, text, comment, PI,\n * message, number\n * - nodeConstruction.js, copyInstructions.js: literal result elements,\n * element, attribute, attribute sets, copy, copy-of\n * - transformation.js: transform entry points and the result tree\n * - functionSupport.js: document(), generate-id() and key() services\n */\n\nimport { parse as parseXPath } from \"../xpath/parser.js\";\nimport { XPathEvaluator, XPathContext } from \"../xpath/evaluator.js\";\nimport { XSLT_NAMESPACE } from \"./elements.js\";\nimport { createXsltFunctions } from \"./functions.js\";\nimport { KeyIndexRegistry } from \"./keys.js\";\nimport { NamespaceAliasMap } from \"./literalResult.js\";\nimport { PatternMatcher } from \"./patterns.js\";\nimport { installMethods } from \"./engine/methods.js\";\nimport {\n createOutputSettings,\n outputDeclarationMethods,\n} from \"./engine/outputDeclaration.js\";\nimport { stylesheetLoadingMethods } from \"./engine/stylesheetLoading.js\";\nimport { topLevelMethods } from \"./engine/topLevel.js\";\nimport { declarationMethods } from \"./engine/declarations.js\";\nimport { templateRuleMethods } from \"./engine/templateRules.js\";\nimport { templateInvocationMethods } from \"./engine/templateInvocation.js\";\nimport { sequenceConstructorMethods } from \"./engine/sequenceConstructor.js\";\nimport { controlFlowMethods } from \"./engine/controlFlow.js\";\nimport { bindingMethods } from \"./engine/bindings.js\";\nimport { textInstructionMethods } from \"./engine/textInstructions.js\";\nimport { numberingMethods } from \"./engine/numbering.js\";\nimport { nodeConstructionMethods } from \"./engine/nodeConstruction.js\";\nimport { copyInstructionMethods } from \"./engine/copyInstructions.js\";\nimport { transformationMethods } from \"./engine/transformation.js\";\nimport { functionSupportMethods } from \"./engine/functionSupport.js\";\nimport {\n XSLT_MAX_TEMPLATE_DEPTH,\n workStackMethods,\n} from \"./engine/workStack.js\";\n\nexport { XsltContext } from \"./engine/context.js\";\nexport { XSLT_MAX_TEMPLATE_DEPTH };\n\n/**\n * Largest node-set a single XPath step may produce inside a transformation.\n *\n * The standalone XPath API keeps its low default (XPathLimits.MAX_RESULT_SIZE)\n * as a guard against untrusted expressions. A stylesheet is trusted program\n * code and commonly walks documents with tens of thousands of nodes, which the\n * native XSLTProcessor handles without any limit, so the engine uses a much\n * higher bound. Override it with the `maxResultSize` engine option.\n */\nexport const XSLT_MAX_RESULT_SIZE = 5000000;\n\n/**\n * Deepest XPath expression nesting allowed inside a transformation.\n *\n * Like XSLT_MAX_RESULT_SIZE, this is higher than the standalone XPath default\n * (XPathLimits.MAX_RECURSION_DEPTH = 100) because stylesheets are trusted and\n * generated ones often contain long chains such as `a + b + c + ...`.\n * Override it with the `maxRecursionDepth` engine option.\n */\nexport const XSLT_MAX_EXPRESSION_DEPTH = 1000;\n\n/**\n * XSLT Engine\n */\nexport class XsltEngine {\n /**\n * @param {object} [options] - Engine options\n * @param {number} [options.maxResultSize] - Largest node-set of one XPath step\n * @param {number} [options.maxRecursionDepth] - Deepest XPath expression nesting\n * @param {number} [options.maxTemplateDepth] - Deepest nesting of template\n * instantiations (default XSLT_MAX_TEMPLATE_DEPTH, 3000 as in libxslt)\n * @param {boolean} [options.legacyNameTests] - Deprecated: unprefixed name\n * tests also match nodes in a namespace, as before 1.2.0\n * @param {Function} [options.stylesheetLoader] - Loader for xsl:import/include\n * @param {Function} [options.documentLoader] - Loader for document()\n * @param {string} [options.baseUri] - Base URI of the stylesheet\n * @param {object} [options.domParser] - Parser for loaded XML strings\n * @param {boolean} [options.enableDynamicEvaluate] - Allow EXSLT\n * `dyn:evaluate()` (off by default: it evaluates XPath built from data)\n * @param {() => Date} [options.clock] - Clock for EXSLT current-time functions\n */\n constructor(options = {}) {\n this.enableDynamicEvaluate = options.enableDynamicEvaluate === true;\n this.clock = options.clock ?? null;\n this.xpathEvaluator = new XPathEvaluator({\n maxResultSize: options.maxResultSize ?? XSLT_MAX_RESULT_SIZE,\n maxRecursionDepth: options.maxRecursionDepth ?? XSLT_MAX_EXPRESSION_DEPTH,\n legacyNameTests: options.legacyNameTests,\n });\n // Template instantiation (see engine/workStack.js)\n this.maxTemplateDepth = options.maxTemplateDepth ?? XSLT_MAX_TEMPLATE_DEPTH;\n this.frames = null;\n this.templateDepth = 0;\n\n this.templates = [];\n this.keys = {};\n this.globalVariables = {};\n this.globalParameters = {};\n this.outputSettings = createOutputSettings();\n this.namespaces = {};\n this.decimalFormats = {};\n this.stylesheetDoc = null;\n this.attributeSets = {};\n this.namespaceAliases = new NamespaceAliasMap();\n this.stripSpace = [];\n this.preserveSpace = [];\n\n // Import/Include support\n this.stylesheetLoader = options.stylesheetLoader || null;\n this.currentImportPrecedence = 0;\n // URIs of the stylesheets being loaded, used to detect import cycles\n this.stylesheetStack = [];\n this.baseUri = options.baseUri || \"\";\n\n // document() support\n this.documentLoader = options.documentLoader || null;\n this.loadedDocuments = new Map();\n\n // Parser for XML strings returned by the loaders (see domParsing.js)\n this.domParser = options.domParser ?? null;\n\n // generate-id() support\n this.generatedIds = new WeakMap();\n this.generatedIdCount = 0;\n\n // Compiled XSLT patterns (template match, xsl:key, xsl:number)\n this.patternMatcher = new PatternMatcher(this.xpathEvaluator);\n\n // key() support\n this.rootContext = null;\n this.keyRegistry = new KeyIndexRegistry({\n keys: this.keys,\n matchesPattern: (node, pattern, definition) =>\n this.matchesPattern(\n node,\n pattern,\n this.rootContext,\n definition?.namespaces,\n ),\n evaluateUse: (node, expression, definition) =>\n this.evaluateKeyValues(node, expression, definition?.namespaces),\n });\n\n // Recoverable errors already reported, so each is reported once\n this.reportedWarnings = new Set();\n\n // Extension element implementations by expanded name `{uri}local`\n this.extensionElements = new Map();\n\n this.xpathEvaluator.registerFunctions(createXsltFunctions(this));\n }\n\n /**\n * Evaluate an XPath expression in an XSLT context.\n *\n * @param {string} expr - The expression\n * @param {XsltContext} context - The current context\n * @returns {*} The value\n */\n evaluateXPath(expr, context) {\n const ast = parseXPath(expr);\n const xpathContext = new XPathContext(\n context.currentNode,\n context.position,\n context.currentNodeList.length,\n context.xpathVariables,\n context.namespaces,\n context,\n );\n return this.xpathEvaluator.evaluate(ast, xpathContext);\n }\n\n /**\n * Whether a node is in the XSLT namespace (or uses the xsl prefix).\n *\n * @param {Node} node - A stylesheet node\n * @returns {boolean} True for an XSLT element\n */\n isXsltNamespace(node) {\n return (\n node.namespaceURI === XSLT_NAMESPACE ||\n (node.nodeName && node.nodeName.startsWith(\"xsl:\"))\n );\n }\n\n /**\n * Whether a node is the XSLT element of a local name.\n *\n * @param {Node} node - A stylesheet node\n * @param {string} localName - The XSLT element name, e.g. \"template\"\n * @returns {boolean} True for that element\n */\n isXsltElement(node, localName) {\n if (node.nodeType !== 1) return false;\n\n const nodeName = node.localName || node.nodeName;\n return (\n (node.namespaceURI === XSLT_NAMESPACE && nodeName === localName) ||\n node.nodeName === `xsl:${localName}`\n );\n }\n\n /**\n * Report a recoverable stylesheet error with console.warn, once per engine\n * and message (libxslt reports these errors and goes on).\n *\n * @param {string} message - The error description\n * @returns {void}\n */\n warnOnce(message) {\n if (this.reportedWarnings.has(message)) return;\n this.reportedWarnings.add(message);\n console.warn(`XSLT: ${message}`);\n }\n}\n\ninstallMethods(\n XsltEngine.prototype,\n stylesheetLoadingMethods,\n topLevelMethods,\n declarationMethods,\n outputDeclarationMethods,\n templateRuleMethods,\n templateInvocationMethods,\n sequenceConstructorMethods,\n workStackMethods,\n controlFlowMethods,\n bindingMethods,\n textInstructionMethods,\n numberingMethods,\n nodeConstructionMethods,\n copyInstructionMethods,\n transformationMethods,\n functionSupportMethods,\n);\n", "/**\n * Statically Known document() URIs\n *\n * Finds the `document('literal')` calls of a stylesheet module, so that the\n * asynchronous API can load those documents before the synchronous\n * transformation runs. Expressions are parsed with the XPath parser and the\n * syntax tree is searched for `document()` calls whose first argument is a\n * string literal; URIs computed at run time (`document(@href)`) and calls\n * with an explicit base (second argument) are left to the synchronous\n * document loader.\n *\n * Expressions are read from the expression attributes of XSLT instructions\n * (`select`, `test`, `use`, `value`) and from the `{...}` parts of every other\n * attribute (attribute value templates).\n *\n * @module async/documentUris\n */\n\nimport { NodeType, parse } from \"../xpath/parser.js\";\nimport { parseAvt } from \"../xslt/avt.js\";\nimport { XSLT_NAMESPACE } from \"../xslt/elements.js\";\nimport { resolveUri, stripFragment } from \"../xslt/uri.js\";\n\n/** Attributes of XSLT instructions holding a whole expression. */\nconst EXPRESSION_ATTRIBUTES = new Set([\"select\", \"test\", \"use\", \"value\"]);\n\n/**\n * The literal arguments of the `document()` calls of an expression.\n *\n * @param {string} expression - XPath expression\n * @returns {string[]} The literal URIs, empty when the expression is invalid\n * (the engine reports that when compiling)\n *\n * @example\n * literalDocumentArguments(\"document('a.xml')/x | document(@b)\"); // [\"a.xml\"]\n */\nexport function literalDocumentArguments(expression) {\n let tree;\n try {\n tree = parse(expression);\n } catch {\n return [];\n }\n const found = [];\n const stack = [tree];\n while (stack.length > 0) {\n const node = stack.pop();\n const [first] = node.args ?? [];\n const isStatic =\n node.type === NodeType.FUNCTION_CALL &&\n node.name === \"document\" &&\n !node.prefix &&\n node.args.length === 1 &&\n first.type === NodeType.LITERAL;\n if (isStatic) found.push(first.value);\n for (const value of Object.values(node)) {\n for (const child of Array.isArray(value) ? value : [value]) {\n if (typeof child?.type === \"string\") stack.push(child);\n }\n }\n }\n return found;\n}\n\n/**\n * The expressions held by an attribute.\n *\n * @param {Attr} attribute - An attribute of a stylesheet element\n * @returns {string[]} The expressions\n */\nfunction attributeExpressions(attribute) {\n const element = attribute.ownerElement;\n const isExpression =\n element.namespaceURI === XSLT_NAMESPACE &&\n !attribute.namespaceURI &&\n EXPRESSION_ATTRIBUTES.has(attribute.localName);\n if (isExpression) return [attribute.value];\n try {\n return parseAvt(attribute.value)\n .filter((part) => typeof part !== \"string\")\n .map((part) => part.expr);\n } catch {\n return [];\n }\n}\n\n/**\n * The resolved URIs of the literal `document()` calls of a stylesheet module.\n * They are resolved against the main stylesheet URI, as the engine resolves\n * `document()` calls without a base argument; fragment identifiers are\n * dropped and `document('')` (the stylesheet itself) is skipped.\n *\n * @param {Node} module - Stylesheet document or element\n * @param {string|undefined} stylesheetUri - URI of the main stylesheet\n * @returns {string[]} Resolved URIs, possibly repeated\n *\n * @example\n * staticDocumentUris(xslDoc, \"/xsl/main.xsl\"); // [\"/xsl/data.xml\"]\n */\nexport function staticDocumentUris(module, stylesheetUri) {\n const root = module.documentElement ?? module;\n const uris = [];\n for (const element of [root, ...root.getElementsByTagName(\"*\")]) {\n if (!hasDocumentCall(element)) continue;\n for (const attribute of element.attributes) {\n for (const expression of attributeExpressions(attribute)) {\n for (const literal of literalDocumentArguments(expression)) {\n const target = stripFragment(literal);\n if (target) uris.push(resolveUri(target, stylesheetUri));\n }\n }\n }\n }\n return uris;\n}\n\n/**\n * Cheap pre-filter: whether any attribute of an element mentions `document`.\n *\n * @param {Element} element - Stylesheet element\n * @returns {boolean} True when an attribute may hold a document() call\n */\nfunction hasDocumentCall(element) {\n for (const attribute of element.attributes) {\n if (attribute.value.includes(\"document\")) return true;\n }\n return false;\n}\n", "/**\n * Stylesheet and Document Preloading\n *\n * The XSLT engine compiles and transforms synchronously. To use asynchronous\n * loaders (`fetch`), everything the engine will ask for is loaded first:\n *\n * 1. the `xsl:import`/`xsl:include` tree, breadth first, every module in\n * parallel and each URI once (diamond imports share one load). A cycle\n * cannot make preloading loop, since a URI is never loaded twice; it is\n * reported by the engine while compiling (\"Circular stylesheet reference\n * detected\"), exactly as with a synchronous loader;\n * 2. the documents named by literal `document('...')` calls of every module\n * (see documentUris.js).\n *\n * The preloaded documents are then served by synchronous loaders, falling\n * back to the synchronous loaders configured on the processor.\n *\n * @module async/preload\n */\n\nimport { resolveUri } from \"../xslt/uri.js\";\nimport { XSLT_NAMESPACE } from \"../xslt/elements.js\";\nimport { staticDocumentUris } from \"./documentUris.js\";\n\n/**\n * The resolved hrefs of the `xsl:import` and `xsl:include` elements of a\n * stylesheet module (top-level children of its root element).\n *\n * @param {Node} module - Stylesheet document or root element\n * @param {string|undefined} moduleUri - URI of the module\n * @returns {string[]} Resolved URIs, in document order\n */\nexport function moduleReferences(module, moduleUri) {\n const root = module.documentElement ?? module;\n const uris = [];\n for (const child of root.childNodes) {\n const isReference =\n child.nodeType === 1 &&\n child.namespaceURI === XSLT_NAMESPACE &&\n (child.localName === \"import\" || child.localName === \"include\");\n const href = isReference ? child.getAttribute(\"href\") : null;\n if (href) uris.push(resolveUri(href, moduleUri));\n }\n return uris;\n}\n\n/**\n * Load the whole import/include tree of a stylesheet.\n *\n * @param {Node} style - The main stylesheet (document or root element)\n * @param {string|undefined} stylesheetUri - Its URI (base of relative hrefs)\n * @param {(uri: string, baseUri?: string) => Promise<Document|null>} fetchDocument -\n * De-duplicating loader (see createDocumentFetcher)\n * @returns {Promise<Map<string, Document>>} Every module by resolved URI\n * @throws {Error} When a module cannot be loaded\n *\n * @example\n * const modules = await preloadModules(xslDoc, \"/xsl/main.xsl\", load);\n */\nexport async function preloadModules(style, stylesheetUri, fetchDocument) {\n const modules = new Map();\n const seen = new Set(stylesheetUri ? [stylesheetUri] : []);\n let level = [{ module: style, uri: stylesheetUri }];\n\n while (level.length > 0) {\n const requests = [];\n for (const { module, uri } of level) {\n for (const target of moduleReferences(module, uri)) {\n if (seen.has(target)) continue;\n seen.add(target);\n requests.push(loadModule(target, uri, fetchDocument));\n }\n }\n level = await Promise.all(requests);\n for (const { module, uri } of level) modules.set(uri, module);\n }\n return modules;\n}\n\n/**\n * Load one stylesheet module.\n *\n * @param {string} uri - Resolved URI\n * @param {string|undefined} baseUri - URI of the referencing module\n * @param {(uri: string, baseUri?: string) => Promise<Document|null>} fetchDocument - Loader\n * @returns {Promise<{module: Document, uri: string}>} The module\n * @throws {Error} When the loader fails or returns nothing\n */\nasync function loadModule(uri, baseUri, fetchDocument) {\n const module = await fetchDocument(uri, baseUri);\n if (!module) throw new Error(`Cannot load stylesheet \"${uri}\"`);\n return { module, uri };\n}\n\n/**\n * Load the documents named by literal `document()` calls. A failed load is\n * not reported here: it is kept and reported when the transformation actually\n * evaluates that call (it may sit in a branch that never runs). Aborting\n * rejects at once.\n *\n * @param {Array<Node>} modules - Stylesheet modules to scan\n * @param {string|undefined} stylesheetUri - Base URI of `document()` calls\n * @param {(uri: string, baseUri?: string) => Promise<Document|null>} fetchDocument - Loader\n * @param {AbortSignal} [signal] - Optional signal\n * @returns {Promise<Map<string, {document?: Document|null, error?: Error}>>}\n * Outcome by resolved URI\n */\nexport async function preloadDocuments(\n modules,\n stylesheetUri,\n fetchDocument,\n signal,\n) {\n const uris = new Set(\n modules.flatMap((module) => staticDocumentUris(module, stylesheetUri)),\n );\n const outcomes = await Promise.all(\n [...uris].map((uri) =>\n fetchDocument(uri, stylesheetUri).then(\n (document) => ({ document }),\n (error) => {\n if (signal?.aborted) throw error;\n return { error };\n },\n ),\n ),\n );\n return new Map([...uris].map((uri, index) => [uri, outcomes[index]]));\n}\n\n/**\n * Synchronous stylesheet loader serving the preloaded modules. Every href of\n * the import tree is literal, so every module the engine asks for while\n * compiling has been preloaded.\n *\n * @param {Map<string, Document>} modules - Preloaded modules by resolved URI\n * @returns {(href: string) => Document} The loader\n */\nexport function preloadedStylesheetLoader(modules) {\n return (href) => modules.get(href);\n}\n\n/**\n * Synchronous `document()` loader serving preloaded documents first; a\n * preload failure is thrown when the document is actually needed.\n *\n * @param {Map<string, {document?: Document|null, error?: Error}>} documents -\n * Preloaded outcomes\n * @param {Function|null} fallback - Loader configured on the processor\n * @returns {(uri: string, baseUri?: string) => (Document|string|null)} The loader\n */\nexport function preloadedDocumentLoader(documents, fallback) {\n return (uri, baseUri) => {\n const outcome = documents.get(uri);\n if (outcome?.error) throw outcome.error;\n if (outcome) return outcome.document;\n return fallback ? fallback(uri, baseUri) : null;\n };\n}\n", "/**\n * XML Input Decoding\n *\n * Turns the raw bytes of an XML document into text following XML 1.0 Appendix F\n * (\"Autodetection of Character Encodings\"): a byte order mark wins, then the\n * `encoding` pseudo-attribute of the XML declaration, then UTF-8. Decoding is\n * done with TextDecoder, so every WHATWG encoding label is accepted\n * (ISO-8859-x, windows-125x, Shift_JIS, EUC-KR, ...).\n *\n * Shared by the command line tool (bin/lib/decode.js) and the asynchronous\n * API (byte streams and loader responses); it only needs the global\n * TextDecoder, so it runs in browsers too.\n *\n * @module io/decode\n */\n\n\"use strict\";\n\n/** Byte order marks, longest first, with the encoding they announce. */\nconst BYTE_ORDER_MARKS = [\n { bytes: [0xef, 0xbb, 0xbf], encoding: \"utf-8\" },\n { bytes: [0xff, 0xfe], encoding: \"utf-16le\" },\n { bytes: [0xfe, 0xff], encoding: \"utf-16be\" },\n];\n\n/** First bytes of `<?` in UTF-16 without a byte order mark. */\nconst UTF16_SIGNATURES = [\n { bytes: [0x3c, 0x00, 0x3f, 0x00], encoding: \"utf-16le\" },\n { bytes: [0x00, 0x3c, 0x00, 0x3f], encoding: \"utf-16be\" },\n];\n\n/** How many leading bytes are scanned for the XML declaration. */\nconst DECLARATION_SCAN_LENGTH = 1024;\n\n/** Matches the encoding pseudo-attribute of an XML declaration. */\nconst ENCODING_DECLARATION =\n /^<\\?xml\\s[^>]*?\\bencoding\\s*=\\s*([\"'])([A-Za-z][\\w.:-]*)\\1/;\n\n/**\n * Error raised when a file declares an encoding the runtime cannot decode.\n */\nexport class EncodingError extends Error {\n /**\n * @param {string} message - Human readable explanation\n */\n constructor(message) {\n super(message);\n this.name = \"EncodingError\";\n }\n}\n\n/**\n * Check whether a buffer starts with the given bytes.\n *\n * @param {Uint8Array} buffer - Raw file content\n * @param {number[]} bytes - Expected leading bytes\n * @returns {boolean} True when the buffer starts with bytes\n */\nfunction startsWith(buffer, bytes) {\n return bytes.every((byte, index) => buffer[index] === byte);\n}\n\n/**\n * Read the encoding pseudo-attribute from an ASCII compatible XML declaration.\n *\n * @param {Uint8Array} buffer - Raw file content\n * @returns {string|null} The declared encoding label, or null when absent\n */\nfunction readDeclaredEncoding(buffer) {\n const prefix = new globalThis.TextDecoder(\"latin1\").decode(\n buffer.subarray(0, DECLARATION_SCAN_LENGTH),\n );\n const match = ENCODING_DECLARATION.exec(prefix);\n return match ? match[2] : null;\n}\n\n/**\n * Detect the character encoding of an XML file (XML 1.0 Appendix F).\n *\n * A UTF-16 label declared in an ASCII compatible file cannot be right (the\n * declaration itself was readable as single bytes), so it falls back to\n * UTF-8, as browsers do.\n *\n * @param {Uint8Array} buffer - Raw file content\n * @returns {{encoding: string, bomLength: number}} Encoding label and the\n * number of byte order mark bytes to skip\n *\n * @example\n * detectEncoding(Buffer.from('<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><a/>'));\n * // { encoding: 'ISO-8859-1', bomLength: 0 }\n */\nexport function detectEncoding(buffer) {\n const bom = BYTE_ORDER_MARKS.find(({ bytes }) => startsWith(buffer, bytes));\n if (bom) {\n return { encoding: bom.encoding, bomLength: bom.bytes.length };\n }\n\n const utf16 = UTF16_SIGNATURES.find(({ bytes }) => startsWith(buffer, bytes));\n if (utf16) {\n return { encoding: utf16.encoding, bomLength: 0 };\n }\n\n const declared = readDeclaredEncoding(buffer);\n if (!declared || /^utf-?16/i.test(declared)) {\n return { encoding: \"utf-8\", bomLength: 0 };\n }\n\n return { encoding: declared, bomLength: 0 };\n}\n\n/**\n * Decode the raw bytes of an XML file into a string without byte order mark.\n *\n * Malformed byte sequences become U+FFFD instead of aborting the run.\n *\n * @param {Uint8Array} buffer - Raw file content\n * @param {string} [label] - Human readable file name used in errors\n * @returns {string} The decoded document text\n * @throws {EncodingError} When the declared encoding is not supported\n *\n * @example\n * decodeXml(readFileSync('latin1.xml')); // '<?xml ... encoding=\"ISO-8859-1\"?><a>caf\u00E9</a>'\n */\nexport function decodeXml(buffer, label = \"document\") {\n const { encoding, bomLength } = detectEncoding(buffer);\n let decoder;\n\n try {\n decoder = new globalThis.TextDecoder(encoding, {\n fatal: false,\n ignoreBOM: true,\n });\n } catch {\n throw new EncodingError(\n `Unsupported encoding \"${encoding}\" declared in ${label}`,\n );\n }\n\n return decoder.decode(buffer.subarray(bomLength));\n}\n", "/**\n * AbortSignal Helpers\n *\n * Every asynchronous entry point takes an optional `signal`. It is checked\n * between steps (and between output chunks), passed to loaders, and raced\n * against loader promises so that a loader ignoring the signal cannot keep an\n * aborted call pending. The synchronous parts (compiling the stylesheet,\n * building the result tree) cannot be interrupted once started.\n *\n * @module async/abort\n */\n\n/**\n * The reason of an aborted signal, with a DOMException fallback for\n * implementations without `reason`.\n *\n * @param {AbortSignal} signal - An aborted signal\n * @returns {*} The abort reason\n */\nfunction abortReason(signal) {\n return (\n signal.reason ??\n new globalThis.DOMException(\"This operation was aborted\", \"AbortError\")\n );\n}\n\n/**\n * Throw the abort reason when a signal is aborted.\n *\n * @param {AbortSignal} [signal] - Optional signal\n * @returns {void}\n * @throws {*} The abort reason\n *\n * @example\n * throwIfAborted(options.signal);\n */\nexport function throwIfAborted(signal) {\n if (signal?.aborted) throw abortReason(signal);\n}\n\n/**\n * Settle with a promise, or reject with the abort reason as soon as the\n * signal aborts, whichever comes first.\n *\n * @template T\n * @param {Promise<T>|T} work - The pending work\n * @param {AbortSignal} [signal] - Optional signal\n * @returns {Promise<T>} The work's outcome, or the abort rejection\n *\n * @example\n * const text = await abortable(loader(uri), signal);\n */\nexport function abortable(work, signal) {\n if (!signal) return Promise.resolve(work);\n if (signal.aborted) return Promise.reject(abortReason(signal));\n return new Promise((resolve, reject) => {\n const onAbort = () => reject(abortReason(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n Promise.resolve(work)\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n", "/**\n * Asynchronous XML Input\n *\n * Reads the input of the asynchronous API: a DOM node, a string, a WHATWG\n * `ReadableStream` or an async iterable of strings or bytes (a Node.js\n * `Readable`, a `Response.body`, a generator...). XSLT 1.0 gives templates\n * random access to the whole source tree (any axis, `key()`, `id()`), so a\n * stream is read to its end and parsed once: input streaming bounds nothing,\n * it only lets callers pass what they have without collecting it first.\n *\n * @module io/readSource\n */\n\nimport { decodeXml } from \"./decode.js\";\nimport { parseXml, resolveDomParser } from \"../xslt/domParsing.js\";\nimport { throwIfAborted } from \"../async/abort.js\";\n\n/**\n * @typedef {string|Uint8Array|ArrayBuffer} SourceChunk\n */\n\n/**\n * Whether a value is a WHATWG ReadableStream (or anything with getReader).\n *\n * @param {unknown} value - Candidate\n * @returns {boolean} True for readable streams\n */\nfunction isReadableStream(value) {\n return typeof value?.getReader === \"function\";\n}\n\n/**\n * Iterate a ReadableStream through its reader, which every implementation\n * has (not every browser makes streams async iterable).\n *\n * @param {ReadableStream} stream - The stream\n * @yields {SourceChunk} Its chunks\n * @returns {AsyncGenerator<SourceChunk, void, void>} The chunks\n */\nasync function* readerChunks(stream) {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Bytes of a binary chunk.\n *\n * @param {Uint8Array|ArrayBuffer} chunk - The chunk\n * @returns {Uint8Array|null} Its bytes, or null for a non-binary value\n */\nfunction toBytes(chunk) {\n if (chunk instanceof Uint8Array) return chunk;\n if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);\n return null;\n}\n\n/**\n * Concatenate byte chunks.\n *\n * @param {Uint8Array[]} chunks - The chunks\n * @returns {Uint8Array} All bytes\n */\nfunction concatBytes(chunks) {\n const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * Read a stream of strings or bytes to its end. Strings are joined; bytes are\n * decoded as a whole (byte order mark, XML declaration encoding, else UTF-8),\n * so a multi-byte character split between chunks is decoded correctly.\n *\n * @param {ReadableStream<SourceChunk>|AsyncIterable<SourceChunk>} stream - Input\n * @param {AbortSignal} [signal] - Cancels the read between chunks\n * @returns {Promise<string>} The text\n * @throws {TypeError} When a chunk is neither a string nor bytes, or strings\n * and bytes are mixed\n * @throws {*} The abort reason when `signal` is aborted\n *\n * @example\n * await readText(Readable.from([\"<a>\", \"</a>\"])); // \"<a></a>\"\n */\nexport async function readText(stream, signal) {\n const iterable = isReadableStream(stream) ? readerChunks(stream) : stream;\n const texts = [];\n const binary = [];\n for await (const chunk of iterable) {\n throwIfAborted(signal);\n const bytes = typeof chunk === \"string\" ? null : toBytes(chunk);\n if (bytes === null && typeof chunk !== \"string\") {\n throw new TypeError(\n \"XML input streams must yield strings, Uint8Arrays or ArrayBuffers\",\n );\n }\n if (bytes) binary.push(bytes);\n else texts.push(chunk);\n if (texts.length > 0 && binary.length > 0) {\n throw new TypeError(\"XML input streams cannot mix strings and bytes\");\n }\n }\n throwIfAborted(signal);\n return binary.length > 0 ? decodeXml(concatBytes(binary)) : texts.join(\"\");\n}\n\n/**\n * Whether a value can be read by {@link readText}.\n *\n * @param {unknown} value - Candidate\n * @returns {boolean} True for readable streams and async iterables\n */\nexport function isStreamSource(value) {\n return (\n isReadableStream(value) ||\n typeof value?.[Symbol.asyncIterator] === \"function\"\n );\n}\n\n/**\n * Turn any supported input into a DOM node: a node is returned as is, bytes\n * are decoded, a stream is read to its end, and text is parsed with the\n * configured DOMParser (see domParsing.js).\n *\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} source - Input\n * @param {object} [options] - Reading options\n * @param {AbortSignal} [options.signal] - Cancels the read\n * @param {import('../xslt/domParsing.js').DomParserLike|null} [options.domParser] -\n * Parser to use instead of the global DOMParser\n * @param {Document|null} [options.referenceDoc] - Document whose window may\n * provide a DOMParser\n * @returns {Promise<Node>} The source node\n * @throws {TypeError} For unsupported inputs\n * @throws {Error} When the markup is not well formed\n *\n * @example\n * const doc = await readSource(response.body);\n */\nexport async function readSource(source, options = {}) {\n const { signal, domParser = null, referenceDoc = null } = options;\n throwIfAborted(signal);\n if (typeof source?.nodeType === \"number\") return source;\n\n let text;\n const bytes = toBytes(source);\n if (typeof source === \"string\") text = source;\n else if (bytes) text = decodeXml(bytes);\n else if (isStreamSource(source)) text = await readText(source, signal);\n else {\n throw new TypeError(\n \"The source must be a Node, a string, bytes, a ReadableStream or an async iterable\",\n );\n }\n return parseXml(text, resolveDomParser(domParser, referenceDoc));\n}\n", "/**\n * Asynchronous Loaders\n *\n * An asynchronous loader fetches a stylesheet module or a `document()`\n * document before the synchronous transformation runs:\n *\n * (uri, baseUri, { signal }) => Promise<Document | string | Uint8Array |\n * ArrayBuffer | Response | null>\n *\n * `uri` is already resolved against `baseUri` (as for the synchronous\n * loaders). Strings are parsed; bytes and `Response` bodies are decoded like\n * files (byte order mark, XML declaration encoding, else UTF-8). Without a\n * loader, the global `fetch` is used when there is one (browsers, Node.js\n * for http(s) URIs).\n *\n * @module async/loaders\n */\n\nimport { decodeXml } from \"../io/decode.js\";\nimport { parseXml, resolveDomParser } from \"../xslt/domParsing.js\";\nimport { abortable } from \"./abort.js\";\n\n/**\n * @typedef {(uri: string, baseUri: string|undefined, init: {signal?: AbortSignal}) =>\n * Promise<Document|string|Uint8Array|ArrayBuffer|Response|null>|Document|string|null} AsyncLoader\n */\n\n/**\n * Loader reading a URI with the global `fetch`.\n *\n * @param {string} uri - The resolved URI\n * @param {string} [_baseUri] - Unused\n * @param {{signal?: AbortSignal}} [init] - Fetch options\n * @returns {Promise<Response>} The response\n */\nfunction fetchLoader(uri, _baseUri, init = {}) {\n return globalThis.fetch(uri, { signal: init.signal });\n}\n\n/**\n * The loader to use: the given one, else `fetch` when available.\n *\n * @param {AsyncLoader|null|undefined} loader - Configured loader\n * @returns {AsyncLoader} A loader\n * @throws {TypeError} When `loader` is not a function, or none is given and\n * there is no global fetch\n */\nexport function resolveAsyncLoader(loader) {\n if (loader !== undefined && loader !== null) {\n if (typeof loader !== \"function\") {\n throw new TypeError(\"The loader must be a function\");\n }\n return loader;\n }\n if (typeof globalThis.fetch !== \"function\") {\n throw new TypeError(\n \"No loader given and no global fetch available to load external resources\",\n );\n }\n return fetchLoader;\n}\n\n/**\n * Whether a value is a fetch `Response` (or looks like one).\n *\n * @param {unknown} value - Candidate\n * @returns {boolean} True for response-like objects\n */\nfunction isResponse(value) {\n return typeof value?.arrayBuffer === \"function\" && \"ok\" in value;\n}\n\n/**\n * Turn what a loader returned into a document.\n *\n * @param {unknown} loaded - Loader result\n * @param {string} uri - The URI, for error messages\n * @param {object|null} parser - DOMParser to parse text with\n * @returns {Promise<Document|null>} The document, or null for a null result\n * @throws {Error} For failed responses, malformed markup or unsupported values\n */\nasync function toDocument(loaded, uri, parser) {\n if (loaded === null || loaded === undefined) return null;\n if (typeof loaded.nodeType === \"number\") return loaded;\n let value = loaded;\n if (isResponse(value)) {\n if (!value.ok) {\n throw new Error(`Failed to load \"${uri}\": HTTP ${value.status}`);\n }\n value = await value.arrayBuffer();\n }\n if (value instanceof ArrayBuffer) value = new Uint8Array(value);\n if (value instanceof Uint8Array) value = decodeXml(value, uri);\n if (typeof value !== \"string\") {\n throw new TypeError(\n `The loader returned an unsupported value for \"${uri}\"`,\n );\n }\n return parseXml(value, parser);\n}\n\n/**\n * Create a function loading documents with an asynchronous loader, each URI\n * once (concurrent requests for the same URI share one load).\n *\n * @param {AsyncLoader} loader - The loader\n * @param {object} options - Loading options\n * @param {AbortSignal} [options.signal] - Passed to the loader; aborting\n * rejects pending loads\n * @param {object|null} [options.domParser] - Parser for loaded text\n * @param {Document|null} [options.referenceDoc] - Document whose window may\n * provide a DOMParser\n * @returns {(uri: string, baseUri?: string) => Promise<Document|null>} The\n * de-duplicating load function\n *\n * @example\n * const load = createDocumentFetcher(resolveAsyncLoader(), { signal });\n * const doc = await load(\"https://example.com/common.xsl\");\n */\nexport function createDocumentFetcher(loader, options = {}) {\n const { signal, domParser = null, referenceDoc = null } = options;\n const parser = resolveDomParser(domParser, referenceDoc);\n const pending = new Map();\n return (uri, baseUri) => {\n if (!pending.has(uri)) {\n const work = abortable(\n Promise.resolve().then(() => loader(uri, baseUri, { signal })),\n signal,\n ).then((loaded) => toDocument(loaded, uri, parser));\n pending.set(uri, work);\n }\n return pending.get(uri);\n };\n}\n", "/**\n * Streaming Output\n *\n * Serializes a transformation result as a WHATWG `ReadableStream<string>`.\n * XSLT 1.0 builds the result tree in memory (templates can read anything\n * they wrote into variables, and the whole source tree), so the tree is built\n * first; what streams is the serialization: chunks are produced on demand\n * (`pull`), one at a time, so the output is never held as one string and a\n * consumer that reads slowly holds serialization back (backpressure).\n *\n * @module async/stream\n */\n\nimport { serializeChunks } from \"../xslt/serializer.js\";\nimport { throwIfAborted } from \"./abort.js\";\n\n/**\n * Serialize the transformation of a source node in chunks, as\n * `engine.transformToString` does in one piece.\n *\n * @param {import('../xslt/engine.js').XsltEngine|import('../bridge/engine.js').Xslt3Engine} engine -\n * Engine with an imported stylesheet\n * @param {Node} sourceNode - Source document or element\n * @param {{chunkSize?: number}} [options] - Chunk size in UTF-16 code units\n * @returns {Iterator<string>} The chunks; the result tree is built by this\n * call, serialization happens as the iterator is consumed\n *\n * @example\n * for (const chunk of transformToChunks(engine, xmlDoc)) out.write(chunk);\n */\nexport function transformToChunks(engine, sourceNode, options = {}) {\n // The @tradik/xslt3 engine (xsltVersion \"auto\") serializes on its own\n if (engine.transformToChunks) {\n return engine.transformToChunks(sourceNode, options);\n }\n const fragment = engine.buildResultTree(\n sourceNode,\n engine.createDocument(sourceNode),\n );\n return serializeChunks(fragment, engine.outputSettings, options);\n}\n\n/**\n * Expose lazily produced chunks as a ReadableStream.\n *\n * @param {() => (Iterator<string>|Promise<Iterator<string>>)} start - Called\n * once, on the first pull, to produce the chunk iterator (may be async, e.g.\n * to read the input first)\n * @param {{signal?: AbortSignal}} [options] - Aborting errors the stream with\n * the abort reason and stops the serialization\n * @returns {ReadableStream<string>} The stream; errors of `start` or of the\n * serialization error the stream\n * @throws {TypeError} When the runtime has no ReadableStream\n *\n * @example\n * const stream = chunkStream(() => serializeChunks(doc, settings));\n */\nexport function chunkStream(start, options = {}) {\n const { signal } = options;\n const Stream = globalThis.ReadableStream;\n if (typeof Stream !== \"function\") {\n throw new TypeError(\"ReadableStream is not available in this runtime\");\n }\n\n let chunks = null;\n const stop = () => chunks?.return?.();\n let onAbort = null;\n\n return new Stream(\n {\n start(controller) {\n if (signal?.aborted) {\n controller.error(signal.reason);\n return;\n }\n onAbort = () => {\n stop();\n controller.error(signal.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n },\n async pull(controller) {\n try {\n chunks ??= await start();\n throwIfAborted(signal);\n const { done, value } = chunks.next();\n if (done) {\n signal?.removeEventListener(\"abort\", onAbort);\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n signal?.removeEventListener(\"abort\", onAbort);\n throw error;\n }\n },\n cancel() {\n signal?.removeEventListener(\"abort\", onAbort);\n stop();\n },\n },\n { highWaterMark: 1 },\n );\n}\n\n/**\n * Transform a source node and stream the serialized result.\n *\n * @param {import('../xslt/engine.js').XsltEngine} engine - Engine with an imported stylesheet\n * @param {Node} sourceNode - Source document or element\n * @param {{signal?: AbortSignal, chunkSize?: number}} [options] - Options\n * @returns {ReadableStream<string>} The serialized result\n *\n * @example\n * const response = new Response(\n * transformToStream(engine, xmlDoc).pipeThrough(new TextEncoderStream()),\n * );\n */\nexport function transformToStream(engine, sourceNode, options = {}) {\n return chunkStream(\n () => transformToChunks(engine, sourceNode, options),\n options,\n );\n}\n", "/**\n * Asynchronous XSLTProcessor Methods\n *\n * Implementation of `importStylesheetAsync`, `transformAsync` and\n * `transformToStream` of {@link XSLTProcessor}. The transformation itself\n * stays synchronous (XPath evaluation cannot await): the asynchronous work is\n * reading the inputs and preloading what the stylesheet references, before\n * the synchronous compile and transform.\n *\n * @module async/processor\n */\n\nimport { readSource } from \"../io/readSource.js\";\nimport { toChunkSize } from \"../xslt/serializer/chunks.js\";\nimport { throwIfAborted } from \"./abort.js\";\nimport { createDocumentFetcher, resolveAsyncLoader } from \"./loaders.js\";\nimport {\n preloadDocuments,\n preloadModules,\n preloadedStylesheetLoader,\n} from \"./preload.js\";\nimport { chunkStream, transformToChunks } from \"./stream.js\";\n\n/**\n * Reject a configured loader that is not a function.\n *\n * @param {Function|null|undefined} loader - Configured loader\n * @returns {void}\n * @throws {TypeError} When `loader` is set but not a function\n */\nfunction checkLoader(loader) {\n if (loader !== undefined && loader !== null) resolveAsyncLoader(loader);\n}\n\n/**\n * A loader that is resolved when first used, so that a stylesheet without\n * external references needs neither a loader nor `fetch`.\n *\n * @param {Function|null|undefined} loader - Configured loader\n * @returns {Function} The lazy loader\n */\nfunction lazyLoader(loader) {\n return (...args) => resolveAsyncLoader(loader)(...args);\n}\n\n/**\n * The document owning a node (for its window's DOMParser).\n *\n * @param {Node} node - A node\n * @returns {Document} The owner document\n */\nfunction ownerOf(node) {\n return node.ownerDocument ?? node;\n}\n\n/**\n * Load the documents of the literal `document()` calls of stylesheet modules.\n *\n * @param {Node[]} modules - The stylesheet modules\n * @param {string|undefined} stylesheetUri - URI of the main stylesheet\n * @param {Function|null|undefined} loader - Asynchronous document loader\n * @param {AbortSignal} [signal] - Optional signal\n * @returns {Promise<Map<string, object>>} Preloaded outcomes by URI\n */\nasync function preloadStaticDocuments(modules, stylesheetUri, loader, signal) {\n const fetchDocument = createDocumentFetcher(lazyLoader(loader), {\n signal,\n referenceDoc: ownerOf(modules[0]),\n });\n const documents = await preloadDocuments(\n modules,\n stylesheetUri,\n fetchDocument,\n signal,\n );\n throwIfAborted(signal);\n return documents;\n}\n\n/**\n * Import a stylesheet whose `xsl:import`/`xsl:include` modules and literal\n * `document()` documents are loaded asynchronously first.\n *\n * @param {import('../XSLTProcessor.js').XSLTProcessor} processor - Processor\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} style -\n * The stylesheet, as a node or as markup (read and parsed first)\n * @param {string} [stylesheetUri] - Base URI of relative hrefs and document() URIs\n * @param {object} [options] - Loading options\n * @param {Function} [options.loader] - Asynchronous stylesheet loader, `fetch` by default\n * @param {Function} [options.documentLoader] - Asynchronous document() loader,\n * `options.loader` by default\n * @param {AbortSignal} [options.signal] - Cancels loading\n * @returns {Promise<void>} Resolves once the stylesheet is compiled\n */\nexport async function importStylesheetAsync(\n processor,\n style,\n stylesheetUri,\n options = {},\n) {\n const { signal, loader } = options;\n const documentLoader = options.documentLoader ?? loader;\n checkLoader(loader);\n checkLoader(documentLoader);\n\n const node = await readSource(style, { signal });\n // XSLT 2.0/3.0 with xsltVersion \"auto\": load @tradik/xslt3 first\n await processor._prepareEngine(node);\n const modules = await preloadModules(\n node,\n stylesheetUri,\n createDocumentFetcher(lazyLoader(loader), {\n signal,\n referenceDoc: ownerOf(node),\n }),\n );\n const allModules = [node, ...modules.values()];\n const documents = await preloadStaticDocuments(\n allModules,\n stylesheetUri,\n documentLoader,\n signal,\n );\n\n processor._compile(node, stylesheetUri, {\n stylesheetLoader: preloadedStylesheetLoader(modules),\n modules: allModules,\n documents,\n });\n}\n\n/**\n * Transform asynchronously: read the source (node, markup or stream),\n * optionally import a stylesheet or preload `document()` documents first,\n * then transform and serialize.\n *\n * @param {import('../XSLTProcessor.js').XSLTProcessor} processor - Processor\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} source - Input\n * @param {object} [options] - Options\n * @param {AbortSignal} [options.signal] - Cancels the call\n * @param {Node|string|ReadableStream|AsyncIterable} [options.stylesheet] -\n * Stylesheet to import first (see importStylesheetAsync)\n * @param {string} [options.stylesheetUri] - Its URI\n * @param {Function} [options.fetchStylesheet] - Asynchronous stylesheet loader\n * @param {Function} [options.fetchDocument] - Asynchronous document() loader\n * @returns {Promise<string>} The serialized result\n * @throws {Error} When loading, parsing or the transformation fails\n */\nexport async function transformAsync(processor, source, options = {}) {\n const { signal, stylesheet, fetchStylesheet, fetchDocument } = options;\n if (stylesheet !== undefined && stylesheet !== null) {\n await importStylesheetAsync(processor, stylesheet, options.stylesheetUri, {\n loader: fetchStylesheet,\n documentLoader: fetchDocument,\n signal,\n });\n } else {\n processor._requireStylesheet(\"transformAsync\");\n if (fetchDocument) {\n checkLoader(fetchDocument);\n processor._usePreloadedDocuments(\n await preloadStaticDocuments(\n processor._modules,\n processor._stylesheetUri,\n fetchDocument,\n signal,\n ),\n );\n }\n }\n const node = await readSource(source, {\n signal,\n referenceDoc: ownerOf(processor._stylesheet),\n });\n processor._checkSource(\"transformAsync\", node);\n throwIfAborted(signal);\n return processor.engine.transformToString(node);\n}\n\n/**\n * Transform and stream the serialized result (see async/stream.js).\n *\n * @param {import('../XSLTProcessor.js').XSLTProcessor} processor - Processor\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} source - Input\n * @param {{signal?: AbortSignal, chunkSize?: number}} [options] - Options\n * @returns {ReadableStream<string>} The serialized result\n * @throws {TypeError|RangeError} For a missing stylesheet, an invalid source\n * node or chunk size (at once; later failures error the stream)\n */\nexport function transformToStream(processor, source, options = {}) {\n processor._requireStylesheet(\"transformToStream\");\n if (typeof source?.nodeType === \"number\") {\n processor._checkSource(\"transformToStream\", source);\n }\n const chunkSize = toChunkSize(options.chunkSize);\n const engine = processor.engine;\n const { signal } = options;\n return chunkStream(async () => {\n const node = await readSource(source, {\n signal,\n referenceDoc: ownerOf(processor._stylesheet),\n });\n processor._checkSource(\"transformToStream\", node);\n return transformToChunks(engine, node, { chunkSize });\n }, options);\n}\n", "/**\n * Loading @tradik/xslt3\n *\n * @tradik/xslt3 is an optional peer dependency: it is loaded with a dynamic\n * `import()` the first time an XSLT 2.0/3.0 stylesheet needs it (or when\n * `XSLTProcessor.preload()` is called), never statically, so the XSLT 1.0\n * bundles do not contain it. Once loaded it is kept for the synchronous API.\n *\n * @module bridge/loader\n */\n\n/** What to do when @tradik/xslt3 is missing. */\nexport const XSLT3_MISSING =\n \"install @tradik/xslt3 to run XSLT 2.0/3.0 stylesheets (npm install @tradik/xslt3)\";\n\n/**\n * The default importer. The specifier is a literal so that bundlers of the\n * application can resolve it; the build of this package keeps it external.\n *\n * @returns {Promise<object>} The @tradik/xslt3 module\n */\nconst importXslt3 = () => import(\"@tradik/xslt3\");\n\nlet importer = importXslt3;\nlet loaded = null;\nlet pending = null;\n\n/**\n * Load @tradik/xslt3 once; concurrent calls share the import.\n *\n * @returns {Promise<object>} The @tradik/xslt3 module\n * @throws {Error} \"Cannot load @tradik/xslt3: install ...\" when the import\n * fails (the import error is the `cause`); a later call tries again\n *\n * @example\n * const { compileStylesheet } = await loadXslt3();\n */\nexport function loadXslt3() {\n if (loaded) return Promise.resolve(loaded);\n pending ??= Promise.resolve()\n .then(() => importer())\n .then(\n (module) => {\n loaded = module;\n return module;\n },\n (error) => {\n pending = null;\n throw new Error(`Cannot load @tradik/xslt3: ${XSLT3_MISSING}`, {\n cause: error,\n });\n },\n );\n return pending;\n}\n\n/**\n * The module loaded by {@link loadXslt3}, for the synchronous API.\n *\n * @returns {object|null} The module, null before it has been loaded\n */\nexport function loadedXslt3() {\n return loaded;\n}\n\n/**\n * Replace the importer of @tradik/xslt3 and forget the loaded module\n * (tests: simulate a missing package without uninstalling it).\n *\n * @param {(() => Promise<object>)|null} [replacement] - The importer, or\n * null for the default `import(\"@tradik/xslt3\")`\n * @returns {void}\n */\nexport function setXslt3Importer(replacement) {\n importer = replacement ?? importXslt3;\n loaded = null;\n pending = null;\n}\n", "/**\n * Shaping @tradik/xslt3 Results for the W3C API\n *\n * The principal result of @tradik/xslt3 is a document (a well-formed tree)\n * or a document fragment. `transformToFragment` and `transformToDocument`\n * return it shaped as the XSLT 1.0 engine shapes its own results (as\n * Chrome does): html output parsed by the HTML parser of an HTML owner\n * document, text output wrapped in a `pre` page, xml output as a document\n * with the `doctype-public`/`doctype-system` of xsl:output.\n *\n * @module bridge/results\n */\n\nimport {\n importResultFragment,\n isHtmlDocument,\n parseHtmlFragment,\n wrapTextResult,\n} from \"../xslt/resultTree.js\";\nimport { fillXmlDocument, parseHtmlDocument } from \"../xslt/resultDocument.js\";\n\n/**\n * Serialization parameters by camelCase name (`omit-xml-declaration`\n * becomes `omitXmlDeclaration`), the form the XSLT 1.0 output settings use.\n *\n * @param {Record<string, *>} output - Parameters of @tradik/xslt3\n * @returns {Record<string, *>} The same parameters, camelCase names\n *\n * @example\n * camelCaseOutput({ \"omit-xml-declaration\": \"yes\" }); // { omitXmlDeclaration: \"yes\" }\n */\nexport function camelCaseOutput(output) {\n return Object.fromEntries(\n Object.entries(output).map(([name, value]) => [\n name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()),\n value,\n ]),\n );\n}\n\n/**\n * The result as a fragment owned by `output`.\n *\n * @param {Node} principal - Principal result (document or fragment)\n * @param {Record<string, *>} params - Its serialization parameters\n * @param {Document} output - The owner document\n * @param {(node: Node, params: object) => string} serialize - Serializer\n * @returns {DocumentFragment} The fragment\n */\nexport function fragmentResult(principal, params, output, serialize) {\n if (isHtmlDocument(output) && params.method === \"html\") {\n return parseHtmlFragment(serialize(principal, params), output);\n }\n return importResultFragment(principal, output, { htmlElements: true });\n}\n\n/**\n * The result as a document.\n *\n * @param {Node} principal - Principal result (document or fragment)\n * @param {Record<string, *>} params - Its serialization parameters\n * @param {Document} doc - An empty document to fill\n * @param {(node: Node, params: object) => string} serialize - Serializer\n * @returns {Document} The result document\n */\nexport function documentResult(principal, params, doc, serialize) {\n if (params.method === \"text\") {\n return wrapTextResult(doc, serialize(principal, params));\n }\n if (params.method === \"html\") {\n const html = parseHtmlDocument(serialize(principal, params), doc);\n if (html) return html;\n }\n return fillXmlDocument(doc, importResultFragment(principal, doc), params);\n}\n", "/**\n * XSLT Version Selection\n *\n * The `xsltVersion` option of XSLTProcessor: \"1.0\" (the default) runs every\n * stylesheet with the XSLT 1.0 engine, a stylesheet declaring a higher\n * version in forwards-compatible mode (as Chrome does); \"auto\" hands a\n * stylesheet whose effective version is 2.0 or more to @tradik/xslt3.\n *\n * @module bridge/version\n */\n\nimport { declaredVersion } from \"../xslt/forwardsCompatible.js\";\n\n/** Values accepted by the `xsltVersion` option. */\nexport const XSLT_VERSION_MODES = Object.freeze([\"1.0\", \"auto\"]);\n\n/**\n * Validate the `xsltVersion` option.\n *\n * @param {string|undefined|null} mode - The option value\n * @returns {\"1.0\"|\"auto\"} The mode, \"1.0\" when not given\n * @throws {RangeError} For any other value\n *\n * @example\n * xsltVersionMode(undefined); // \"1.0\"\n */\nexport function xsltVersionMode(mode) {\n const value = mode ?? \"1.0\";\n if (!XSLT_VERSION_MODES.includes(value)) {\n throw new RangeError(\n `Invalid xsltVersion \"${value}\": expected \"1.0\" or \"auto\"`,\n );\n }\n return value;\n}\n\n/**\n * The effective version of a stylesheet: the `version` attribute of\n * `xsl:stylesheet`/`xsl:transform`, or the `xsl:version` attribute of a\n * simplified stylesheet (literal result element).\n *\n * @param {Node} style - Stylesheet document or root element\n * @returns {number} The version, NaN when missing or not a number\n *\n * @example\n * stylesheetVersion(xslDoc); // 2 for <xsl:stylesheet version=\"2.0\">\n */\nexport function stylesheetVersion(style) {\n const root = style.nodeType === 9 ? style.documentElement : style;\n const version = root ? declaredVersion(root) : null;\n return version ? Number(version.trim()) : NaN;\n}\n\n/**\n * Whether a stylesheet is run by @tradik/xslt3 in the given mode.\n *\n * @param {Node} style - Stylesheet document or root element\n * @param {\"1.0\"|\"auto\"} mode - The `xsltVersion` option\n * @returns {boolean} True in \"auto\" mode for version 2.0 and above\n */\nexport function usesXslt3(style, mode) {\n return mode === \"auto\" && stylesheetVersion(style) >= 2;\n}\n", "/**\n * Xslt3Engine: @tradik/xslt3 behind the interface of the XSLT 1.0 engine\n *\n * XSLTProcessor drives its engine through a small interface (loaders,\n * parameters, importStylesheet, transformToFragment/Document/String,\n * outputSettings). This class implements it with `compileStylesheet` and\n * `CompiledStylesheet#transform` of @tradik/xslt3, so the W3C API, the\n * asynchronous API and the command line tool run XSLT 2.0/3.0 stylesheets\n * unchanged when `xsltVersion` is \"auto\".\n *\n * @module bridge/engine\n */\n\nimport { parseXml, resolveDomParser } from \"../xslt/domParsing.js\";\nimport { transformationMethods } from \"../xslt/engine/transformation.js\";\nimport { loadedXslt3 } from \"./loader.js\";\nimport { camelCaseOutput, documentResult, fragmentResult } from \"./results.js\";\nimport { stylesheetVersion } from \"./version.js\";\n\n/**\n * A parameter value for @tradik/xslt3: node lists become arrays (sequences\n * of nodes); other values are converted by @tradik/xslt3 (strings to\n * xs:string, numbers to xs:double, booleans, nodes, arrays, Dates, maps).\n *\n * @param {*} value - Value given to setParameter\n * @returns {*} The value to pass\n */\nfunction parameterValue(value) {\n const isNodeList =\n typeof value?.length === \"number\" && typeof value.item === \"function\";\n return isNodeList ? Array.from(value) : value;\n}\n\n/** Runs XSLT 2.0/3.0 stylesheets with @tradik/xslt3. */\nexport class Xslt3Engine {\n /**\n * @param {object} xslt3 - The @tradik/xslt3 module\n * @param {object} [options] - Options of XSLTProcessor\n * @param {Function|null} [options.stylesheetLoader] - xsl:import/include loader\n * @param {Function|null} [options.documentLoader] - doc()/document() loader\n * @param {(() => Date)|null} [options.clock] - current-dateTime() clock\n */\n constructor(xslt3, options = {}) {\n this.xslt3 = xslt3;\n this.stylesheetLoader = options.stylesheetLoader ?? null;\n this.documentLoader = options.documentLoader ?? null;\n this.clock = options.clock ?? null;\n /** @type {Map<string, *>} Parameters by `{uri}local` or `local` */\n this.parameters = new Map();\n this.compiled = null;\n this.stylesheetDoc = null;\n /** Output settings (camelCase); changes override the stylesheet's. */\n this.outputSettings = {};\n this.declaredOutput = {};\n }\n\n /** @param {Function|null} loader - xsl:import/xsl:include loader */\n setStylesheetLoader(loader) {\n this.stylesheetLoader = loader;\n }\n\n /** @param {Function|null} loader - doc()/document() loader */\n setDocumentLoader(loader) {\n this.documentLoader = loader;\n }\n\n /**\n * @param {string} key - `{uri}local` or `local`\n * @param {*} value - The value\n */\n setParameterValue(key, value) {\n this.parameters.set(key, parameterValue(value));\n }\n\n /** @param {string} key - `{uri}local` or `local` */\n clearParameterValue(key) {\n this.parameters.delete(key);\n }\n\n /** Remove every parameter. */\n clearParameterValues() {\n this.parameters.clear();\n }\n\n /**\n * Parse markup returned by a loader.\n *\n * @param {string} text - XML markup\n * @returns {Document} The document\n */\n parseXmlString(text) {\n return parseXml(text, resolveDomParser(null, this.stylesheetDoc));\n }\n\n /**\n * A loader result as a document (markup is parsed).\n *\n * @param {Document|string|null} loaded - What a loader returned\n * @returns {Document|null} The document\n */\n toDocument(loaded) {\n return typeof loaded === \"string\" ? this.parseXmlString(loaded) : loaded;\n }\n\n /**\n * Compile a stylesheet.\n *\n * @param {Node} style - Stylesheet document or root element\n * @param {string} [stylesheetUri] - Its URI\n * @returns {void}\n * @throws {Error} The static errors of @tradik/xslt3 (XTSE...)\n */\n importStylesheet(style, stylesheetUri) {\n this.stylesheetDoc = style.ownerDocument ?? style;\n this.compiled = this.xslt3.compileStylesheet(style, {\n baseUri: stylesheetUri,\n // A module returned as markup is parsed with parseXml\n loadStylesheet: (uri) => this.stylesheetLoader?.(uri),\n parseXml: (text) => this.parseXmlString(text),\n });\n const declared = this.compiled.output;\n this.declaredOutput = camelCaseOutput({ encoding: \"UTF-8\", ...declared });\n this.outputSettings = { ...this.declaredOutput };\n }\n\n /**\n * Run the stylesheet on a source.\n *\n * @param {Node} source - Source document or element\n * @returns {{principal: Node, params: object}} The principal result and\n * its serialization parameters\n */\n run(source) {\n const loader = this.documentLoader;\n const result = this.compiled.transform({\n source,\n params: this.parameters,\n documentLoader: loader && ((uri) => this.toDocument(loader(uri))),\n onMessage: (message) => console.log(\"XSLT Message:\", message.textContent),\n currentDateTime: this.clock?.(),\n });\n return { principal: result.principal, params: this.paramsOf(result) };\n }\n\n /**\n * The serialization parameters of a result: those @tradik/xslt3 reports,\n * with the output settings changed through `outputSettings` on top.\n *\n * @param {{output: object}} result - A transformation result\n * @returns {Record<string, *>} camelCase parameters\n */\n paramsOf(result) {\n const params = camelCaseOutput(result.output);\n for (const [name, value] of Object.entries(this.outputSettings)) {\n if (value !== this.declaredOutput[name]) params[name] = value;\n }\n return params;\n }\n\n /**\n * @param {Node} source - Source document or element\n * @param {Document} output - Document that owns the fragment\n * @returns {DocumentFragment} The result fragment\n */\n transformToFragment(source, output) {\n const { principal, params } = this.run(source);\n return fragmentResult(principal, params, output, this.xslt3.serialize);\n }\n\n /**\n * @param {Node} source - Source document or element\n * @returns {Document} The result document\n */\n transformToDocument(source) {\n const { principal, params } = this.run(source);\n const doc = transformationMethods.createDocument(source);\n return documentResult(principal, params, doc, this.xslt3.serialize);\n }\n\n /**\n * @param {Node} source - Source document or element\n * @returns {string} The serialized result\n */\n transformToString(source) {\n const { principal, params } = this.run(source);\n return this.xslt3.serialize(principal, params);\n }\n\n /**\n * The serialized result in chunks (transformToStream, the CLI).\n *\n * @param {Node} source - Source document or element\n * @param {{chunkSize?: number}} [options] - Chunk size\n * @returns {Iterator<string>} The chunks\n */\n transformToChunks(source, options = {}) {\n const { principal, params } = this.run(source);\n return this.xslt3.serializeChunks(principal, params, options);\n }\n}\n\n/**\n * Create the engine of an XSLT 2.0/3.0 stylesheet, with the @tradik/xslt3\n * module loaded before (XSLTProcessor.preload or the asynchronous API).\n *\n * @param {Node} style - The stylesheet (for the error message)\n * @param {object} options - See {@link Xslt3Engine}\n * @returns {Xslt3Engine} The engine\n * @throws {Error} When @tradik/xslt3 has not been loaded\n */\nexport function createXslt3Engine(style, options) {\n const xslt3 = loadedXslt3();\n if (!xslt3) {\n throw new Error(\n `This XSLT ${stylesheetVersion(style).toFixed(1)} stylesheet needs @tradik/xslt3: ` +\n 'call \"await XSLTProcessor.preload()\" before importStylesheet(), ' +\n \"or use importStylesheetAsync() / transformAsync()\",\n );\n }\n return new Xslt3Engine(xslt3, options);\n}\n", "/**\n * XSLTProcessor - JavaScript Implementation\n *\n * Native-compatible XSLTProcessor implementation for browser environments.\n * Based on W3C DOM Level 3 XSL Transformations and XSLT 1.0 Specification.\n *\n * With the `xsltVersion: \"auto\"` option, XSLT 2.0/3.0 stylesheets are run by\n * the optional peer dependency @tradik/xslt3 (see bridge/).\n *\n * Reference: https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor\n * XSLT 1.0: http://www.w3.org/TR/1999/REC-xslt-19991116\n * XPath 1.0: http://www.w3.org/TR/1999/REC-xpath-19991116\n *\n * This implementation provides 1:1 API compatibility with the native\n * browser XSLTProcessor. It can be used as a replacement when native\n * XSLT support is deprecated or unavailable.\n */\n\nimport { XsltEngine } from \"./xslt/engine.js\";\nimport { findParseError } from \"./xslt/domParsing.js\";\nimport { preloadedDocumentLoader } from \"./async/preload.js\";\nimport {\n importStylesheetAsync,\n transformAsync,\n transformToStream,\n} from \"./async/processor.js\";\nimport { createXslt3Engine } from \"./bridge/engine.js\";\nimport { loadXslt3 } from \"./bridge/loader.js\";\nimport { usesXslt3, xsltVersionMode } from \"./bridge/version.js\";\n\n/**\n * The native XSLTProcessor constructor that installGlobal() replaced, kept so\n * that isNativeXSLTSupported() keeps probing the browser's implementation\n * rather than this one.\n */\nlet nativeProcessor = null;\n\n/**\n * XSLTProcessor\n *\n * Applies XSLT stylesheet transformations to XML documents.\n *\n * @example\n * const processor = new XSLTProcessor();\n * processor.importStylesheet(xsltDoc);\n * const fragment = processor.transformToFragment(xmlDoc, document);\n */\nexport class XSLTProcessor {\n /**\n * @param {object} [options] - Non-standard options (the native constructor\n * takes none)\n * @param {boolean} [options.legacyNameTests] - Deprecated: let unprefixed\n * name tests (`item`, `@a`) also match nodes in a namespace, as before\n * 1.2.0. XPath 1.0 and Chrome only match nodes in no namespace.\n * @param {boolean} [options.enableDynamicEvaluate] - Allow EXSLT\n * `dyn:evaluate()`, which evaluates XPath built from strings; enable it\n * only for trusted input.\n * @param {() => Date} [options.clock] - Clock for EXSLT current-time\n * functions (reproducible output).\n * @param {number} [options.maxTemplateDepth] - Deepest nesting of template\n * instantiations; deeper recursion throws \"Template recursion too deep\"\n * (default 3000, libxslt's limit).\n * @param {\"1.0\"|\"auto\"} [options.xsltVersion] - \"1.0\" (default): every\n * stylesheet runs with the XSLT 1.0 engine, a `version=\"2.0\"` one in\n * forwards-compatible mode, as in Chrome. \"auto\": a stylesheet whose\n * version is 2.0 or more runs with @tradik/xslt3 (an optional peer\n * dependency, loaded on demand; see {@link XSLTProcessor.preload}).\n * @throws {RangeError} For an invalid `xsltVersion`\n *\n * @example\n * // Temporary migration aid for stylesheets written against 1.1.x\n * const processor = new XSLTProcessor({ legacyNameTests: true });\n *\n * @example\n * // XSLT 2.0/3.0 stylesheets through the same API\n * const processor = new XSLTProcessor({ xsltVersion: \"auto\" });\n * await processor.importStylesheetAsync(xsl20Doc);\n */\n constructor(options = {}) {\n this._options = {\n legacyNameTests: options?.legacyNameTests === true,\n enableDynamicEvaluate: options?.enableDynamicEvaluate === true,\n clock: options?.clock ?? null,\n maxTemplateDepth: options?.maxTemplateDepth,\n xsltVersion: xsltVersionMode(options?.xsltVersion),\n };\n this._engine = null;\n this._stylesheet = null;\n this._parameters = new Map();\n this._stylesheetLoader = null;\n this._documentLoader = null;\n // Set by importStylesheet/importStylesheetAsync: the URI and modules of\n // the stylesheet, and the document() documents preloaded asynchronously\n this._stylesheetUri = undefined;\n this._modules = [];\n this._preloadedDocuments = null;\n }\n\n /**\n * Load @tradik/xslt3, so that the synchronous API of processors created\n * with `xsltVersion: \"auto\"` can run XSLT 2.0/3.0 stylesheets (the\n * asynchronous API loads it by itself). Non-W3C.\n *\n * @param {\"2.0\"|\"3.0\"} [version] - The XSLT version to prepare for\n * @returns {Promise<void>} Resolves once the engine is loaded\n * @throws {RangeError} For another version (synchronously)\n * @throws {Error} Rejects with \"Cannot load @tradik/xslt3: install\n * @tradik/xslt3 to run XSLT 2.0/3.0 stylesheets\" when it is missing\n *\n * @example\n * await XSLTProcessor.preload(\"3.0\");\n * const processor = new XSLTProcessor({ xsltVersion: \"auto\" });\n * processor.importStylesheet(xsl30Doc);\n */\n static preload(version = \"3.0\") {\n if (version !== \"2.0\" && version !== \"3.0\") {\n throw new RangeError(\n `Invalid XSLT version \"${version}\": expected \"2.0\" or \"3.0\"`,\n );\n }\n return loadXslt3().then(() => undefined);\n }\n\n /**\n * The underlying XSLT engine (advanced usage).\n *\n * The engine is created lazily by {@link XSLTProcessor#importStylesheet},\n * so this getter returns `null` until a stylesheet has been imported.\n * Prefer the public {@link XSLTProcessor#setStylesheetLoader} over reaching\n * into the engine directly. A stylesheet run by @tradik/xslt3\n * (`xsltVersion: \"auto\"`) has an `Xslt3Engine` (bridge/engine.js).\n *\n * @returns {import('./xslt/engine.js').XsltEngine|import('./bridge/engine.js').Xslt3Engine|null}\n * The engine, or null before import\n *\n * @example\n * processor.importStylesheet(xslDoc, '/styles/main.xsl');\n * console.log(processor.engine.outputSettings.method);\n */\n get engine() {\n return this._engine;\n }\n\n /**\n * Sets the loader used to resolve `xsl:import` and `xsl:include` references.\n *\n * The loader is synchronous: it MUST return the external stylesheet as a\n * `Document` or as an XML string (which is parsed automatically). Promises\n * are not awaited by the engine, so pre-load remote stylesheets before\n * calling `importStylesheet`.\n *\n * The loader may be set before or after `importStylesheet`. When set before,\n * it is passed to the engine on creation, which is required for the loader to\n * be used while the stylesheet is being compiled. When set after, the live\n * engine is updated as well.\n *\n * @param {((href: string, baseUri?: string) => (Document|string))|null} loader\n * The loader function, or null to remove a previously configured loader\n * @returns {XSLTProcessor} This processor, to allow chaining\n * @throws {TypeError} If the loader is neither a function nor null\n *\n * @example\n * processor.setStylesheetLoader((href) => readFileSync(href, 'utf8'));\n * processor.importStylesheet(mainStylesheet, '/styles/main.xsl');\n */\n setStylesheetLoader(loader) {\n if (\n loader !== null &&\n loader !== undefined &&\n typeof loader !== \"function\"\n ) {\n throw new TypeError(\n \"Failed to execute 'setStylesheetLoader' on 'XSLTProcessor': The loader argument must be a function or null.\",\n );\n }\n\n this._stylesheetLoader = loader ?? null;\n\n // Keep an already created engine in sync\n if (this._engine) {\n this._engine.setStylesheetLoader(this._stylesheetLoader);\n }\n\n return this;\n }\n\n /**\n * Sets the loader used to resolve the XSLT `document()` function.\n *\n * The loader is synchronous: it MUST return the referenced document as a\n * `Document`, as an XML string (which is parsed automatically) or as `null`\n * when the document cannot be provided. Returning `null`, like configuring no\n * loader at all, makes `document()` evaluate to an empty node-set rather than\n * failing the transformation.\n *\n * The loader may be set before or after `importStylesheet`; a live engine is\n * kept in sync.\n *\n * @param {((uri: string, baseUri?: string) => (Document|string|null))|null} loader\n * The loader function, or null to remove a previously configured loader\n * @returns {XSLTProcessor} This processor, to allow chaining\n * @throws {TypeError} If the loader is neither a function nor null\n *\n * @example\n * // Node.js: resolve document() against the file system\n * import { readFileSync } from 'node:fs';\n * processor.setDocumentLoader((uri) => readFileSync(uri, 'utf8'));\n * processor.importStylesheet(xslDoc, '/styles/main.xsl');\n */\n setDocumentLoader(loader) {\n if (\n loader !== null &&\n loader !== undefined &&\n typeof loader !== \"function\"\n ) {\n throw new TypeError(\n \"Failed to execute 'setDocumentLoader' on 'XSLTProcessor': The loader argument must be a function or null.\",\n );\n }\n\n this._documentLoader = loader ?? null;\n\n // Keep an already created engine in sync\n if (this._engine) {\n this._engine.setDocumentLoader(this._engineDocumentLoader());\n }\n\n return this;\n }\n\n /**\n * Imports the XSLT stylesheet.\n *\n * If the given node is a document node, you can pass in a full XSL Transform\n * or a literal result element transform; otherwise, it must be an\n * <xsl:stylesheet> or <xsl:transform> element.\n *\n * @param {Node} style - The XSLT stylesheet to import (Document or Element)\n * @param {string} [stylesheetUri] - Optional URI of the stylesheet, used as the\n * base URI when resolving relative `xsl:import`/`xsl:include` hrefs. When\n * omitted, hrefs are passed to the loader unresolved.\n * @returns {void}\n * @throws {Error} When the stylesheet is malformed or invalid, e.g. has an\n * invalid pattern (XSLT 1.0 section 5.2), or, with `xsltVersion: \"auto\"`,\n * is an XSLT 2.0/3.0 stylesheet and @tradik/xslt3 has not been loaded\n * ({@link XSLTProcessor.preload})\n *\n * @example\n * const parser = new DOMParser();\n * const xslDoc = parser.parseFromString(xslText, 'application/xml');\n * processor.importStylesheet(xslDoc, '/styles/main.xsl');\n */\n importStylesheet(style, stylesheetUri) {\n if (!style) {\n throw new TypeError(\n \"Failed to execute 'importStylesheet' on 'XSLTProcessor': 1 argument required, but only 0 present.\",\n );\n }\n\n // Validate node type\n if (style.nodeType !== 1 && style.nodeType !== 9) {\n throw new TypeError(\n \"Failed to execute 'importStylesheet' on 'XSLTProcessor': The node provided is not a Document or Element.\",\n );\n }\n\n // Check for parser errors\n if (findParseError(style)) {\n throw new Error(\"XSLT stylesheet contains parse errors\");\n }\n\n this._compile(style, stylesheetUri);\n }\n\n /**\n * Imports a stylesheet whose `xsl:import`/`xsl:include` modules and\n * literal `document('...')` documents are loaded asynchronously first\n * (non-W3C). The modules are loaded in parallel, each URI once; a cycle\n * rejects with \"Circular stylesheet reference detected\". A document that\n * fails to load is reported only if the transformation evaluates that\n * `document()` call. Computed `document()` URIs still go through the\n * synchronous {@link XSLTProcessor#setDocumentLoader} loader, and modules\n * that were not preloaded through {@link XSLTProcessor#setStylesheetLoader}.\n *\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} style -\n * The stylesheet: a node, or markup / a stream of markup to parse\n * @param {string} [stylesheetUri] - Base URI of relative hrefs and\n * `document()` URIs\n * @param {object} [options] - Loading options\n * @param {Function} [options.loader] - `(uri, baseUri, { signal }) =>\n * Promise<Document|string|Uint8Array|ArrayBuffer|Response|null>`; the\n * global `fetch` by default\n * @param {Function} [options.documentLoader] - Loader of `document()`\n * documents, `options.loader` by default\n * @param {AbortSignal} [options.signal] - Cancels loading\n * @returns {Promise<void>} Resolves once the stylesheet is imported; on\n * failure the processor keeps its previous stylesheet\n *\n * @example\n * await processor.importStylesheetAsync(xslDoc, \"https://example.com/xsl/main.xsl\");\n */\n importStylesheetAsync(style, stylesheetUri, options = {}) {\n return importStylesheetAsync(this, style, stylesheetUri, options);\n }\n\n /**\n * Compile a stylesheet into a new engine; the processor is only updated\n * when compiling succeeds.\n *\n * @param {Node} style - The stylesheet\n * @param {string} [stylesheetUri] - Its URI\n * @param {object} [preloaded] - What importStylesheetAsync loaded\n * @param {Function|null} [preloaded.stylesheetLoader] - Module loader\n * @param {Node[]} [preloaded.modules] - Every stylesheet module\n * @param {Map<string, object>|null} [preloaded.documents] - document() documents\n * @returns {void}\n * @private\n */\n _compile(style, stylesheetUri, preloaded = {}) {\n const {\n stylesheetLoader = this._stylesheetLoader,\n modules = [style],\n documents = null,\n } = preloaded;\n const engineOptions = {\n legacyNameTests: this._options.legacyNameTests,\n enableDynamicEvaluate: this._options.enableDynamicEvaluate,\n clock: this._options.clock,\n maxTemplateDepth: this._options.maxTemplateDepth,\n stylesheetLoader,\n documentLoader: this._engineDocumentLoader(documents),\n };\n const engine = this._usesXslt3(style)\n ? createXslt3Engine(style, engineOptions)\n : new XsltEngine(engineOptions);\n\n // Apply any previously set parameters\n for (const [key, value] of this._parameters) {\n engine.setParameterValue(key, value);\n }\n\n // An invalid stylesheet (e.g. an invalid pattern) throws here and leaves\n // the processor as it was\n engine.importStylesheet(style, stylesheetUri);\n // Modules not preloaded keep going through the configured loader\n engine.setStylesheetLoader(this._stylesheetLoader);\n this._engine = engine;\n this._stylesheet = style;\n this._stylesheetUri = stylesheetUri;\n this._modules = modules;\n this._preloadedDocuments = documents;\n }\n\n /**\n * Whether a stylesheet is run by @tradik/xslt3 (`xsltVersion: \"auto\"` and\n * version 2.0 or more).\n *\n * @param {Node} style - The stylesheet\n * @returns {boolean} True for @tradik/xslt3\n * @private\n */\n _usesXslt3(style) {\n return usesXslt3(style, this._options.xsltVersion);\n }\n\n /**\n * Load the engine a stylesheet needs before compiling it (async API).\n *\n * @param {Node} style - The stylesheet\n * @returns {Promise<void>} Resolves once the engine is available\n * @private\n */\n async _prepareEngine(style) {\n if (this._usesXslt3(style)) await loadXslt3();\n }\n\n /**\n * The document() loader given to the engine: preloaded documents first,\n * then the configured synchronous loader.\n *\n * @param {Map<string, object>|null} [documents] - Preloaded documents\n * @returns {Function|null} The loader\n * @private\n */\n _engineDocumentLoader(documents = this._preloadedDocuments) {\n return documents\n ? preloadedDocumentLoader(documents, this._documentLoader)\n : this._documentLoader;\n }\n\n /**\n * Add asynchronously preloaded document() documents.\n *\n * @param {Map<string, object>} documents - Preloaded outcomes by URI\n * @returns {void}\n * @private\n */\n _usePreloadedDocuments(documents) {\n this._preloadedDocuments = new Map([\n ...(this._preloadedDocuments ?? []),\n ...documents,\n ]);\n this._engine.setDocumentLoader(this._engineDocumentLoader());\n }\n\n /**\n * Throw the native error of a transformation without stylesheet.\n *\n * @param {string} method - The method called\n * @returns {void}\n * @throws {Error} When no stylesheet has been imported\n * @private\n */\n _requireStylesheet(method) {\n if (!this._engine || !this._stylesheet) {\n throw new Error(\n `Failed to execute '${method}' on 'XSLTProcessor': No stylesheet has been imported.`,\n );\n }\n }\n\n /**\n * Throw the native error of a source that is not a document, element or\n * fragment.\n *\n * @param {string} method - The method called\n * @param {Node} source - The source node\n * @returns {void}\n * @throws {TypeError} For other node types\n * @private\n */\n _checkSource(method, source) {\n if (\n source.nodeType !== 1 &&\n source.nodeType !== 9 &&\n source.nodeType !== 11\n ) {\n throw new TypeError(\n `Failed to execute '${method}' on 'XSLTProcessor': The source is not a valid node type.`,\n );\n }\n }\n\n /**\n * Transforms the node source by applying the XSLT stylesheet.\n * Returns a document fragment.\n *\n * As in Chrome, when `output` is an HTML document and the output method is\n * `html` (declared, or detected from an `<html>` result root), the result\n * is serialized and parsed by the HTML parser of `output`, so it holds\n * real `HTMLElement`s (`<a>` is an `HTMLAnchorElement`, `<script>` runs\n * when inserted). Other results keep the element names and namespaces of\n * the result tree.\n *\n * @param {Node} source - The XML document to transform\n * @param {Document} output - The document that will own the generated fragment\n * @returns {DocumentFragment} The transformed result as a DocumentFragment\n *\n * @example\n * const fragment = processor.transformToFragment(xmlDoc, document);\n * document.getElementById('output').appendChild(fragment);\n */\n transformToFragment(source, output) {\n if (!source) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': 2 arguments required, but only 0 present.\",\n );\n }\n\n if (!output) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': 2 arguments required, but only 1 present.\",\n );\n }\n\n this._requireStylesheet(\"transformToFragment\");\n\n this._checkSource(\"transformToFragment\", source);\n\n // Validate output document\n if (output.nodeType !== 9) {\n throw new TypeError(\n \"Failed to execute 'transformToFragment' on 'XSLTProcessor': The output is not a Document.\",\n );\n }\n\n try {\n return this._engine.transformToFragment(source, output);\n } catch (error) {\n // Match native behavior - return null on error\n console.error(\"XSLT transformation error:\", error);\n return null;\n }\n }\n\n /**\n * Transforms the node source by applying the XSLT stylesheet.\n * Returns a full XML document.\n *\n * @param {Node} source - The XML document to transform\n * @returns {XMLDocument} The transformed result as an XMLDocument\n *\n * @example\n * const resultDoc = processor.transformToDocument(xmlDoc);\n * const serialized = new XMLSerializer().serializeToString(resultDoc);\n */\n transformToDocument(source) {\n if (!source) {\n throw new TypeError(\n \"Failed to execute 'transformToDocument' on 'XSLTProcessor': 1 argument required, but only 0 present.\",\n );\n }\n\n this._requireStylesheet(\"transformToDocument\");\n\n this._checkSource(\"transformToDocument\", source);\n\n try {\n return this._engine.transformToDocument(source);\n } catch (error) {\n // Match native behavior - return null on error\n console.error(\"XSLT transformation error:\", error);\n return null;\n }\n }\n\n /**\n * Transforms the node source by applying the XSLT stylesheet and serializes\n * the result to a string honoring the stylesheet `xsl:output` settings.\n *\n * Non-W3C convenience method: the native XSLTProcessor has no equivalent.\n * Output method, indentation, XML declaration, document type declaration,\n * CDATA sections and `disable-output-escaping` are all honored\n * (XSLT 1.0 section 16).\n *\n * @param {Node} source - The XML document to transform\n * @returns {string|null} The serialized result, or null on a transformation error\n *\n * @example\n * const xml = processor.transformToString(xmlDoc);\n * // '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<BAR>\\n <QUX/>\\n</BAR>'\n */\n transformToString(source) {\n if (!source) {\n throw new TypeError(\n \"Failed to execute 'transformToString' on 'XSLTProcessor': 1 argument required, but only 0 present.\",\n );\n }\n\n this._requireStylesheet(\"transformToString\");\n\n this._checkSource(\"transformToString\", source);\n\n try {\n return this._engine.transformToString(source);\n } catch (error) {\n // Match transformToDocument behavior - return null on error\n console.error(\"XSLT transformation error:\", error);\n return null;\n }\n }\n\n /**\n * Transforms asynchronously and resolves with the serialized result\n * (non-W3C). The source may be a node, markup, bytes, a `ReadableStream`\n * or an async iterable of strings or bytes; streams are read to their end\n * before parsing, because XSLT 1.0 needs the whole source tree. Unlike\n * {@link XSLTProcessor#transformToString}, failures reject the promise.\n *\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} source - Input\n * @param {object} [options] - Options\n * @param {AbortSignal} [options.signal] - Cancels loading and reading\n * @param {Node|string|ReadableStream|AsyncIterable} [options.stylesheet] -\n * A stylesheet to import first with importStylesheetAsync\n * @param {string} [options.stylesheetUri] - The URI of that stylesheet\n * @param {Function} [options.fetchStylesheet] - Asynchronous loader of its\n * xsl:import/xsl:include modules (`fetch` by default)\n * @param {Function} [options.fetchDocument] - Asynchronous loader of the\n * literal document() documents (`fetchStylesheet` by default when a\n * stylesheet is given)\n * @returns {Promise<string>} The serialized result\n *\n * @example\n * const html = await processor.transformAsync((await fetch(\"data.xml\")).body);\n */\n transformAsync(source, options = {}) {\n return transformAsync(this, source, options);\n }\n\n /**\n * Transforms and returns the serialized result as a `ReadableStream` of\n * strings (non-W3C). The result tree is built in memory on the first read;\n * serialization then produces chunks of about `chunkSize` code units on\n * demand, so the output is never one string and the first bytes are\n * available before serialization ends. Failures error the stream.\n *\n * @param {Node|string|Uint8Array|ArrayBuffer|ReadableStream|AsyncIterable} source - Input\n * @param {{signal?: AbortSignal, chunkSize?: number}} [options] - `signal`\n * cancels (errors the stream with its reason); `chunkSize` defaults to\n * 16384\n * @returns {ReadableStream<string>} The serialized result\n * @throws {Error} When no stylesheet has been imported\n * @throws {TypeError} For a source node of the wrong type\n * @throws {RangeError} For an invalid chunk size\n *\n * @example\n * // Node.js\n * Readable.fromWeb(processor.transformToStream(xmlDoc)).pipe(process.stdout);\n */\n transformToStream(source, options = {}) {\n return transformToStream(this, source, options);\n }\n\n /**\n * Sets a parameter in the XSLT stylesheet.\n *\n * @param {string|null} namespaceURI - The namespace URI of the XSLT parameter (use null for no namespace)\n * @param {string} localName - The local name of the parameter\n * @param {*} value - The value to set (string, number, boolean, or node-set)\n * @returns {void}\n *\n * @example\n * processor.setParameter(null, 'sortOrder', 'ascending');\n * processor.setParameter('http://example.com/ns', 'limit', 10);\n */\n setParameter(namespaceURI, localName, value) {\n if (arguments.length < 3) {\n throw new TypeError(\n `Failed to execute 'setParameter' on 'XSLTProcessor': 3 arguments required, but only ${arguments.length} present.`,\n );\n }\n\n if (typeof localName !== \"string\" || localName === \"\") {\n throw new TypeError(\n \"Failed to execute 'setParameter' on 'XSLTProcessor': The localName argument must be a non-empty string.\",\n );\n }\n\n const key = namespaceURI ? `{${namespaceURI}}${localName}` : localName;\n this._parameters.set(key, value);\n\n // If engine is already initialized, update it\n if (this._engine) {\n this._engine.setParameterValue(key, value);\n }\n }\n\n /**\n * Gets the value of a parameter from the XSLT stylesheet.\n *\n * @param {string|null} namespaceURI - The namespace URI of the parameter\n * @param {string} localName - The local name of the parameter\n * @returns {*} The parameter value, or empty string if not set\n *\n * @example\n * const sortOrder = processor.getParameter(null, 'sortOrder');\n */\n getParameter(namespaceURI, localName) {\n if (arguments.length < 2) {\n throw new TypeError(\n `Failed to execute 'getParameter' on 'XSLTProcessor': 2 arguments required, but only ${arguments.length} present.`,\n );\n }\n\n if (typeof localName !== \"string\") {\n throw new TypeError(\n \"Failed to execute 'getParameter' on 'XSLTProcessor': The localName argument must be a string.\",\n );\n }\n\n const key = namespaceURI ? `{${namespaceURI}}${localName}` : localName;\n\n if (this._parameters.has(key)) {\n return this._parameters.get(key);\n }\n\n // Return empty string for unset parameters (matches native behavior)\n return \"\";\n }\n\n /**\n * Removes a parameter from the XSLT processor.\n *\n * The XSLTProcessor will use the default value for the parameter\n * as specified in the XSLT stylesheet.\n *\n * @param {string|null} namespaceURI - The namespace URI of the parameter\n * @param {string} localName - The local name of the parameter\n * @returns {void}\n *\n * @example\n * processor.removeParameter(null, 'sortOrder');\n */\n removeParameter(namespaceURI, localName) {\n if (arguments.length < 2) {\n throw new TypeError(\n `Failed to execute 'removeParameter' on 'XSLTProcessor': 2 arguments required, but only ${arguments.length} present.`,\n );\n }\n\n if (typeof localName !== \"string\") {\n throw new TypeError(\n \"Failed to execute 'removeParameter' on 'XSLTProcessor': The localName argument must be a string.\",\n );\n }\n\n const key = namespaceURI ? `{${namespaceURI}}${localName}` : localName;\n this._parameters.delete(key);\n\n if (this._engine) {\n this._engine.clearParameterValue(key);\n }\n }\n\n /**\n * Removes all set parameters from the XSLTProcessor.\n *\n * The processor will use default values specified in the XSLT stylesheet.\n *\n * @returns {void}\n *\n * @example\n * processor.clearParameters();\n */\n clearParameters() {\n this._parameters.clear();\n\n if (this._engine) {\n this._engine.clearParameterValues();\n }\n }\n\n /**\n * Removes all parameters and stylesheets from the XSLTProcessor.\n *\n * Per the W3C `XSLTProcessor` semantics, `reset()` clears stylesheet state and\n * parameters only. The stylesheet and document loaders are processor\n * configuration rather than stylesheet state, so they are deliberately\n * preserved and stay effective for the next `importStylesheet()` call. Pass\n * `null` to {@link XSLTProcessor#setStylesheetLoader} or\n * {@link XSLTProcessor#setDocumentLoader} to remove them explicitly.\n *\n * @returns {void}\n *\n * @example\n * processor.reset();\n * // Now need to call importStylesheet() again before transforming\n */\n reset() {\n this._engine = null;\n this._stylesheet = null;\n this._stylesheetUri = undefined;\n this._modules = [];\n this._preloadedDocuments = null;\n this._parameters.clear();\n }\n}\n\n/**\n * Check if native XSLTProcessor is available and functional.\n *\n * After installGlobal() replaced the global, the original native constructor\n * is probed; this implementation never counts as native.\n *\n * @returns {boolean} True if native XSLTProcessor works correctly\n */\nexport function isNativeXSLTSupported() {\n const current = globalThis.XSLTProcessor;\n const Native = current === XSLTProcessor ? nativeProcessor : current;\n if (typeof Native !== \"function\") return false;\n\n try {\n const processor = new Native();\n const parser = new DOMParser();\n\n const xslt = parser.parseFromString(\n `<?xml version=\"1.0\"?>\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"/\"><test/></xsl:template>\n </xsl:stylesheet>`,\n \"application/xml\",\n );\n\n processor.importStylesheet(xslt);\n\n const xml = parser.parseFromString(\"<root/>\", \"application/xml\");\n const result = processor.transformToFragment(xml, document);\n\n return result !== null && result.childNodes.length > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Install as global XSLTProcessor replacement if native is not functional\n *\n * @param {boolean} force - Force installation even if native is available\n * @returns {boolean} True if installed as global\n */\nexport function installGlobal(force = false) {\n if (!force && isNativeXSLTSupported()) {\n return false;\n }\n\n const current = globalThis.XSLTProcessor;\n if (typeof current === \"function\" && current !== XSLTProcessor) {\n nativeProcessor = current;\n }\n globalThis.XSLTProcessor = XSLTProcessor;\n return true;\n}\n\nexport default XSLTProcessor;\n", "/**\n * XPath 1.0 Module\n * Based on W3C XPath 1.0 Specification: http://www.w3.org/TR/1999/REC-xpath-19991116\n */\n\n\"use strict\";\n\nexport { TokenType, Token, XPathTokenizer, tokenize } from \"./tokenizer.js\";\nexport { NodeType, ASTNode, XPathParser, parse } from \"./parser.js\";\nexport {\n XPathResultType,\n XPathContext,\n XPathEvaluator,\n XPathLimits,\n} from \"./evaluator.js\";\n\nimport { parse } from \"./parser.js\";\nimport { XPathEvaluator, XPathContext } from \"./evaluator.js\";\n\n/**\n * Evaluate an XPath expression against a node\n *\n * @param {string} expression - XPath expression\n * @param {Node} contextNode - Context node\n * @param {Object} options - Options: variables, namespaces, and the\n * evaluator limits maxResultSize, maxRecursionDepth and maxStringLength\n * (defaults in XPathLimits)\n * @returns {*} Evaluation result\n */\nexport function evaluate(expression, contextNode, options = {}) {\n const ast = parse(expression);\n const evaluator = new XPathEvaluator({\n maxResultSize: options.maxResultSize,\n maxRecursionDepth: options.maxRecursionDepth,\n maxStringLength: options.maxStringLength,\n });\n const context = new XPathContext(\n contextNode,\n 1,\n 1,\n options.variables || {},\n options.namespaces || {},\n );\n return evaluator.evaluate(ast, context);\n}\n\n/**\n * Select nodes matching an XPath expression\n *\n * @param {string} expression - XPath expression\n * @param {Node} contextNode - Context node\n * @param {Object} options - Options\n * @returns {Node[]} Matching nodes\n */\nexport function select(expression, contextNode, options = {}) {\n const result = evaluate(expression, contextNode, options);\n if (Array.isArray(result)) return result;\n if (result && result.nodeType) return [result];\n return [];\n}\n\n/**\n * Select first node matching an XPath expression\n *\n * @param {string} expression - XPath expression\n * @param {Node} contextNode - Context node\n * @param {Object} options - Options\n * @returns {Node|null} First matching node or null\n */\nexport function selectFirst(expression, contextNode, options = {}) {\n const nodes = select(expression, contextNode, options);\n return nodes.length > 0 ? nodes[0] : null;\n}\n", "/**\n * @tradik/xslt-processor\n *\n * JavaScript implementation of XSLTProcessor for browser environments.\n *\n * This package provides a JavaScript implementation of the W3C XSLTProcessor API\n * that can be used as a drop-in replacement for the native browser implementation.\n *\n * Specifications implemented:\n * - XPath 1.0: http://www.w3.org/TR/1999/REC-xpath-19991116\n * - XSLT 1.0: http://www.w3.org/TR/1999/REC-xslt-19991116\n * - DOM Level 3: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/\n *\n * @example\n * // ESM import\n * import { XSLTProcessor, installGlobal } from '@tradik/xslt-processor';\n *\n * // Install as global replacement\n * installGlobal();\n *\n * // Or use directly\n * const processor = new XSLTProcessor();\n * processor.importStylesheet(xsltDoc);\n * const result = processor.transformToFragment(xmlDoc, document);\n */\n\n// Main XSLTProcessor class\nexport {\n XSLTProcessor,\n isNativeXSLTSupported,\n installGlobal,\n default,\n} from \"./XSLTProcessor.js\";\n\n// XPath module (for advanced users)\nexport {\n evaluate as evaluateXPath,\n select as selectXPath,\n selectFirst as selectFirstXPath,\n XPathEvaluator,\n XPathContext,\n XPathResultType,\n XPathLimits,\n parse as parseXPath,\n} from \"./xpath/index.js\";\n\n// XSLT engine (for advanced users)\nexport {\n XsltEngine,\n XsltContext,\n XSLT_MAX_RESULT_SIZE,\n XSLT_MAX_EXPRESSION_DEPTH,\n XSLT_MAX_TEMPLATE_DEPTH,\n} from \"./xslt/index.js\";\n\n// Output serializer (xsl:output, XSLT 1.0 section 16)\nexport {\n serializeResult,\n serializeChunks,\n DEFAULT_CHUNK_SIZE,\n markRawText,\n isRawText,\n resolveOutputSettings,\n} from \"./xslt/serializer.js\";\n\n// Streaming output on the engine side (advanced users)\nexport { transformToChunks, transformToStream } from \"./async/stream.js\";\n\n/**\n * Version information\n */\nexport const VERSION = \"1.3.0\";\n\n/**\n * Check if we're running in a browser environment\n */\nexport const isBrowser =\n typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\n/**\n * Check if we're running in Node.js\n */\nexport const isNode =\n typeof process !== \"undefined\" && process.versions?.node != null;\n"],
|
|
5
|
+
"mappings": ";AASO,IAAM,YAAY;AAAA;AAAA,EAEvB,QAAQ;AAAA,EACR,SAAS;AAAA;AAAA,EAGT,OAAO;AAAA,EACP,cAAc;AAAA,EACd,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,KAAK;AAAA,EACL,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,KAAK;AAAA,EACL,IAAI;AAAA;AAAA,EAGJ,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,UAAU;AAAA;AAAA,EAGV,MAAM;AAAA,EACN,IAAI;AAA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M,QAAQ,MAAM,EAAG,QAAO;AAClC,MAAI,UAAU,OAAO,SAAU,QAAO,CAAC,MAAM;AAC7C,SAAO,CAAC;AACV;AAUO,SAAS,YAAY,YAAY,aAAa,UAAU,CAAC,GAAG;AACjE,QAAM,QAAQ,OAAO,YAAY,aAAa,OAAO;AACrD,SAAO,MAAM,SAAS,IAAI,MAAM,CAAC,IAAI;AACvC;;;ACDO,IAAM,UAAU;AAKhB,IAAM,YACX,OAAO,WAAW,eAAe,OAAO,aAAa;AAKhD,IAAM,SACX,OAAO,YAAY,eAAe,QAAQ,UAAU,QAAQ;",
|
|
6
|
+
"names": ["cache", "XMLNS_NAMESPACE", "XML_NAMESPACE", "result", "ending", "evaluate", "evaluate", "nodeSet", "attributeName", "alias", "XMLNS_NAMESPACE", "rootOf", "isNamespaceDeclaration", "XMLNS_NAMESPACE", "isNamespaceDeclaration", "rootOf", "XMLNS_NAMESPACE", "XML_NAMESPACE", "declaredPrefix", "splitQName", "XMLNS_NAMESPACE", "XML_NAMESPACE", "splitQName", "loaded", "splitQName", "XMLNS_NAMESPACE", "XML_NAMESPACE", "splitQName", "select", "select", "XML_WHITESPACE_ONLY", "evaluate", "select", "evaluate", "splitQName", "XMLNS_NAMESPACE", "select", "XHTML_NAMESPACE", "cache", "XML_NAMESPACE", "XMLNS_NAMESPACE", "XMLNS_NAMESPACE", "hasContentTypeMeta", "doc", "loaded", "document", "loaded", "pending", "transformToStream", "loaded", "transformToStream"]
|
|
7
7
|
}
|