kwikqa 0.3.0 → 0.3.1

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/dist/kwikqa.mjs CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __kwikqaCreateRequire } from "node:module";const require=__kwikqaCreateRequire(import.meta.url);
3
- var zv=Object.create;var gf=Object.defineProperty;var Vv=Object.getOwnPropertyDescriptor;var Uv=Object.getOwnPropertyNames;var qv=Object.getPrototypeOf,Gv=Object.prototype.hasOwnProperty;var Kv=(t,n)=>()=>{try{return n||t((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}};var Wv=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Uv(n))!Gv.call(t,i)&&i!==e&&gf(t,i,{get:()=>n[i],enumerable:!(r=Vv(n,i))||r.enumerable});return t};var Bs=(t,n,e)=>(e=t!=null?zv(qv(t)):{},Wv(n||!t||!t.__esModule?gf(e,"default",{value:t,enumerable:!0}):e,t));var vi=Kv(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});function mk(t,n){if(t==null)return{};var e={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(n.indexOf(r)!==-1)continue;e[r]=t[r]}return e}var xt=class{constructor(n,e,r){this.line=void 0,this.column=void 0,this.index=void 0,this.line=n,this.column=e,this.index=r}},dr=class{constructor(n,e){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=n,this.end=e}};function _e(t,n){let{line:e,column:r,index:i}=t;return new xt(e,r+n,i+n)}var Cf="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",yk={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:Cf},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:Cf}},Nf={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},Xs=t=>t.type==="UpdateExpression"?Nf.UpdateExpression[`${t.prefix}`]:Nf[t.type],gk={AccessorIsGenerator:({kind:t})=>`A ${t}ter cannot be a generator.`,ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:({kind:t})=>`Missing initializer in ${t} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:({exportName:t})=>`\`${t}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName:t,exportName:n})=>`A string literal cannot be used as an exported binding without \`from\`.
3
+ var zv=Object.create;var gf=Object.defineProperty;var Vv=Object.getOwnPropertyDescriptor;var Uv=Object.getOwnPropertyNames;var qv=Object.getPrototypeOf,Gv=Object.prototype.hasOwnProperty;var Kv=(t,n)=>()=>{try{return n||t((n={exports:{}}).exports,n),n.exports}catch(e){throw n=0,e}};var Wv=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Uv(n))!Gv.call(t,i)&&i!==e&&gf(t,i,{get:()=>n[i],enumerable:!(r=Vv(n,i))||r.enumerable});return t};var Bs=(t,n,e)=>(e=t!=null?zv(qv(t)):{},Wv(n||!t||!t.__esModule?gf(e,"default",{value:t,enumerable:!0}):e,t));var vi=Kv(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});function mk(t,n){if(t==null)return{};var e={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(n.indexOf(r)!==-1)continue;e[r]=t[r]}return e}var xt=class{constructor(n,e,r){this.line=void 0,this.column=void 0,this.index=void 0,this.line=n,this.column=e,this.index=r}},cr=class{constructor(n,e){this.start=void 0,this.end=void 0,this.filename=void 0,this.identifierName=void 0,this.start=n,this.end=e}};function _e(t,n){let{line:e,column:r,index:i}=t;return new xt(e,r+n,i+n)}var Cf="BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED",yk={ImportMetaOutsideModule:{message:`import.meta may appear only with 'sourceType: "module"'`,code:Cf},ImportOutsideModule:{message:`'import' and 'export' may appear only with 'sourceType: "module"'`,code:Cf}},Nf={ArrayPattern:"array destructuring pattern",AssignmentExpression:"assignment expression",AssignmentPattern:"assignment expression",ArrowFunctionExpression:"arrow function expression",ConditionalExpression:"conditional expression",CatchClause:"catch clause",ForOfStatement:"for-of statement",ForInStatement:"for-in statement",ForStatement:"for-loop",FormalParameters:"function parameter list",Identifier:"identifier",ImportSpecifier:"import specifier",ImportDefaultSpecifier:"import default specifier",ImportNamespaceSpecifier:"import namespace specifier",ObjectPattern:"object destructuring pattern",ParenthesizedExpression:"parenthesized expression",RestElement:"rest element",UpdateExpression:{true:"prefix operation",false:"postfix operation"},VariableDeclarator:"variable declaration",YieldExpression:"yield expression"},Xs=t=>t.type==="UpdateExpression"?Nf.UpdateExpression[`${t.prefix}`]:Nf[t.type],gk={AccessorIsGenerator:({kind:t})=>`A ${t}ter cannot be a generator.`,ArgumentsInClass:"'arguments' is only allowed in functions and class methods.",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block.",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function.",AwaitBindingIdentifierInStaticBlock:"Can not use 'await' as identifier inside a static block.",AwaitExpressionFormalParameter:"'await' is not allowed in async function parameters.",AwaitUsingNotInAsyncContext:"'await using' is only allowed within async functions and at the top levels of modules.",AwaitNotInAsyncContext:"'await' is only allowed within async functions and at the top levels of modules.",BadGetterArity:"A 'get' accessor must not have any formal parameters.",BadSetterArity:"A 'set' accessor must have exactly one formal parameter.",BadSetterRestParameter:"A 'set' accessor function argument must not be a rest parameter.",ConstructorClassField:"Classes may not have a field named 'constructor'.",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'.",ConstructorIsAccessor:"Class constructor may not be an accessor.",ConstructorIsAsync:"Constructor can't be an async function.",ConstructorIsGenerator:"Constructor can't be a generator.",DeclarationMissingInitializer:({kind:t})=>`Missing initializer in ${t} declaration.`,DecoratorArgumentsOutsideParentheses:"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",DecoratorsBeforeAfterExport:"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",DecoratorSemicolon:"Decorators must not be followed by a semicolon.",DecoratorStaticBlock:"Decorators can't be used with a static block.",DeferImportRequiresNamespace:'Only `import defer * as x from "./module"` is valid.',DeletePrivateField:"Deleting a private field is not allowed.",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class.",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:({exportName:t})=>`\`${t}\` has already been exported. Exported identifiers must be unique.`,DuplicateProto:"Redefinition of __proto__ property.",DuplicateRegExpFlags:"Duplicate regular expression flag.",ElementAfterRest:"Rest element must be last element.",EscapedCharNotAnIdentifier:"Invalid Unicode escape.",ExportBindingIsString:({localName:t,exportName:n})=>`A string literal cannot be used as an exported binding without \`from\`.
4
4
  - Did you mean \`export { '${t}' as '${n}' } from 'some-module'\`?`,ExportDefaultFromAsIdentifier:"'from' is not allowed as an identifier after 'export default'.",ForInOfLoopInitializer:({type:t})=>`'${t==="ForInStatement"?"for-in":"for-of"}' loop variable declaration may not have an initializer.`,ForInUsing:"For-in loop may not start with 'using' declaration.",ForOfAsync:"The left-hand side of a for-of loop may not be 'async'.",ForOfLet:"The left-hand side of a for-of loop may not start with 'let'.",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block.",IllegalBreakContinue:({type:t})=>`Unsyntactic ${t==="BreakStatement"?"break":"continue"}.`,IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list.",IllegalReturn:"'return' outside of function.",ImportAttributesUseAssert:"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",ImportBindingIsString:({importName:t})=>`A string literal cannot be used as an imported binding.
5
- - Did you mean \`import { "${t}" as foo }\`?`,ImportCallArity:"`import()` requires exactly one or two arguments.",ImportCallNotNewExpression:"Cannot use new with import(...).",ImportCallSpreadArgument:"`...` is not allowed in `import()`.",ImportJSONBindingNotDefault:"A JSON module can only be imported with `default`.",ImportReflectionHasAssertion:"`import module x` cannot have assertions.",ImportReflectionNotBinding:'Only `import module x from "./module"` is valid.',IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix:t})=>`Expected number in radix ${t}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:t})=>`Escape sequence in keyword ${t}.`,InvalidIdentifier:({identifierName:t})=>`Invalid identifier ${t}.`,InvalidLhs:({ancestor:t})=>`Invalid left-hand side in ${Xs(t)}.`,InvalidLhsBinding:({ancestor:t})=>`Binding invalid left-hand side in ${Xs(t)}.`,InvalidLhsOptionalChaining:({ancestor:t})=>`Invalid optional chaining in the left-hand side of ${Xs(t)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:t})=>`Unexpected character '${t}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:t})=>`Private name #${t} is not defined.`,InvalidPropertyBindingPattern:"Binding member expression.",InvalidRecordProperty:"Only properties and spread elements are allowed in record definitions.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:({labelName:t})=>`Label '${t}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:({missingPlugin:t})=>`This experimental syntax requires enabling the parser plugin: ${t.map(n=>JSON.stringify(n)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:t})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${t.map(n=>JSON.stringify(n)).join(", ")}.`,MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeDifferentFromType:"The only accepted module attribute is `type`.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:({key:t})=>`Duplicate key "${t}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:t})=>`An export name cannot include a lone surrogate, found '\\u${t.toString(16)}'.`,ModuleExportUndefined:({localName:t})=>`Export '${t}' is not defined.`,MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:({identifierName:t})=>`Private names are only allowed in property accesses (\`obj.#${t}\`) or in \`in\` expressions (\`#${t} in obj\`).`,PrivateNameRedeclaration:({identifierName:t})=>`Duplicate private name #${t}.`,RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",RecordNoProto:"'__proto__' is not allowed in Record expressions.",RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode code, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperCallNotNewExpression:"Cannot use new with super(...).",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:({keyword:t})=>`Unexpected keyword '${t}'.`,UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:({reservedWord:t})=>`Unexpected reserved word '${t}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:t,unexpected:n})=>`Unexpected token${n?` '${n}'.`:""}${t?`, expected "${t}"`:""}`,UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:({target:t,onlyValidPropertyName:n})=>`The only valid meta property for ${t} is ${t}.${n}.`,UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:t})=>`Identifier '${t}' has already been declared.`,VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},wk={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:t})=>`Assigning to '${t}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:t})=>`Binding '${t}' in strict mode.`,StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block.",StrictNumericEscape:"The only valid numeric escape in strict mode is '\\0'.",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode.",StrictWith:"'with' in strict mode."},bk={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:t})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(t)}\`.`},xk=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),vk=Object.assign({PipeBodyIsTighter:"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",PipeTopicRequiresHackPipes:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:({token:t})=>`Invalid topic token ${t}. In order to use ${t} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${t}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:t})=>`Hack-style pipe body cannot be an unparenthesized ${Xs({type:t})}; please wrap it in parentheses.`},{PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression.",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression.",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference.",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding.",PrimaryTopicRequiresSmartPipeline:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'}),kk={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."},Rk=["message"];function Of(t,n,e){Object.defineProperty(t,n,{enumerable:!1,configurable:!0,value:e})}function Ik({toMessage:t,code:n,reasonCode:e,syntaxPlugin:r}){let i=e==="MissingPlugin"||e==="MissingOneOfPlugins",s={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return s[e]&&(e=s[e]),function a(o,d){let c=new SyntaxError;return c.code=n,c.reasonCode=e,c.loc=o,c.pos=o.index,c.syntaxPlugin=r,i&&(c.missingPlugin=d.missingPlugin),Of(c,"clone",function(u={}){var p;let{line:f,column:h,index:m}=(p=u.loc)!=null?p:o;return a(new xt(f,h,m),Object.assign({},d,u.details))}),Of(c,"details",d),Object.defineProperty(c,"message",{configurable:!0,get(){let l=`${t(d)} (${o.line}:${o.column})`;return this.message=l,l},set(l){Object.defineProperty(this,"message",{value:l,writable:!0})}}),c}}function ot(t,n){if(Array.isArray(t))return r=>ot(r,t[0]);let e={};for(let r of Object.keys(t)){let i=t[r],s=typeof i=="string"?{message:()=>i}:typeof i=="function"?{message:i}:i,{message:a}=s,o=mk(s,Rk),d=typeof a=="string"?()=>a:a;e[r]=Ik(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:r,toMessage:d},n?{syntaxPlugin:n}:{},o))}return e}var b=Object.assign({},ot(yk),ot(gk),ot(wk),ot(bk),ot`pipelineOperator`(vk),ot`functionBind`(kk));function Ak(){return{sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:void 0,ranges:!1,tokens:!1,createImportExpressions:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0}}function Tk(t){let n=Ak();if(t==null)return n;if(t.annexB!=null&&t.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(let e of Object.keys(n))t[e]!=null&&(n[e]=t[e]);if(n.startLine===1)t.startIndex==null&&n.startColumn>0?n.startIndex=n.startColumn:t.startColumn==null&&n.startIndex>0&&(n.startColumn=n.startIndex);else if((t.startColumn==null||t.startIndex==null)&&t.startIndex!=null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(n.sourceType==="commonjs"){if(t.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(t.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(t.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return n}var{defineProperty:Pk}=Object,$f=(t,n)=>{t&&Pk(t,n,{enumerable:!1,value:t[n]})};function ui(t){return $f(t.loc.start,"index"),$f(t.loc.end,"index"),t}var Sk=t=>class extends t{parse(){let e=ui(super.parse());return this.optionFlags&256&&(e.tokens=e.tokens.map(ui)),e}parseRegExpLiteral({pattern:e,flags:r}){let i=null;try{i=new RegExp(e,r)}catch{}let s=this.estreeParseLiteral(i);return s.regex={pattern:e,flags:r},s}parseBigIntLiteral(e){let r;try{r=BigInt(e)}catch{r=null}let i=this.estreeParseLiteral(r);return i.bigint=String(i.value||e),i}parseDecimalLiteral(e){let i=this.estreeParseLiteral(null);return i.decimal=String(i.value||e),i}estreeParseLiteral(e){return this.parseLiteral(e,"Literal")}parseStringLiteral(e){return this.estreeParseLiteral(e)}parseNumericLiteral(e){return this.estreeParseLiteral(e)}parseNullLiteral(){return this.estreeParseLiteral(null)}parseBooleanLiteral(e){return this.estreeParseLiteral(e)}estreeParseChainExpression(e,r){let i=this.startNodeAtNode(e);return i.expression=e,this.finishNodeAt(i,"ChainExpression",r)}directiveToStmt(e){let r=e.value;delete e.value,this.castNodeTo(r,"Literal"),r.raw=r.extra.raw,r.value=r.extra.expressionValue;let i=this.castNodeTo(e,"ExpressionStatement");return i.expression=r,i.directive=r.extra.rawValue,delete r.extra,i}fillOptionalPropertiesForTSESLint(e){}cloneEstreeStringLiteral(e){let{start:r,end:i,loc:s,range:a,raw:o,value:d}=e,c=Object.create(e.constructor.prototype);return c.type="Literal",c.start=r,c.end=i,c.loc=s,c.range=a,c.raw=o,c.value=d,c}initFunction(e,r){super.initFunction(e,r),e.expression=!1}checkDeclaration(e){e!=null&&this.isObjectProperty(e)?this.checkDeclaration(e.value):super.checkDeclaration(e)}getObjectOrClassMethodParams(e){return e.value.params}isValidDirective(e){var r;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((r=e.expression.extra)!=null&&r.parenthesized)}parseBlockBody(e,r,i,s,a){super.parseBlockBody(e,r,i,s,a);let o=e.directives.map(d=>this.directiveToStmt(d));e.body=o.concat(e.body),delete e.directives}parsePrivateName(){let e=super.parsePrivateName();return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(e):e}convertPrivateNameToPrivateIdentifier(e){let r=super.getPrivateNameSV(e);return delete e.id,e.name=r,this.castNodeTo(e,"PrivateIdentifier")}isPrivateName(e){return this.getPluginOption("estree","classFeatures")?e.type==="PrivateIdentifier":super.isPrivateName(e)}getPrivateNameSV(e){return this.getPluginOption("estree","classFeatures")?e.name:super.getPrivateNameSV(e)}parseLiteral(e,r){let i=super.parseLiteral(e,r);return i.raw=i.extra.raw,delete i.extra,i}parseFunctionBody(e,r,i=!1){super.parseFunctionBody(e,r,i),e.expression=e.body.type!=="BlockStatement"}parseMethod(e,r,i,s,a,o,d=!1){let c=this.startNode();c.kind=e.kind,c=super.parseMethod(c,r,i,s,a,o,d),delete c.kind;let{typeParameters:l}=e;l&&(delete e.typeParameters,c.typeParameters=l,this.resetStartLocationFromNode(c,l));let u=this.castNodeTo(c,"FunctionExpression");return e.value=u,o==="ClassPrivateMethod"&&(e.computed=!1),o==="ObjectMethod"?(e.kind==="method"&&(e.kind="init"),e.shorthand=!1,this.finishNode(e,"Property")):this.finishNode(e,"MethodDefinition")}nameIsConstructor(e){return e.type==="Literal"?e.value==="constructor":super.nameIsConstructor(e)}parseClassProperty(...e){let r=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&this.castNodeTo(r,"PropertyDefinition"),r}parseClassPrivateProperty(...e){let r=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(this.castNodeTo(r,"PropertyDefinition"),r.computed=!1),r}parseClassAccessorProperty(e){let r=super.parseClassAccessorProperty(e);return this.getPluginOption("estree","classFeatures")&&(r.abstract&&this.hasPlugin("typescript")?(delete r.abstract,this.castNodeTo(r,"TSAbstractAccessorProperty")):this.castNodeTo(r,"AccessorProperty")),r}parseObjectProperty(e,r,i,s){let a=super.parseObjectProperty(e,r,i,s);return a&&(a.kind="init",this.castNodeTo(a,"Property")),a}finishObjectProperty(e){return e.kind="init",this.finishNode(e,"Property")}isValidLVal(e,r,i,s){return e==="Property"?"value":super.isValidLVal(e,r,i,s)}isAssignable(e,r){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,r):super.isAssignable(e,r)}toAssignable(e,r=!1){if(e!=null&&this.isObjectProperty(e)){let{key:i,value:s}=e;this.isPrivateName(i)&&this.classScope.usePrivateName(this.getPrivateNameSV(i),i.loc.start),this.toAssignable(s,r)}else super.toAssignable(e,r)}toAssignableObjectExpressionProp(e,r,i){e.type==="Property"&&(e.kind==="get"||e.kind==="set")?this.raise(b.PatternHasAccessor,e.key):e.type==="Property"&&e.method?this.raise(b.PatternHasMethod,e.key):super.toAssignableObjectExpressionProp(e,r,i)}finishCallExpression(e,r){let i=super.finishCallExpression(e,r);if(i.callee.type==="Import"){var s,a;this.castNodeTo(i,"ImportExpression"),i.source=i.arguments[0],i.options=(s=i.arguments[1])!=null?s:null,i.attributes=(a=i.arguments[1])!=null?a:null,delete i.arguments,delete i.callee}else i.type==="OptionalCallExpression"?this.castNodeTo(i,"CallExpression"):i.optional=!1;return i}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e)}parseExport(e,r){let i=this.state.lastTokStartLoc,s=super.parseExport(e,r);switch(s.type){case"ExportAllDeclaration":s.exported=null;break;case"ExportNamedDeclaration":s.specifiers.length===1&&s.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(s,"ExportAllDeclaration"),s.exported=s.specifiers[0].exported,delete s.specifiers);case"ExportDefaultDeclaration":{var a;let{declaration:o}=s;o?.type==="ClassDeclaration"&&((a=o.decorators)==null?void 0:a.length)>0&&o.start===s.start&&this.resetStartLocation(s,i)}break}return s}stopParseSubscript(e,r){let i=super.stopParseSubscript(e,r);return r.optionalChainMember?this.estreeParseChainExpression(i,e.loc.end):i}parseMember(e,r,i,s,a){let o=super.parseMember(e,r,i,s,a);return o.type==="OptionalMemberExpression"?this.castNodeTo(o,"MemberExpression"):o.optional=!1,o}isOptionalMemberExpression(e){return e.type==="ChainExpression"?e.expression.type==="MemberExpression":super.isOptionalMemberExpression(e)}hasPropertyAsPrivateName(e){return e.type==="ChainExpression"&&(e=e.expression),super.hasPropertyAsPrivateName(e)}isObjectProperty(e){return e.type==="Property"&&e.kind==="init"&&!e.method}isObjectMethod(e){return e.type==="Property"&&(e.method||e.kind==="get"||e.kind==="set")}castNodeTo(e,r){let i=super.castNodeTo(e,r);return this.fillOptionalPropertiesForTSESLint(i),i}cloneIdentifier(e){let r=super.cloneIdentifier(e);return this.fillOptionalPropertiesForTSESLint(r),r}cloneStringLiteral(e){return e.type==="Literal"?this.cloneEstreeStringLiteral(e):super.cloneStringLiteral(e)}finishNodeAt(e,r,i){return ui(super.finishNodeAt(e,r,i))}finishNode(e,r){let i=super.finishNode(e,r);return this.fillOptionalPropertiesForTSESLint(i),i}resetStartLocation(e,r){super.resetStartLocation(e,r),ui(e)}resetEndLocation(e,r=this.state.lastTokEndLoc){super.resetEndLocation(e,r),ui(e)}},gn=class{constructor(n,e){this.token=void 0,this.preserveSpace=void 0,this.token=n,this.preserveSpace=!!e}},ie={brace:new gn("{"),j_oTag:new gn("<tag"),j_cTag:new gn("</tag"),j_expr:new gn("<tag>...</tag>",!0)};ie.template=new gn("`",!0);var W=!0,O=!0,zd=!0,pi=!0,Wt=!0,Ek=!0,ea=class{constructor(n,e={}){this.label=void 0,this.keyword=void 0,this.beforeExpr=void 0,this.startsExpr=void 0,this.rightAssociative=void 0,this.isLoop=void 0,this.isAssign=void 0,this.prefix=void 0,this.postfix=void 0,this.binop=void 0,this.label=n,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop!=null?e.binop:null,this.updateContext=null}},mc=new Map;function Z(t,n={}){n.keyword=t;let e=z(t,n);return mc.set(t,e),e}function Me(t,n){return z(t,{beforeExpr:W,binop:n})}var yi=-1,Ct=[],yc=[],gc=[],wc=[],bc=[],xc=[];function z(t,n={}){var e,r,i,s;return++yi,yc.push(t),gc.push((e=n.binop)!=null?e:-1),wc.push((r=n.beforeExpr)!=null?r:!1),bc.push((i=n.startsExpr)!=null?i:!1),xc.push((s=n.prefix)!=null?s:!1),Ct.push(new ea(t,n)),yi}function J(t,n={}){var e,r,i,s;return++yi,mc.set(t,yi),yc.push(t),gc.push((e=n.binop)!=null?e:-1),wc.push((r=n.beforeExpr)!=null?r:!1),bc.push((i=n.startsExpr)!=null?i:!1),xc.push((s=n.prefix)!=null?s:!1),Ct.push(new ea("name",n)),yi}var Ck={bracketL:z("[",{beforeExpr:W,startsExpr:O}),bracketHashL:z("#[",{beforeExpr:W,startsExpr:O}),bracketBarL:z("[|",{beforeExpr:W,startsExpr:O}),bracketR:z("]"),bracketBarR:z("|]"),braceL:z("{",{beforeExpr:W,startsExpr:O}),braceBarL:z("{|",{beforeExpr:W,startsExpr:O}),braceHashL:z("#{",{beforeExpr:W,startsExpr:O}),braceR:z("}"),braceBarR:z("|}"),parenL:z("(",{beforeExpr:W,startsExpr:O}),parenR:z(")"),comma:z(",",{beforeExpr:W}),semi:z(";",{beforeExpr:W}),colon:z(":",{beforeExpr:W}),doubleColon:z("::",{beforeExpr:W}),dot:z("."),question:z("?",{beforeExpr:W}),questionDot:z("?."),arrow:z("=>",{beforeExpr:W}),template:z("template"),ellipsis:z("...",{beforeExpr:W}),backQuote:z("`",{startsExpr:O}),dollarBraceL:z("${",{beforeExpr:W,startsExpr:O}),templateTail:z("...`",{startsExpr:O}),templateNonTail:z("...${",{beforeExpr:W,startsExpr:O}),at:z("@"),hash:z("#",{startsExpr:O}),interpreterDirective:z("#!..."),eq:z("=",{beforeExpr:W,isAssign:pi}),assign:z("_=",{beforeExpr:W,isAssign:pi}),slashAssign:z("_=",{beforeExpr:W,isAssign:pi}),xorAssign:z("_=",{beforeExpr:W,isAssign:pi}),moduloAssign:z("_=",{beforeExpr:W,isAssign:pi}),incDec:z("++/--",{prefix:Wt,postfix:Ek,startsExpr:O}),bang:z("!",{beforeExpr:W,prefix:Wt,startsExpr:O}),tilde:z("~",{beforeExpr:W,prefix:Wt,startsExpr:O}),doubleCaret:z("^^",{startsExpr:O}),doubleAt:z("@@",{startsExpr:O}),pipeline:Me("|>",0),nullishCoalescing:Me("??",1),logicalOR:Me("||",1),logicalAND:Me("&&",2),bitwiseOR:Me("|",3),bitwiseXOR:Me("^",4),bitwiseAND:Me("&",5),equality:Me("==/!=/===/!==",6),lt:Me("</>/<=/>=",7),gt:Me("</>/<=/>=",7),relational:Me("</>/<=/>=",7),bitShift:Me("<</>>/>>>",8),bitShiftL:Me("<</>>/>>>",8),bitShiftR:Me("<</>>/>>>",8),plusMin:z("+/-",{beforeExpr:W,binop:9,prefix:Wt,startsExpr:O}),modulo:z("%",{binop:10,startsExpr:O}),star:z("*",{binop:10}),slash:Me("/",10),exponent:z("**",{beforeExpr:W,binop:11,rightAssociative:!0}),_in:Z("in",{beforeExpr:W,binop:7}),_instanceof:Z("instanceof",{beforeExpr:W,binop:7}),_break:Z("break"),_case:Z("case",{beforeExpr:W}),_catch:Z("catch"),_continue:Z("continue"),_debugger:Z("debugger"),_default:Z("default",{beforeExpr:W}),_else:Z("else",{beforeExpr:W}),_finally:Z("finally"),_function:Z("function",{startsExpr:O}),_if:Z("if"),_return:Z("return",{beforeExpr:W}),_switch:Z("switch"),_throw:Z("throw",{beforeExpr:W,prefix:Wt,startsExpr:O}),_try:Z("try"),_var:Z("var"),_const:Z("const"),_with:Z("with"),_new:Z("new",{beforeExpr:W,startsExpr:O}),_this:Z("this",{startsExpr:O}),_super:Z("super",{startsExpr:O}),_class:Z("class",{startsExpr:O}),_extends:Z("extends",{beforeExpr:W}),_export:Z("export"),_import:Z("import",{startsExpr:O}),_null:Z("null",{startsExpr:O}),_true:Z("true",{startsExpr:O}),_false:Z("false",{startsExpr:O}),_typeof:Z("typeof",{beforeExpr:W,prefix:Wt,startsExpr:O}),_void:Z("void",{beforeExpr:W,prefix:Wt,startsExpr:O}),_delete:Z("delete",{beforeExpr:W,prefix:Wt,startsExpr:O}),_do:Z("do",{isLoop:zd,beforeExpr:W}),_for:Z("for",{isLoop:zd}),_while:Z("while",{isLoop:zd}),_as:J("as",{startsExpr:O}),_assert:J("assert",{startsExpr:O}),_async:J("async",{startsExpr:O}),_await:J("await",{startsExpr:O}),_defer:J("defer",{startsExpr:O}),_from:J("from",{startsExpr:O}),_get:J("get",{startsExpr:O}),_let:J("let",{startsExpr:O}),_meta:J("meta",{startsExpr:O}),_of:J("of",{startsExpr:O}),_sent:J("sent",{startsExpr:O}),_set:J("set",{startsExpr:O}),_source:J("source",{startsExpr:O}),_static:J("static",{startsExpr:O}),_using:J("using",{startsExpr:O}),_yield:J("yield",{startsExpr:O}),_asserts:J("asserts",{startsExpr:O}),_checks:J("checks",{startsExpr:O}),_exports:J("exports",{startsExpr:O}),_global:J("global",{startsExpr:O}),_implements:J("implements",{startsExpr:O}),_intrinsic:J("intrinsic",{startsExpr:O}),_infer:J("infer",{startsExpr:O}),_is:J("is",{startsExpr:O}),_mixins:J("mixins",{startsExpr:O}),_proto:J("proto",{startsExpr:O}),_require:J("require",{startsExpr:O}),_satisfies:J("satisfies",{startsExpr:O}),_keyof:J("keyof",{startsExpr:O}),_readonly:J("readonly",{startsExpr:O}),_unique:J("unique",{startsExpr:O}),_abstract:J("abstract",{startsExpr:O}),_declare:J("declare",{startsExpr:O}),_enum:J("enum",{startsExpr:O}),_module:J("module",{startsExpr:O}),_namespace:J("namespace",{startsExpr:O}),_interface:J("interface",{startsExpr:O}),_type:J("type",{startsExpr:O}),_opaque:J("opaque",{startsExpr:O}),name:z("name",{startsExpr:O}),placeholder:z("%%",{startsExpr:O}),string:z("string",{startsExpr:O}),num:z("num",{startsExpr:O}),bigint:z("bigint",{startsExpr:O}),decimal:z("decimal",{startsExpr:O}),regexp:z("regexp",{startsExpr:O}),privateName:z("#name",{startsExpr:O}),eof:z("eof"),jsxName:z("jsxName"),jsxText:z("jsxText",{beforeExpr:W}),jsxTagStart:z("jsxTagStart",{startsExpr:O}),jsxTagEnd:z("jsxTagEnd")};function se(t){return t>=93&&t<=133}function Nk(t){return t<=92}function dt(t){return t>=58&&t<=133}function qf(t){return t>=58&&t<=137}function Ok(t){return wc[t]}function hi(t){return bc[t]}function $k(t){return t>=29&&t<=33}function Df(t){return t>=129&&t<=131}function Dk(t){return t>=90&&t<=92}function vc(t){return t>=58&&t<=92}function Lk(t){return t>=39&&t<=59}function Mk(t){return t===34}function _k(t){return xc[t]}function jk(t){return t>=121&&t<=123}function Fk(t){return t>=124&&t<=130}function Yt(t){return yc[t]}function Qs(t){return gc[t]}function Bk(t){return t===57}function ta(t){return t>=24&&t<=25}function Et(t){return Ct[t]}Ct[8].updateContext=t=>{t.pop()};Ct[5].updateContext=Ct[7].updateContext=Ct[23].updateContext=t=>{t.push(ie.brace)};Ct[22].updateContext=t=>{t[t.length-1]===ie.template?t.pop():t.push(ie.template)};Ct[143].updateContext=t=>{t.push(ie.j_expr,ie.j_oTag)};var kc="\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC",Gf="\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65",Hk=new RegExp("["+kc+"]"),zk=new RegExp("["+kc+Gf+"]");kc=Gf=null;var Kf=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],Vk=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];function Wd(t,n){let e=65536;for(let r=0,i=n.length;r<i;r+=2){if(e+=n[r],e>t)return!1;if(e+=n[r+1],e>=t)return!0}return!1}function bt(t){return t<65?t===36:t<=90?!0:t<97?t===95:t<=122?!0:t<=65535?t>=170&&Hk.test(String.fromCharCode(t)):Wd(t,Kf)}function wn(t){return t<48?t===36:t<58?!0:t<65?!1:t<=90?!0:t<97?t===95:t<=122?!0:t<=65535?t>=170&&zk.test(String.fromCharCode(t)):Wd(t,Kf)||Wd(t,Vk)}var Rc={keyword:["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"],strict:["implements","interface","let","package","private","protected","public","static","yield"],strictBind:["eval","arguments"]},Uk=new Set(Rc.keyword),qk=new Set(Rc.strict),Gk=new Set(Rc.strictBind);function Wf(t,n){return n&&t==="await"||t==="enum"}function Jf(t,n){return Wf(t,n)||qk.has(t)}function Yf(t){return Gk.has(t)}function Xf(t,n){return Jf(t,n)||Yf(t)}function Kk(t){return Uk.has(t)}function Wk(t,n,e){return t===64&&n===64&&bt(e)}var Jk=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);function Yk(t){return Jk.has(t)}var gi=class{constructor(n){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=n}},wi=class{constructor(n,e){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=n,this.inModule=e}get inTopLevel(){return(this.currentScope().flags&1)>0}get inFunction(){return(this.currentVarScopeFlags()&2)>0}get allowSuper(){return(this.currentThisScopeFlags()&16)>0}get allowDirectSuper(){return(this.currentThisScopeFlags()&32)>0}get allowNewTarget(){return(this.currentThisScopeFlags()&512)>0}get inClass(){return(this.currentThisScopeFlags()&64)>0}get inClassAndNotInNonArrowFunction(){let n=this.currentThisScopeFlags();return(n&64)>0&&(n&2)===0}get inStaticBlock(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&128)return!0;if(e&1731)return!1}}get inNonArrowFunction(){return(this.currentThisScopeFlags()&2)>0}get inBareCaseStatement(){return(this.currentScope().flags&256)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(n){return new gi(n)}enter(n){this.scopeStack.push(this.createScope(n))}exit(){return this.scopeStack.pop().flags}treatFunctionsAsVarInScope(n){return!!(n.flags&130||!this.parser.inModule&&n.flags&1)}declareName(n,e,r){let i=this.currentScope();if(e&8||e&16){this.checkRedeclarationInScope(i,n,e,r);let s=i.names.get(n)||0;e&16?s=s|4:(i.firstLexicalName||(i.firstLexicalName=n),s=s|2),i.names.set(n,s),e&8&&this.maybeExportDefined(i,n)}else if(e&4)for(let s=this.scopeStack.length-1;s>=0&&(i=this.scopeStack[s],this.checkRedeclarationInScope(i,n,e,r),i.names.set(n,(i.names.get(n)||0)|1),this.maybeExportDefined(i,n),!(i.flags&1667));--s);this.parser.inModule&&i.flags&1&&this.undefinedExports.delete(n)}maybeExportDefined(n,e){this.parser.inModule&&n.flags&1&&this.undefinedExports.delete(e)}checkRedeclarationInScope(n,e,r,i){this.isRedeclaredInScope(n,e,r)&&this.parser.raise(b.VarRedeclaration,i,{identifierName:e})}isRedeclaredInScope(n,e,r){if(!(r&1))return!1;if(r&8)return n.names.has(e);let i=n.names.get(e)||0;return r&16?(i&2)>0||!this.treatFunctionsAsVarInScope(n)&&(i&1)>0:(i&2)>0&&!(n.flags&8&&n.firstLexicalName===e)||!this.treatFunctionsAsVarInScope(n)&&(i&4)>0}checkLocalExport(n){let{name:e}=n;this.scopeStack[0].names.has(e)||this.undefinedExports.set(e,n.loc.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&1667)return e}}currentThisScopeFlags(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&1731&&!(e&4))return e}}},Jd=class extends gi{constructor(...n){super(...n),this.declareFunctions=new Set}},Yd=class extends wi{createScope(n){return new Jd(n)}declareName(n,e,r){let i=this.currentScope();if(e&2048){this.checkRedeclarationInScope(i,n,e,r),this.maybeExportDefined(i,n),i.declareFunctions.add(n);return}super.declareName(n,e,r)}isRedeclaredInScope(n,e,r){if(super.isRedeclaredInScope(n,e,r))return!0;if(r&2048&&!n.declareFunctions.has(e)){let i=n.names.get(e);return(i&4)>0||(i&2)>0}return!1}checkLocalExport(n){this.scopeStack[0].declareFunctions.has(n.name)||super.checkLocalExport(n)}},Xk=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),V=ot`flow`({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType:t})=>`Cannot overwrite reserved type ${t}.`,DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:({memberName:t,enumName:n})=>`Boolean enum members need to be initialized. Use either \`${t} = true,\` or \`${t} = false,\` in enum \`${n}\`.`,EnumDuplicateMemberName:({memberName:t,enumName:n})=>`Enum member names need to be unique, but the name \`${t}\` has already been used before in enum \`${n}\`.`,EnumInconsistentMemberValues:({enumName:t})=>`Enum \`${t}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:t,enumName:n})=>`Enum type \`${t}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${n}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:t})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:t,memberName:n,explicitType:e})=>`Enum \`${t}\` has type \`${e}\`, so the initializer of \`${n}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:t,memberName:n})=>`Symbol enum members cannot be initialized. Use \`${n},\` in enum \`${t}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:t,memberName:n})=>`The enum member initializer for \`${n}\` needs to be a literal (either a boolean, number, or string) in enum \`${t}\`.`,EnumInvalidMemberName:({enumName:t,memberName:n,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${n}\`, consider using \`${e}\`, in enum \`${t}\`.`,EnumNumberMemberNotInitialized:({enumName:t,memberName:n})=>`Number enum members need to be initialized, e.g. \`${n} = 1\` in enum \`${t}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:t})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${t}\`.`,GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` or `typeof` keyword.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:Object.assign({message:"A binding pattern parameter cannot be optional in an implementation signature."},{reasonCode:"OptionalBindingPattern"}),SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:({reservedType:t})=>`Unexpected reserved type ${t}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:t,suggestion:n})=>`\`declare export ${t}\` is not supported. Use \`${n}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function Qk(t){return t.type==="DeclareExportAllDeclaration"||t.type==="DeclareExportDeclaration"&&(!t.declaration||t.declaration.type!=="TypeAlias"&&t.declaration.type!=="InterfaceDeclaration")}function Lf(t){return t.importKind==="type"||t.importKind==="typeof"}var Zk={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function eR(t,n){let e=[],r=[];for(let i=0;i<t.length;i++)(n(t[i],i,t)?e:r).push(t[i]);return[e,r]}var tR=/\*?\s*@((?:no)?flow)\b/,nR=t=>class extends t{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return Yd}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(e,r){e!==134&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,r)}addComment(e){if(this.flowPragma===void 0){let r=tR.exec(e.value);if(r)if(r[1]==="flow")this.flowPragma="flow";else if(r[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e)}flowParseTypeInitialiser(e){let r=this.state.inType;this.state.inType=!0,this.expect(e||14);let i=this.flowParseType();return this.state.inType=r,i}flowParsePredicate(){let e=this.startNode(),r=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>r.index+1&&this.raise(V.UnexpectedSpaceBetweenModuloChecks,r),this.eat(10)?(e.value=super.parseExpression(),this.expect(11),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(){let e=this.state.inType;this.state.inType=!0,this.expect(14);let r=null,i=null;return this.match(54)?(this.state.inType=e,i=this.flowParsePredicate()):(r=this.flowParseType(),this.state.inType=e,this.match(54)&&(i=this.flowParsePredicate())),[r,i]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let r=e.id=this.parseIdentifier(),i=this.startNode(),s=this.startNode();this.match(47)?i.typeParameters=this.flowParseTypeParameterDeclaration():i.typeParameters=null,this.expect(10);let a=this.flowParseFunctionTypeParams();return i.params=a.params,i.rest=a.rest,i.this=a._this,this.expect(11),[i.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),s.typeAnnotation=this.finishNode(i,"FunctionTypeAnnotation"),r.typeAnnotation=this.finishNode(s,"TypeAnnotation"),this.resetEndLocation(r),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,r){if(this.match(80))return this.flowParseDeclareClass(e);if(this.match(68))return this.flowParseDeclareFunction(e);if(this.match(74))return this.flowParseDeclareVariable(e);if(this.eatContextual(127))return this.match(16)?this.flowParseDeclareModuleExports(e):(r&&this.raise(V.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e));if(this.isContextual(130))return this.flowParseDeclareTypeAlias(e);if(this.isContextual(131))return this.flowParseDeclareOpaqueType(e);if(this.isContextual(129))return this.flowParseDeclareInterface(e);if(this.match(82))return this.flowParseDeclareExportDeclaration(e,r);throw this.unexpected()}flowParseDeclareVariable(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.scope.declareName(e.id.name,5,e.id.loc.start),this.semicolon(),this.finishNode(e,"DeclareVariable")}flowParseDeclareModule(e){this.scope.enter(0),this.match(134)?e.id=super.parseExprAtom():e.id=this.parseIdentifier();let r=e.body=this.startNode(),i=r.body=[];for(this.expect(5);!this.match(8);){let o=this.startNode();this.match(83)?(this.next(),!this.isContextual(130)&&!this.match(87)&&this.raise(V.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),i.push(super.parseImport(o))):(this.expectContextual(125,V.UnsupportedStatementInDeclareModule),i.push(this.flowParseDeclare(o,!0)))}this.scope.exit(),this.expect(8),this.finishNode(r,"BlockStatement");let s=null,a=!1;return i.forEach(o=>{Qk(o)?(s==="CommonJS"&&this.raise(V.AmbiguousDeclareModuleKind,o),s="ES"):o.type==="DeclareModuleExports"&&(a&&this.raise(V.DuplicateDeclareModuleExports,o),s==="ES"&&this.raise(V.AmbiguousDeclareModuleKind,o),s="CommonJS",a=!0)}),e.kind=s||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,r){if(this.expect(82),this.eat(65))return this.match(68)||this.match(80)?e.declaration=this.flowParseDeclare(this.startNode()):(e.declaration=this.flowParseType(),this.semicolon()),e.default=!0,this.finishNode(e,"DeclareExportDeclaration");if(this.match(75)||this.isLet()||(this.isContextual(130)||this.isContextual(129))&&!r){let i=this.state.value;throw this.raise(V.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:i,suggestion:Zk[i]})}if(this.match(74)||this.match(68)||this.match(80)||this.isContextual(131))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");if(this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131))return e=this.parseExport(e,null),e.type==="ExportNamedDeclaration"?(e.default=!1,delete e.exportKind,this.castNodeTo(e,"DeclareExportDeclaration")):this.castNodeTo(e,"DeclareExportAllDeclaration");throw this.unexpected()}flowParseDeclareModuleExports(e){return this.next(),this.expectContextual(111),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")}flowParseDeclareTypeAlias(e){this.next();let r=this.flowParseTypeAlias(e);return this.castNodeTo(r,"DeclareTypeAlias"),r}flowParseDeclareOpaqueType(e){this.next();let r=this.flowParseOpaqueType(e,!0);return this.castNodeTo(r,"DeclareOpaqueType"),r}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,r){if(e.id=this.flowParseRestrictedIdentifier(!r,!0),this.scope.declareName(e.id.name,r?17:8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],this.eat(81))do e.extends.push(this.flowParseInterfaceExtends());while(!r&&this.eat(12));if(r){if(e.implements=[],e.mixins=[],this.eatContextual(117))do e.mixins.push(this.flowParseInterfaceExtends());while(this.eat(12));if(this.eatContextual(113))do e.implements.push(this.flowParseInterfaceExtends());while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:r,allowExact:!1,allowSpread:!1,allowProto:r,allowInexact:!1})}flowParseInterfaceExtends(){let e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.match(47)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")}flowParseInterface(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")}checkNotUnderscore(e){e==="_"&&this.raise(V.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(e,r,i){Xk.has(e)&&this.raise(i?V.AssignReservedType:V.UnexpectedReservedType,r,{reservedType:e})}flowParseRestrictedIdentifierName(e,r){return this.checkReservedType(this.state.value,this.state.startLoc,r),this.parseIdentifierName(e)}flowParseRestrictedIdentifier(e,r){let i=this.startNode(),s=this.flowParseRestrictedIdentifierName(e,r);return this.createIdentifier(i,s)}flowParseTypeAlias(e){return e.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(29),this.semicolon(),this.finishNode(e,"TypeAlias")}flowParseOpaqueType(e,r){return this.expectContextual(130),e.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(14)&&(e.supertype=this.flowParseTypeInitialiser(14)),e.impltype=null,r||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")}flowParseTypeParameterBound(){if(this.match(14)||this.isContextual(81)){let e=this.startNode();return this.next(),e.typeAnnotation=this.flowParseType(),this.finishNode(e,"TypeAnnotation")}}flowParseTypeParameter(e=!1){let r=this.state.startLoc,i=this.startNode(),s=this.flowParseVariance();return i.name=this.flowParseRestrictedIdentifierName(),i.variance=s,i.bound=this.flowParseTypeParameterBound(),this.match(29)?(this.eat(29),i.default=this.flowParseType()):e&&this.raise(V.MissingTypeParamDefault,r),this.finishNode(i,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,r=this.startNode();r.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let i=!1;do{let s=this.flowParseTypeParameter(i);r.params.push(s),s.default&&(i=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(r,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()!==ie.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===47)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){let e=this.startNode(),r=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext(()=>{this.expect(47);let i=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.match(48);)e.params.push(this.flowParseType()),this.match(48)||this.expect(12);this.state.noAnonFunctionType=i}),this.state.inType=r,!this.state.inType&&this.curContext()===ie.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;let e=this.startNode(),r=this.state.inType;for(e.params=[],this.state.inType=!0,this.expect(47);!this.match(48);)e.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(48)||this.expect(12);return this.expect(48),this.state.inType=r,this.finishNode(e,"TypeParameterInstantiation")}flowParseInterfaceType(){let e=this.startNode();if(this.expectContextual(129),e.extends=[],this.eat(81))do e.extends.push(this.flowParseInterfaceExtends());while(this.eat(12));return e.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(e,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(135)||this.match(134)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(e,r,i){return e.static=r,this.lookahead().type===14?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(3),e.value=this.flowParseTypeInitialiser(),e.variance=i,this.finishNode(e,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(e,r){return e.static=r,e.id=this.flowParseObjectPropertyKey(),this.expect(3),this.expect(3),this.match(47)||this.match(10)?(e.method=!0,e.optional=!1,e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start))):(e.method=!1,this.eat(17)&&(e.optional=!0),e.value=this.flowParseTypeInitialiser()),this.finishNode(e,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(e){for(e.params=[],e.rest=null,e.typeParameters=null,e.this=null,this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(10),this.match(78)&&(e.this=this.flowParseFunctionTypeParam(!0),e.this.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.params.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(e.rest=this.flowParseFunctionTypeParam(!1)),this.expect(11),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(e,r){let i=this.startNode();return e.static=r,e.value=this.flowParseObjectTypeMethodish(i),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:r,allowSpread:i,allowProto:s,allowInexact:a}){let o=this.state.inType;this.state.inType=!0;let d=this.startNode();d.callProperties=[],d.properties=[],d.indexers=[],d.internalSlots=[];let c,l,u=!1;for(r&&this.match(6)?(this.expect(6),c=9,l=!0):(this.expect(5),c=8,l=!1),d.exact=l;!this.match(c);){let f=!1,h=null,m=null,g=this.startNode();if(s&&this.isContextual(118)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),h=this.state.startLoc,e=!1)}if(e&&this.isContextual(106)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),f=!0)}let y=this.flowParseVariance();if(this.eat(0))h!=null&&this.unexpected(h),this.eat(0)?(y&&this.unexpected(y.loc.start),d.internalSlots.push(this.flowParseObjectTypeInternalSlot(g,f))):d.indexers.push(this.flowParseObjectTypeIndexer(g,f,y));else if(this.match(10)||this.match(47))h!=null&&this.unexpected(h),y&&this.unexpected(y.loc.start),d.callProperties.push(this.flowParseObjectTypeCallProperty(g,f));else{let w="init";if(this.isContextual(99)||this.isContextual(104)){let v=this.lookahead();qf(v.type)&&(w=this.state.value,this.next())}let x=this.flowParseObjectTypeProperty(g,f,h,y,w,i,a??!l);x===null?(u=!0,m=this.state.lastTokStartLoc):d.properties.push(x)}this.flowObjectTypeSemicolon(),m&&!this.match(8)&&!this.match(9)&&this.raise(V.UnexpectedExplicitInexactInObject,m)}this.expect(c),i&&(d.inexact=u);let p=this.finishNode(d,"ObjectTypeAnnotation");return this.state.inType=o,p}flowParseObjectTypeProperty(e,r,i,s,a,o,d){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(o?d||this.raise(V.InexactInsideExact,this.state.lastTokStartLoc):this.raise(V.InexactInsideNonObject,this.state.lastTokStartLoc),s&&this.raise(V.InexactVariance,s),null):(o||this.raise(V.UnexpectedSpreadType,this.state.lastTokStartLoc),i!=null&&this.unexpected(i),s&&this.raise(V.SpreadVariance,s),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=r,e.proto=i!=null,e.kind=a;let c=!1;return this.match(47)||this.match(10)?(e.method=!0,i!=null&&this.unexpected(i),s&&this.unexpected(s.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),(a==="get"||a==="set")&&this.flowCheckGetterSetterParams(e),!o&&e.key.name==="constructor"&&e.value.this&&this.raise(V.ThisParamBannedInConstructor,e.value.this)):(a!=="init"&&this.unexpected(),e.method=!1,this.eat(17)&&(c=!0),e.value=this.flowParseTypeInitialiser(),e.variance=s),e.optional=c,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let r=e.kind==="get"?0:1,i=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?V.GetterMayNotHaveThisParam:V.SetterMayNotHaveThisParam,e.value.this),i!==r&&this.raise(e.kind==="get"?b.BadGetterArity:b.BadSetterArity,e),e.kind==="set"&&e.value.rest&&this.raise(b.BadSetterRestParameter,e)}flowObjectTypeSemicolon(){!this.eat(13)&&!this.eat(12)&&!this.match(8)&&!this.match(9)&&this.unexpected()}flowParseQualifiedTypeIdentifier(e,r){e??(e=this.state.startLoc);let i=r||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let s=this.startNodeAt(e);s.qualification=i,s.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(s,"QualifiedTypeIdentifier")}return i}flowParseGenericType(e,r){let i=this.startNodeAt(e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(e,r),this.match(47)&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")}flowParseTypeofType(){let e=this.startNode();return this.expect(87),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")}flowParseTupleType(){let e=this.startNode();for(e.types=[],this.expect(0);this.state.pos<this.length&&!this.match(3)&&(e.types.push(this.flowParseType()),!this.match(3));)this.expect(12);return this.expect(3),this.finishNode(e,"TupleTypeAnnotation")}flowParseFunctionTypeParam(e){let r=null,i=!1,s=null,a=this.startNode(),o=this.lookahead(),d=this.state.type===78;return o.type===14||o.type===17?(d&&!e&&this.raise(V.ThisParamMustBeFirst,a),r=this.parseIdentifier(d),this.eat(17)&&(i=!0,d&&this.raise(V.ThisParamMayNotBeOptional,a)),s=this.flowParseTypeInitialiser()):s=this.flowParseType(),a.name=r,a.optional=i,a.typeAnnotation=s,this.finishNode(a,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){let r=this.startNodeAt(e.loc.start);return r.name=null,r.optional=!1,r.typeAnnotation=e,this.finishNode(r,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let r=null,i=null;for(this.match(78)&&(i=this.flowParseFunctionTypeParam(!0),i.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(r=this.flowParseFunctionTypeParam(!1)),{params:e,rest:r,_this:i}}flowIdentToTypeAnnotation(e,r,i){switch(i.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");case"symbol":return this.finishNode(r,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(i.name),this.flowParseGenericType(e,i)}}flowParsePrimaryType(){let e=this.state.startLoc,r=this.startNode(),i,s,a=!1,o=this.state.noAnonFunctionType;switch(this.state.type){case 5:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case 6:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case 0:return this.state.noAnonFunctionType=!1,s=this.flowParseTupleType(),this.state.noAnonFunctionType=o,s;case 47:{let d=this.startNode();return d.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),this.finishNode(d,"FunctionTypeAnnotation")}case 10:{let d=this.startNode();if(this.next(),!this.match(11)&&!this.match(21))if(se(this.state.type)||this.match(78)){let c=this.lookahead().type;a=c!==17&&c!==14}else a=!0;if(a){if(this.state.noAnonFunctionType=!1,s=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19))return this.expect(11),s;this.eat(12)}return s?i=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(s)]):i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),d.typeParameters=null,this.finishNode(d,"FunctionTypeAnnotation")}case 134:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 85:case 86:return r.value=this.match(85),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",r);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",r);throw this.raise(V.UnexpectedSubtractionOperand,this.state.startLoc)}throw this.unexpected();case 135:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 136:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 88:return this.next(),this.finishNode(r,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(r,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(r,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(vc(this.state.type)){let d=Yt(this.state.type);return this.next(),super.createIdentifier(r,d)}else if(se(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,r,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){let e=this.state.startLoc,r=this.flowParsePrimaryType(),i=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){let s=this.startNodeAt(e),a=this.eat(18);i=i||a,this.expect(0),!a&&this.match(3)?(s.elementType=r,this.next(),r=this.finishNode(s,"ArrayTypeAnnotation")):(s.objectType=r,s.indexType=this.flowParseType(),this.expect(3),i?(s.optional=a,r=this.finishNode(s,"OptionalIndexedAccessType")):r=this.finishNode(s,"IndexedAccessType"))}return r}flowParsePrefixType(){let e=this.startNode();return this.eat(17)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){let e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(19)){let r=this.startNodeAt(e.loc.start);return r.params=[this.reinterpretTypeAsFunctionTypeParam(e)],r.rest=null,r.this=null,r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){let e=this.startNode();this.eat(45);let r=this.flowParseAnonFunctionWithoutParens();for(e.types=[r];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return e.types.length===1?r:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){let e=this.startNode();this.eat(43);let r=this.flowParseIntersectionType();for(e.types=[r];this.eat(43);)e.types.push(this.flowParseIntersectionType());return e.types.length===1?r:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){let e=this.state.inType;this.state.inType=!0;let r=this.flowParseUnionType();return this.state.inType=e,r}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){let e=this.state.startLoc,r=this.parseIdentifier();return this.flowParseGenericType(e,r)}else return this.flowParseType()}flowParseTypeAnnotation(){let e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){let e=this.startNode(),r=this.parseIdentifierName();return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(e,r)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}flowParseVariance(){let e=null;return this.match(53)?(e=this.startNode(),this.state.value==="+"?e.kind="plus":e.kind="minus",this.next(),this.finishNode(e,"Variance")):e}parseFunctionBody(e,r,i=!1){if(r){this.forwardNoArrowParamsConversionAt(e,()=>super.parseFunctionBody(e,!0,i));return}super.parseFunctionBody(e,!1,i)}parseFunctionBodyAndFinish(e,r,i=!1){if(this.match(14)){let s=this.startNode();[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=s.typeAnnotation?this.finishNode(s,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,r,i)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){let i=this.lookahead();if(dt(i.type)){let s=this.startNode();return this.next(),this.flowParseInterface(s)}}else if(this.isContextual(126)){let i=this.startNode();return this.next(),this.flowParseEnumDeclaration(i)}let r=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(r)&&(this.flowPragma=null),r}parseExpressionStatement(e,r,i){if(r.type==="Identifier"){if(r.name==="declare"){if(this.match(80)||se(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(se(this.state.type)){if(r.name==="interface")return this.flowParseInterface(e);if(r.name==="type")return this.flowParseTypeAlias(e);if(r.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,r,i)}shouldParseExportDeclaration(){let{type:e}=this.state;return e===126||Df(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return e===126||Df(e)?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(126)){let e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDefaultExpression()}parseConditional(e,r,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let p=this.lookaheadCharCode();if(p===44||p===61||p===58||p===41)return this.setOptionalParametersError(i),e}this.expect(17);let s=this.state.clone(),a=this.state.noArrowAt,o=this.startNodeAt(r),{consequent:d,failed:c}=this.tryParseConditionalConsequent(),[l,u]=this.getArrowLikeExpressions(d);if(c||u.length>0){let p=[...a];if(u.length>0){this.state=s,this.state.noArrowAt=p;for(let f=0;f<u.length;f++)p.push(u[f].start);({consequent:d,failed:c}=this.tryParseConditionalConsequent()),[l,u]=this.getArrowLikeExpressions(d)}c&&l.length>1&&this.raise(V.AmbiguousConditionalArrow,s.startLoc),c&&l.length===1&&(this.state=s,p.push(l[0].start),this.state.noArrowAt=p,{consequent:d,failed:c}=this.tryParseConditionalConsequent())}return this.getArrowLikeExpressions(d,!0),this.state.noArrowAt=a,this.expect(14),o.test=e,o.consequent=d,o.alternate=this.forwardNoArrowParamsConversionAt(o,()=>this.parseMaybeAssign(void 0,void 0)),this.finishNode(o,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);let e=this.parseMaybeAssignAllowIn(),r=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:r}}getArrowLikeExpressions(e,r){let i=[e],s=[];for(;i.length!==0;){let a=i.pop();a.type==="ArrowFunctionExpression"?(a.typeParameters||!a.returnType?this.finishArrowValidation(a):s.push(a),a.body.type!=="BlockStatement"&&i.push(a.body)):a.type==="ConditionalExpression"&&(i.push(a.consequent),i.push(a.alternate))}return r?(s.forEach(a=>this.finishArrowValidation(a)),[s,[]]):eR(s,a=>a.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var r;this.toAssignableList(e.params,(r=e.extra)==null?void 0:r.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,r){let i;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),i=r(),this.state.noArrowParamsConversionAt.pop()):i=r(),i}parseParenItem(e,r){let i=super.parseParenItem(e,r);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(r);return s.expression=i,s.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(s,"TypeCastExpression")}return i}assertModuleNodeAllowed(e){e.type==="ImportDeclaration"&&(e.importKind==="type"||e.importKind==="typeof")||e.type==="ExportNamedDeclaration"&&e.exportKind==="type"||e.type==="ExportAllDeclaration"&&e.exportKind==="type"||super.assertModuleNodeAllowed(e)}parseExportDeclaration(e){if(this.isContextual(130)){e.exportKind="type";let r=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(r)}else if(this.isContextual(131)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseOpaqueType(r,!1)}else if(this.isContextual(129)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseInterface(r)}else if(this.isContextual(126)){e.exportKind="value";let r=this.startNode();return this.next(),this.flowParseEnumDeclaration(r)}else return super.parseExportDeclaration(e)}eatExportStar(e){return super.eatExportStar(e)?!0:this.isContextual(130)&&this.lookahead().type===55?(e.exportKind="type",this.next(),this.next(),!0):!1}maybeParseExportNamespaceSpecifier(e){let{startLoc:r}=this.state,i=super.maybeParseExportNamespaceSpecifier(e);return i&&e.exportKind==="type"&&this.unexpected(r),i}parseClassId(e,r,i){super.parseClassId(e,r,i),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,r,i){let{startLoc:s}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,r))return;r.declare=!0}super.parseClassMember(e,r,i),r.declare&&(r.type!=="ClassProperty"&&r.type!=="ClassPrivateProperty"&&r.type!=="PropertyDefinition"?this.raise(V.DeclareClassElement,s):r.value&&this.raise(V.DeclareClassFieldInitializer,r.value))}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),r="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(b.InvalidIdentifier,this.state.curPosition(),{identifierName:r}),this.finishToken(132,r)}getTokenFromCode(e){let r=this.input.charCodeAt(this.state.pos+1);e===123&&r===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?r===46?this.finishOp(18,2):this.finishOp(17,1):Wk(e,r,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e)}isAssignable(e,r){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,r):super.isAssignable(e,r)}toAssignable(e,r=!1){!r&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,r)}toAssignableList(e,r,i){for(let s=0;s<e.length;s++){let a=e[s];a?.type==="TypeCastExpression"&&(e[s]=this.typeCastToParameter(a))}super.toAssignableList(e,r,i)}toReferencedList(e,r){for(let s=0;s<e.length;s++){var i;let a=e[s];a&&a.type==="TypeCastExpression"&&!((i=a.extra)!=null&&i.parenthesized)&&(e.length>1||!r)&&this.raise(V.TypeCastInPattern,a.typeAnnotation)}return e}parseArrayLike(e,r,i){let s=super.parseArrayLike(e,r,i);return i!=null&&!this.state.maybeInArrowParameters&&this.toReferencedList(s.elements),s}isValidLVal(e,r,i,s){return e==="TypeCastExpression"||super.isValidLVal(e,r,i,s)}parseClassProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(e)}parseClassPrivateProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(e){return!this.match(14)&&super.isNonstaticConstructor(e)}pushClassMethod(e,r,i,s,a,o){if(r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,r,i,s,a,o),r.params&&a){let d=r.params;d.length>0&&this.isThisParam(d[0])&&this.raise(V.ThisParamBannedInConstructor,r)}else if(r.type==="MethodDefinition"&&a&&r.value.params){let d=r.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(V.ThisParamBannedInConstructor,r)}}pushClassPrivateMethod(e,r,i,s){r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,r,i,s)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();let r=e.implements=[];do{let i=this.startNode();i.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?i.typeParameters=this.flowParseTypeParameterInstantiation():i.typeParameters=null,r.push(this.finishNode(i,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let r=this.getObjectOrClassMethodParams(e);if(r.length>0){let i=r[0];this.isThisParam(i)&&e.kind==="get"?this.raise(V.GetterMayNotHaveThisParam,i):this.isThisParam(i)&&this.raise(V.SetterMayNotHaveThisParam,i)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,r,i,s,a,o,d){e.variance&&this.unexpected(e.variance.loc.start),delete e.variance;let c;this.match(47)&&!o&&(c=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());let l=super.parseObjPropValue(e,r,i,s,a,o,d);return c&&((l.value||l).typeParameters=c),l}parseFunctionParamType(e){return this.eat(17)&&(e.type!=="Identifier"&&this.raise(V.PatternIsOptional,e),this.isThisParam(e)&&this.raise(V.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(V.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(V.ThisParamNoDefault,e),this.resetEndLocation(e),e}parseMaybeDefault(e,r){let i=super.parseMaybeDefault(e,r);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(V.TypeBeforeInitializer,i.typeAnnotation),i}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(V.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,r,i){r.local=Lf(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(r,i))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;let r=this.lookaheadCharCode();return r===123||r===42}return!e&&this.isContextual(87)}applyImportPhase(e,r,i,s){if(super.applyImportPhase(e,r,i,s),r){if(!i&&this.match(65))return;e.exportKind=i==="type"?i:"value"}else i==="type"&&this.match(55)&&this.unexpected(),e.importKind=i==="type"||i==="typeof"?i:"value"}parseImportSpecifier(e,r,i,s,a){let o=e.imported,d=null;o.type==="Identifier"&&(o.name==="type"?d="type":o.name==="typeof"&&(d="typeof"));let c=!1;if(this.isContextual(93)&&!this.isLookaheadContextual("as")){let u=this.parseIdentifier(!0);d!==null&&!dt(this.state.type)?(e.imported=u,e.importKind=d,e.local=this.cloneIdentifier(u)):(e.imported=o,e.importKind=null,e.local=this.parseIdentifier())}else{if(d!==null&&dt(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=d;else{if(r)throw this.raise(b.ImportBindingIsString,e,{importName:o.value});e.imported=o,e.importKind=null}this.eatContextual(93)?e.local=this.parseIdentifier():(c=!0,e.local=this.cloneIdentifier(e.imported))}let l=Lf(e);return i&&l&&this.raise(V.ImportTypeShorthandOnlyInPureImport,e),(i||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),c&&!i&&!l&&this.checkReservedWord(e.local.name,e.loc.start,!0,!0),this.finishImportSpecifier(e,"ImportSpecifier")}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseFunctionParams(e,r){let i=e.kind;i!=="get"&&i!=="set"&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){if(this.match(14)){let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=i}return super.parseAsyncArrowFromCallExpression(e,r)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,r){var i;let s=null,a;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(s=this.state.clone(),a=this.tryParse(()=>super.parseMaybeAssign(e,r),s),!a.error)return a.node;let{context:c}=this.state,l=c[c.length-1];(l===ie.j_oTag||l===ie.j_expr)&&c.pop()}if((i=a)!=null&&i.error||this.match(47)){var o,d;s=s||this.state.clone();let c,l=this.tryParse(p=>{var f;c=this.flowParseTypeParameterDeclaration();let h=this.forwardNoArrowParamsConversionAt(c,()=>{let g=super.parseMaybeAssign(e,r);return this.resetStartLocationFromNode(g,c),g});(f=h.extra)!=null&&f.parenthesized&&p();let m=this.maybeUnwrapTypeCastExpression(h);return m.type!=="ArrowFunctionExpression"&&p(),m.typeParameters=c,this.resetStartLocationFromNode(m,c),h},s),u=null;if(l.node&&this.maybeUnwrapTypeCastExpression(l.node).type==="ArrowFunctionExpression"){if(!l.error&&!l.aborted)return l.node.async&&this.raise(V.UnexpectedTypeParameterBeforeAsyncArrowFunction,c),l.node;u=l.node}if((o=a)!=null&&o.node)return this.state=a.failState,a.node;if(u)return this.state=l.failState,u;throw(d=a)!=null&&d.thrown?a.error:l.thrown?l.error:this.raise(V.UnexpectedTokenAfterTypeParameter,c)}return super.parseMaybeAssign(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(()=>{let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let s=this.startNode();return[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),s});if(r.thrown)return null;r.error&&(this.state=r.failState),e.returnType=r.node.typeAnnotation?this.finishNode(r.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,r){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=r:super.setArrowFunctionParameters(e,r)}checkParams(e,r,i,s=!0){if(!(i&&this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start)))){for(let a=0;a<e.params.length;a++)this.isThisParam(e.params[a])&&a>0&&this.raise(V.ThisParamMustBeFirst,e.params[a]);super.checkParams(e,r,i,s)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,r,i){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.includes(r.index)){this.next();let s=this.startNodeAt(r);s.callee=e,s.arguments=super.parseCallExpressionArguments(),e=this.finishNode(s,"CallExpression")}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let s=this.state.clone(),a=this.tryParse(d=>this.parseAsyncArrowWithTypeParameters(r)||d(),s);if(!a.error&&!a.aborted)return a.node;let o=this.tryParse(()=>super.parseSubscripts(e,r,i),s);if(o.node&&!o.error)return o.node;if(a.node)return this.state=a.failState,a.node;if(o.node)return this.state=o.failState,o.node;throw a.error||o.error}return super.parseSubscripts(e,r,i)}parseSubscript(e,r,i,s){if(this.match(18)&&this.isLookaheadToken_lt()){if(s.optionalChainMember=!0,i)return s.stop=!0,e;this.next();let a=this.startNodeAt(r);return a.callee=e,a.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),a.arguments=this.parseCallExpressionArguments(),a.optional=!0,this.finishCallExpression(a,!0)}else if(!i&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){let a=this.startNodeAt(r);a.callee=e;let o=this.tryParse(()=>(a.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),a.arguments=super.parseCallExpressionArguments(),s.optionalChainMember&&(a.optional=!1),this.finishCallExpression(a,s.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,r,i,s)}parseNewCallee(e){super.parseNewCallee(e);let r=null;this.shouldParseTypes()&&this.match(47)&&(r=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=r}parseAsyncArrowWithTypeParameters(e){let r=this.startNodeAt(e);if(this.parseFunctionParams(r,!1),!!this.parseArrow(r))return super.parseArrowExpression(r,void 0,!0)}readToken_mult_modulo(e){let r=this.input.charCodeAt(this.state.pos+1);if(e===42&&r===47&&this.state.hasFlowComment){this.state.hasFlowComment=!1,this.state.pos+=2,this.nextToken();return}super.readToken_mult_modulo(e)}readToken_pipe_amp(e){let r=this.input.charCodeAt(this.state.pos+1);if(e===124&&r===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e)}parseTopLevel(e,r){let i=super.parseTopLevel(e,r);return this.state.hasFlowComment&&this.raise(V.UnterminatedFlowComment,this.state.curPosition()),i}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(V.NestedFlowComment,this.state.startLoc);this.hasFlowCommentCompletion();let e=this.skipFlowComment();e&&(this.state.pos+=e,this.state.hasFlowComment=!0);return}return super.skipBlockComment(this.state.hasFlowComment?"*-/":"*/")}skipFlowComment(){let{pos:e}=this.state,r=2;for(;[32,9].includes(this.input.charCodeAt(e+r));)r++;let i=this.input.charCodeAt(r+e),s=this.input.charCodeAt(r+e+1);return i===58&&s===58?r+2:this.input.slice(r+e,r+e+12)==="flow-include"?r+12:i===58&&s!==58?r:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:r,memberName:i}){this.raise(V.EnumBooleanMemberNotInitialized,e,{memberName:i,enumName:r})}flowEnumErrorInvalidMemberInitializer(e,r){return this.raise(r.explicitType?r.explicitType==="symbol"?V.EnumInvalidMemberInitializerSymbolType:V.EnumInvalidMemberInitializerPrimaryType:V.EnumInvalidMemberInitializerUnknownType,e,r)}flowEnumErrorNumberMemberNotInitialized(e,r){this.raise(V.EnumNumberMemberNotInitialized,e,r)}flowEnumErrorStringMemberInconsistentlyInitialized(e,r){this.raise(V.EnumStringMemberInconsistentlyInitialized,e,r)}flowEnumMemberInit(){let e=this.state.startLoc,r=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{let i=this.parseNumericLiteral(this.state.value);return r()?{type:"number",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 134:{let i=this.parseStringLiteral(this.state.value);return r()?{type:"string",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 85:case 86:{let i=this.parseBooleanLiteral(this.match(85));return r()?{type:"boolean",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,r=this.parseIdentifier(!0),i=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return{id:r,init:i}}flowEnumCheckExplicitTypeMismatch(e,r,i){let{explicitType:s}=r;s!==null&&s!==i&&this.flowEnumErrorInvalidMemberInitializer(e,r)}flowEnumMembers({enumName:e,explicitType:r}){let i=new Set,s={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},a=!1;for(;!this.match(8);){if(this.eat(21)){a=!0;break}let o=this.startNode(),{id:d,init:c}=this.flowEnumMemberRaw(),l=d.name;if(l==="")continue;/^[a-z]/.test(l)&&this.raise(V.EnumInvalidMemberName,d,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:e}),i.has(l)&&this.raise(V.EnumDuplicateMemberName,d,{memberName:l,enumName:e}),i.add(l);let u={enumName:e,explicitType:r,memberName:l};switch(o.id=d,c.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,s.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,s.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,s.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(r){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:s.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:s,hasUnknownMembers:a}}flowEnumStringMembers(e,r,{enumName:i}){if(e.length===0)return r;if(r.length===0)return e;if(r.length>e.length){for(let s of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return r}else{for(let s of r)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!se(this.state.type))throw this.raise(V.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});let{value:r}=this.state;return this.next(),r!=="boolean"&&r!=="number"&&r!=="string"&&r!=="symbol"&&this.raise(V.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:r}),r}flowEnumBody(e,r){let i=r.name,s=r.loc.start,a=this.flowEnumParseExplicitType({enumName:i});this.expect(5);let{members:o,hasUnknownMembers:d}=this.flowEnumMembers({enumName:i,explicitType:a});switch(e.hasUnknownMembers=d,a){case"boolean":return e.explicitType=!0,e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody");case"number":return e.explicitType=!0,e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody");case"string":return e.explicitType=!0,e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");case"symbol":return e.members=o.defaultedMembers,this.expect(8),this.finishNode(e,"EnumSymbolBody");default:{let c=()=>(e.members=[],this.expect(8),this.finishNode(e,"EnumStringBody"));e.explicitType=!1;let l=o.booleanMembers.length,u=o.numberMembers.length,p=o.stringMembers.length,f=o.defaultedMembers.length;if(!l&&!u&&!p&&!f)return c();if(!l&&!u)return e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!p&&l>=f){for(let h of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody")}else if(!l&&!p&&u>=f){for(let h of o.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(V.EnumInconsistentMemberValues,s,{enumName:i}),c()}}}flowParseEnumDeclaration(e){let r=this.parseIdentifier();return e.id=r,e.body=this.flowEnumBody(this.startNode(),r),this.finishNode(e,"EnumDeclaration")}jsxParseOpeningElementAfterName(e){return this.shouldParseTypes()&&(this.match(47)||this.match(51))&&(e.typeArguments=this.flowParseTypeParameterInstantiationInExpression()),super.jsxParseOpeningElementAfterName(e)}isLookaheadToken_lt(){let e=this.nextTokenStart();if(this.input.charCodeAt(e)===60){let r=this.input.charCodeAt(e+1);return r!==60&&r!==61}return!1}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}maybeUnwrapTypeCastExpression(e){return e.type==="TypeCastExpression"?e.expression:e}},rR={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02C6",tilde:"\u02DC",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203A",oline:"\u203E",frasl:"\u2044",euro:"\u20AC",image:"\u2111",weierp:"\u2118",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},iR=/\r\n|[\r\n\u2028\u2029]/,Js=new RegExp(iR.source,"g");function ar(t){switch(t){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Mf(t,n,e){for(let r=n;r<e;r++)if(ar(t.charCodeAt(r)))return!0;return!1}var Vd=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,Ud=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function sR(t){switch(t){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}var yn=ot`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:t})=>`Expected corresponding JSX closing tag for <${t}>.`,MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:({unexpected:t,HTMLEntity:n})=>`Unexpected token \`${t}\`. Did you mean \`${n}\` or \`{'${t}'}\`?`,UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"});function Jt(t){return t?t.type==="JSXOpeningFragment"||t.type==="JSXClosingFragment":!1}function sr(t){if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXNamespacedName")return t.namespace.name+":"+t.name.name;if(t.type==="JSXMemberExpression")return sr(t.object)+"."+sr(t.property);throw new Error("Node had unexpected type: "+t.type)}var aR=t=>class extends t{jsxReadToken(){let e="",r=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(yn.UnterminatedJsxContent,this.state.startLoc);let i=this.input.charCodeAt(this.state.pos);switch(i){case 60:case 123:if(this.state.pos===this.state.start){i===60&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(143)):super.getTokenFromCode(i);return}e+=this.input.slice(r,this.state.pos),this.finishToken(142,e);return;case 38:e+=this.input.slice(r,this.state.pos),e+=this.jsxReadEntity(),r=this.state.pos;break;default:ar(i)?(e+=this.input.slice(r,this.state.pos),e+=this.jsxReadNewLine(!0),r=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){let r=this.input.charCodeAt(this.state.pos),i;return++this.state.pos,r===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,i=e?`
5
+ - Did you mean \`import { "${t}" as foo }\`?`,ImportCallArity:"`import()` requires exactly one or two arguments.",ImportCallNotNewExpression:"Cannot use new with import(...).",ImportCallSpreadArgument:"`...` is not allowed in `import()`.",ImportJSONBindingNotDefault:"A JSON module can only be imported with `default`.",ImportReflectionHasAssertion:"`import module x` cannot have assertions.",ImportReflectionNotBinding:'Only `import module x from "./module"` is valid.',IncompatibleRegExpUVFlags:"The 'u' and 'v' regular expression flags cannot be enabled at the same time.",InvalidBigIntLiteral:"Invalid BigIntLiteral.",InvalidCodePoint:"Code point out of bounds.",InvalidCoverDiscardElement:"'void' must be followed by an expression when not used in a binding position.",InvalidCoverInitializedName:"Invalid shorthand property initializer.",InvalidDecimal:"Invalid decimal.",InvalidDigit:({radix:t})=>`Expected number in radix ${t}.`,InvalidEscapeSequence:"Bad character escape sequence.",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template.",InvalidEscapedReservedWord:({reservedWord:t})=>`Escape sequence in keyword ${t}.`,InvalidIdentifier:({identifierName:t})=>`Invalid identifier ${t}.`,InvalidLhs:({ancestor:t})=>`Invalid left-hand side in ${Xs(t)}.`,InvalidLhsBinding:({ancestor:t})=>`Binding invalid left-hand side in ${Xs(t)}.`,InvalidLhsOptionalChaining:({ancestor:t})=>`Invalid optional chaining in the left-hand side of ${Xs(t)}.`,InvalidNumber:"Invalid number.",InvalidOrMissingExponent:"Floating-point numbers require a valid exponent after the 'e'.",InvalidOrUnexpectedToken:({unexpected:t})=>`Unexpected character '${t}'.`,InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern.",InvalidPrivateFieldResolution:({identifierName:t})=>`Private name #${t} is not defined.`,InvalidPropertyBindingPattern:"Binding member expression.",InvalidRecordProperty:"Only properties and spread elements are allowed in record definitions.",InvalidRestAssignmentPattern:"Invalid rest operator's argument.",LabelRedeclaration:({labelName:t})=>`Label '${t}' is already declared.`,LetInLexicalBinding:"'let' is disallowed as a lexically bound name.",LineTerminatorBeforeArrow:"No line break is allowed before '=>'.",MalformedRegExpFlags:"Invalid regular expression flag.",MissingClassName:"A class name is required.",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingSemicolon:"Missing semicolon.",MissingPlugin:({missingPlugin:t})=>`This experimental syntax requires enabling the parser plugin: ${t.map(n=>JSON.stringify(n)).join(", ")}.`,MissingOneOfPlugins:({missingPlugin:t})=>`This experimental syntax requires enabling one of the following parser plugin(s): ${t.map(n=>JSON.stringify(n)).join(", ")}.`,MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX.",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators.",ModuleAttributeDifferentFromType:"The only accepted module attribute is `type`.",ModuleAttributeInvalidValue:"Only string literals are allowed as module attribute values.",ModuleAttributesWithDuplicateKeys:({key:t})=>`Duplicate key "${t}" is not allowed in module attributes.`,ModuleExportNameHasLoneSurrogate:({surrogateCharCode:t})=>`An export name cannot include a lone surrogate, found '\\u${t.toString(16)}'.`,ModuleExportUndefined:({localName:t})=>`Export '${t}' is not defined.`,MultipleDefaultsInSwitch:"Multiple default clauses.",NewlineAfterThrow:"Illegal newline after throw.",NoCatchOrFinally:"Missing catch or finally clause.",NumberIdentifier:"Identifier directly after number.",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",ObsoleteAwaitStar:"'await*' has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"Constructors in/after an Optional Chain are not allowed.",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain.",OverrideOnConstructor:"'override' modifier cannot appear on a constructor declaration.",ParamDupe:"Argument name clash.",PatternHasAccessor:"Object pattern can't contain getter or setter.",PatternHasMethod:"Object pattern can't contain methods.",PrivateInExpectedIn:({identifierName:t})=>`Private names are only allowed in property accesses (\`obj.#${t}\`) or in \`in\` expressions (\`#${t} in obj\`).`,PrivateNameRedeclaration:({identifierName:t})=>`Duplicate private name #${t}.`,RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",RecordNoProto:"'__proto__' is not allowed in Record expressions.",RestTrailingComma:"Unexpected trailing comma after rest element.",SloppyFunction:"In non-strict mode code, functions can only be declared at top level or inside a block.",SloppyFunctionAnnexB:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",SourcePhaseImportRequiresDefault:'Only `import source x from "./module"` is valid.',StaticPrototype:"Classes may not have static property named prototype.",SuperCallNotNewExpression:"Cannot use new with super(...).",SuperNotAllowed:"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super.",TrailingDecorator:"Decorators must be attached to a class element.",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder.",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',UnexpectedDigitAfterHash:"Unexpected digit after hash token.",UnexpectedImportExport:"'import' and 'export' may only appear at the top level.",UnexpectedKeyword:({keyword:t})=>`Unexpected keyword '${t}'.`,UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration.",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context.",UnexpectedNewTarget:"`new.target` can only be used in functions or class properties.",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits.",UnexpectedPrivateField:"Unexpected private name.",UnexpectedReservedWord:({reservedWord:t})=>`Unexpected reserved word '${t}'.`,UnexpectedSuper:"'super' is only allowed in object methods and classes.",UnexpectedToken:({expected:t,unexpected:n})=>`Unexpected token${n?` '${n}'.`:""}${t?`, expected "${t}"`:""}`,UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnexpectedUsingDeclaration:"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",UnexpectedVoidPattern:"Unexpected void binding.",UnsupportedDecoratorExport:"A decorated export must export a class declaration.",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"`import` can only be used in `import()` or `import.meta`.",UnsupportedMetaProperty:({target:t,onlyValidPropertyName:n})=>`The only valid meta property for ${t} is ${t}.${n}.`,UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters.",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties.",UnsupportedSuper:"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",UnterminatedComment:"Unterminated comment.",UnterminatedRegExp:"Unterminated regular expression.",UnterminatedString:"Unterminated string constant.",UnterminatedTemplate:"Unterminated template.",UsingDeclarationExport:"Using declaration cannot be exported.",UsingDeclarationHasBindingPattern:"Using declaration cannot have destructuring patterns.",VarRedeclaration:({identifierName:t})=>`Identifier '${t}' has already been declared.`,VoidPatternCatchClauseParam:"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",VoidPatternInitializer:"A void binding may not have an initializer.",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator.",YieldInParameter:"Yield expression is not allowed in formal parameters.",YieldNotInGeneratorFunction:"'yield' is only allowed within generator functions.",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0."},wk={StrictDelete:"Deleting local variable in strict mode.",StrictEvalArguments:({referenceName:t})=>`Assigning to '${t}' in strict mode.`,StrictEvalArgumentsBinding:({bindingName:t})=>`Binding '${t}' in strict mode.`,StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block.",StrictNumericEscape:"The only valid numeric escape in strict mode is '\\0'.",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode.",StrictWith:"'with' in strict mode."},bk={ParseExpressionEmptyInput:"Unexpected parseExpression() input: The input is empty or contains only comments.",ParseExpressionExpectsEOF:({unexpected:t})=>`Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(t)}\`.`},xk=new Set(["ArrowFunctionExpression","AssignmentExpression","ConditionalExpression","YieldExpression"]),vk=Object.assign({PipeBodyIsTighter:"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",PipeTopicRequiresHackPipes:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',PipeTopicUnbound:"Topic reference is unbound; it must be inside a pipe body.",PipeTopicUnconfiguredToken:({token:t})=>`Invalid topic token ${t}. In order to use ${t} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${t}" }.`,PipeTopicUnused:"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",PipeUnparenthesizedBody:({type:t})=>`Hack-style pipe body cannot be an unparenthesized ${Xs({type:t})}; please wrap it in parentheses.`},{PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression.",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression.",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference.",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding.",PrimaryTopicRequiresSmartPipeline:'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'}),kk={UnsupportedBind:"Binding should be performed on object property.",UnsupportedBindRHS:"The right-hand side of binding can not be super or import."},Rk=["message"];function Of(t,n,e){Object.defineProperty(t,n,{enumerable:!1,configurable:!0,value:e})}function Ik({toMessage:t,code:n,reasonCode:e,syntaxPlugin:r}){let i=e==="MissingPlugin"||e==="MissingOneOfPlugins",s={AccessorCannotDeclareThisParameter:"AccesorCannotDeclareThisParameter",AccessorCannotHaveTypeParameters:"AccesorCannotHaveTypeParameters",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",SetAccessorCannotHaveOptionalParameter:"SetAccesorCannotHaveOptionalParameter",SetAccessorCannotHaveRestParameter:"SetAccesorCannotHaveRestParameter",SetAccessorCannotHaveReturnType:"SetAccesorCannotHaveReturnType"};return s[e]&&(e=s[e]),function a(o,d){let c=new SyntaxError;return c.code=n,c.reasonCode=e,c.loc=o,c.pos=o.index,c.syntaxPlugin=r,i&&(c.missingPlugin=d.missingPlugin),Of(c,"clone",function(u={}){var p;let{line:f,column:h,index:m}=(p=u.loc)!=null?p:o;return a(new xt(f,h,m),Object.assign({},d,u.details))}),Of(c,"details",d),Object.defineProperty(c,"message",{configurable:!0,get(){let l=`${t(d)} (${o.line}:${o.column})`;return this.message=l,l},set(l){Object.defineProperty(this,"message",{value:l,writable:!0})}}),c}}function ot(t,n){if(Array.isArray(t))return r=>ot(r,t[0]);let e={};for(let r of Object.keys(t)){let i=t[r],s=typeof i=="string"?{message:()=>i}:typeof i=="function"?{message:i}:i,{message:a}=s,o=mk(s,Rk),d=typeof a=="string"?()=>a:a;e[r]=Ik(Object.assign({code:"BABEL_PARSER_SYNTAX_ERROR",reasonCode:r,toMessage:d},n?{syntaxPlugin:n}:{},o))}return e}var b=Object.assign({},ot(yk),ot(gk),ot(wk),ot(bk),ot`pipelineOperator`(vk),ot`functionBind`(kk));function Ak(){return{sourceType:"script",sourceFilename:void 0,startIndex:0,startColumn:0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowNewTargetOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,allowYieldOutsideFunction:!1,plugins:[],strictMode:void 0,ranges:!1,tokens:!1,createImportExpressions:!1,createParenthesizedExpressions:!1,errorRecovery:!1,attachComment:!0,annexB:!0}}function Tk(t){let n=Ak();if(t==null)return n;if(t.annexB!=null&&t.annexB!==!1)throw new Error("The `annexB` option can only be set to `false`.");for(let e of Object.keys(n))t[e]!=null&&(n[e]=t[e]);if(n.startLine===1)t.startIndex==null&&n.startColumn>0?n.startIndex=n.startColumn:t.startColumn==null&&n.startIndex>0&&(n.startColumn=n.startIndex);else if((t.startColumn==null||t.startIndex==null)&&t.startIndex!=null)throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");if(n.sourceType==="commonjs"){if(t.allowAwaitOutsideFunction!=null)throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");if(t.allowReturnOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");if(t.allowNewTargetOutsideFunction!=null)throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.")}return n}var{defineProperty:Pk}=Object,$f=(t,n)=>{t&&Pk(t,n,{enumerable:!1,value:t[n]})};function ui(t){return $f(t.loc.start,"index"),$f(t.loc.end,"index"),t}var Sk=t=>class extends t{parse(){let e=ui(super.parse());return this.optionFlags&256&&(e.tokens=e.tokens.map(ui)),e}parseRegExpLiteral({pattern:e,flags:r}){let i=null;try{i=new RegExp(e,r)}catch{}let s=this.estreeParseLiteral(i);return s.regex={pattern:e,flags:r},s}parseBigIntLiteral(e){let r;try{r=BigInt(e)}catch{r=null}let i=this.estreeParseLiteral(r);return i.bigint=String(i.value||e),i}parseDecimalLiteral(e){let i=this.estreeParseLiteral(null);return i.decimal=String(i.value||e),i}estreeParseLiteral(e){return this.parseLiteral(e,"Literal")}parseStringLiteral(e){return this.estreeParseLiteral(e)}parseNumericLiteral(e){return this.estreeParseLiteral(e)}parseNullLiteral(){return this.estreeParseLiteral(null)}parseBooleanLiteral(e){return this.estreeParseLiteral(e)}estreeParseChainExpression(e,r){let i=this.startNodeAtNode(e);return i.expression=e,this.finishNodeAt(i,"ChainExpression",r)}directiveToStmt(e){let r=e.value;delete e.value,this.castNodeTo(r,"Literal"),r.raw=r.extra.raw,r.value=r.extra.expressionValue;let i=this.castNodeTo(e,"ExpressionStatement");return i.expression=r,i.directive=r.extra.rawValue,delete r.extra,i}fillOptionalPropertiesForTSESLint(e){}cloneEstreeStringLiteral(e){let{start:r,end:i,loc:s,range:a,raw:o,value:d}=e,c=Object.create(e.constructor.prototype);return c.type="Literal",c.start=r,c.end=i,c.loc=s,c.range=a,c.raw=o,c.value=d,c}initFunction(e,r){super.initFunction(e,r),e.expression=!1}checkDeclaration(e){e!=null&&this.isObjectProperty(e)?this.checkDeclaration(e.value):super.checkDeclaration(e)}getObjectOrClassMethodParams(e){return e.value.params}isValidDirective(e){var r;return e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&!((r=e.expression.extra)!=null&&r.parenthesized)}parseBlockBody(e,r,i,s,a){super.parseBlockBody(e,r,i,s,a);let o=e.directives.map(d=>this.directiveToStmt(d));e.body=o.concat(e.body),delete e.directives}parsePrivateName(){let e=super.parsePrivateName();return this.getPluginOption("estree","classFeatures")?this.convertPrivateNameToPrivateIdentifier(e):e}convertPrivateNameToPrivateIdentifier(e){let r=super.getPrivateNameSV(e);return delete e.id,e.name=r,this.castNodeTo(e,"PrivateIdentifier")}isPrivateName(e){return this.getPluginOption("estree","classFeatures")?e.type==="PrivateIdentifier":super.isPrivateName(e)}getPrivateNameSV(e){return this.getPluginOption("estree","classFeatures")?e.name:super.getPrivateNameSV(e)}parseLiteral(e,r){let i=super.parseLiteral(e,r);return i.raw=i.extra.raw,delete i.extra,i}parseFunctionBody(e,r,i=!1){super.parseFunctionBody(e,r,i),e.expression=e.body.type!=="BlockStatement"}parseMethod(e,r,i,s,a,o,d=!1){let c=this.startNode();c.kind=e.kind,c=super.parseMethod(c,r,i,s,a,o,d),delete c.kind;let{typeParameters:l}=e;l&&(delete e.typeParameters,c.typeParameters=l,this.resetStartLocationFromNode(c,l));let u=this.castNodeTo(c,"FunctionExpression");return e.value=u,o==="ClassPrivateMethod"&&(e.computed=!1),o==="ObjectMethod"?(e.kind==="method"&&(e.kind="init"),e.shorthand=!1,this.finishNode(e,"Property")):this.finishNode(e,"MethodDefinition")}nameIsConstructor(e){return e.type==="Literal"?e.value==="constructor":super.nameIsConstructor(e)}parseClassProperty(...e){let r=super.parseClassProperty(...e);return this.getPluginOption("estree","classFeatures")&&this.castNodeTo(r,"PropertyDefinition"),r}parseClassPrivateProperty(...e){let r=super.parseClassPrivateProperty(...e);return this.getPluginOption("estree","classFeatures")&&(this.castNodeTo(r,"PropertyDefinition"),r.computed=!1),r}parseClassAccessorProperty(e){let r=super.parseClassAccessorProperty(e);return this.getPluginOption("estree","classFeatures")&&(r.abstract&&this.hasPlugin("typescript")?(delete r.abstract,this.castNodeTo(r,"TSAbstractAccessorProperty")):this.castNodeTo(r,"AccessorProperty")),r}parseObjectProperty(e,r,i,s){let a=super.parseObjectProperty(e,r,i,s);return a&&(a.kind="init",this.castNodeTo(a,"Property")),a}finishObjectProperty(e){return e.kind="init",this.finishNode(e,"Property")}isValidLVal(e,r,i,s){return e==="Property"?"value":super.isValidLVal(e,r,i,s)}isAssignable(e,r){return e!=null&&this.isObjectProperty(e)?this.isAssignable(e.value,r):super.isAssignable(e,r)}toAssignable(e,r=!1){if(e!=null&&this.isObjectProperty(e)){let{key:i,value:s}=e;this.isPrivateName(i)&&this.classScope.usePrivateName(this.getPrivateNameSV(i),i.loc.start),this.toAssignable(s,r)}else super.toAssignable(e,r)}toAssignableObjectExpressionProp(e,r,i){e.type==="Property"&&(e.kind==="get"||e.kind==="set")?this.raise(b.PatternHasAccessor,e.key):e.type==="Property"&&e.method?this.raise(b.PatternHasMethod,e.key):super.toAssignableObjectExpressionProp(e,r,i)}finishCallExpression(e,r){let i=super.finishCallExpression(e,r);if(i.callee.type==="Import"){var s,a;this.castNodeTo(i,"ImportExpression"),i.source=i.arguments[0],i.options=(s=i.arguments[1])!=null?s:null,i.attributes=(a=i.arguments[1])!=null?a:null,delete i.arguments,delete i.callee}else i.type==="OptionalCallExpression"?this.castNodeTo(i,"CallExpression"):i.optional=!1;return i}toReferencedArguments(e){e.type!=="ImportExpression"&&super.toReferencedArguments(e)}parseExport(e,r){let i=this.state.lastTokStartLoc,s=super.parseExport(e,r);switch(s.type){case"ExportAllDeclaration":s.exported=null;break;case"ExportNamedDeclaration":s.specifiers.length===1&&s.specifiers[0].type==="ExportNamespaceSpecifier"&&(this.castNodeTo(s,"ExportAllDeclaration"),s.exported=s.specifiers[0].exported,delete s.specifiers);case"ExportDefaultDeclaration":{var a;let{declaration:o}=s;o?.type==="ClassDeclaration"&&((a=o.decorators)==null?void 0:a.length)>0&&o.start===s.start&&this.resetStartLocation(s,i)}break}return s}stopParseSubscript(e,r){let i=super.stopParseSubscript(e,r);return r.optionalChainMember?this.estreeParseChainExpression(i,e.loc.end):i}parseMember(e,r,i,s,a){let o=super.parseMember(e,r,i,s,a);return o.type==="OptionalMemberExpression"?this.castNodeTo(o,"MemberExpression"):o.optional=!1,o}isOptionalMemberExpression(e){return e.type==="ChainExpression"?e.expression.type==="MemberExpression":super.isOptionalMemberExpression(e)}hasPropertyAsPrivateName(e){return e.type==="ChainExpression"&&(e=e.expression),super.hasPropertyAsPrivateName(e)}isObjectProperty(e){return e.type==="Property"&&e.kind==="init"&&!e.method}isObjectMethod(e){return e.type==="Property"&&(e.method||e.kind==="get"||e.kind==="set")}castNodeTo(e,r){let i=super.castNodeTo(e,r);return this.fillOptionalPropertiesForTSESLint(i),i}cloneIdentifier(e){let r=super.cloneIdentifier(e);return this.fillOptionalPropertiesForTSESLint(r),r}cloneStringLiteral(e){return e.type==="Literal"?this.cloneEstreeStringLiteral(e):super.cloneStringLiteral(e)}finishNodeAt(e,r,i){return ui(super.finishNodeAt(e,r,i))}finishNode(e,r){let i=super.finishNode(e,r);return this.fillOptionalPropertiesForTSESLint(i),i}resetStartLocation(e,r){super.resetStartLocation(e,r),ui(e)}resetEndLocation(e,r=this.state.lastTokEndLoc){super.resetEndLocation(e,r),ui(e)}},gn=class{constructor(n,e){this.token=void 0,this.preserveSpace=void 0,this.token=n,this.preserveSpace=!!e}},ie={brace:new gn("{"),j_oTag:new gn("<tag"),j_cTag:new gn("</tag"),j_expr:new gn("<tag>...</tag>",!0)};ie.template=new gn("`",!0);var W=!0,O=!0,zd=!0,pi=!0,Wt=!0,Ek=!0,ea=class{constructor(n,e={}){this.label=void 0,this.keyword=void 0,this.beforeExpr=void 0,this.startsExpr=void 0,this.rightAssociative=void 0,this.isLoop=void 0,this.isAssign=void 0,this.prefix=void 0,this.postfix=void 0,this.binop=void 0,this.label=n,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop!=null?e.binop:null,this.updateContext=null}},mc=new Map;function Z(t,n={}){n.keyword=t;let e=z(t,n);return mc.set(t,e),e}function Me(t,n){return z(t,{beforeExpr:W,binop:n})}var yi=-1,Ct=[],yc=[],gc=[],wc=[],bc=[],xc=[];function z(t,n={}){var e,r,i,s;return++yi,yc.push(t),gc.push((e=n.binop)!=null?e:-1),wc.push((r=n.beforeExpr)!=null?r:!1),bc.push((i=n.startsExpr)!=null?i:!1),xc.push((s=n.prefix)!=null?s:!1),Ct.push(new ea(t,n)),yi}function J(t,n={}){var e,r,i,s;return++yi,mc.set(t,yi),yc.push(t),gc.push((e=n.binop)!=null?e:-1),wc.push((r=n.beforeExpr)!=null?r:!1),bc.push((i=n.startsExpr)!=null?i:!1),xc.push((s=n.prefix)!=null?s:!1),Ct.push(new ea("name",n)),yi}var Ck={bracketL:z("[",{beforeExpr:W,startsExpr:O}),bracketHashL:z("#[",{beforeExpr:W,startsExpr:O}),bracketBarL:z("[|",{beforeExpr:W,startsExpr:O}),bracketR:z("]"),bracketBarR:z("|]"),braceL:z("{",{beforeExpr:W,startsExpr:O}),braceBarL:z("{|",{beforeExpr:W,startsExpr:O}),braceHashL:z("#{",{beforeExpr:W,startsExpr:O}),braceR:z("}"),braceBarR:z("|}"),parenL:z("(",{beforeExpr:W,startsExpr:O}),parenR:z(")"),comma:z(",",{beforeExpr:W}),semi:z(";",{beforeExpr:W}),colon:z(":",{beforeExpr:W}),doubleColon:z("::",{beforeExpr:W}),dot:z("."),question:z("?",{beforeExpr:W}),questionDot:z("?."),arrow:z("=>",{beforeExpr:W}),template:z("template"),ellipsis:z("...",{beforeExpr:W}),backQuote:z("`",{startsExpr:O}),dollarBraceL:z("${",{beforeExpr:W,startsExpr:O}),templateTail:z("...`",{startsExpr:O}),templateNonTail:z("...${",{beforeExpr:W,startsExpr:O}),at:z("@"),hash:z("#",{startsExpr:O}),interpreterDirective:z("#!..."),eq:z("=",{beforeExpr:W,isAssign:pi}),assign:z("_=",{beforeExpr:W,isAssign:pi}),slashAssign:z("_=",{beforeExpr:W,isAssign:pi}),xorAssign:z("_=",{beforeExpr:W,isAssign:pi}),moduloAssign:z("_=",{beforeExpr:W,isAssign:pi}),incDec:z("++/--",{prefix:Wt,postfix:Ek,startsExpr:O}),bang:z("!",{beforeExpr:W,prefix:Wt,startsExpr:O}),tilde:z("~",{beforeExpr:W,prefix:Wt,startsExpr:O}),doubleCaret:z("^^",{startsExpr:O}),doubleAt:z("@@",{startsExpr:O}),pipeline:Me("|>",0),nullishCoalescing:Me("??",1),logicalOR:Me("||",1),logicalAND:Me("&&",2),bitwiseOR:Me("|",3),bitwiseXOR:Me("^",4),bitwiseAND:Me("&",5),equality:Me("==/!=/===/!==",6),lt:Me("</>/<=/>=",7),gt:Me("</>/<=/>=",7),relational:Me("</>/<=/>=",7),bitShift:Me("<</>>/>>>",8),bitShiftL:Me("<</>>/>>>",8),bitShiftR:Me("<</>>/>>>",8),plusMin:z("+/-",{beforeExpr:W,binop:9,prefix:Wt,startsExpr:O}),modulo:z("%",{binop:10,startsExpr:O}),star:z("*",{binop:10}),slash:Me("/",10),exponent:z("**",{beforeExpr:W,binop:11,rightAssociative:!0}),_in:Z("in",{beforeExpr:W,binop:7}),_instanceof:Z("instanceof",{beforeExpr:W,binop:7}),_break:Z("break"),_case:Z("case",{beforeExpr:W}),_catch:Z("catch"),_continue:Z("continue"),_debugger:Z("debugger"),_default:Z("default",{beforeExpr:W}),_else:Z("else",{beforeExpr:W}),_finally:Z("finally"),_function:Z("function",{startsExpr:O}),_if:Z("if"),_return:Z("return",{beforeExpr:W}),_switch:Z("switch"),_throw:Z("throw",{beforeExpr:W,prefix:Wt,startsExpr:O}),_try:Z("try"),_var:Z("var"),_const:Z("const"),_with:Z("with"),_new:Z("new",{beforeExpr:W,startsExpr:O}),_this:Z("this",{startsExpr:O}),_super:Z("super",{startsExpr:O}),_class:Z("class",{startsExpr:O}),_extends:Z("extends",{beforeExpr:W}),_export:Z("export"),_import:Z("import",{startsExpr:O}),_null:Z("null",{startsExpr:O}),_true:Z("true",{startsExpr:O}),_false:Z("false",{startsExpr:O}),_typeof:Z("typeof",{beforeExpr:W,prefix:Wt,startsExpr:O}),_void:Z("void",{beforeExpr:W,prefix:Wt,startsExpr:O}),_delete:Z("delete",{beforeExpr:W,prefix:Wt,startsExpr:O}),_do:Z("do",{isLoop:zd,beforeExpr:W}),_for:Z("for",{isLoop:zd}),_while:Z("while",{isLoop:zd}),_as:J("as",{startsExpr:O}),_assert:J("assert",{startsExpr:O}),_async:J("async",{startsExpr:O}),_await:J("await",{startsExpr:O}),_defer:J("defer",{startsExpr:O}),_from:J("from",{startsExpr:O}),_get:J("get",{startsExpr:O}),_let:J("let",{startsExpr:O}),_meta:J("meta",{startsExpr:O}),_of:J("of",{startsExpr:O}),_sent:J("sent",{startsExpr:O}),_set:J("set",{startsExpr:O}),_source:J("source",{startsExpr:O}),_static:J("static",{startsExpr:O}),_using:J("using",{startsExpr:O}),_yield:J("yield",{startsExpr:O}),_asserts:J("asserts",{startsExpr:O}),_checks:J("checks",{startsExpr:O}),_exports:J("exports",{startsExpr:O}),_global:J("global",{startsExpr:O}),_implements:J("implements",{startsExpr:O}),_intrinsic:J("intrinsic",{startsExpr:O}),_infer:J("infer",{startsExpr:O}),_is:J("is",{startsExpr:O}),_mixins:J("mixins",{startsExpr:O}),_proto:J("proto",{startsExpr:O}),_require:J("require",{startsExpr:O}),_satisfies:J("satisfies",{startsExpr:O}),_keyof:J("keyof",{startsExpr:O}),_readonly:J("readonly",{startsExpr:O}),_unique:J("unique",{startsExpr:O}),_abstract:J("abstract",{startsExpr:O}),_declare:J("declare",{startsExpr:O}),_enum:J("enum",{startsExpr:O}),_module:J("module",{startsExpr:O}),_namespace:J("namespace",{startsExpr:O}),_interface:J("interface",{startsExpr:O}),_type:J("type",{startsExpr:O}),_opaque:J("opaque",{startsExpr:O}),name:z("name",{startsExpr:O}),placeholder:z("%%",{startsExpr:O}),string:z("string",{startsExpr:O}),num:z("num",{startsExpr:O}),bigint:z("bigint",{startsExpr:O}),decimal:z("decimal",{startsExpr:O}),regexp:z("regexp",{startsExpr:O}),privateName:z("#name",{startsExpr:O}),eof:z("eof"),jsxName:z("jsxName"),jsxText:z("jsxText",{beforeExpr:W}),jsxTagStart:z("jsxTagStart",{startsExpr:O}),jsxTagEnd:z("jsxTagEnd")};function se(t){return t>=93&&t<=133}function Nk(t){return t<=92}function dt(t){return t>=58&&t<=133}function qf(t){return t>=58&&t<=137}function Ok(t){return wc[t]}function hi(t){return bc[t]}function $k(t){return t>=29&&t<=33}function Df(t){return t>=129&&t<=131}function Dk(t){return t>=90&&t<=92}function vc(t){return t>=58&&t<=92}function Lk(t){return t>=39&&t<=59}function Mk(t){return t===34}function _k(t){return xc[t]}function jk(t){return t>=121&&t<=123}function Fk(t){return t>=124&&t<=130}function Yt(t){return yc[t]}function Qs(t){return gc[t]}function Bk(t){return t===57}function ta(t){return t>=24&&t<=25}function Et(t){return Ct[t]}Ct[8].updateContext=t=>{t.pop()};Ct[5].updateContext=Ct[7].updateContext=Ct[23].updateContext=t=>{t.push(ie.brace)};Ct[22].updateContext=t=>{t[t.length-1]===ie.template?t.pop():t.push(ie.template)};Ct[143].updateContext=t=>{t.push(ie.j_expr,ie.j_oTag)};var kc="\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC",Gf="\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65",Hk=new RegExp("["+kc+"]"),zk=new RegExp("["+kc+Gf+"]");kc=Gf=null;var Kf=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],Vk=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239];function Wd(t,n){let e=65536;for(let r=0,i=n.length;r<i;r+=2){if(e+=n[r],e>t)return!1;if(e+=n[r+1],e>=t)return!0}return!1}function bt(t){return t<65?t===36:t<=90?!0:t<97?t===95:t<=122?!0:t<=65535?t>=170&&Hk.test(String.fromCharCode(t)):Wd(t,Kf)}function wn(t){return t<48?t===36:t<58?!0:t<65?!1:t<=90?!0:t<97?t===95:t<=122?!0:t<=65535?t>=170&&zk.test(String.fromCharCode(t)):Wd(t,Kf)||Wd(t,Vk)}var Rc={keyword:["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"],strict:["implements","interface","let","package","private","protected","public","static","yield"],strictBind:["eval","arguments"]},Uk=new Set(Rc.keyword),qk=new Set(Rc.strict),Gk=new Set(Rc.strictBind);function Wf(t,n){return n&&t==="await"||t==="enum"}function Jf(t,n){return Wf(t,n)||qk.has(t)}function Yf(t){return Gk.has(t)}function Xf(t,n){return Jf(t,n)||Yf(t)}function Kk(t){return Uk.has(t)}function Wk(t,n,e){return t===64&&n===64&&bt(e)}var Jk=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete","implements","interface","let","package","private","protected","public","static","yield","eval","arguments","enum","await"]);function Yk(t){return Jk.has(t)}var gi=class{constructor(n){this.flags=0,this.names=new Map,this.firstLexicalName="",this.flags=n}},wi=class{constructor(n,e){this.parser=void 0,this.scopeStack=[],this.inModule=void 0,this.undefinedExports=new Map,this.parser=n,this.inModule=e}get inTopLevel(){return(this.currentScope().flags&1)>0}get inFunction(){return(this.currentVarScopeFlags()&2)>0}get allowSuper(){return(this.currentThisScopeFlags()&16)>0}get allowDirectSuper(){return(this.currentThisScopeFlags()&32)>0}get allowNewTarget(){return(this.currentThisScopeFlags()&512)>0}get inClass(){return(this.currentThisScopeFlags()&64)>0}get inClassAndNotInNonArrowFunction(){let n=this.currentThisScopeFlags();return(n&64)>0&&(n&2)===0}get inStaticBlock(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&128)return!0;if(e&1731)return!1}}get inNonArrowFunction(){return(this.currentThisScopeFlags()&2)>0}get inBareCaseStatement(){return(this.currentScope().flags&256)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(n){return new gi(n)}enter(n){this.scopeStack.push(this.createScope(n))}exit(){return this.scopeStack.pop().flags}treatFunctionsAsVarInScope(n){return!!(n.flags&130||!this.parser.inModule&&n.flags&1)}declareName(n,e,r){let i=this.currentScope();if(e&8||e&16){this.checkRedeclarationInScope(i,n,e,r);let s=i.names.get(n)||0;e&16?s=s|4:(i.firstLexicalName||(i.firstLexicalName=n),s=s|2),i.names.set(n,s),e&8&&this.maybeExportDefined(i,n)}else if(e&4)for(let s=this.scopeStack.length-1;s>=0&&(i=this.scopeStack[s],this.checkRedeclarationInScope(i,n,e,r),i.names.set(n,(i.names.get(n)||0)|1),this.maybeExportDefined(i,n),!(i.flags&1667));--s);this.parser.inModule&&i.flags&1&&this.undefinedExports.delete(n)}maybeExportDefined(n,e){this.parser.inModule&&n.flags&1&&this.undefinedExports.delete(e)}checkRedeclarationInScope(n,e,r,i){this.isRedeclaredInScope(n,e,r)&&this.parser.raise(b.VarRedeclaration,i,{identifierName:e})}isRedeclaredInScope(n,e,r){if(!(r&1))return!1;if(r&8)return n.names.has(e);let i=n.names.get(e)||0;return r&16?(i&2)>0||!this.treatFunctionsAsVarInScope(n)&&(i&1)>0:(i&2)>0&&!(n.flags&8&&n.firstLexicalName===e)||!this.treatFunctionsAsVarInScope(n)&&(i&4)>0}checkLocalExport(n){let{name:e}=n;this.scopeStack[0].names.has(e)||this.undefinedExports.set(e,n.loc.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScopeFlags(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&1667)return e}}currentThisScopeFlags(){for(let n=this.scopeStack.length-1;;n--){let{flags:e}=this.scopeStack[n];if(e&1731&&!(e&4))return e}}},Jd=class extends gi{constructor(...n){super(...n),this.declareFunctions=new Set}},Yd=class extends wi{createScope(n){return new Jd(n)}declareName(n,e,r){let i=this.currentScope();if(e&2048){this.checkRedeclarationInScope(i,n,e,r),this.maybeExportDefined(i,n),i.declareFunctions.add(n);return}super.declareName(n,e,r)}isRedeclaredInScope(n,e,r){if(super.isRedeclaredInScope(n,e,r))return!0;if(r&2048&&!n.declareFunctions.has(e)){let i=n.names.get(e);return(i&4)>0||(i&2)>0}return!1}checkLocalExport(n){this.scopeStack[0].declareFunctions.has(n.name)||super.checkLocalExport(n)}},Xk=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),V=ot`flow`({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",AssignReservedType:({reservedType:t})=>`Cannot overwrite reserved type ${t}.`,DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement.",EnumBooleanMemberNotInitialized:({memberName:t,enumName:n})=>`Boolean enum members need to be initialized. Use either \`${t} = true,\` or \`${t} = false,\` in enum \`${n}\`.`,EnumDuplicateMemberName:({memberName:t,enumName:n})=>`Enum member names need to be unique, but the name \`${t}\` has already been used before in enum \`${n}\`.`,EnumInconsistentMemberValues:({enumName:t})=>`Enum \`${t}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,EnumInvalidExplicitType:({invalidEnumType:t,enumName:n})=>`Enum type \`${t}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${n}\`.`,EnumInvalidExplicitTypeUnknownSupplied:({enumName:t})=>`Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${t}\`.`,EnumInvalidMemberInitializerPrimaryType:({enumName:t,memberName:n,explicitType:e})=>`Enum \`${t}\` has type \`${e}\`, so the initializer of \`${n}\` needs to be a ${e} literal.`,EnumInvalidMemberInitializerSymbolType:({enumName:t,memberName:n})=>`Symbol enum members cannot be initialized. Use \`${n},\` in enum \`${t}\`.`,EnumInvalidMemberInitializerUnknownType:({enumName:t,memberName:n})=>`The enum member initializer for \`${n}\` needs to be a literal (either a boolean, number, or string) in enum \`${t}\`.`,EnumInvalidMemberName:({enumName:t,memberName:n,suggestion:e})=>`Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${n}\`, consider using \`${e}\`, in enum \`${t}\`.`,EnumNumberMemberNotInitialized:({enumName:t,memberName:n})=>`Number enum members need to be initialized, e.g. \`${n} = 1\` in enum \`${t}\`.`,EnumStringMemberInconsistentlyInitialized:({enumName:t})=>`String enum members need to consistently either all use initializers, or use no initializers, in enum \`${t}\`.`,GetterMayNotHaveThisParam:"A getter cannot have a `this` parameter.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` or `typeof` keyword.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type.",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions.",InexactVariance:"Explicit inexact syntax cannot have variance.",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`.",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`.",NestedFlowComment:"Cannot have a flow comment inside another flow comment.",PatternIsOptional:Object.assign({message:"A binding pattern parameter cannot be optional in an implementation signature."},{reasonCode:"OptionalBindingPattern"}),SetterMayNotHaveThisParam:"A setter cannot have a `this` parameter.",SpreadVariance:"Spread properties cannot have variance.",ThisParamAnnotationRequired:"A type annotation is required for the `this` parameter.",ThisParamBannedInConstructor:"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",ThisParamMayNotBeOptional:"The `this` parameter cannot be optional.",ThisParamMustBeFirst:"The `this` parameter must be the first function parameter.",ThisParamNoDefault:"The `this` parameter may not have a default value.",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis.",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object.",UnexpectedReservedType:({reservedType:t})=>`Unexpected reserved type ${t}.`,UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new.",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions.",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint".',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration.",UnexpectedTypeParameterBeforeAsyncArrowFunction:"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",UnsupportedDeclareExportKind:({unsupportedExportKind:t,suggestion:n})=>`\`declare export ${t}\` is not supported. Use \`${n}\` instead.`,UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module.",UnterminatedFlowComment:"Unterminated flow-comment."});function Qk(t){return t.type==="DeclareExportAllDeclaration"||t.type==="DeclareExportDeclaration"&&(!t.declaration||t.declaration.type!=="TypeAlias"&&t.declaration.type!=="InterfaceDeclaration")}function Lf(t){return t.importKind==="type"||t.importKind==="typeof"}var Zk={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};function eR(t,n){let e=[],r=[];for(let i=0;i<t.length;i++)(n(t[i],i,t)?e:r).push(t[i]);return[e,r]}var tR=/\*?\s*@((?:no)?flow)\b/,nR=t=>class extends t{constructor(...e){super(...e),this.flowPragma=void 0}getScopeHandler(){return Yd}shouldParseTypes(){return this.getPluginOption("flow","all")||this.flowPragma==="flow"}finishToken(e,r){e!==134&&e!==13&&e!==28&&this.flowPragma===void 0&&(this.flowPragma=null),super.finishToken(e,r)}addComment(e){if(this.flowPragma===void 0){let r=tR.exec(e.value);if(r)if(r[1]==="flow")this.flowPragma="flow";else if(r[1]==="noflow")this.flowPragma="noflow";else throw new Error("Unexpected flow pragma")}super.addComment(e)}flowParseTypeInitialiser(e){let r=this.state.inType;this.state.inType=!0,this.expect(e||14);let i=this.flowParseType();return this.state.inType=r,i}flowParsePredicate(){let e=this.startNode(),r=this.state.startLoc;return this.next(),this.expectContextual(110),this.state.lastTokStartLoc.index>r.index+1&&this.raise(V.UnexpectedSpaceBetweenModuloChecks,r),this.eat(10)?(e.value=super.parseExpression(),this.expect(11),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(){let e=this.state.inType;this.state.inType=!0,this.expect(14);let r=null,i=null;return this.match(54)?(this.state.inType=e,i=this.flowParsePredicate()):(r=this.flowParseType(),this.state.inType=e,this.match(54)&&(i=this.flowParsePredicate())),[r,i]}flowParseDeclareClass(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")}flowParseDeclareFunction(e){this.next();let r=e.id=this.parseIdentifier(),i=this.startNode(),s=this.startNode();this.match(47)?i.typeParameters=this.flowParseTypeParameterDeclaration():i.typeParameters=null,this.expect(10);let a=this.flowParseFunctionTypeParams();return i.params=a.params,i.rest=a.rest,i.this=a._this,this.expect(11),[i.returnType,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),s.typeAnnotation=this.finishNode(i,"FunctionTypeAnnotation"),r.typeAnnotation=this.finishNode(s,"TypeAnnotation"),this.resetEndLocation(r),this.semicolon(),this.scope.declareName(e.id.name,2048,e.id.loc.start),this.finishNode(e,"DeclareFunction")}flowParseDeclare(e,r){if(this.match(80))return this.flowParseDeclareClass(e);if(this.match(68))return this.flowParseDeclareFunction(e);if(this.match(74))return this.flowParseDeclareVariable(e);if(this.eatContextual(127))return this.match(16)?this.flowParseDeclareModuleExports(e):(r&&this.raise(V.NestedDeclareModule,this.state.lastTokStartLoc),this.flowParseDeclareModule(e));if(this.isContextual(130))return this.flowParseDeclareTypeAlias(e);if(this.isContextual(131))return this.flowParseDeclareOpaqueType(e);if(this.isContextual(129))return this.flowParseDeclareInterface(e);if(this.match(82))return this.flowParseDeclareExportDeclaration(e,r);throw this.unexpected()}flowParseDeclareVariable(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.scope.declareName(e.id.name,5,e.id.loc.start),this.semicolon(),this.finishNode(e,"DeclareVariable")}flowParseDeclareModule(e){this.scope.enter(0),this.match(134)?e.id=super.parseExprAtom():e.id=this.parseIdentifier();let r=e.body=this.startNode(),i=r.body=[];for(this.expect(5);!this.match(8);){let o=this.startNode();this.match(83)?(this.next(),!this.isContextual(130)&&!this.match(87)&&this.raise(V.InvalidNonTypeImportInDeclareModule,this.state.lastTokStartLoc),i.push(super.parseImport(o))):(this.expectContextual(125,V.UnsupportedStatementInDeclareModule),i.push(this.flowParseDeclare(o,!0)))}this.scope.exit(),this.expect(8),this.finishNode(r,"BlockStatement");let s=null,a=!1;return i.forEach(o=>{Qk(o)?(s==="CommonJS"&&this.raise(V.AmbiguousDeclareModuleKind,o),s="ES"):o.type==="DeclareModuleExports"&&(a&&this.raise(V.DuplicateDeclareModuleExports,o),s==="ES"&&this.raise(V.AmbiguousDeclareModuleKind,o),s="CommonJS",a=!0)}),e.kind=s||"CommonJS",this.finishNode(e,"DeclareModule")}flowParseDeclareExportDeclaration(e,r){if(this.expect(82),this.eat(65))return this.match(68)||this.match(80)?e.declaration=this.flowParseDeclare(this.startNode()):(e.declaration=this.flowParseType(),this.semicolon()),e.default=!0,this.finishNode(e,"DeclareExportDeclaration");if(this.match(75)||this.isLet()||(this.isContextual(130)||this.isContextual(129))&&!r){let i=this.state.value;throw this.raise(V.UnsupportedDeclareExportKind,this.state.startLoc,{unsupportedExportKind:i,suggestion:Zk[i]})}if(this.match(74)||this.match(68)||this.match(80)||this.isContextual(131))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");if(this.match(55)||this.match(5)||this.isContextual(129)||this.isContextual(130)||this.isContextual(131))return e=this.parseExport(e,null),e.type==="ExportNamedDeclaration"?(e.default=!1,delete e.exportKind,this.castNodeTo(e,"DeclareExportDeclaration")):this.castNodeTo(e,"DeclareExportAllDeclaration");throw this.unexpected()}flowParseDeclareModuleExports(e){return this.next(),this.expectContextual(111),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")}flowParseDeclareTypeAlias(e){this.next();let r=this.flowParseTypeAlias(e);return this.castNodeTo(r,"DeclareTypeAlias"),r}flowParseDeclareOpaqueType(e){this.next();let r=this.flowParseOpaqueType(e,!0);return this.castNodeTo(r,"DeclareOpaqueType"),r}flowParseDeclareInterface(e){return this.next(),this.flowParseInterfaceish(e,!1),this.finishNode(e,"DeclareInterface")}flowParseInterfaceish(e,r){if(e.id=this.flowParseRestrictedIdentifier(!r,!0),this.scope.declareName(e.id.name,r?17:8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],this.eat(81))do e.extends.push(this.flowParseInterfaceExtends());while(!r&&this.eat(12));if(r){if(e.implements=[],e.mixins=[],this.eatContextual(117))do e.mixins.push(this.flowParseInterfaceExtends());while(this.eat(12));if(this.eatContextual(113))do e.implements.push(this.flowParseInterfaceExtends());while(this.eat(12))}e.body=this.flowParseObjectType({allowStatic:r,allowExact:!1,allowSpread:!1,allowProto:r,allowInexact:!1})}flowParseInterfaceExtends(){let e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.match(47)?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")}flowParseInterface(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")}checkNotUnderscore(e){e==="_"&&this.raise(V.UnexpectedReservedUnderscore,this.state.startLoc)}checkReservedType(e,r,i){Xk.has(e)&&this.raise(i?V.AssignReservedType:V.UnexpectedReservedType,r,{reservedType:e})}flowParseRestrictedIdentifierName(e,r){return this.checkReservedType(this.state.value,this.state.startLoc,r),this.parseIdentifierName(e)}flowParseRestrictedIdentifier(e,r){let i=this.startNode(),s=this.flowParseRestrictedIdentifierName(e,r);return this.createIdentifier(i,s)}flowParseTypeAlias(e){return e.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(29),this.semicolon(),this.finishNode(e,"TypeAlias")}flowParseOpaqueType(e,r){return this.expectContextual(130),e.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(e.id.name,8201,e.id.loc.start),this.match(47)?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(14)&&(e.supertype=this.flowParseTypeInitialiser(14)),e.impltype=null,r||(e.impltype=this.flowParseTypeInitialiser(29)),this.semicolon(),this.finishNode(e,"OpaqueType")}flowParseTypeParameterBound(){if(this.match(14)||this.isContextual(81)){let e=this.startNode();return this.next(),e.typeAnnotation=this.flowParseType(),this.finishNode(e,"TypeAnnotation")}}flowParseTypeParameter(e=!1){let r=this.state.startLoc,i=this.startNode(),s=this.flowParseVariance();return i.name=this.flowParseRestrictedIdentifierName(),i.variance=s,i.bound=this.flowParseTypeParameterBound(),this.match(29)?(this.eat(29),i.default=this.flowParseType()):e&&this.raise(V.MissingTypeParamDefault,r),this.finishNode(i,"TypeParameter")}flowParseTypeParameterDeclaration(){let e=this.state.inType,r=this.startNode();r.params=[],this.state.inType=!0,this.match(47)||this.match(143)?this.next():this.unexpected();let i=!1;do{let s=this.flowParseTypeParameter(i);r.params.push(s),s.default&&(i=!0),this.match(48)||this.expect(12)}while(!this.match(48));return this.expect(48),this.state.inType=e,this.finishNode(r,"TypeParameterDeclaration")}flowInTopLevelContext(e){if(this.curContext()!==ie.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}flowParseTypeParameterInstantiationInExpression(){if(this.reScan_lt()===47)return this.flowParseTypeParameterInstantiation()}flowParseTypeParameterInstantiation(){let e=this.startNode(),r=this.state.inType;return this.state.inType=!0,e.params=[],this.flowInTopLevelContext(()=>{this.expect(47);let i=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.match(48);)e.params.push(this.flowParseType()),this.match(48)||this.expect(12);this.state.noAnonFunctionType=i}),this.state.inType=r,!this.state.inType&&this.curContext()===ie.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){if(this.reScan_lt()!==47)return null;let e=this.startNode(),r=this.state.inType;for(e.params=[],this.state.inType=!0,this.expect(47);!this.match(48);)e.params.push(this.flowParseTypeOrImplicitInstantiation()),this.match(48)||this.expect(12);return this.expect(48),this.state.inType=r,this.finishNode(e,"TypeParameterInstantiation")}flowParseInterfaceType(){let e=this.startNode();if(this.expectContextual(129),e.extends=[],this.eat(81))do e.extends.push(this.flowParseInterfaceExtends());while(this.eat(12));return e.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(e,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(135)||this.match(134)?super.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(e,r,i){return e.static=r,this.lookahead().type===14?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(3),e.value=this.flowParseTypeInitialiser(),e.variance=i,this.finishNode(e,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(e,r){return e.static=r,e.id=this.flowParseObjectPropertyKey(),this.expect(3),this.expect(3),this.match(47)||this.match(10)?(e.method=!0,e.optional=!1,e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start))):(e.method=!1,this.eat(17)&&(e.optional=!0),e.value=this.flowParseTypeInitialiser()),this.finishNode(e,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(e){for(e.params=[],e.rest=null,e.typeParameters=null,e.this=null,this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(10),this.match(78)&&(e.this=this.flowParseFunctionTypeParam(!0),e.this.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.params.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(e.rest=this.flowParseFunctionTypeParam(!1)),this.expect(11),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(e,r){let i=this.startNode();return e.static=r,e.value=this.flowParseObjectTypeMethodish(i),this.finishNode(e,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:e,allowExact:r,allowSpread:i,allowProto:s,allowInexact:a}){let o=this.state.inType;this.state.inType=!0;let d=this.startNode();d.callProperties=[],d.properties=[],d.indexers=[],d.internalSlots=[];let c,l,u=!1;for(r&&this.match(6)?(this.expect(6),c=9,l=!0):(this.expect(5),c=8,l=!1),d.exact=l;!this.match(c);){let f=!1,h=null,m=null,g=this.startNode();if(s&&this.isContextual(118)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),h=this.state.startLoc,e=!1)}if(e&&this.isContextual(106)){let w=this.lookahead();w.type!==14&&w.type!==17&&(this.next(),f=!0)}let y=this.flowParseVariance();if(this.eat(0))h!=null&&this.unexpected(h),this.eat(0)?(y&&this.unexpected(y.loc.start),d.internalSlots.push(this.flowParseObjectTypeInternalSlot(g,f))):d.indexers.push(this.flowParseObjectTypeIndexer(g,f,y));else if(this.match(10)||this.match(47))h!=null&&this.unexpected(h),y&&this.unexpected(y.loc.start),d.callProperties.push(this.flowParseObjectTypeCallProperty(g,f));else{let w="init";if(this.isContextual(99)||this.isContextual(104)){let v=this.lookahead();qf(v.type)&&(w=this.state.value,this.next())}let x=this.flowParseObjectTypeProperty(g,f,h,y,w,i,a??!l);x===null?(u=!0,m=this.state.lastTokStartLoc):d.properties.push(x)}this.flowObjectTypeSemicolon(),m&&!this.match(8)&&!this.match(9)&&this.raise(V.UnexpectedExplicitInexactInObject,m)}this.expect(c),i&&(d.inexact=u);let p=this.finishNode(d,"ObjectTypeAnnotation");return this.state.inType=o,p}flowParseObjectTypeProperty(e,r,i,s,a,o,d){if(this.eat(21))return this.match(12)||this.match(13)||this.match(8)||this.match(9)?(o?d||this.raise(V.InexactInsideExact,this.state.lastTokStartLoc):this.raise(V.InexactInsideNonObject,this.state.lastTokStartLoc),s&&this.raise(V.InexactVariance,s),null):(o||this.raise(V.UnexpectedSpreadType,this.state.lastTokStartLoc),i!=null&&this.unexpected(i),s&&this.raise(V.SpreadVariance,s),e.argument=this.flowParseType(),this.finishNode(e,"ObjectTypeSpreadProperty"));{e.key=this.flowParseObjectPropertyKey(),e.static=r,e.proto=i!=null,e.kind=a;let c=!1;return this.match(47)||this.match(10)?(e.method=!0,i!=null&&this.unexpected(i),s&&this.unexpected(s.loc.start),e.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e.loc.start)),(a==="get"||a==="set")&&this.flowCheckGetterSetterParams(e),!o&&e.key.name==="constructor"&&e.value.this&&this.raise(V.ThisParamBannedInConstructor,e.value.this)):(a!=="init"&&this.unexpected(),e.method=!1,this.eat(17)&&(c=!0),e.value=this.flowParseTypeInitialiser(),e.variance=s),e.optional=c,this.finishNode(e,"ObjectTypeProperty")}}flowCheckGetterSetterParams(e){let r=e.kind==="get"?0:1,i=e.value.params.length+(e.value.rest?1:0);e.value.this&&this.raise(e.kind==="get"?V.GetterMayNotHaveThisParam:V.SetterMayNotHaveThisParam,e.value.this),i!==r&&this.raise(e.kind==="get"?b.BadGetterArity:b.BadSetterArity,e),e.kind==="set"&&e.value.rest&&this.raise(b.BadSetterRestParameter,e)}flowObjectTypeSemicolon(){!this.eat(13)&&!this.eat(12)&&!this.match(8)&&!this.match(9)&&this.unexpected()}flowParseQualifiedTypeIdentifier(e,r){e??(e=this.state.startLoc);let i=r||this.flowParseRestrictedIdentifier(!0);for(;this.eat(16);){let s=this.startNodeAt(e);s.qualification=i,s.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(s,"QualifiedTypeIdentifier")}return i}flowParseGenericType(e,r){let i=this.startNodeAt(e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(e,r),this.match(47)&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")}flowParseTypeofType(){let e=this.startNode();return this.expect(87),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")}flowParseTupleType(){let e=this.startNode();for(e.types=[],this.expect(0);this.state.pos<this.length&&!this.match(3)&&(e.types.push(this.flowParseType()),!this.match(3));)this.expect(12);return this.expect(3),this.finishNode(e,"TupleTypeAnnotation")}flowParseFunctionTypeParam(e){let r=null,i=!1,s=null,a=this.startNode(),o=this.lookahead(),d=this.state.type===78;return o.type===14||o.type===17?(d&&!e&&this.raise(V.ThisParamMustBeFirst,a),r=this.parseIdentifier(d),this.eat(17)&&(i=!0,d&&this.raise(V.ThisParamMayNotBeOptional,a)),s=this.flowParseTypeInitialiser()):s=this.flowParseType(),a.name=r,a.optional=i,a.typeAnnotation=s,this.finishNode(a,"FunctionTypeParam")}reinterpretTypeAsFunctionTypeParam(e){let r=this.startNodeAt(e.loc.start);return r.name=null,r.optional=!1,r.typeAnnotation=e,this.finishNode(r,"FunctionTypeParam")}flowParseFunctionTypeParams(e=[]){let r=null,i=null;for(this.match(78)&&(i=this.flowParseFunctionTypeParam(!0),i.name=null,this.match(11)||this.expect(12));!this.match(11)&&!this.match(21);)e.push(this.flowParseFunctionTypeParam(!1)),this.match(11)||this.expect(12);return this.eat(21)&&(r=this.flowParseFunctionTypeParam(!1)),{params:e,rest:r,_this:i}}flowIdentToTypeAnnotation(e,r,i){switch(i.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");case"symbol":return this.finishNode(r,"SymbolTypeAnnotation");default:return this.checkNotUnderscore(i.name),this.flowParseGenericType(e,i)}}flowParsePrimaryType(){let e=this.state.startLoc,r=this.startNode(),i,s,a=!1,o=this.state.noAnonFunctionType;switch(this.state.type){case 5:return this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!0,allowProto:!1,allowInexact:!0});case 6:return this.flowParseObjectType({allowStatic:!1,allowExact:!0,allowSpread:!0,allowProto:!1,allowInexact:!1});case 0:return this.state.noAnonFunctionType=!1,s=this.flowParseTupleType(),this.state.noAnonFunctionType=o,s;case 47:{let d=this.startNode();return d.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(10),i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),this.finishNode(d,"FunctionTypeAnnotation")}case 10:{let d=this.startNode();if(this.next(),!this.match(11)&&!this.match(21))if(se(this.state.type)||this.match(78)){let c=this.lookahead().type;a=c!==17&&c!==14}else a=!0;if(a){if(this.state.noAnonFunctionType=!1,s=this.flowParseType(),this.state.noAnonFunctionType=o,this.state.noAnonFunctionType||!(this.match(12)||this.match(11)&&this.lookahead().type===19))return this.expect(11),s;this.eat(12)}return s?i=this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(s)]):i=this.flowParseFunctionTypeParams(),d.params=i.params,d.rest=i.rest,d.this=i._this,this.expect(11),this.expect(19),d.returnType=this.flowParseType(),d.typeParameters=null,this.finishNode(d,"FunctionTypeAnnotation")}case 134:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case 85:case 86:return r.value=this.match(85),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case 53:if(this.state.value==="-"){if(this.next(),this.match(135))return this.parseLiteralAtNode(-this.state.value,"NumberLiteralTypeAnnotation",r);if(this.match(136))return this.parseLiteralAtNode(-this.state.value,"BigIntLiteralTypeAnnotation",r);throw this.raise(V.UnexpectedSubtractionOperand,this.state.startLoc)}throw this.unexpected();case 135:return this.parseLiteral(this.state.value,"NumberLiteralTypeAnnotation");case 136:return this.parseLiteral(this.state.value,"BigIntLiteralTypeAnnotation");case 88:return this.next(),this.finishNode(r,"VoidTypeAnnotation");case 84:return this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case 78:return this.next(),this.finishNode(r,"ThisTypeAnnotation");case 55:return this.next(),this.finishNode(r,"ExistsTypeAnnotation");case 87:return this.flowParseTypeofType();default:if(vc(this.state.type)){let d=Yt(this.state.type);return this.next(),super.createIdentifier(r,d)}else if(se(this.state.type))return this.isContextual(129)?this.flowParseInterfaceType():this.flowIdentToTypeAnnotation(e,r,this.parseIdentifier())}throw this.unexpected()}flowParsePostfixType(){let e=this.state.startLoc,r=this.flowParsePrimaryType(),i=!1;for(;(this.match(0)||this.match(18))&&!this.canInsertSemicolon();){let s=this.startNodeAt(e),a=this.eat(18);i=i||a,this.expect(0),!a&&this.match(3)?(s.elementType=r,this.next(),r=this.finishNode(s,"ArrayTypeAnnotation")):(s.objectType=r,s.indexType=this.flowParseType(),this.expect(3),i?(s.optional=a,r=this.finishNode(s,"OptionalIndexedAccessType")):r=this.finishNode(s,"IndexedAccessType"))}return r}flowParsePrefixType(){let e=this.startNode();return this.eat(17)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()}flowParseAnonFunctionWithoutParens(){let e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(19)){let r=this.startNodeAt(e.loc.start);return r.params=[this.reinterpretTypeAsFunctionTypeParam(e)],r.rest=null,r.this=null,r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation")}return e}flowParseIntersectionType(){let e=this.startNode();this.eat(45);let r=this.flowParseAnonFunctionWithoutParens();for(e.types=[r];this.eat(45);)e.types.push(this.flowParseAnonFunctionWithoutParens());return e.types.length===1?r:this.finishNode(e,"IntersectionTypeAnnotation")}flowParseUnionType(){let e=this.startNode();this.eat(43);let r=this.flowParseIntersectionType();for(e.types=[r];this.eat(43);)e.types.push(this.flowParseIntersectionType());return e.types.length===1?r:this.finishNode(e,"UnionTypeAnnotation")}flowParseType(){let e=this.state.inType;this.state.inType=!0;let r=this.flowParseUnionType();return this.state.inType=e,r}flowParseTypeOrImplicitInstantiation(){if(this.state.type===132&&this.state.value==="_"){let e=this.state.startLoc,r=this.parseIdentifier();return this.flowParseGenericType(e,r)}else return this.flowParseType()}flowParseTypeAnnotation(){let e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")}flowParseTypeAnnotatableIdentifier(){let e=this.startNode(),r=this.parseIdentifierName();return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),this.createIdentifier(e,r)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}flowParseVariance(){let e=null;return this.match(53)?(e=this.startNode(),this.state.value==="+"?e.kind="plus":e.kind="minus",this.next(),this.finishNode(e,"Variance")):e}parseFunctionBody(e,r,i=!1){if(r){this.forwardNoArrowParamsConversionAt(e,()=>super.parseFunctionBody(e,!0,i));return}super.parseFunctionBody(e,!1,i)}parseFunctionBodyAndFinish(e,r,i=!1){if(this.match(14)){let s=this.startNode();[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),e.returnType=s.typeAnnotation?this.finishNode(s,"TypeAnnotation"):null}return super.parseFunctionBodyAndFinish(e,r,i)}parseStatementLike(e){if(this.state.strict&&this.isContextual(129)){let i=this.lookahead();if(dt(i.type)){let s=this.startNode();return this.next(),this.flowParseInterface(s)}}else if(this.isContextual(126)){let i=this.startNode();return this.next(),this.flowParseEnumDeclaration(i)}let r=super.parseStatementLike(e);return this.flowPragma===void 0&&!this.isValidDirective(r)&&(this.flowPragma=null),r}parseExpressionStatement(e,r,i){if(r.type==="Identifier"){if(r.name==="declare"){if(this.match(80)||se(this.state.type)||this.match(68)||this.match(74)||this.match(82))return this.flowParseDeclare(e)}else if(se(this.state.type)){if(r.name==="interface")return this.flowParseInterface(e);if(r.name==="type")return this.flowParseTypeAlias(e);if(r.name==="opaque")return this.flowParseOpaqueType(e,!1)}}return super.parseExpressionStatement(e,r,i)}shouldParseExportDeclaration(){let{type:e}=this.state;return e===126||Df(e)?!this.state.containsEsc:super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){let{type:e}=this.state;return e===126||Df(e)?this.state.containsEsc:super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.isContextual(126)){let e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDefaultExpression()}parseConditional(e,r,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let p=this.lookaheadCharCode();if(p===44||p===61||p===58||p===41)return this.setOptionalParametersError(i),e}this.expect(17);let s=this.state.clone(),a=this.state.noArrowAt,o=this.startNodeAt(r),{consequent:d,failed:c}=this.tryParseConditionalConsequent(),[l,u]=this.getArrowLikeExpressions(d);if(c||u.length>0){let p=[...a];if(u.length>0){this.state=s,this.state.noArrowAt=p;for(let f=0;f<u.length;f++)p.push(u[f].start);({consequent:d,failed:c}=this.tryParseConditionalConsequent()),[l,u]=this.getArrowLikeExpressions(d)}c&&l.length>1&&this.raise(V.AmbiguousConditionalArrow,s.startLoc),c&&l.length===1&&(this.state=s,p.push(l[0].start),this.state.noArrowAt=p,{consequent:d,failed:c}=this.tryParseConditionalConsequent())}return this.getArrowLikeExpressions(d,!0),this.state.noArrowAt=a,this.expect(14),o.test=e,o.consequent=d,o.alternate=this.forwardNoArrowParamsConversionAt(o,()=>this.parseMaybeAssign(void 0,void 0)),this.finishNode(o,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);let e=this.parseMaybeAssignAllowIn(),r=!this.match(14);return this.state.noArrowParamsConversionAt.pop(),{consequent:e,failed:r}}getArrowLikeExpressions(e,r){let i=[e],s=[];for(;i.length!==0;){let a=i.pop();a.type==="ArrowFunctionExpression"?(a.typeParameters||!a.returnType?this.finishArrowValidation(a):s.push(a),a.body.type!=="BlockStatement"&&i.push(a.body)):a.type==="ConditionalExpression"&&(i.push(a.consequent),i.push(a.alternate))}return r?(s.forEach(a=>this.finishArrowValidation(a)),[s,[]]):eR(s,a=>a.params.every(o=>this.isAssignable(o,!0)))}finishArrowValidation(e){var r;this.toAssignableList(e.params,(r=e.extra)==null?void 0:r.trailingCommaLoc,!1),this.scope.enter(518),super.checkParams(e,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(e,r){let i;return this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?(this.state.noArrowParamsConversionAt.push(this.state.start),i=r(),this.state.noArrowParamsConversionAt.pop()):i=r(),i}parseParenItem(e,r){let i=super.parseParenItem(e,r);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(r);return s.expression=i,s.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(s,"TypeCastExpression")}return i}assertModuleNodeAllowed(e){e.type==="ImportDeclaration"&&(e.importKind==="type"||e.importKind==="typeof")||e.type==="ExportNamedDeclaration"&&e.exportKind==="type"||e.type==="ExportAllDeclaration"&&e.exportKind==="type"||super.assertModuleNodeAllowed(e)}parseExportDeclaration(e){if(this.isContextual(130)){e.exportKind="type";let r=this.startNode();return this.next(),this.match(5)?(e.specifiers=this.parseExportSpecifiers(!0),super.parseExportFrom(e),null):this.flowParseTypeAlias(r)}else if(this.isContextual(131)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseOpaqueType(r,!1)}else if(this.isContextual(129)){e.exportKind="type";let r=this.startNode();return this.next(),this.flowParseInterface(r)}else if(this.isContextual(126)){e.exportKind="value";let r=this.startNode();return this.next(),this.flowParseEnumDeclaration(r)}else return super.parseExportDeclaration(e)}eatExportStar(e){return super.eatExportStar(e)?!0:this.isContextual(130)&&this.lookahead().type===55?(e.exportKind="type",this.next(),this.next(),!0):!1}maybeParseExportNamespaceSpecifier(e){let{startLoc:r}=this.state,i=super.maybeParseExportNamespaceSpecifier(e);return i&&e.exportKind==="type"&&this.unexpected(r),i}parseClassId(e,r,i){super.parseClassId(e,r,i),this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(e,r,i){let{startLoc:s}=this.state;if(this.isContextual(125)){if(super.parseClassMemberFromModifier(e,r))return;r.declare=!0}super.parseClassMember(e,r,i),r.declare&&(r.type!=="ClassProperty"&&r.type!=="ClassPrivateProperty"&&r.type!=="PropertyDefinition"?this.raise(V.DeclareClassElement,s):r.value&&this.raise(V.DeclareClassFieldInitializer,r.value))}isIterator(e){return e==="iterator"||e==="asyncIterator"}readIterator(){let e=super.readWord1(),r="@@"+e;(!this.isIterator(e)||!this.state.inType)&&this.raise(b.InvalidIdentifier,this.state.curPosition(),{identifierName:r}),this.finishToken(132,r)}getTokenFromCode(e){let r=this.input.charCodeAt(this.state.pos+1);e===123&&r===124?this.finishOp(6,2):this.state.inType&&(e===62||e===60)?this.finishOp(e===62?48:47,1):this.state.inType&&e===63?r===46?this.finishOp(18,2):this.finishOp(17,1):Wk(e,r,this.input.charCodeAt(this.state.pos+2))?(this.state.pos+=2,this.readIterator()):super.getTokenFromCode(e)}isAssignable(e,r){return e.type==="TypeCastExpression"?this.isAssignable(e.expression,r):super.isAssignable(e,r)}toAssignable(e,r=!1){!r&&e.type==="AssignmentExpression"&&e.left.type==="TypeCastExpression"&&(e.left=this.typeCastToParameter(e.left)),super.toAssignable(e,r)}toAssignableList(e,r,i){for(let s=0;s<e.length;s++){let a=e[s];a?.type==="TypeCastExpression"&&(e[s]=this.typeCastToParameter(a))}super.toAssignableList(e,r,i)}toReferencedList(e,r){for(let s=0;s<e.length;s++){var i;let a=e[s];a&&a.type==="TypeCastExpression"&&!((i=a.extra)!=null&&i.parenthesized)&&(e.length>1||!r)&&this.raise(V.TypeCastInPattern,a.typeAnnotation)}return e}parseArrayLike(e,r,i){let s=super.parseArrayLike(e,r,i);return i!=null&&!this.state.maybeInArrowParameters&&this.toReferencedList(s.elements),s}isValidLVal(e,r,i,s){return e==="TypeCastExpression"||super.isValidLVal(e,r,i,s)}parseClassProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(e)}parseClassPrivateProperty(e){return this.match(14)&&(e.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(14)||super.isClassProperty()}isNonstaticConstructor(e){return!this.match(14)&&super.isNonstaticConstructor(e)}pushClassMethod(e,r,i,s,a,o){if(r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(e,r,i,s,a,o),r.params&&a){let d=r.params;d.length>0&&this.isThisParam(d[0])&&this.raise(V.ThisParamBannedInConstructor,r)}else if(r.type==="MethodDefinition"&&a&&r.value.params){let d=r.value.params;d.length>0&&this.isThisParam(d[0])&&this.raise(V.ThisParamBannedInConstructor,r)}}pushClassPrivateMethod(e,r,i,s){r.variance&&this.unexpected(r.variance.loc.start),delete r.variance,this.match(47)&&(r.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(e,r,i,s)}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass&&(this.match(47)||this.match(51))&&(e.superTypeParameters=this.flowParseTypeParameterInstantiationInExpression()),this.isContextual(113)){this.next();let r=e.implements=[];do{let i=this.startNode();i.id=this.flowParseRestrictedIdentifier(!0),this.match(47)?i.typeParameters=this.flowParseTypeParameterInstantiation():i.typeParameters=null,r.push(this.finishNode(i,"ClassImplements"))}while(this.eat(12))}}checkGetterSetterParams(e){super.checkGetterSetterParams(e);let r=this.getObjectOrClassMethodParams(e);if(r.length>0){let i=r[0];this.isThisParam(i)&&e.kind==="get"?this.raise(V.GetterMayNotHaveThisParam,i):this.isThisParam(i)&&this.raise(V.SetterMayNotHaveThisParam,i)}}parsePropertyNamePrefixOperator(e){e.variance=this.flowParseVariance()}parseObjPropValue(e,r,i,s,a,o,d){e.variance&&this.unexpected(e.variance.loc.start),delete e.variance;let c;this.match(47)&&!o&&(c=this.flowParseTypeParameterDeclaration(),this.match(10)||this.unexpected());let l=super.parseObjPropValue(e,r,i,s,a,o,d);return c&&((l.value||l).typeParameters=c),l}parseFunctionParamType(e){return this.eat(17)&&(e.type!=="Identifier"&&this.raise(V.PatternIsOptional,e),this.isThisParam(e)&&this.raise(V.ThisParamMayNotBeOptional,e),e.optional=!0),this.match(14)?e.typeAnnotation=this.flowParseTypeAnnotation():this.isThisParam(e)&&this.raise(V.ThisParamAnnotationRequired,e),this.match(29)&&this.isThisParam(e)&&this.raise(V.ThisParamNoDefault,e),this.resetEndLocation(e),e}parseMaybeDefault(e,r){let i=super.parseMaybeDefault(e,r);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(V.TypeBeforeInitializer,i.typeAnnotation),i}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(V.ImportReflectionHasImportType,e.specifiers[0].loc.start)}parseImportSpecifierLocal(e,r,i){r.local=Lf(e)?this.flowParseRestrictedIdentifier(!0,!0):this.parseIdentifier(),e.specifiers.push(this.finishImportSpecifier(r,i))}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){if(!e)return!0;let r=this.lookaheadCharCode();return r===123||r===42}return!e&&this.isContextual(87)}applyImportPhase(e,r,i,s){if(super.applyImportPhase(e,r,i,s),r){if(!i&&this.match(65))return;e.exportKind=i==="type"?i:"value"}else i==="type"&&this.match(55)&&this.unexpected(),e.importKind=i==="type"||i==="typeof"?i:"value"}parseImportSpecifier(e,r,i,s,a){let o=e.imported,d=null;o.type==="Identifier"&&(o.name==="type"?d="type":o.name==="typeof"&&(d="typeof"));let c=!1;if(this.isContextual(93)&&!this.isLookaheadContextual("as")){let u=this.parseIdentifier(!0);d!==null&&!dt(this.state.type)?(e.imported=u,e.importKind=d,e.local=this.cloneIdentifier(u)):(e.imported=o,e.importKind=null,e.local=this.parseIdentifier())}else{if(d!==null&&dt(this.state.type))e.imported=this.parseIdentifier(!0),e.importKind=d;else{if(r)throw this.raise(b.ImportBindingIsString,e,{importName:o.value});e.imported=o,e.importKind=null}this.eatContextual(93)?e.local=this.parseIdentifier():(c=!0,e.local=this.cloneIdentifier(e.imported))}let l=Lf(e);return i&&l&&this.raise(V.ImportTypeShorthandOnlyInPureImport,e),(i||l)&&this.checkReservedType(e.local.name,e.local.loc.start,!0),c&&!i&&!l&&this.checkReservedWord(e.local.name,e.loc.start,!0,!0),this.finishImportSpecifier(e,"ImportSpecifier")}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseFunctionParams(e,r){let i=e.kind;i!=="get"&&i!=="set"&&this.match(47)&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),this.match(14)&&(e.id.typeAnnotation=this.flowParseTypeAnnotation(),this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){if(this.match(14)){let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0,e.returnType=this.flowParseTypeAnnotation(),this.state.noAnonFunctionType=i}return super.parseAsyncArrowFromCallExpression(e,r)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}parseMaybeAssign(e,r){var i;let s=null,a;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(s=this.state.clone(),a=this.tryParse(()=>super.parseMaybeAssign(e,r),s),!a.error)return a.node;let{context:c}=this.state,l=c[c.length-1];(l===ie.j_oTag||l===ie.j_expr)&&c.pop()}if((i=a)!=null&&i.error||this.match(47)){var o,d;s=s||this.state.clone();let c,l=this.tryParse(p=>{var f;c=this.flowParseTypeParameterDeclaration();let h=this.forwardNoArrowParamsConversionAt(c,()=>{let g=super.parseMaybeAssign(e,r);return this.resetStartLocationFromNode(g,c),g});(f=h.extra)!=null&&f.parenthesized&&p();let m=this.maybeUnwrapTypeCastExpression(h);return m.type!=="ArrowFunctionExpression"&&p(),m.typeParameters=c,this.resetStartLocationFromNode(m,c),h},s),u=null;if(l.node&&this.maybeUnwrapTypeCastExpression(l.node).type==="ArrowFunctionExpression"){if(!l.error&&!l.aborted)return l.node.async&&this.raise(V.UnexpectedTypeParameterBeforeAsyncArrowFunction,c),l.node;u=l.node}if((o=a)!=null&&o.node)return this.state=a.failState,a.node;if(u)return this.state=l.failState,u;throw(d=a)!=null&&d.thrown?a.error:l.thrown?l.error:this.raise(V.UnexpectedTokenAfterTypeParameter,c)}return super.parseMaybeAssign(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(()=>{let i=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;let s=this.startNode();return[s.typeAnnotation,e.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=i,this.canInsertSemicolon()&&this.unexpected(),this.match(19)||this.unexpected(),s});if(r.thrown)return null;r.error&&(this.state=r.failState),e.returnType=r.node.typeAnnotation?this.finishNode(r.node,"TypeAnnotation"):null}return super.parseArrow(e)}shouldParseArrow(e){return this.match(14)||super.shouldParseArrow(e)}setArrowFunctionParameters(e,r){this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start))?e.params=r:super.setArrowFunctionParameters(e,r)}checkParams(e,r,i,s=!0){if(!(i&&this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(e.start)))){for(let a=0;a<e.params.length;a++)this.isThisParam(e.params[a])&&a>0&&this.raise(V.ThisParamMustBeFirst,e.params[a]);super.checkParams(e,r,i,s)}}parseParenAndDistinguishExpression(e){return super.parseParenAndDistinguishExpression(e&&!this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)))}parseSubscripts(e,r,i){if(e.type==="Identifier"&&e.name==="async"&&this.state.noArrowAt.includes(r.index)){this.next();let s=this.startNodeAt(r);s.callee=e,s.arguments=super.parseCallExpressionArguments(),e=this.finishNode(s,"CallExpression")}else if(e.type==="Identifier"&&e.name==="async"&&this.match(47)){let s=this.state.clone(),a=this.tryParse(d=>this.parseAsyncArrowWithTypeParameters(r)||d(),s);if(!a.error&&!a.aborted)return a.node;let o=this.tryParse(()=>super.parseSubscripts(e,r,i),s);if(o.node&&!o.error)return o.node;if(a.node)return this.state=a.failState,a.node;if(o.node)return this.state=o.failState,o.node;throw a.error||o.error}return super.parseSubscripts(e,r,i)}parseSubscript(e,r,i,s){if(this.match(18)&&this.isLookaheadToken_lt()){if(s.optionalChainMember=!0,i)return s.stop=!0,e;this.next();let a=this.startNodeAt(r);return a.callee=e,a.typeArguments=this.flowParseTypeParameterInstantiationInExpression(),this.expect(10),a.arguments=this.parseCallExpressionArguments(),a.optional=!0,this.finishCallExpression(a,!0)}else if(!i&&this.shouldParseTypes()&&(this.match(47)||this.match(51))){let a=this.startNodeAt(r);a.callee=e;let o=this.tryParse(()=>(a.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(10),a.arguments=super.parseCallExpressionArguments(),s.optionalChainMember&&(a.optional=!1),this.finishCallExpression(a,s.optionalChainMember)));if(o.node)return o.error&&(this.state=o.failState),o.node}return super.parseSubscript(e,r,i,s)}parseNewCallee(e){super.parseNewCallee(e);let r=null;this.shouldParseTypes()&&this.match(47)&&(r=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),e.typeArguments=r}parseAsyncArrowWithTypeParameters(e){let r=this.startNodeAt(e);if(this.parseFunctionParams(r,!1),!!this.parseArrow(r))return super.parseArrowExpression(r,void 0,!0)}readToken_mult_modulo(e){let r=this.input.charCodeAt(this.state.pos+1);if(e===42&&r===47&&this.state.hasFlowComment){this.state.hasFlowComment=!1,this.state.pos+=2,this.nextToken();return}super.readToken_mult_modulo(e)}readToken_pipe_amp(e){let r=this.input.charCodeAt(this.state.pos+1);if(e===124&&r===125){this.finishOp(9,2);return}super.readToken_pipe_amp(e)}parseTopLevel(e,r){let i=super.parseTopLevel(e,r);return this.state.hasFlowComment&&this.raise(V.UnterminatedFlowComment,this.state.curPosition()),i}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment()){if(this.state.hasFlowComment)throw this.raise(V.NestedFlowComment,this.state.startLoc);this.hasFlowCommentCompletion();let e=this.skipFlowComment();e&&(this.state.pos+=e,this.state.hasFlowComment=!0);return}return super.skipBlockComment(this.state.hasFlowComment?"*-/":"*/")}skipFlowComment(){let{pos:e}=this.state,r=2;for(;[32,9].includes(this.input.charCodeAt(e+r));)r++;let i=this.input.charCodeAt(r+e),s=this.input.charCodeAt(r+e+1);return i===58&&s===58?r+2:this.input.slice(r+e,r+e+12)==="flow-include"?r+12:i===58&&s!==58?r:!1}hasFlowCommentCompletion(){if(this.input.indexOf("*/",this.state.pos)===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition())}flowEnumErrorBooleanMemberNotInitialized(e,{enumName:r,memberName:i}){this.raise(V.EnumBooleanMemberNotInitialized,e,{memberName:i,enumName:r})}flowEnumErrorInvalidMemberInitializer(e,r){return this.raise(r.explicitType?r.explicitType==="symbol"?V.EnumInvalidMemberInitializerSymbolType:V.EnumInvalidMemberInitializerPrimaryType:V.EnumInvalidMemberInitializerUnknownType,e,r)}flowEnumErrorNumberMemberNotInitialized(e,r){this.raise(V.EnumNumberMemberNotInitialized,e,r)}flowEnumErrorStringMemberInconsistentlyInitialized(e,r){this.raise(V.EnumStringMemberInconsistentlyInitialized,e,r)}flowEnumMemberInit(){let e=this.state.startLoc,r=()=>this.match(12)||this.match(8);switch(this.state.type){case 135:{let i=this.parseNumericLiteral(this.state.value);return r()?{type:"number",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 134:{let i=this.parseStringLiteral(this.state.value);return r()?{type:"string",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}case 85:case 86:{let i=this.parseBooleanLiteral(this.match(85));return r()?{type:"boolean",loc:i.loc.start,value:i}:{type:"invalid",loc:e}}default:return{type:"invalid",loc:e}}}flowEnumMemberRaw(){let e=this.state.startLoc,r=this.parseIdentifier(!0),i=this.eat(29)?this.flowEnumMemberInit():{type:"none",loc:e};return{id:r,init:i}}flowEnumCheckExplicitTypeMismatch(e,r,i){let{explicitType:s}=r;s!==null&&s!==i&&this.flowEnumErrorInvalidMemberInitializer(e,r)}flowEnumMembers({enumName:e,explicitType:r}){let i=new Set,s={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]},a=!1;for(;!this.match(8);){if(this.eat(21)){a=!0;break}let o=this.startNode(),{id:d,init:c}=this.flowEnumMemberRaw(),l=d.name;if(l==="")continue;/^[a-z]/.test(l)&&this.raise(V.EnumInvalidMemberName,d,{memberName:l,suggestion:l[0].toUpperCase()+l.slice(1),enumName:e}),i.has(l)&&this.raise(V.EnumDuplicateMemberName,d,{memberName:l,enumName:e}),i.add(l);let u={enumName:e,explicitType:r,memberName:l};switch(o.id=d,c.type){case"boolean":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"boolean"),o.init=c.value,s.booleanMembers.push(this.finishNode(o,"EnumBooleanMember"));break}case"number":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"number"),o.init=c.value,s.numberMembers.push(this.finishNode(o,"EnumNumberMember"));break}case"string":{this.flowEnumCheckExplicitTypeMismatch(c.loc,u,"string"),o.init=c.value,s.stringMembers.push(this.finishNode(o,"EnumStringMember"));break}case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(c.loc,u);case"none":switch(r){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(c.loc,u);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(c.loc,u);break;default:s.defaultedMembers.push(this.finishNode(o,"EnumDefaultedMember"))}}this.match(8)||this.expect(12)}return{members:s,hasUnknownMembers:a}}flowEnumStringMembers(e,r,{enumName:i}){if(e.length===0)return r;if(r.length===0)return e;if(r.length>e.length){for(let s of e)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return r}else{for(let s of r)this.flowEnumErrorStringMemberInconsistentlyInitialized(s,{enumName:i});return e}}flowEnumParseExplicitType({enumName:e}){if(!this.eatContextual(102))return null;if(!se(this.state.type))throw this.raise(V.EnumInvalidExplicitTypeUnknownSupplied,this.state.startLoc,{enumName:e});let{value:r}=this.state;return this.next(),r!=="boolean"&&r!=="number"&&r!=="string"&&r!=="symbol"&&this.raise(V.EnumInvalidExplicitType,this.state.startLoc,{enumName:e,invalidEnumType:r}),r}flowEnumBody(e,r){let i=r.name,s=r.loc.start,a=this.flowEnumParseExplicitType({enumName:i});this.expect(5);let{members:o,hasUnknownMembers:d}=this.flowEnumMembers({enumName:i,explicitType:a});switch(e.hasUnknownMembers=d,a){case"boolean":return e.explicitType=!0,e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody");case"number":return e.explicitType=!0,e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody");case"string":return e.explicitType=!0,e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");case"symbol":return e.members=o.defaultedMembers,this.expect(8),this.finishNode(e,"EnumSymbolBody");default:{let c=()=>(e.members=[],this.expect(8),this.finishNode(e,"EnumStringBody"));e.explicitType=!1;let l=o.booleanMembers.length,u=o.numberMembers.length,p=o.stringMembers.length,f=o.defaultedMembers.length;if(!l&&!u&&!p&&!f)return c();if(!l&&!u)return e.members=this.flowEnumStringMembers(o.stringMembers,o.defaultedMembers,{enumName:i}),this.expect(8),this.finishNode(e,"EnumStringBody");if(!u&&!p&&l>=f){for(let h of o.defaultedMembers)this.flowEnumErrorBooleanMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.booleanMembers,this.expect(8),this.finishNode(e,"EnumBooleanBody")}else if(!l&&!p&&u>=f){for(let h of o.defaultedMembers)this.flowEnumErrorNumberMemberNotInitialized(h.loc.start,{enumName:i,memberName:h.id.name});return e.members=o.numberMembers,this.expect(8),this.finishNode(e,"EnumNumberBody")}else return this.raise(V.EnumInconsistentMemberValues,s,{enumName:i}),c()}}}flowParseEnumDeclaration(e){let r=this.parseIdentifier();return e.id=r,e.body=this.flowEnumBody(this.startNode(),r),this.finishNode(e,"EnumDeclaration")}jsxParseOpeningElementAfterName(e){return this.shouldParseTypes()&&(this.match(47)||this.match(51))&&(e.typeArguments=this.flowParseTypeParameterInstantiationInExpression()),super.jsxParseOpeningElementAfterName(e)}isLookaheadToken_lt(){let e=this.nextTokenStart();if(this.input.charCodeAt(e)===60){let r=this.input.charCodeAt(e+1);return r!==60&&r!==61}return!1}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}maybeUnwrapTypeCastExpression(e){return e.type==="TypeCastExpression"?e.expression:e}},rR={__proto__:null,quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",fnof:"\u0192",circ:"\u02C6",tilde:"\u02DC",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",bull:"\u2022",hellip:"\u2026",permil:"\u2030",prime:"\u2032",Prime:"\u2033",lsaquo:"\u2039",rsaquo:"\u203A",oline:"\u203E",frasl:"\u2044",euro:"\u20AC",image:"\u2111",weierp:"\u2118",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666"},iR=/\r\n|[\r\n\u2028\u2029]/,Js=new RegExp(iR.source,"g");function or(t){switch(t){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function Mf(t,n,e){for(let r=n;r<e;r++)if(or(t.charCodeAt(r)))return!0;return!1}var Vd=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,Ud=/(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;function sR(t){switch(t){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}var yn=ot`jsx`({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression.",MissingClosingTagElement:({openingTagName:t})=>`Expected corresponding JSX closing tag for <${t}>.`,MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>.",UnexpectedSequenceExpression:"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",UnexpectedToken:({unexpected:t,HTMLEntity:n})=>`Unexpected token \`${t}\`. Did you mean \`${n}\` or \`{'${t}'}\`?`,UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text.",UnterminatedJsxContent:"Unterminated JSX contents.",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"});function Jt(t){return t?t.type==="JSXOpeningFragment"||t.type==="JSXClosingFragment":!1}function ar(t){if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXNamespacedName")return t.namespace.name+":"+t.name.name;if(t.type==="JSXMemberExpression")return ar(t.object)+"."+ar(t.property);throw new Error("Node had unexpected type: "+t.type)}var aR=t=>class extends t{jsxReadToken(){let e="",r=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(yn.UnterminatedJsxContent,this.state.startLoc);let i=this.input.charCodeAt(this.state.pos);switch(i){case 60:case 123:if(this.state.pos===this.state.start){i===60&&this.state.canStartJSXElement?(++this.state.pos,this.finishToken(143)):super.getTokenFromCode(i);return}e+=this.input.slice(r,this.state.pos),this.finishToken(142,e);return;case 38:e+=this.input.slice(r,this.state.pos),e+=this.jsxReadEntity(),r=this.state.pos;break;default:or(i)?(e+=this.input.slice(r,this.state.pos),e+=this.jsxReadNewLine(!0),r=this.state.pos):++this.state.pos}}}jsxReadNewLine(e){let r=this.input.charCodeAt(this.state.pos),i;return++this.state.pos,r===13&&this.input.charCodeAt(this.state.pos)===10?(++this.state.pos,i=e?`
6
6
  `:`\r
7
- `):i=String.fromCharCode(r),++this.state.curLine,this.state.lineStart=this.state.pos,i}jsxReadString(e){let r="",i=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(b.UnterminatedString,this.state.startLoc);let s=this.input.charCodeAt(this.state.pos);if(s===e)break;s===38?(r+=this.input.slice(i,this.state.pos),r+=this.jsxReadEntity(),i=this.state.pos):ar(s)?(r+=this.input.slice(i,this.state.pos),r+=this.jsxReadNewLine(!1),i=this.state.pos):++this.state.pos}r+=this.input.slice(i,this.state.pos++),this.finishToken(134,r)}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let r=10;this.codePointAtPos(this.state.pos)===120&&(r=16,++this.state.pos);let i=this.readInt(r,void 0,!1,"bail");if(i!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(i)}else{let r=0,i=!1;for(;r++<10&&this.state.pos<this.length&&!(i=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(i){let s=this.input.slice(e,this.state.pos),a=rR[s];if(++this.state.pos,a)return a}}return this.state.pos=e,"&"}jsxReadWord(){let e,r=this.state.pos;do e=this.input.charCodeAt(++this.state.pos);while(wn(e)||e===45);this.finishToken(141,this.input.slice(r,this.state.pos))}jsxParseIdentifier(){let e=this.startNode();return this.match(141)?e.name=this.state.value:vc(this.state.type)?e.name=Yt(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){let e=this.state.startLoc,r=this.jsxParseIdentifier();if(!this.eat(14))return r;let i=this.startNodeAt(e);return i.namespace=r,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")}jsxParseElementName(){let e=this.state.startLoc,r=this.jsxParseNamespacedName();if(r.type==="JSXNamespacedName")return r;for(;this.eat(16);){let i=this.startNodeAt(e);i.object=r,i.property=this.jsxParseIdentifier(),r=this.finishNode(i,"JSXMemberExpression")}return r}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(ie.brace),this.next(),e=this.jsxParseExpressionContainer(e,ie.j_oTag),e.expression.type==="JSXEmptyExpression"&&this.raise(yn.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(yn.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){let e=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(e,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(e){return this.next(),e.expression=this.parseExpression(),this.setContext(ie.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,r){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{let i=this.parseExpression();e.expression=i}return this.setContext(r),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){let e=this.startNode();return this.match(5)?(this.setContext(ie.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(ie.j_oTag),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsxParseNamespacedName(),e.value=this.eat(29)?this.jsxParseAttributeValue():null,this.finishNode(e,"JSXAttribute"))}jsxParseOpeningElementAt(e){let r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXOpeningFragment"):(r.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(r))}jsxParseOpeningElementAfterName(e){let r=[];for(;!this.match(56)&&!this.match(144);)r.push(this.jsxParseAttribute());return e.attributes=r,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){let r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXClosingFragment"):(r.name=this.jsxParseElementName(),this.expect(144),this.finishNode(r,"JSXClosingElement"))}jsxParseElementAt(e){let r=this.startNodeAt(e),i=[],s=this.jsxParseOpeningElementAt(e),a=null;if(!s.selfClosing){e:for(;;)switch(this.state.type){case 143:if(e=this.state.startLoc,this.next(),this.eat(56)){a=this.jsxParseClosingElementAt(e);break e}i.push(this.jsxParseElementAt(e));break;case 142:i.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let o=this.startNode();this.setContext(ie.brace),this.next(),this.match(21)?i.push(this.jsxParseSpreadChild(o)):i.push(this.jsxParseExpressionContainer(o,ie.j_expr));break}default:this.unexpected()}Jt(s)&&!Jt(a)&&a!==null?this.raise(yn.MissingClosingTagFragment,a):!Jt(s)&&Jt(a)?this.raise(yn.MissingClosingTagElement,a,{openingTagName:sr(s.name)}):!Jt(s)&&!Jt(a)&&sr(a.name)!==sr(s.name)&&this.raise(yn.MissingClosingTagElement,a,{openingTagName:sr(s.name)})}if(Jt(s)?(r.openingFragment=s,r.closingFragment=a):(r.openingElement=s,r.closingElement=a),r.children=i,this.match(47))throw this.raise(yn.UnwrappedAdjacentJSXElements,this.state.startLoc);return Jt(s)?this.finishNode(r,"JSXFragment"):this.finishNode(r,"JSXElement")}jsxParseElement(){let e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){let{context:r}=this.state;r[r.length-1]=e}parseExprAtom(e){return this.match(143)?this.jsxParseElement():this.match(47)&&this.input.charCodeAt(this.state.pos)!==33?(this.replaceToken(143),this.jsxParseElement()):super.parseExprAtom(e)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(e){let r=this.curContext();if(r===ie.j_expr){this.jsxReadToken();return}if(r===ie.j_oTag||r===ie.j_cTag){if(bt(e)){this.jsxReadWord();return}if(e===62){++this.state.pos,this.finishToken(144);return}if((e===34||e===39)&&r===ie.j_oTag){this.jsxReadString(e);return}}if(e===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos,this.finishToken(143);return}super.getTokenFromCode(e)}updateContext(e){let{context:r,type:i}=this.state;if(i===56&&e===143)r.splice(-2,2,ie.j_cTag),this.state.canStartJSXElement=!1;else if(i===143)r.push(ie.j_oTag);else if(i===144){let s=r[r.length-1];s===ie.j_oTag&&e===56||s===ie.j_cTag?(r.pop(),this.state.canStartJSXElement=r[r.length-1]===ie.j_expr):(this.setContext(ie.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=Ok(i)}},Xd=class extends gi{constructor(...n){super(...n),this.tsNames=new Map}},Qd=class extends wi{constructor(...n){super(...n),this.importsStack=[]}createScope(n){return this.importsStack.push(new Set),new Xd(n)}enter(n){n===1024&&this.importsStack.push(new Set),super.enter(n)}exit(){let n=super.exit();return n===1024&&this.importsStack.pop(),n}hasImport(n,e){let r=this.importsStack.length;if(this.importsStack[r-1].has(n))return!0;if(!e&&r>1){for(let i=0;i<r-1;i++)if(this.importsStack[i].has(n))return!0}return!1}declareName(n,e,r){if(e&4096){this.hasImport(n,!0)&&this.parser.raise(b.VarRedeclaration,r,{identifierName:n}),this.importsStack[this.importsStack.length-1].add(n);return}let i=this.currentScope(),s=i.tsNames.get(n)||0;if(e&1024){this.maybeExportDefined(i,n),i.tsNames.set(n,s|16);return}super.declareName(n,e,r),e&2&&(e&1||(this.checkRedeclarationInScope(i,n,e,r),this.maybeExportDefined(i,n)),s=s|1),e&256&&(s=s|2),e&512&&(s=s|4),e&128&&(s=s|8),s&&i.tsNames.set(n,s)}isRedeclaredInScope(n,e,r){let i=n.tsNames.get(e);if((i&2)>0){if(r&256){let s=!!(r&512),a=(i&4)>0;return s!==a}return!0}return r&128&&(i&8)>0?n.names.get(e)&2?!!(r&1):!1:r&2&&(i&1)>0?!0:super.isRedeclaredInScope(n,e,r)}checkLocalExport(n){let{name:e}=n;if(this.hasImport(e))return;let r=this.scopeStack.length;for(let i=r-1;i>=0;i--){let a=this.scopeStack[i].tsNames.get(e);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(n)}},Zd=class{constructor(){this.stacks=[]}enter(n){this.stacks.push(n)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(this.currentFlags()&2)>0}get hasYield(){return(this.currentFlags()&1)>0}get hasReturn(){return(this.currentFlags()&4)>0}get hasIn(){return(this.currentFlags()&8)>0}};function Zs(t,n){return(t?2:0)|(n?1:0)}var ec=class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}sourceToOffsetPos(n){return n+this.startIndex}offsetToSourcePos(n){return n-this.startIndex}hasPlugin(n){if(typeof n=="string")return this.plugins.has(n);{let[e,r]=n;if(!this.hasPlugin(e))return!1;let i=this.plugins.get(e);for(let s of Object.keys(r))if(i?.[s]!==r[s])return!1;return!0}}getPluginOption(n,e){var r;return(r=this.plugins.get(n))==null?void 0:r[e]}};function Qf(t,n){t.trailingComments===void 0?t.trailingComments=n:t.trailingComments.unshift(...n)}function oR(t,n){t.leadingComments===void 0?t.leadingComments=n:t.leadingComments.unshift(...n)}function bi(t,n){t.innerComments===void 0?t.innerComments=n:t.innerComments.unshift(...n)}function at(t,n,e){let r=null,i=n.length;for(;r===null&&i>0;)r=n[--i];r===null||r.start>e.start?bi(t,e.comments):Qf(r,e.comments)}var tc=class extends ec{addComment(n){this.filename&&(n.loc.filename=this.filename);let{commentsLen:e}=this.state;this.comments.length!==e&&(this.comments.length=e),this.comments.push(n),this.state.commentsLen++}processComment(n){let{commentStack:e}=this.state,r=e.length;if(r===0)return;let i=r-1,s=e[i];s.start===n.end&&(s.leadingNode=n,i--);let{start:a}=n;for(;i>=0;i--){let o=e[i],d=o.end;if(d>a)o.containingNode=n,this.finalizeComment(o),e.splice(i,1);else{d===a&&(o.trailingNode=n);break}}}finalizeComment(n){var e;let{comments:r}=n;if(n.leadingNode!==null||n.trailingNode!==null)n.leadingNode!==null&&Qf(n.leadingNode,r),n.trailingNode!==null&&oR(n.trailingNode,r);else{let i=n.containingNode,s=n.start;if(this.input.charCodeAt(this.offsetToSourcePos(s)-1)===44)switch(i.type){case"ObjectExpression":case"ObjectPattern":at(i,i.properties,n);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":at(i,i.arguments,n);break;case"ImportExpression":at(i,[i.source,(e=i.options)!=null?e:null],n);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":at(i,i.params,n);break;case"ArrayExpression":case"ArrayPattern":at(i,i.elements,n);break;case"ExportNamedDeclaration":case"ImportDeclaration":at(i,i.specifiers,n);break;case"TSEnumDeclaration":at(i,i.members,n);break;case"TSEnumBody":at(i,i.members,n);break;case"TSInterfaceBody":at(i,i.body,n);break;default:{if(i.type==="RecordExpression"){at(i,i.properties,n);break}if(i.type==="TupleExpression"){at(i,i.elements,n);break}bi(i,r)}}else bi(i,r)}}finalizeRemainingComments(){let{commentStack:n}=this.state;for(let e=n.length-1;e>=0;e--)this.finalizeComment(n[e]);this.state.commentStack=[]}resetPreviousNodeTrailingComments(n){let{commentStack:e}=this.state,{length:r}=e;if(r===0)return;let i=e[r-1];i.leadingNode===n&&(i.leadingNode=null)}takeSurroundingComments(n,e,r){let{commentStack:i}=this.state,s=i.length;if(s===0)return;let a=s-1;for(;a>=0;a--){let o=i[a],d=o.end;if(o.start===r)o.leadingNode=n;else if(d===e)o.trailingNode=n;else if(d<e)break}}},nc=class t{constructor(){this.flags=1024,this.startIndex=void 0,this.curLine=void 0,this.lineStart=void 0,this.startLoc=void 0,this.endLoc=void 0,this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.labels=[],this.commentsLen=0,this.commentStack=[],this.pos=0,this.type=140,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.context=[ie.brace],this.firstInvalidTemplateEscapePos=null,this.strictErrors=new Map,this.tokensLength=0}get strict(){return(this.flags&1)>0}set strict(n){n?this.flags|=1:this.flags&=-2}init({strictMode:n,sourceType:e,startIndex:r,startLine:i,startColumn:s}){this.strict=n===!1?!1:n===!0?!0:e==="module",this.startIndex=r,this.curLine=i,this.lineStart=-s,this.startLoc=this.endLoc=new xt(i,s,r)}get maybeInArrowParameters(){return(this.flags&2)>0}set maybeInArrowParameters(n){n?this.flags|=2:this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(n){n?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(n){n?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(n){n?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(n){n?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(n){n?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(n){n?this.flags|=128:this.flags&=-129}get soloAwait(){return(this.flags&256)>0}set soloAwait(n){n?this.flags|=256:this.flags&=-257}get inFSharpPipelineDirectBody(){return(this.flags&512)>0}set inFSharpPipelineDirectBody(n){n?this.flags|=512:this.flags&=-513}get canStartJSXElement(){return(this.flags&1024)>0}set canStartJSXElement(n){n?this.flags|=1024:this.flags&=-1025}get containsEsc(){return(this.flags&2048)>0}set containsEsc(n){n?this.flags|=2048:this.flags&=-2049}get hasTopLevelAwait(){return(this.flags&4096)>0}set hasTopLevelAwait(n){n?this.flags|=4096:this.flags&=-4097}curPosition(){return new xt(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let n=new t;return n.flags=this.flags,n.startIndex=this.startIndex,n.curLine=this.curLine,n.lineStart=this.lineStart,n.startLoc=this.startLoc,n.endLoc=this.endLoc,n.errors=this.errors.slice(),n.potentialArrowAt=this.potentialArrowAt,n.noArrowAt=this.noArrowAt.slice(),n.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),n.topicContext=this.topicContext,n.labels=this.labels.slice(),n.commentsLen=this.commentsLen,n.commentStack=this.commentStack.slice(),n.pos=this.pos,n.type=this.type,n.value=this.value,n.start=this.start,n.end=this.end,n.lastTokEndLoc=this.lastTokEndLoc,n.lastTokStartLoc=this.lastTokStartLoc,n.context=this.context.slice(),n.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,n.strictErrors=this.strictErrors,n.tokensLength=this.tokensLength,n}},dR=function(n){return n>=48&&n<=57},_f={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},Ys={bin:t=>t===48||t===49,oct:t=>t>=48&&t<=55,dec:t=>t>=48&&t<=57,hex:t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102};function jf(t,n,e,r,i,s){let a=e,o=r,d=i,c="",l=null,u=e,{length:p}=n;for(;;){if(e>=p){s.unterminated(a,o,d),c+=n.slice(u,e);break}let f=n.charCodeAt(e);if(cR(t,f,n,e)){c+=n.slice(u,e);break}if(f===92){c+=n.slice(u,e);let h=lR(n,e,r,i,t==="template",s);h.ch===null&&!l?l={pos:e,lineStart:r,curLine:i}:c+=h.ch,{pos:e,lineStart:r,curLine:i}=h,u=e}else f===8232||f===8233?(++e,++i,r=e):f===10||f===13?t==="template"?(c+=n.slice(u,e)+`
7
+ `):i=String.fromCharCode(r),++this.state.curLine,this.state.lineStart=this.state.pos,i}jsxReadString(e){let r="",i=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(b.UnterminatedString,this.state.startLoc);let s=this.input.charCodeAt(this.state.pos);if(s===e)break;s===38?(r+=this.input.slice(i,this.state.pos),r+=this.jsxReadEntity(),i=this.state.pos):or(s)?(r+=this.input.slice(i,this.state.pos),r+=this.jsxReadNewLine(!1),i=this.state.pos):++this.state.pos}r+=this.input.slice(i,this.state.pos++),this.finishToken(134,r)}jsxReadEntity(){let e=++this.state.pos;if(this.codePointAtPos(this.state.pos)===35){++this.state.pos;let r=10;this.codePointAtPos(this.state.pos)===120&&(r=16,++this.state.pos);let i=this.readInt(r,void 0,!1,"bail");if(i!==null&&this.codePointAtPos(this.state.pos)===59)return++this.state.pos,String.fromCodePoint(i)}else{let r=0,i=!1;for(;r++<10&&this.state.pos<this.length&&!(i=this.codePointAtPos(this.state.pos)===59);)++this.state.pos;if(i){let s=this.input.slice(e,this.state.pos),a=rR[s];if(++this.state.pos,a)return a}}return this.state.pos=e,"&"}jsxReadWord(){let e,r=this.state.pos;do e=this.input.charCodeAt(++this.state.pos);while(wn(e)||e===45);this.finishToken(141,this.input.slice(r,this.state.pos))}jsxParseIdentifier(){let e=this.startNode();return this.match(141)?e.name=this.state.value:vc(this.state.type)?e.name=Yt(this.state.type):this.unexpected(),this.next(),this.finishNode(e,"JSXIdentifier")}jsxParseNamespacedName(){let e=this.state.startLoc,r=this.jsxParseIdentifier();if(!this.eat(14))return r;let i=this.startNodeAt(e);return i.namespace=r,i.name=this.jsxParseIdentifier(),this.finishNode(i,"JSXNamespacedName")}jsxParseElementName(){let e=this.state.startLoc,r=this.jsxParseNamespacedName();if(r.type==="JSXNamespacedName")return r;for(;this.eat(16);){let i=this.startNodeAt(e);i.object=r,i.property=this.jsxParseIdentifier(),r=this.finishNode(i,"JSXMemberExpression")}return r}jsxParseAttributeValue(){let e;switch(this.state.type){case 5:return e=this.startNode(),this.setContext(ie.brace),this.next(),e=this.jsxParseExpressionContainer(e,ie.j_oTag),e.expression.type==="JSXEmptyExpression"&&this.raise(yn.AttributeIsEmpty,e),e;case 143:case 134:return this.parseExprAtom();default:throw this.raise(yn.UnsupportedJsxValue,this.state.startLoc)}}jsxParseEmptyExpression(){let e=this.startNodeAt(this.state.lastTokEndLoc);return this.finishNodeAt(e,"JSXEmptyExpression",this.state.startLoc)}jsxParseSpreadChild(e){return this.next(),e.expression=this.parseExpression(),this.setContext(ie.j_expr),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadChild")}jsxParseExpressionContainer(e,r){if(this.match(8))e.expression=this.jsxParseEmptyExpression();else{let i=this.parseExpression();e.expression=i}return this.setContext(r),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXExpressionContainer")}jsxParseAttribute(){let e=this.startNode();return this.match(5)?(this.setContext(ie.brace),this.next(),this.expect(21),e.argument=this.parseMaybeAssignAllowIn(),this.setContext(ie.j_oTag),this.state.canStartJSXElement=!0,this.expect(8),this.finishNode(e,"JSXSpreadAttribute")):(e.name=this.jsxParseNamespacedName(),e.value=this.eat(29)?this.jsxParseAttributeValue():null,this.finishNode(e,"JSXAttribute"))}jsxParseOpeningElementAt(e){let r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXOpeningFragment"):(r.name=this.jsxParseElementName(),this.jsxParseOpeningElementAfterName(r))}jsxParseOpeningElementAfterName(e){let r=[];for(;!this.match(56)&&!this.match(144);)r.push(this.jsxParseAttribute());return e.attributes=r,e.selfClosing=this.eat(56),this.expect(144),this.finishNode(e,"JSXOpeningElement")}jsxParseClosingElementAt(e){let r=this.startNodeAt(e);return this.eat(144)?this.finishNode(r,"JSXClosingFragment"):(r.name=this.jsxParseElementName(),this.expect(144),this.finishNode(r,"JSXClosingElement"))}jsxParseElementAt(e){let r=this.startNodeAt(e),i=[],s=this.jsxParseOpeningElementAt(e),a=null;if(!s.selfClosing){e:for(;;)switch(this.state.type){case 143:if(e=this.state.startLoc,this.next(),this.eat(56)){a=this.jsxParseClosingElementAt(e);break e}i.push(this.jsxParseElementAt(e));break;case 142:i.push(this.parseLiteral(this.state.value,"JSXText"));break;case 5:{let o=this.startNode();this.setContext(ie.brace),this.next(),this.match(21)?i.push(this.jsxParseSpreadChild(o)):i.push(this.jsxParseExpressionContainer(o,ie.j_expr));break}default:this.unexpected()}Jt(s)&&!Jt(a)&&a!==null?this.raise(yn.MissingClosingTagFragment,a):!Jt(s)&&Jt(a)?this.raise(yn.MissingClosingTagElement,a,{openingTagName:ar(s.name)}):!Jt(s)&&!Jt(a)&&ar(a.name)!==ar(s.name)&&this.raise(yn.MissingClosingTagElement,a,{openingTagName:ar(s.name)})}if(Jt(s)?(r.openingFragment=s,r.closingFragment=a):(r.openingElement=s,r.closingElement=a),r.children=i,this.match(47))throw this.raise(yn.UnwrappedAdjacentJSXElements,this.state.startLoc);return Jt(s)?this.finishNode(r,"JSXFragment"):this.finishNode(r,"JSXElement")}jsxParseElement(){let e=this.state.startLoc;return this.next(),this.jsxParseElementAt(e)}setContext(e){let{context:r}=this.state;r[r.length-1]=e}parseExprAtom(e){return this.match(143)?this.jsxParseElement():this.match(47)&&this.input.charCodeAt(this.state.pos)!==33?(this.replaceToken(143),this.jsxParseElement()):super.parseExprAtom(e)}skipSpace(){this.curContext().preserveSpace||super.skipSpace()}getTokenFromCode(e){let r=this.curContext();if(r===ie.j_expr){this.jsxReadToken();return}if(r===ie.j_oTag||r===ie.j_cTag){if(bt(e)){this.jsxReadWord();return}if(e===62){++this.state.pos,this.finishToken(144);return}if((e===34||e===39)&&r===ie.j_oTag){this.jsxReadString(e);return}}if(e===60&&this.state.canStartJSXElement&&this.input.charCodeAt(this.state.pos+1)!==33){++this.state.pos,this.finishToken(143);return}super.getTokenFromCode(e)}updateContext(e){let{context:r,type:i}=this.state;if(i===56&&e===143)r.splice(-2,2,ie.j_cTag),this.state.canStartJSXElement=!1;else if(i===143)r.push(ie.j_oTag);else if(i===144){let s=r[r.length-1];s===ie.j_oTag&&e===56||s===ie.j_cTag?(r.pop(),this.state.canStartJSXElement=r[r.length-1]===ie.j_expr):(this.setContext(ie.j_expr),this.state.canStartJSXElement=!0)}else this.state.canStartJSXElement=Ok(i)}},Xd=class extends gi{constructor(...n){super(...n),this.tsNames=new Map}},Qd=class extends wi{constructor(...n){super(...n),this.importsStack=[]}createScope(n){return this.importsStack.push(new Set),new Xd(n)}enter(n){n===1024&&this.importsStack.push(new Set),super.enter(n)}exit(){let n=super.exit();return n===1024&&this.importsStack.pop(),n}hasImport(n,e){let r=this.importsStack.length;if(this.importsStack[r-1].has(n))return!0;if(!e&&r>1){for(let i=0;i<r-1;i++)if(this.importsStack[i].has(n))return!0}return!1}declareName(n,e,r){if(e&4096){this.hasImport(n,!0)&&this.parser.raise(b.VarRedeclaration,r,{identifierName:n}),this.importsStack[this.importsStack.length-1].add(n);return}let i=this.currentScope(),s=i.tsNames.get(n)||0;if(e&1024){this.maybeExportDefined(i,n),i.tsNames.set(n,s|16);return}super.declareName(n,e,r),e&2&&(e&1||(this.checkRedeclarationInScope(i,n,e,r),this.maybeExportDefined(i,n)),s=s|1),e&256&&(s=s|2),e&512&&(s=s|4),e&128&&(s=s|8),s&&i.tsNames.set(n,s)}isRedeclaredInScope(n,e,r){let i=n.tsNames.get(e);if((i&2)>0){if(r&256){let s=!!(r&512),a=(i&4)>0;return s!==a}return!0}return r&128&&(i&8)>0?n.names.get(e)&2?!!(r&1):!1:r&2&&(i&1)>0?!0:super.isRedeclaredInScope(n,e,r)}checkLocalExport(n){let{name:e}=n;if(this.hasImport(e))return;let r=this.scopeStack.length;for(let i=r-1;i>=0;i--){let a=this.scopeStack[i].tsNames.get(e);if((a&1)>0||(a&16)>0)return}super.checkLocalExport(n)}},Zd=class{constructor(){this.stacks=[]}enter(n){this.stacks.push(n)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(this.currentFlags()&2)>0}get hasYield(){return(this.currentFlags()&1)>0}get hasReturn(){return(this.currentFlags()&4)>0}get hasIn(){return(this.currentFlags()&8)>0}};function Zs(t,n){return(t?2:0)|(n?1:0)}var ec=class{constructor(){this.sawUnambiguousESM=!1,this.ambiguousScriptDifferentAst=!1}sourceToOffsetPos(n){return n+this.startIndex}offsetToSourcePos(n){return n-this.startIndex}hasPlugin(n){if(typeof n=="string")return this.plugins.has(n);{let[e,r]=n;if(!this.hasPlugin(e))return!1;let i=this.plugins.get(e);for(let s of Object.keys(r))if(i?.[s]!==r[s])return!1;return!0}}getPluginOption(n,e){var r;return(r=this.plugins.get(n))==null?void 0:r[e]}};function Qf(t,n){t.trailingComments===void 0?t.trailingComments=n:t.trailingComments.unshift(...n)}function oR(t,n){t.leadingComments===void 0?t.leadingComments=n:t.leadingComments.unshift(...n)}function bi(t,n){t.innerComments===void 0?t.innerComments=n:t.innerComments.unshift(...n)}function at(t,n,e){let r=null,i=n.length;for(;r===null&&i>0;)r=n[--i];r===null||r.start>e.start?bi(t,e.comments):Qf(r,e.comments)}var tc=class extends ec{addComment(n){this.filename&&(n.loc.filename=this.filename);let{commentsLen:e}=this.state;this.comments.length!==e&&(this.comments.length=e),this.comments.push(n),this.state.commentsLen++}processComment(n){let{commentStack:e}=this.state,r=e.length;if(r===0)return;let i=r-1,s=e[i];s.start===n.end&&(s.leadingNode=n,i--);let{start:a}=n;for(;i>=0;i--){let o=e[i],d=o.end;if(d>a)o.containingNode=n,this.finalizeComment(o),e.splice(i,1);else{d===a&&(o.trailingNode=n);break}}}finalizeComment(n){var e;let{comments:r}=n;if(n.leadingNode!==null||n.trailingNode!==null)n.leadingNode!==null&&Qf(n.leadingNode,r),n.trailingNode!==null&&oR(n.trailingNode,r);else{let i=n.containingNode,s=n.start;if(this.input.charCodeAt(this.offsetToSourcePos(s)-1)===44)switch(i.type){case"ObjectExpression":case"ObjectPattern":at(i,i.properties,n);break;case"CallExpression":case"NewExpression":case"OptionalCallExpression":at(i,i.arguments,n);break;case"ImportExpression":at(i,[i.source,(e=i.options)!=null?e:null],n);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":case"ObjectMethod":case"ClassMethod":case"ClassPrivateMethod":case"TSTypeParameterDeclaration":at(i,i.params,n);break;case"ArrayExpression":case"ArrayPattern":at(i,i.elements,n);break;case"ExportNamedDeclaration":case"ImportDeclaration":at(i,i.specifiers,n);break;case"TSEnumDeclaration":at(i,i.members,n);break;case"TSEnumBody":at(i,i.members,n);break;case"TSInterfaceBody":at(i,i.body,n);break;default:{if(i.type==="RecordExpression"){at(i,i.properties,n);break}if(i.type==="TupleExpression"){at(i,i.elements,n);break}bi(i,r)}}else bi(i,r)}}finalizeRemainingComments(){let{commentStack:n}=this.state;for(let e=n.length-1;e>=0;e--)this.finalizeComment(n[e]);this.state.commentStack=[]}resetPreviousNodeTrailingComments(n){let{commentStack:e}=this.state,{length:r}=e;if(r===0)return;let i=e[r-1];i.leadingNode===n&&(i.leadingNode=null)}takeSurroundingComments(n,e,r){let{commentStack:i}=this.state,s=i.length;if(s===0)return;let a=s-1;for(;a>=0;a--){let o=i[a],d=o.end;if(o.start===r)o.leadingNode=n;else if(d===e)o.trailingNode=n;else if(d<e)break}}},nc=class t{constructor(){this.flags=1024,this.startIndex=void 0,this.curLine=void 0,this.lineStart=void 0,this.startLoc=void 0,this.endLoc=void 0,this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.labels=[],this.commentsLen=0,this.commentStack=[],this.pos=0,this.type=140,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.context=[ie.brace],this.firstInvalidTemplateEscapePos=null,this.strictErrors=new Map,this.tokensLength=0}get strict(){return(this.flags&1)>0}set strict(n){n?this.flags|=1:this.flags&=-2}init({strictMode:n,sourceType:e,startIndex:r,startLine:i,startColumn:s}){this.strict=n===!1?!1:n===!0?!0:e==="module",this.startIndex=r,this.curLine=i,this.lineStart=-s,this.startLoc=this.endLoc=new xt(i,s,r)}get maybeInArrowParameters(){return(this.flags&2)>0}set maybeInArrowParameters(n){n?this.flags|=2:this.flags&=-3}get inType(){return(this.flags&4)>0}set inType(n){n?this.flags|=4:this.flags&=-5}get noAnonFunctionType(){return(this.flags&8)>0}set noAnonFunctionType(n){n?this.flags|=8:this.flags&=-9}get hasFlowComment(){return(this.flags&16)>0}set hasFlowComment(n){n?this.flags|=16:this.flags&=-17}get isAmbientContext(){return(this.flags&32)>0}set isAmbientContext(n){n?this.flags|=32:this.flags&=-33}get inAbstractClass(){return(this.flags&64)>0}set inAbstractClass(n){n?this.flags|=64:this.flags&=-65}get inDisallowConditionalTypesContext(){return(this.flags&128)>0}set inDisallowConditionalTypesContext(n){n?this.flags|=128:this.flags&=-129}get soloAwait(){return(this.flags&256)>0}set soloAwait(n){n?this.flags|=256:this.flags&=-257}get inFSharpPipelineDirectBody(){return(this.flags&512)>0}set inFSharpPipelineDirectBody(n){n?this.flags|=512:this.flags&=-513}get canStartJSXElement(){return(this.flags&1024)>0}set canStartJSXElement(n){n?this.flags|=1024:this.flags&=-1025}get containsEsc(){return(this.flags&2048)>0}set containsEsc(n){n?this.flags|=2048:this.flags&=-2049}get hasTopLevelAwait(){return(this.flags&4096)>0}set hasTopLevelAwait(n){n?this.flags|=4096:this.flags&=-4097}curPosition(){return new xt(this.curLine,this.pos-this.lineStart,this.pos+this.startIndex)}clone(){let n=new t;return n.flags=this.flags,n.startIndex=this.startIndex,n.curLine=this.curLine,n.lineStart=this.lineStart,n.startLoc=this.startLoc,n.endLoc=this.endLoc,n.errors=this.errors.slice(),n.potentialArrowAt=this.potentialArrowAt,n.noArrowAt=this.noArrowAt.slice(),n.noArrowParamsConversionAt=this.noArrowParamsConversionAt.slice(),n.topicContext=this.topicContext,n.labels=this.labels.slice(),n.commentsLen=this.commentsLen,n.commentStack=this.commentStack.slice(),n.pos=this.pos,n.type=this.type,n.value=this.value,n.start=this.start,n.end=this.end,n.lastTokEndLoc=this.lastTokEndLoc,n.lastTokStartLoc=this.lastTokStartLoc,n.context=this.context.slice(),n.firstInvalidTemplateEscapePos=this.firstInvalidTemplateEscapePos,n.strictErrors=this.strictErrors,n.tokensLength=this.tokensLength,n}},dR=function(n){return n>=48&&n<=57},_f={decBinOct:new Set([46,66,69,79,95,98,101,111]),hex:new Set([46,88,95,120])},Ys={bin:t=>t===48||t===49,oct:t=>t>=48&&t<=55,dec:t=>t>=48&&t<=57,hex:t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102};function jf(t,n,e,r,i,s){let a=e,o=r,d=i,c="",l=null,u=e,{length:p}=n;for(;;){if(e>=p){s.unterminated(a,o,d),c+=n.slice(u,e);break}let f=n.charCodeAt(e);if(cR(t,f,n,e)){c+=n.slice(u,e);break}if(f===92){c+=n.slice(u,e);let h=lR(n,e,r,i,t==="template",s);h.ch===null&&!l?l={pos:e,lineStart:r,curLine:i}:c+=h.ch,{pos:e,lineStart:r,curLine:i}=h,u=e}else f===8232||f===8233?(++e,++i,r=e):f===10||f===13?t==="template"?(c+=n.slice(u,e)+`
8
8
  `,++e,f===13&&n.charCodeAt(e)===10&&++e,++i,u=r=e):s.unterminated(a,o,d):++e}return{pos:e,str:c,firstInvalidLoc:l,lineStart:r,curLine:i,containsInvalid:!!l}}function cR(t,n,e,r){return t==="template"?n===96||n===36&&e.charCodeAt(r+1)===123:n===(t==="double"?34:39)}function lR(t,n,e,r,i,s){let a=!i;n++;let o=c=>({pos:n,ch:c,lineStart:e,curLine:r}),d=t.charCodeAt(n++);switch(d){case 110:return o(`
9
- `);case 114:return o("\r");case 120:{let c;return{code:c,pos:n}=rc(t,n,e,r,2,!1,a,s),o(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:n}=eh(t,n,e,r,a,s),o(c===null?null:String.fromCodePoint(c))}case 116:return o(" ");case 98:return o("\b");case 118:return o("\v");case 102:return o("\f");case 13:t.charCodeAt(n)===10&&++n;case 10:e=n,++r;case 8232:case 8233:return o("");case 56:case 57:if(i)return o(null);s.strictNumericEscape(n-1,e,r);default:if(d>=48&&d<=55){let c=n-1,u=/^[0-7]+/.exec(t.slice(c,n+2))[0],p=parseInt(u,8);p>255&&(u=u.slice(0,-1),p=parseInt(u,8)),n+=u.length-1;let f=t.charCodeAt(n);if(u!=="0"||f===56||f===57){if(i)return o(null);s.strictNumericEscape(c,e,r)}return o(String.fromCharCode(p))}return o(String.fromCharCode(d))}}function rc(t,n,e,r,i,s,a,o){let d=n,c;return{n:c,pos:n}=Zf(t,n,e,r,16,i,s,!1,o,!a),c===null&&(a?o.invalidEscapeSequence(d,e,r):n=d-1),{code:c,pos:n}}function Zf(t,n,e,r,i,s,a,o,d,c){let l=n,u=i===16?_f.hex:_f.decBinOct,p=i===16?Ys.hex:i===10?Ys.dec:i===8?Ys.oct:Ys.bin,f=!1,h=0;for(let m=0,g=s??1/0;m<g;++m){let y=t.charCodeAt(n),w;if(y===95&&o!=="bail"){let x=t.charCodeAt(n-1),v=t.charCodeAt(n+1);if(o){if(Number.isNaN(v)||!p(v)||u.has(x)||u.has(v)){if(c)return{n:null,pos:n};d.unexpectedNumericSeparator(n,e,r)}}else{if(c)return{n:null,pos:n};d.numericSeparatorInEscapeSequence(n,e,r)}++n;continue}if(y>=97?w=y-97+10:y>=65?w=y-65+10:dR(y)?w=y-48:w=1/0,w>=i){if(w<=9&&c)return{n:null,pos:n};if(w<=9&&d.invalidDigit(n,e,r,i))w=0;else if(a)w=0,f=!0;else break}++n,h=h*i+w}return n===l||s!=null&&n-l!==s||f?{n:null,pos:n}:{n:h,pos:n}}function eh(t,n,e,r,i,s){let a=t.charCodeAt(n),o;if(a===123){if(++n,{code:o,pos:n}=rc(t,n,e,r,t.indexOf("}",n)-n,!0,i,s),++n,o!==null&&o>1114111)if(i)s.invalidCodePoint(n,e,r);else return{code:null,pos:n}}else({code:o,pos:n}=rc(t,n,e,r,4,!1,i,s));return{code:o,pos:n}}function fi(t,n,e){return new xt(e,t-n,t)}var uR=new Set([103,109,115,105,121,117,100,118]),wt=class{constructor(n){let e=n.startIndex||0;this.type=n.type,this.value=n.value,this.start=e+n.start,this.end=e+n.end,this.loc=new dr(n.startLoc,n.endLoc)}},ic=class extends tc{constructor(n,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(r,i,s,a)=>this.optionFlags&2048?(this.raise(b.InvalidDigit,fi(r,i,s),{radix:a}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(b.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(b.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(b.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(b.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(r,i,s)=>{this.recordStrictModeErrors(b.StrictNumericEscape,fi(r,i,s))},unterminated:(r,i,s)=>{throw this.raise(b.UnterminatedString,fi(r-1,i,s))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(b.StrictNumericEscape),unterminated:(r,i,s)=>{throw this.raise(b.UnterminatedTemplate,fi(r,i,s))}}),this.state=new nc,this.state.init(n),this.input=e,this.length=e.length,this.comments=[],this.isLookahead=!1}pushToken(n){this.tokens.length=this.state.tokensLength,this.tokens.push(n),++this.state.tokensLength}next(){this.checkKeywordEscapes(),this.optionFlags&256&&this.pushToken(new wt(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(n){return this.match(n)?(this.next(),!0):!1}match(n){return this.state.type===n}createLookaheadState(n){return{pos:n.pos,value:null,type:n.type,start:n.start,end:n.end,context:[this.curContext()],inType:n.inType,startLoc:n.startLoc,lastTokEndLoc:n.lastTokEndLoc,curLine:n.curLine,lineStart:n.lineStart,curPosition:n.curPosition}}lookahead(){let n=this.state;this.state=this.createLookaheadState(n),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;let e=this.state;return this.state=n,e}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(n){return Vd.lastIndex=n,Vd.test(this.input)?Vd.lastIndex:n}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(n){return this.input.charCodeAt(this.nextTokenStartSince(n))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(n){return Ud.lastIndex=n,Ud.test(this.input)?Ud.lastIndex:n}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(n){let e=this.input.charCodeAt(n);if((e&64512)===55296&&++n<this.input.length){let r=this.input.charCodeAt(n);(r&64512)===56320&&(e=65536+((e&1023)<<10)+(r&1023))}return e}setStrict(n){this.state.strict=n,n&&(this.state.strictErrors.forEach(([e,r])=>this.raise(e,r)),this.state.strictErrors.clear())}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){if(this.skipSpace(),this.state.start=this.state.pos,this.isLookahead||(this.state.startLoc=this.state.curPosition()),this.state.pos>=this.length){this.finishToken(140);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(n){let e;this.isLookahead||(e=this.state.curPosition());let r=this.state.pos,i=this.input.indexOf(n,r+2);if(i===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition());for(this.state.pos=i+n.length,Js.lastIndex=r+2;Js.test(this.input)&&Js.lastIndex<=i;)++this.state.curLine,this.state.lineStart=Js.lastIndex;if(this.isLookahead)return;let s={type:"CommentBlock",value:this.input.slice(r+2,i),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(i+n.length),loc:new dr(e,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(s),s}skipLineComment(n){let e=this.state.pos,r;this.isLookahead||(r=this.state.curPosition());let i=this.input.charCodeAt(this.state.pos+=n);if(this.state.pos<this.length)for(;!ar(i)&&++this.state.pos<this.length;)i=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let s=this.state.pos,o={type:"CommentLine",value:this.input.slice(e+n,s),start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(s),loc:new dr(r,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(o),o}skipSpace(){let n=this.state.pos,e=this.optionFlags&4096?[]:null;e:for(;this.state.pos<this.length;){let r=this.input.charCodeAt(this.state.pos);switch(r){case 32:case 160:case 9:++this.state.pos;break;case 13:this.input.charCodeAt(this.state.pos+1)===10&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{let i=this.skipBlockComment("*/");i!==void 0&&(this.addComment(i),e?.push(i));break}case 47:{let i=this.skipLineComment(2);i!==void 0&&(this.addComment(i),e?.push(i));break}default:break e}break;default:if(sR(r))++this.state.pos;else if(r===45&&!this.inModule&&this.optionFlags&8192){let i=this.state.pos;if(this.input.charCodeAt(i+1)===45&&this.input.charCodeAt(i+2)===62&&(n===0||this.state.lineStart>n)){let s=this.skipLineComment(3);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else if(r===60&&!this.inModule&&this.optionFlags&8192){let i=this.state.pos;if(this.input.charCodeAt(i+1)===33&&this.input.charCodeAt(i+2)===45&&this.input.charCodeAt(i+3)===45){let s=this.skipLineComment(4);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else break e}}if(e?.length>0){let r=this.state.pos,i={start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(r),comments:e,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(i)}}finishToken(n,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();let r=this.state.type;this.state.type=n,this.state.value=e,this.isLookahead||this.updateContext(r)}replaceToken(n){this.state.type=n,this.updateContext()}readToken_numberSign(){if(this.state.pos===0&&this.readToken_interpreter())return;let n=this.state.pos+1,e=this.codePointAtPos(n);if(e>=48&&e<=57)throw this.raise(b.UnexpectedDigitAfterHash,this.state.curPosition());if(e===123||e===91&&this.hasPlugin("recordAndTuple")){if(this.expectPlugin("recordAndTuple"),this.getPluginOption("recordAndTuple","syntaxType")==="bar")throw this.raise(e===123?b.RecordExpressionHashIncorrectStartSyntaxType:b.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,e===123?this.finishToken(7):this.finishToken(1)}else bt(e)?(++this.state.pos,this.finishToken(139,this.readWord1(e))):e===92?(++this.state.pos,this.finishToken(139,this.readWord1())):this.finishOp(27,1)}readToken_dot(){let n=this.input.charCodeAt(this.state.pos+1);if(n>=48&&n<=57){this.readNumber(!0);return}n===46&&this.input.charCodeAt(this.state.pos+2)===46?(this.state.pos+=3,this.finishToken(21)):(++this.state.pos,this.finishToken(16))}readToken_slash(){this.input.charCodeAt(this.state.pos+1)===61?this.finishOp(31,2):this.finishOp(56,1)}readToken_interpreter(){if(this.state.pos!==0||this.length<2)return!1;let n=this.input.charCodeAt(this.state.pos+1);if(n!==33)return!1;let e=this.state.pos;for(this.state.pos+=1;!ar(n)&&++this.state.pos<this.length;)n=this.input.charCodeAt(this.state.pos);let r=this.input.slice(e+2,this.state.pos);return this.finishToken(28,r),!0}readToken_mult_modulo(n){let e=n===42?55:54,r=1,i=this.input.charCodeAt(this.state.pos+1);n===42&&i===42&&(r++,i=this.input.charCodeAt(this.state.pos+2),e=57),i===61&&!this.state.inType&&(r++,e=n===37?33:30),this.finishOp(e,r)}readToken_pipe_amp(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===n){this.input.charCodeAt(this.state.pos+2)===61?this.finishOp(30,3):this.finishOp(n===124?41:42,2);return}if(n===124){if(e===62){this.finishOp(39,2);return}if(this.hasPlugin("recordAndTuple")&&e===125){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(9);return}if(this.hasPlugin("recordAndTuple")&&e===93){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(4);return}}if(e===61){this.finishOp(30,2);return}this.finishOp(n===124?43:45,1)}readToken_caret(){let n=this.input.charCodeAt(this.state.pos+1);n===61&&!this.state.inType?this.finishOp(32,2):n===94&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])?(this.finishOp(37,2),this.input.codePointAt(this.state.pos)===94&&this.unexpected()):this.finishOp(44,1)}readToken_atSign(){this.input.charCodeAt(this.state.pos+1)===64&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])?this.finishOp(38,2):this.finishOp(26,1)}readToken_plus_min(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===n){this.finishOp(34,2);return}e===61?this.finishOp(30,2):this.finishOp(53,1)}readToken_lt(){let{pos:n}=this.state,e=this.input.charCodeAt(n+1);if(e===60){if(this.input.charCodeAt(n+2)===61){this.finishOp(30,3);return}this.finishOp(51,2);return}if(e===61){this.finishOp(49,2);return}this.finishOp(47,1)}readToken_gt(){let{pos:n}=this.state,e=this.input.charCodeAt(n+1);if(e===62){let r=this.input.charCodeAt(n+2)===62?3:2;if(this.input.charCodeAt(n+r)===61){this.finishOp(30,r+1);return}this.finishOp(52,r);return}if(e===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===61){this.finishOp(46,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(n===61&&e===62){this.state.pos+=2,this.finishToken(19);return}this.finishOp(n===61?29:35,1)}readToken_question(){let n=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);n===63?e===61?this.finishOp(30,3):this.finishOp(40,2):n===46&&!(e>=48&&e<=57)?(this.state.pos+=2,this.finishToken(18)):(++this.state.pos,this.finishToken(17))}getTokenFromCode(n){switch(n){case 46:this.readToken_dot();return;case 40:++this.state.pos,this.finishToken(10);return;case 41:++this.state.pos,this.finishToken(11);return;case 59:++this.state.pos,this.finishToken(13);return;case 44:++this.state.pos,this.finishToken(12);return;case 91:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.TupleExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(2)}else++this.state.pos,this.finishToken(0);return;case 93:++this.state.pos,this.finishToken(3);return;case 123:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.RecordExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(6)}else++this.state.pos,this.finishToken(5);return;case 125:++this.state.pos,this.finishToken(8);return;case 58:this.hasPlugin("functionBind")&&this.input.charCodeAt(this.state.pos+1)===58?this.finishOp(15,2):(++this.state.pos,this.finishToken(14));return;case 63:this.readToken_question();return;case 96:this.readTemplateToken();return;case 48:{let e=this.input.charCodeAt(this.state.pos+1);if(e===120||e===88){this.readRadixNumber(16);return}if(e===111||e===79){this.readRadixNumber(8);return}if(e===98||e===66){this.readRadixNumber(2);return}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:this.readNumber(!1);return;case 34:case 39:this.readString(n);return;case 47:this.readToken_slash();return;case 37:case 42:this.readToken_mult_modulo(n);return;case 124:case 38:this.readToken_pipe_amp(n);return;case 94:this.readToken_caret();return;case 43:case 45:this.readToken_plus_min(n);return;case 60:this.readToken_lt();return;case 62:this.readToken_gt();return;case 61:case 33:this.readToken_eq_excl(n);return;case 126:this.finishOp(36,1);return;case 64:this.readToken_atSign();return;case 35:this.readToken_numberSign();return;case 92:this.readWord();return;default:if(bt(n)){this.readWord(n);return}}throw this.raise(b.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(n)})}finishOp(n,e){let r=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(n,r)}readRegexp(){let n=this.state.startLoc,e=this.state.start+1,r,i,{pos:s}=this.state;for(;;++s){if(s>=this.length)throw this.raise(b.UnterminatedRegExp,_e(n,1));let c=this.input.charCodeAt(s);if(ar(c))throw this.raise(b.UnterminatedRegExp,_e(n,1));if(r)r=!1;else{if(c===91)i=!0;else if(c===93&&i)i=!1;else if(c===47&&!i)break;r=c===92}}let a=this.input.slice(e,s);++s;let o="",d=()=>_e(n,s+2-e);for(;s<this.length;){let c=this.codePointAtPos(s),l=String.fromCharCode(c);if(uR.has(c))c===118?o.includes("u")&&this.raise(b.IncompatibleRegExpUVFlags,d()):c===117&&o.includes("v")&&this.raise(b.IncompatibleRegExpUVFlags,d()),o.includes(l)&&this.raise(b.DuplicateRegExpFlags,d());else if(wn(c)||c===92)this.raise(b.MalformedRegExpFlags,d());else break;++s,o+=l}this.state.pos=s,this.finishToken(138,{pattern:a,flags:o})}readInt(n,e,r=!1,i=!0){let{n:s,pos:a}=Zf(this.input,this.state.pos,this.state.lineStart,this.state.curLine,n,e,r,i,this.errorHandlers_readInt,!1);return this.state.pos=a,s}readRadixNumber(n){let e=this.state.pos,r=this.state.curPosition(),i=!1;this.state.pos+=2;let s=this.readInt(n);s==null&&this.raise(b.InvalidDigit,_e(r,2),{radix:n});let a=this.input.charCodeAt(this.state.pos);if(a===110)++this.state.pos,i=!0;else if(a===109)throw this.raise(b.InvalidDecimal,r);if(bt(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());if(i){let o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,o);return}this.finishToken(135,s)}readNumber(n){let e=this.state.pos,r=this.state.curPosition(),i=!1,s=!1,a=!1,o=!1;!n&&this.readInt(10)===null&&this.raise(b.InvalidNumber,this.state.curPosition());let d=this.state.pos-e>=2&&this.input.charCodeAt(e)===48;if(d){let f=this.input.slice(e,this.state.pos);if(this.recordStrictModeErrors(b.StrictOctalLiteral,r),!this.state.strict){let h=f.indexOf("_");h>0&&this.raise(b.ZeroDigitNumericSeparator,_e(r,h))}o=d&&!/[89]/.test(f)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!o&&(++this.state.pos,this.readInt(10),i=!0,c=this.input.charCodeAt(this.state.pos)),(c===69||c===101)&&!o&&(c=this.input.charCodeAt(++this.state.pos),(c===43||c===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(b.InvalidOrMissingExponent,r),i=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((i||d)&&this.raise(b.InvalidBigIntLiteral,r),++this.state.pos,s=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||d)&&this.raise(b.InvalidDecimal,r),++this.state.pos;var l=!0}if(bt(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());let u=this.input.slice(e,this.state.pos).replace(/[_mn]/g,"");if(s){this.finishToken(136,u);return}if(l){this.finishToken(137,u);return}let p=o?parseInt(u,8):parseFloat(u);this.finishToken(135,p)}readCodePoint(n){let{code:e,pos:r}=eh(this.input,this.state.pos,this.state.lineStart,this.state.curLine,n,this.errorHandlers_readCodePoint);return this.state.pos=r,e}readString(n){let{str:e,pos:r,curLine:i,lineStart:s}=jf(n===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=r+1,this.state.lineStart=s,this.state.curLine=i,this.finishToken(134,e)}readTemplateContinuation(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken()}readTemplateToken(){let n=this.input[this.state.pos],{str:e,firstInvalidLoc:r,pos:i,curLine:s,lineStart:a}=jf("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=i+1,this.state.lineStart=a,this.state.curLine=s,r&&(this.state.firstInvalidTemplateEscapePos=new xt(r.curLine,r.pos-r.lineStart,this.sourceToOffsetPos(r.pos))),this.input.codePointAt(i)===96?this.finishToken(24,r?null:n+e+"`"):(this.state.pos++,this.finishToken(25,r?null:n+e+"${"))}recordStrictModeErrors(n,e){let r=e.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(n,e):this.state.strictErrors.set(r,[n,e])}readWord1(n){this.state.containsEsc=!1;let e="",r=this.state.pos,i=this.state.pos;for(n!==void 0&&(this.state.pos+=n<=65535?1:2);this.state.pos<this.length;){let s=this.codePointAtPos(this.state.pos);if(wn(s))this.state.pos+=s<=65535?1:2;else if(s===92){this.state.containsEsc=!0,e+=this.input.slice(i,this.state.pos);let a=this.state.curPosition(),o=this.state.pos===r?bt:wn;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(b.MissingUnicodeEscape,this.state.curPosition()),i=this.state.pos-1;continue}++this.state.pos;let d=this.readCodePoint(!0);d!==null&&(o(d)||this.raise(b.EscapedCharNotAnIdentifier,a),e+=String.fromCodePoint(d)),i=this.state.pos}else break}return e+this.input.slice(i,this.state.pos)}readWord(n){let e=this.readWord1(n),r=mc.get(e);r!==void 0?this.finishToken(r,Yt(r)):this.finishToken(132,e)}checkKeywordEscapes(){let{type:n}=this.state;vc(n)&&this.state.containsEsc&&this.raise(b.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Yt(n)})}raise(n,e,r={}){let i=e instanceof xt?e:e.loc.start,s=n(i,r);if(!(this.optionFlags&2048))throw s;return this.isLookahead||this.state.errors.push(s),s}raiseOverwrite(n,e,r={}){let i=e instanceof xt?e:e.loc.start,s=i.index,a=this.state.errors;for(let o=a.length-1;o>=0;o--){let d=a[o];if(d.loc.index===s)return a[o]=n(i,r);if(d.loc.index<s)break}return this.raise(n,e,r)}updateContext(n){}unexpected(n,e){throw this.raise(b.UnexpectedToken,n??this.state.startLoc,{expected:e?Yt(e):null})}expectPlugin(n,e){if(this.hasPlugin(n))return!0;throw this.raise(b.MissingPlugin,e??this.state.startLoc,{missingPlugin:[n]})}expectOnePlugin(n){if(!n.some(e=>this.hasPlugin(e)))throw this.raise(b.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:n})}errorBuilder(n){return(e,r,i)=>{this.raise(n,fi(e,r,i))}}},sc=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},ac=class{constructor(n){this.parser=void 0,this.stack=[],this.undefinedPrivateNames=new Map,this.parser=n}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new sc)}exit(){let n=this.stack.pop(),e=this.current();for(let[r,i]of Array.from(n.undefinedPrivateNames))e?e.undefinedPrivateNames.has(r)||e.undefinedPrivateNames.set(r,i):this.parser.raise(b.InvalidPrivateFieldResolution,i,{identifierName:r})}declarePrivateName(n,e,r){let{privateNames:i,loneAccessors:s,undefinedPrivateNames:a}=this.current(),o=i.has(n);if(e&3){let d=o&&s.get(n);if(d){let c=d&4,l=e&4,u=d&3,p=e&3;o=u===p||c!==l,o||s.delete(n)}else o||s.set(n,e)}o&&this.parser.raise(b.PrivateNameRedeclaration,r,{identifierName:n}),i.add(n),a.delete(n)}usePrivateName(n,e){let r;for(r of this.stack)if(r.privateNames.has(n))return;r?r.undefinedPrivateNames.set(n,e):this.parser.raise(b.InvalidPrivateFieldResolution,e,{identifierName:n})}},cr=class{constructor(n=0){this.type=n}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},na=class extends cr{constructor(n){super(n),this.declarationErrors=new Map}recordDeclarationError(n,e){let r=e.index;this.declarationErrors.set(r,[n,e])}clearDeclarationError(n){this.declarationErrors.delete(n)}iterateErrors(n){this.declarationErrors.forEach(n)}},oc=class{constructor(n){this.parser=void 0,this.stack=[new cr],this.parser=n}enter(n){this.stack.push(n)}exit(){this.stack.pop()}recordParameterInitializerError(n,e){let r=e.loc.start,{stack:i}=this,s=i.length-1,a=i[s];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(n,r);else return;a=i[--s]}this.parser.raise(n,r)}recordArrowParameterBindingError(n,e){let{stack:r}=this,i=r[r.length-1],s=e.loc.start;if(i.isCertainlyParameterDeclaration())this.parser.raise(n,s);else if(i.canBeArrowParameterDeclaration())i.recordDeclarationError(n,s);else return}recordAsyncArrowParametersError(n){let{stack:e}=this,r=e.length-1,i=e[r];for(;i.canBeArrowParameterDeclaration();)i.type===2&&i.recordDeclarationError(b.AwaitBindingIdentifier,n),i=e[--r]}validateAsPattern(){let{stack:n}=this,e=n[n.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([r,i])=>{this.parser.raise(r,i);let s=n.length-2,a=n[s];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(i.index),a=n[--s]})}};function pR(){return new cr(3)}function fR(){return new na(1)}function hR(){return new na(2)}function th(){return new cr}var dc=class extends ic{addExtra(n,e,r,i=!0){if(!n)return;let{extra:s}=n;s==null&&(s={},n.extra=s),i?s[e]=r:Object.defineProperty(s,e,{enumerable:i,value:r})}isContextual(n){return this.state.type===n&&!this.state.containsEsc}isUnparsedContextual(n,e){if(this.input.startsWith(e,n)){let r=this.input.charCodeAt(n+e.length);return!(wn(r)||(r&64512)===55296)}return!1}isLookaheadContextual(n){let e=this.nextTokenStart();return this.isUnparsedContextual(e,n)}eatContextual(n){return this.isContextual(n)?(this.next(),!0):!1}expectContextual(n,e){if(!this.eatContextual(n)){if(e!=null)throw this.raise(e,this.state.startLoc);this.unexpected(null,n)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return Mf(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return Mf(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(n=!0){(n?this.isLineTerminator():this.eat(13))||this.raise(b.MissingSemicolon,this.state.lastTokEndLoc)}expect(n,e){this.eat(n)||this.unexpected(e,n)}tryParse(n,e=this.state.clone()){let r={node:null};try{let i=n((s=null)=>{throw r.node=s,r});if(this.state.errors.length>e.errors.length){let s=this.state;return this.state=e,this.state.tokensLength=s.tokensLength,{node:i,error:s.errors[e.errors.length],thrown:!1,aborted:!1,failState:s}}return{node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(i){let s=this.state;if(this.state=e,i instanceof SyntaxError)return{node:null,error:i,thrown:!0,aborted:!1,failState:s};if(i===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:s};throw i}}checkExpressionErrors(n,e){if(!n)return!1;let{shorthandAssignLoc:r,doubleProtoLoc:i,privateKeyLoc:s,optionalParametersLoc:a,voidPatternLoc:o}=n,d=!!r||!!i||!!a||!!s||!!o;if(!e)return d;r!=null&&this.raise(b.InvalidCoverInitializedName,r),i!=null&&this.raise(b.DuplicateProto,i),s!=null&&this.raise(b.UnexpectedPrivateField,s),a!=null&&this.unexpected(a),o!=null&&this.raise(b.InvalidCoverDiscardElement,o)}isLiteralPropertyName(){return qf(this.state.type)}isPrivateName(n){return n.type==="PrivateName"}getPrivateNameSV(n){return n.id.name}hasPropertyAsPrivateName(n){return(n.type==="MemberExpression"||n.type==="OptionalMemberExpression")&&this.isPrivateName(n.property)}isObjectProperty(n){return n.type==="ObjectProperty"}isObjectMethod(n){return n.type==="ObjectMethod"}initializeScopes(n=this.options.sourceType==="module"){let e=this.state.labels;this.state.labels=[];let r=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let i=this.inModule;this.inModule=n;let s=this.scope,a=this.getScopeHandler();this.scope=new a(this,n);let o=this.prodParam;this.prodParam=new Zd;let d=this.classScope;this.classScope=new ac(this);let c=this.expressionScope;return this.expressionScope=new oc(this),()=>{this.state.labels=e,this.exportedIdentifiers=r,this.inModule=i,this.scope=s,this.prodParam=o,this.classScope=d,this.expressionScope=c}}enterInitialScopes(){let n=0;(this.inModule||this.optionFlags&1)&&(n|=2),this.optionFlags&32&&(n|=1);let e=!this.inModule&&this.options.sourceType==="commonjs";(e||this.optionFlags&2)&&(n|=4),this.prodParam.enter(n);let r=e?514:1;this.optionFlags&4&&(r|=512),this.scope.enter(r)}checkDestructuringPrivate(n){let{privateKeyLoc:e}=n;e!==null&&this.expectPlugin("destructuringPrivate",e)}},or=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},lr=class{constructor(n,e,r){this.type="",this.start=e,this.end=0,this.loc=new dr(r),n?.optionFlags&128&&(this.range=[e,0]),n!=null&&n.filename&&(this.loc.filename=n.filename)}},cc=lr.prototype;cc.__clone=function(){let t=new lr(void 0,this.start,this.loc.start),n=Object.keys(this);for(let e=0,r=n.length;e<r;e++){let i=n[e];i!=="leadingComments"&&i!=="trailingComments"&&i!=="innerComments"&&(t[i]=this[i])}return t};var lc=class extends dc{startNode(){let n=this.state.startLoc;return new lr(this,n.index,n)}startNodeAt(n){return new lr(this,n.index,n)}startNodeAtNode(n){return this.startNodeAt(n.loc.start)}finishNode(n,e){return this.finishNodeAt(n,e,this.state.lastTokEndLoc)}finishNodeAt(n,e,r){return n.type=e,n.end=r.index,n.loc.end=r,this.optionFlags&128&&(n.range[1]=r.index),this.optionFlags&4096&&this.processComment(n),n}resetStartLocation(n,e){n.start=e.index,n.loc.start=e,this.optionFlags&128&&(n.range[0]=e.index)}resetEndLocation(n,e=this.state.lastTokEndLoc){n.end=e.index,n.loc.end=e,this.optionFlags&128&&(n.range[1]=e.index)}resetStartLocationFromNode(n,e){this.resetStartLocation(n,e.loc.start)}castNodeTo(n,e){return n.type=e,n}cloneIdentifier(n){let{type:e,start:r,end:i,loc:s,range:a,name:o}=n,d=Object.create(cc);return d.type=e,d.start=r,d.end=i,d.loc=s,d.range=a,d.name=o,n.extra&&(d.extra=n.extra),d}cloneStringLiteral(n){let{type:e,start:r,end:i,loc:s,range:a,extra:o}=n,d=Object.create(cc);return d.type=e,d.start=r,d.end=i,d.loc=s,d.range=a,d.extra=o,d.value=n.value,d}},uc=t=>t.type==="ParenthesizedExpression"?uc(t.expression):t,pc=class extends lc{toAssignable(n,e=!1){var r,i;let s;switch((n.type==="ParenthesizedExpression"||(r=n.extra)!=null&&r.parenthesized)&&(s=uc(n),e?s.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(b.InvalidParenthesizedAssignment,n):s.type!=="CallExpression"&&s.type!=="MemberExpression"&&!this.isOptionalMemberExpression(s)&&this.raise(b.InvalidParenthesizedAssignment,n):this.raise(b.InvalidParenthesizedAssignment,n)),n.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(n,"ObjectPattern");for(let o=0,d=n.properties.length,c=d-1;o<d;o++){var a;let l=n.properties[o],u=o===c;this.toAssignableObjectExpressionProp(l,u,e),u&&l.type==="RestElement"&&(a=n.extra)!=null&&a.trailingCommaLoc&&this.raise(b.RestTrailingComma,n.extra.trailingCommaLoc)}break;case"ObjectProperty":{let{key:o,value:d}=n;this.isPrivateName(o)&&this.classScope.usePrivateName(this.getPrivateNameSV(o),o.loc.start),this.toAssignable(d,e);break}case"SpreadElement":throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");case"ArrayExpression":this.castNodeTo(n,"ArrayPattern"),this.toAssignableList(n.elements,(i=n.extra)==null?void 0:i.trailingCommaLoc,e);break;case"AssignmentExpression":n.operator!=="="&&this.raise(b.MissingEqInAssignment,n.left.loc.end),this.castNodeTo(n,"AssignmentPattern"),delete n.operator,n.left.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,n.left),this.toAssignable(n.left,e);break;case"ParenthesizedExpression":this.toAssignable(s,e);break}}toAssignableObjectExpressionProp(n,e,r){if(n.type==="ObjectMethod")this.raise(n.kind==="get"||n.kind==="set"?b.PatternHasAccessor:b.PatternHasMethod,n.key);else if(n.type==="SpreadElement"){this.castNodeTo(n,"RestElement");let i=n.argument;this.checkToRestConversion(i,!1),this.toAssignable(i,r),e||this.raise(b.RestTrailingComma,n)}else this.toAssignable(n,r)}toAssignableList(n,e,r){let i=n.length-1;for(let s=0;s<=i;s++){let a=n[s];a&&(this.toAssignableListItem(n,s,r),a.type==="RestElement"&&(s<i?this.raise(b.RestTrailingComma,a):e&&this.raise(b.RestTrailingComma,e)))}}toAssignableListItem(n,e,r){let i=n[e];if(i.type==="SpreadElement"){this.castNodeTo(i,"RestElement");let s=i.argument;this.checkToRestConversion(s,!0),this.toAssignable(s,r)}else this.toAssignable(i,r)}isAssignable(n,e){switch(n.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{let r=n.properties.length-1;return n.properties.every((i,s)=>i.type!=="ObjectMethod"&&(s===r||i.type!=="SpreadElement")&&this.isAssignable(i))}case"ObjectProperty":return this.isAssignable(n.value);case"SpreadElement":return this.isAssignable(n.argument);case"ArrayExpression":return n.elements.every(r=>r===null||this.isAssignable(r));case"AssignmentExpression":return n.operator==="=";case"ParenthesizedExpression":return this.isAssignable(n.expression);case"MemberExpression":case"OptionalMemberExpression":return!e;default:return!1}}toReferencedList(n,e){return n}toReferencedListDeep(n,e){this.toReferencedList(n,e);for(let r of n)r?.type==="ArrayExpression"&&this.toReferencedListDeep(r.elements)}parseSpread(n){let e=this.startNode();return this.next(),e.argument=this.parseMaybeAssignAllowIn(n,void 0),this.finishNode(e,"SpreadElement")}parseRestBinding(){let n=this.startNode();this.next();let e=this.parseBindingAtom();return e.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,e),n.argument=e,this.finishNode(n,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{let n=this.startNode();return this.next(),n.elements=this.parseBindingList(3,93,1),this.finishNode(n,"ArrayPattern")}case 5:return this.parseObjectLike(8,!0);case 88:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(n,e,r){let i=r&1,s=[],a=!0;for(;!this.eat(n);)if(a?a=!1:this.expect(12),i&&this.match(12))s.push(null);else{if(this.eat(n))break;if(this.match(21)){let o=this.parseRestBinding();if((this.hasPlugin("flow")||r&2)&&(o=this.parseFunctionParamType(o)),s.push(o),!this.checkCommaAfterRest(e)){this.expect(n);break}}else{let o=[];if(r&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(b.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)o.push(this.parseDecorator());s.push(this.parseBindingElement(r,o))}}return s}parseBindingRestProperty(n){return this.next(),this.hasPlugin("discardBinding")&&this.match(88)?(n.argument=this.parseVoidPattern(null),this.raise(b.UnexpectedVoidPattern,n.argument)):n.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(n,"RestElement")}parseBindingProperty(){let{type:n,startLoc:e}=this.state;if(n===21)return this.parseBindingRestProperty(this.startNode());let r=this.startNode();return n===139?(this.expectPlugin("destructuringPrivate",e),this.classScope.usePrivateName(this.state.value,e),r.key=this.parsePrivateName()):this.parsePropertyName(r),r.method=!1,this.parseObjPropValue(r,e,!1,!1,!0,!1)}parseBindingElement(n,e){let r=this.parseMaybeDefault();return(this.hasPlugin("flow")||n&2)&&this.parseFunctionParamType(r),e.length&&(r.decorators=e,this.resetStartLocationFromNode(r,e[0])),this.parseMaybeDefault(r.loc.start,r)}parseFunctionParamType(n){return n}parseMaybeDefault(n,e){if(n??(n=this.state.startLoc),e=e??this.parseBindingAtom(),!this.eat(29))return e;let r=this.startNodeAt(n);return e.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,e),r.left=e,r.right=this.parseMaybeAssignAllowIn(),this.finishNode(r,"AssignmentPattern")}isValidLVal(n,e,r,i){switch(n){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties";case"VoidPattern":return!0;case"CallExpression":if(!e&&!this.state.strict&&this.optionFlags&8192)return!0}return!1}isOptionalMemberExpression(n){return n.type==="OptionalMemberExpression"}checkLVal(n,e,r=64,i=!1,s=!1,a=!1,o=!1){var d;let c=n.type;if(this.isObjectMethod(n))return;let l=this.isOptionalMemberExpression(n);if(l||c==="MemberExpression"){l&&(this.expectPlugin("optionalChainingAssign",n.loc.start),e.type!=="AssignmentExpression"&&this.raise(b.InvalidLhsOptionalChaining,n,{ancestor:e})),r!==64&&this.raise(b.InvalidPropertyBindingPattern,n);return}if(c==="Identifier"){this.checkIdentifier(n,r,s);let{name:y}=n;i&&(i.has(y)?this.raise(b.ParamDupe,n):i.add(y));return}else c==="VoidPattern"&&e.type==="CatchClause"&&this.raise(b.VoidPatternCatchClauseParam,n);let u=uc(n);o||(o=u.type==="CallExpression"&&(u.callee.type==="Import"||u.callee.type==="Super"));let p=this.isValidLVal(c,o,!(a||(d=n.extra)!=null&&d.parenthesized)&&e.type==="AssignmentExpression",r);if(p===!0)return;if(p===!1){let y=r===64?b.InvalidLhs:b.InvalidLhsBinding;this.raise(y,n,{ancestor:e});return}let f,h;typeof p=="string"?(f=p,h=c==="ParenthesizedExpression"):[f,h]=p;let m=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:e,g=n[f];if(Array.isArray(g))for(let y of g)y&&this.checkLVal(y,m,r,i,s,h,!0);else g&&this.checkLVal(g,m,r,i,s,h,o)}checkIdentifier(n,e,r=!1){this.state.strict&&(r?Xf(n.name,this.inModule):Yf(n.name))&&(e===64?this.raise(b.StrictEvalArguments,n,{referenceName:n.name}):this.raise(b.StrictEvalArgumentsBinding,n,{bindingName:n.name})),e&8192&&n.name==="let"&&this.raise(b.LetInLexicalBinding,n),e&64||this.declareNameFromIdentifier(n,e)}declareNameFromIdentifier(n,e){this.scope.declareName(n.name,e,n.loc.start)}checkToRestConversion(n,e){switch(n.type){case"ParenthesizedExpression":this.checkToRestConversion(n.expression,e);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(e)break;default:this.raise(b.InvalidRestAssignmentPattern,n)}}checkCommaAfterRest(n){return this.match(12)?(this.raise(this.lookaheadCharCode()===n?b.RestTrailingComma:b.ElementAfterRest,this.state.startLoc),!0):!1}},qd=/in(?:stanceof)?|as|satisfies/y;function mR(t){if(t==null)throw new Error(`Unexpected ${t} value.`);return t}function Ff(t){if(!t)throw new Error("Assert fail")}var F=ot`typescript`({AbstractMethodHasImplementation:({methodName:t})=>`Method '${t}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:t})=>`Property '${t}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",ConstructorHasTypeParameters:"Type parameters cannot appear on a constructor declaration.",DeclareAccessor:({kind:t})=>`'declare' is not allowed in ${t}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:t})=>`Accessibility modifier already seen: '${t}'.`,DuplicateModifier:({modifier:t})=>`Duplicate modifier: '${t}'.`,EmptyHeritageClauseType:({token:t})=>`'${t}' list cannot be empty.`,EmptyTypeArguments:"Type argument list cannot be empty.",EmptyTypeParameters:"Type parameter list cannot be empty.",ExpectedAmbientAfterExportDeclare:"'export declare' must be followed by an ambient declaration.",ImportAliasHasImportType:"An import alias can not use 'import type'.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` modifier",IncompatibleModifiers:({modifiers:t})=>`'${t[0]}' modifier cannot be used with '${t[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:t})=>`Index signatures cannot have an accessibility modifier ('${t}').`,IndexSignatureHasDeclare:"Index signatures cannot have the 'declare' modifier.",IndexSignatureHasOverride:"'override' modifier cannot appear on an index signature.",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier.",InitializerNotAllowedInAmbientContext:"Initializers are not allowed in ambient contexts.",InvalidHeritageClauseType:({token:t})=>`'${t}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:t=>`'${t}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:t})=>`'${t}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:t})=>`'${t}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:t})=>`'${t}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:t=>`'${t}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:t})=>`'${t[0]}' modifier must precede '${t[1]}' modifier.`,InvalidPropertyAccessAfterInstantiationExpression:"Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",InvalidTupleMemberLabel:"Tuple members must be labeled with a simple identifier.",MissingInterfaceName:"'interface' declarations must be followed by an identifier.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifier:"'abstract' modifier can only appear on a class, method, or property declaration.",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",OverrideNotInSubClass:"This member cannot have an 'override' modifier because its containing class does not extend another class.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:({modifier:t})=>`Private elements cannot have an accessibility modifier ('${t}').`,ReadonlyForMethodSignature:"'readonly' modifier can only appear on a property declaration or index signature.",ReservedArrowTypeParam:"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:t})=>`Single type parameter ${t} should have a trailing comma. Example usage: <${t},>.`,StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:({type:t})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${t}.`,UsingDeclarationInAmbientContext:t=>`'${t}' declarations are not allowed in ambient contexts.`});function yR(t){switch(t){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}function Bf(t){return t==="private"||t==="public"||t==="protected"}function gR(t){return t==="in"||t==="out"}var wR=t=>class extends t{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:F.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter})}getScopeHandler(){return Qd}tsIsIdentifier(){return se(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(139)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){return this.next(),this.hasPrecedingLineBreak()?!1:this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){return this.match(106)?(this.next(),this.tsTokenCanFollowModifier()):this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(e,r,i){if(!se(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let s=this.state.value;if(e.includes(s)){if(i&&this.match(106)||r&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return s}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:r,stopOnStartOfClassStaticBlock:i,errorTemplate:s=F.InvalidModifierOnTypeMember},a){let o=(c,l,u,p)=>{l===u&&a[p]&&this.raise(F.InvalidModifiersOrder,c,{orderedModifiers:[u,p]})},d=(c,l,u,p)=>{(a[u]&&l===p||a[p]&&l===u)&&this.raise(F.IncompatibleModifiers,c,{modifiers:[u,p]})};for(;;){let{startLoc:c}=this.state,l=this.tsParseModifier(e.concat(r??[]),i,a.static);if(!l)break;Bf(l)?a.accessibility?this.raise(F.DuplicateAccessibilityModifier,c,{modifier:l}):(o(c,l,l,"override"),o(c,l,l,"static"),o(c,l,l,"readonly"),a.accessibility=l):gR(l)?(a[l]&&this.raise(F.DuplicateModifier,c,{modifier:l}),a[l]=!0,o(c,l,"in","out")):(hasOwnProperty.call(a,l)?this.raise(F.DuplicateModifier,c,{modifier:l}):(o(c,l,"static","readonly"),o(c,l,"static","override"),o(c,l,"override","readonly"),o(c,l,"abstract","override"),d(c,l,"declare","override"),d(c,l,"static","abstract")),a[l]=!0),r!=null&&r.includes(l)&&this.raise(s,c,{modifier:l})}}tsIsListTerminator(e){switch(e){case"EnumMembers":case"TypeMembers":return this.match(8);case"HeritageClauseElement":return this.match(5);case"TupleElementTypes":return this.match(3);case"TypeParametersOrArguments":return this.match(48)}}tsParseList(e,r){let i=[];for(;!this.tsIsListTerminator(e);)i.push(r());return i}tsParseDelimitedList(e,r,i){return mR(this.tsParseDelimitedListWorker(e,r,!0,i))}tsParseDelimitedListWorker(e,r,i,s){let a=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let d=r();if(d==null)return;if(a.push(d),this.eat(12)){o=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(e))break;i&&this.expect(12);return}return s&&(s.value=o),a}tsParseBracketedList(e,r,i,s,a){s||(i?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,r,a);return i?this.expect(3):this.expect(48),o}tsParseImportType(){let e=this.startNode();return this.expect(83),this.expect(10),this.match(134)?e.argument=this.parseStringLiteral(this.state.value):(this.raise(F.UnsupportedImportTypeArgument,this.state.startLoc),e.argument=super.parseExprAtom()),this.eat(12)?e.options=this.tsParseImportTypeOptions():e.options=null,this.expect(11),this.eat(16)&&(e.qualifier=this.tsParseEntityName(3)),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSImportType")}tsParseImportTypeOptions(){let e=this.startNode();this.expect(5);let r=this.startNode();return this.isContextual(76)?(r.method=!1,r.key=this.parseIdentifier(!0),r.computed=!1,r.shorthand=!1):this.unexpected(null,76),this.expect(14),r.value=this.tsParseImportTypeWithPropertyValue(),e.properties=[this.finishObjectProperty(r)],this.eat(12),this.expect(8),this.finishNode(e,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let e=this.startNode(),r=[];for(this.expect(5);!this.match(8);){let i=this.state.type;se(i)||i===134?r.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return e.properties=r,this.next(),this.finishNode(e,"ObjectExpression")}tsParseEntityName(e){let r;if(e&1&&this.match(78))if(e&2)r=this.parseIdentifier(!0);else{let i=this.startNode();this.next(),r=this.finishNode(i,"ThisExpression")}else r=this.parseIdentifier(!!(e&1));for(;this.eat(16);){let i=this.startNodeAtNode(r);i.left=r,i.right=this.parseIdentifier(!!(e&1)),r=this.finishNode(i,"TSQualifiedName")}return r}tsParseTypeReference(){let e=this.startNode();return e.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeReference")}tsParseThisTypePredicate(e){this.next();let r=this.startNodeAtNode(e);return r.parameterName=e,r.typeAnnotation=this.tsParseTypeAnnotation(!1),r.asserts=!1,this.finishNode(r,"TSTypePredicate")}tsParseThisTypeNode(){let e=this.startNode();return this.next(),this.finishNode(e,"TSThisType")}tsParseTypeQuery(){let e=this.startNode();return this.expect(87),this.match(83)?e.exprName=this.tsParseImportType():e.exprName=this.tsParseEntityName(3),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeQuery")}tsParseTypeParameter(e){let r=this.startNode();return e(r),r.name=this.tsParseTypeParameterName(),r.constraint=this.tsEatThenParseType(81),r.default=this.tsEatThenParseType(29),this.finishNode(r,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let r=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();let i={value:-1};return r.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,i),r.params.length===0&&this.raise(F.EmptyTypeParameters,r),i.value!==-1&&this.addExtra(r,"trailingComma",i.value),this.finishNode(r,"TSTypeParameterDeclaration")}tsFillSignature(e,r){let i=e===19,s="parameters",a="typeAnnotation";r.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),r[s]=this.tsParseBindingListForSignature(),i?r[a]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(r[a]=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let r of e){let{type:i}=r;(i==="AssignmentPattern"||i==="TSParameterProperty")&&this.raise(F.UnsupportedSignatureParameterKind,r,{type:i})}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(e,r){return this.tsFillSignature(14,r),this.tsParseTypeMemberSemicolon(),this.finishNode(r,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),se(this.state.type)?(this.next(),this.match(14)):!1}tsTryParseIndexSignature(e){if(!(this.match(0)&&this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))))return;this.expect(0);let r=this.parseIdentifier();r.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(r),this.expect(3),e.parameters=[r];let i=this.tsTryParseTypeAnnotation();return i&&(e.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,r){if(this.eat(17)&&(e.optional=!0),this.match(10)||this.match(47)){r&&this.raise(F.ReadonlyForMethodSignature,e);let i=e;i.kind&&this.match(47)&&this.raise(F.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,i),this.tsParseTypeMemberSemicolon();let s="parameters",a="typeAnnotation";if(i.kind==="get")i[s].length>0&&(this.raise(b.BadGetterArity,this.state.curPosition()),this.isThisParam(i[s][0])&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(i.kind==="set"){if(i[s].length!==1)this.raise(b.BadSetterArity,this.state.curPosition());else{let o=i[s][0];this.isThisParam(o)&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(F.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(F.SetAccessorCannotHaveRestParameter,this.state.curPosition())}i[a]&&this.raise(F.SetAccessorCannotHaveReturnType,i[a])}else i.kind="method";return this.finishNode(i,"TSMethodSignature")}else{let i=e;r&&(i.readonly=!0);let s=this.tsTryParseTypeAnnotation();return s&&(i.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(i,"TSPropertySignature")}}tsParseTypeMember(){let e=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",e);if(this.match(77)){let i=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",e):(e.key=this.createIdentifier(i,"new"),this.tsParsePropertyOrMethodSignature(e,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},e);let r=this.tsTryParseIndexSignature(e);return r||(super.parsePropertyName(e),!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&this.tsTokenCanFollowModifier()&&(e.kind=e.key.name,super.parsePropertyName(e),!this.match(10)&&!this.match(47)&&this.unexpected(null,10)),this.tsParsePropertyOrMethodSignature(e,!!e.readonly))}tsParseTypeLiteral(){let e=this.startNode();return e.members=this.tsParseObjectTypeMembers(),this.finishNode(e,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(5);let e=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(8),e}tsIsStartOfMappedType(){return this.next(),this.eat(53)?this.isContextual(122):(this.isContextual(122)&&this.next(),!this.match(0)||(this.next(),!this.tsIsIdentifier())?!1:(this.next(),this.match(58)))}tsParseMappedType(){let e=this.startNode();this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(e.readonly=!0),this.expect(0);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(r,"TSTypeParameter"),e.nameType=this.eatContextual(93)?this.tsParseType():null,this.expect(3),this.match(53)?(e.optional=this.state.value,this.next(),this.expect(17)):this.eat(17)&&(e.optional=!0),e.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(8),this.finishNode(e,"TSMappedType")}tsParseTupleType(){let e=this.startNode();e.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let r=!1;return e.elementTypes.forEach(i=>{let{type:s}=i;r&&s!=="TSRestType"&&s!=="TSOptionalType"&&!(s==="TSNamedTupleMember"&&i.optional)&&this.raise(F.OptionalTypeBeforeRequired,i),r||(r=s==="TSNamedTupleMember"&&i.optional||s==="TSOptionalType")}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let e=this.state.startLoc,r=this.eat(21),{startLoc:i}=this.state,s,a,o,d,l=dt(this.state.type)?this.lookaheadCharCode():null;if(l===58)s=!0,o=!1,a=this.parseIdentifier(!0),this.expect(14),d=this.tsParseType();else if(l===63){o=!0;let u=this.state.value,p=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(s=!0,a=this.createIdentifier(this.startNodeAt(i),u),this.expect(17),this.expect(14),d=this.tsParseType()):(s=!1,d=p,this.expect(17))}else d=this.tsParseType(),o=this.eat(17),s=this.eat(14);if(s){let u;a?(u=this.startNodeAt(i),u.optional=o,u.label=a,u.elementType=d,this.eat(17)&&(u.optional=!0,this.raise(F.TupleOptionalAfterType,this.state.lastTokStartLoc))):(u=this.startNodeAt(i),u.optional=o,this.raise(F.InvalidTupleMemberLabel,d),u.label=d,u.elementType=this.tsParseType()),d=this.finishNode(u,"TSNamedTupleMember")}else if(o){let u=this.startNodeAt(i);u.typeAnnotation=d,d=this.finishNode(u,"TSOptionalType")}if(r){let u=this.startNodeAt(e);u.typeAnnotation=d,d=this.finishNode(u,"TSRestType")}return d}tsParseParenthesizedType(){let e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")}tsParseFunctionOrConstructorType(e,r){let i=this.startNode();return e==="TSConstructorType"&&(i.abstract=!!r,r&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,i)),this.finishNode(i,e)}tsParseLiteralTypeNode(){let e=this.startNode();switch(this.state.type){case 135:case 136:case 134:case 85:case 86:e.literal=super.parseExprAtom();break;default:this.unexpected()}return this.finishNode(e,"TSLiteralType")}tsParseTemplateLiteralType(){let e=this.startNode();return e.literal=super.parseTemplate(!1),this.finishNode(e,"TSLiteralType")}parseTemplateSubstitution(){return this.state.inType?this.tsParseType():super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){let e=this.tsParseThisTypeNode();return this.isContextual(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e}tsParseNonArrayType(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if(this.state.value==="-"){let e=this.startNode(),r=this.lookahead();return r.type!==135&&r.type!==136&&this.unexpected(),e.literal=this.parseMaybeUnary(),this.finishNode(e,"TSLiteralType")}break;case 78:return this.tsParseThisTypeOrThisTypePredicate();case 87:return this.tsParseTypeQuery();case 83:return this.tsParseImportType();case 5:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 10:return this.tsParseParenthesizedType();case 25:case 24:return this.tsParseTemplateLiteralType();default:{let{type:e}=this.state;if(se(e)||e===88||e===84){let r=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":yR(this.state.value);if(r!==void 0&&this.lookaheadCharCode()!==46){let i=this.startNode();return this.next(),this.finishNode(i,r)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){let{startLoc:e}=this.state,r=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let i=this.startNodeAt(e);i.elementType=r,this.expect(3),r=this.finishNode(i,"TSArrayType")}else{let i=this.startNodeAt(e);i.objectType=r,i.indexType=this.tsParseType(),this.expect(3),r=this.finishNode(i,"TSIndexedAccessType")}return r}tsParseTypeOperator(){let e=this.startNode(),r=this.state.value;return this.next(),e.operator=r,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),r==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(F.UnexpectedReadonly,e)}}tsParseInferType(){let e=this.startNode();this.expectContextual(115);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(r,"TSTypeParameter"),this.finishNode(e,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(81)){let e=this.tsInDisallowConditionalTypesContext(()=>this.tsParseType());if(this.state.inDisallowConditionalTypesContext||!this.match(17))return e}}tsParseTypeOperatorOrHigher(){return jk(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,r,i){let s=this.startNode(),a=this.eat(i),o=[];do o.push(r());while(this.eat(i));return o.length===1&&!a?o[0]:(s.types=o,this.finishNode(s,e))}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),45)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),43)}tsIsStartOfFunctionType(){return this.match(47)?!0:this.match(10)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(se(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,r=e.length;try{return this.parseObjectLike(8,!0),e.length===r}catch{return!1}}if(this.match(0)){this.next();let{errors:e}=this.state,r=e.length;try{return super.parseBindingList(3,93,1),e.length===r}catch{return!1}}return!1}tsIsUnambiguouslyStartOfFunctionType(){return this.next(),!!(this.match(11)||this.match(21)||this.tsSkipParameterStart()&&(this.match(14)||this.match(12)||this.match(17)||this.match(29)||this.match(11)&&(this.next(),this.match(19))))}tsParseTypeOrTypePredicateAnnotation(e){return this.tsInType(()=>{let r=this.startNode();this.expect(e);let i=this.startNode(),s=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(s&&this.match(78)){let d=this.tsParseThisTypeOrThisTypePredicate();return d.type==="TSThisType"?(i.parameterName=d,i.asserts=!0,i.typeAnnotation=null,d=this.finishNode(i,"TSTypePredicate")):(this.resetStartLocationFromNode(d,i),d.asserts=!0),r.typeAnnotation=d,this.finishNode(r,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return s?(i.parameterName=this.parseIdentifier(),i.asserts=s,i.typeAnnotation=null,r.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,r);let o=this.tsParseTypeAnnotation(!1);return i.parameterName=a,i.typeAnnotation=o,i.asserts=s,r.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){if(this.match(14))return this.tsParseTypeOrTypePredicateAnnotation(14)}tsTryParseTypeAnnotation(){if(this.match(14))return this.tsParseTypeAnnotation()}tsTryParseType(){return this.tsEatThenParseType(14)}tsParseTypePredicatePrefix(){let e=this.parseIdentifier();if(this.isContextual(116)&&!this.hasPrecedingLineBreak())return this.next(),e}tsParseTypePredicateAsserts(){if(this.state.type!==109)return!1;let e=this.state.containsEsc;return this.next(),!se(this.state.type)&&!this.match(78)?!1:(e&&this.raise(b.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,r=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),r.typeAnnotation=this.tsParseType()}),this.finishNode(r,"TSTypeAnnotation")}tsParseType(){Ff(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let r=this.startNodeAtNode(e);return r.checkType=e,r.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),r.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),r.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(r,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(124)&&this.isLookaheadContextual("new")}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(77)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(F.ReservedTypeAssertion,this.state.startLoc);let e=this.startNode();return e.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?this.tsParseTypeReference():this.tsParseType())),this.expect(48),e.expression=this.parseMaybeUnary(),this.finishNode(e,"TSTypeAssertion")}tsParseHeritageClause(e){let r=this.state.startLoc,i=this.tsParseDelimitedList("HeritageClauseElement",()=>{let s=this.startNode();return s.expression=this.tsParseEntityName(3),this.match(47)&&(s.typeParameters=this.tsParseTypeArguments()),this.finishNode(s,"TSExpressionWithTypeArguments")});return i.length||this.raise(F.EmptyHeritageClauseType,r,{token:e}),i}tsParseInterfaceDeclaration(e,r={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),r.declare&&(e.declare=!0),se(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(F.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));let i=this.startNode();return i.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(i,"TSInterfaceBody"),this.finishNode(e,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(e){return e.id=this.parseIdentifier(),this.checkIdentifier(e.id,2),e.typeAnnotation=this.tsInType(()=>{if(e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutModifiers),this.expect(29),this.isContextual(114)&&this.lookaheadCharCode()!==46){let r=this.startNode();return this.next(),this.finishNode(r,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()!==ie.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}tsInType(e){let r=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=r}}tsInDisallowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}tsInAllowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}tsEatThenParseType(e){if(this.match(e))return this.tsNextThenParseType()}tsExpectThenParseType(e){return this.tsInType(()=>(this.expect(e),this.tsParseType()))}tsNextThenParseType(){return this.tsInType(()=>(this.next(),this.tsParseType()))}tsParseEnumMember(){let e=this.startNode();return e.id=this.match(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(e.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(e,"TSEnumMember")}tsParseEnumDeclaration(e,r={}){return r.const&&(e.const=!0),r.declare&&(e.declare=!0),this.expectContextual(126),e.id=this.parseIdentifier(),this.checkIdentifier(e.id,e.const?8971:8459),this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumDeclaration")}tsParseEnumBody(){let e=this.startNode();return this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumBody")}tsParseModuleBlock(){let e=this.startNode();return this.scope.enter(0),this.expect(5),super.parseBlockOrModuleBlockBody(e.body=[],void 0,!0,8),this.scope.exit(),this.finishNode(e,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(e,r=!1){if(e.id=this.parseIdentifier(),r||this.checkIdentifier(e.id,1024),this.eat(16)){let i=this.startNode();this.tsParseModuleOrNamespaceDeclaration(i,!0),e.body=i}else this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(e){return this.isContextual(112)?(e.kind="global",e.global=!0,e.id=this.parseIdentifier()):this.match(134)?(e.kind="module",e.id=super.parseStringLiteral(this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(e,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(e,r,i){e.isExport=i||!1,e.id=r||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let s=this.tsParseModuleReference();return e.importKind==="type"&&s.type!=="TSExternalModuleReference"&&this.raise(F.ImportAliasHasImportType,s),e.moduleReference=s,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){let e=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),e.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(e,"TSExternalModuleReference")}tsLookAhead(e){let r=this.state.clone(),i=e();return this.state=r,i}tsTryParseAndCatch(e){let r=this.tryParse(i=>e()||i());if(!(r.aborted||!r.node))return r.error&&(this.state=r.failState),r.node}tsTryParse(e){let r=this.state.clone(),i=e();if(i!==void 0&&i!==!1)return i;this.state=r}tsTryParseDeclare(e){if(this.isLineTerminator())return;let r=this.state.type;return this.tsInAmbientContext(()=>{switch(r){case 68:return e.declare=!0,super.parseFunctionStatement(e,!1,!1);case 80:return e.declare=!0,this.parseClass(e,!0,!1);case 126:return this.tsParseEnumDeclaration(e,{declare:!0});case 112:return this.tsParseAmbientExternalModuleDeclaration(e);case 100:if(this.state.containsEsc)return;case 75:case 74:return!this.match(75)||!this.isLookaheadContextual("enum")?(e.declare=!0,this.parseVarStatement(e,this.state.value,!0)):(this.expect(75),this.tsParseEnumDeclaration(e,{const:!0,declare:!0}));case 107:if(this.isUsing())return this.raise(F.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.parseVarStatement(e,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(F.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.next(),this.parseVarStatement(e,"await using",!0);break;case 129:{let i=this.tsParseInterfaceDeclaration(e,{declare:!0});if(i)return i}default:if(se(r))return this.tsParseDeclaration(e,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(e,r,i,s){switch(r){case 124:if(this.tsCheckLineTerminator(i)&&(this.match(80)||se(this.state.type)))return this.tsParseAbstractDeclaration(e,s);break;case 127:if(this.tsCheckLineTerminator(i)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(se(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case 128:if(this.tsCheckLineTerminator(i)&&se(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case 130:if(this.tsCheckLineTerminator(i)&&se(this.state.type))return this.tsParseTypeAliasDeclaration(e);break}}tsCheckLineTerminator(e){return e?this.hasFollowingLineBreak()?!1:(this.next(),!0):!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(e){if(!this.match(47))return;let r=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let i=this.tsTryParseAndCatch(()=>{let s=this.startNodeAt(e);return s.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(s),s.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),s});if(this.state.maybeInArrowParameters=r,!!i)return super.parseArrowExpression(i,null,!0)}tsParseTypeArgumentsInExpression(){if(this.reScan_lt()===47)return this.tsParseTypeArguments()}tsParseTypeArguments(){let e=this.startNode();return e.params=this.tsInType(()=>this.tsInTopLevelContext(()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),e.params.length===0?this.raise(F.EmptyTypeArguments,e):!this.state.inType&&this.curContext()===ie.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return Fk(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(e,r){let i=r.length?r[0].loc.start:this.state.startLoc,s={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},s);let a=s.accessibility,o=s.override,d=s.readonly;!(e&4)&&(a||d||o)&&this.raise(F.UnexpectedParameterModifier,i);let c=this.parseMaybeDefault();e&2&&this.parseFunctionParamType(c);let l=this.parseMaybeDefault(c.loc.start,c);if(a||d||o){let u=this.startNodeAt(i);return r.length&&(u.decorators=r),a&&(u.accessibility=a),d&&(u.readonly=d),o&&(u.override=o),l.type!=="Identifier"&&l.type!=="AssignmentPattern"&&this.raise(F.UnsupportedParameterPropertyKind,u),u.parameter=l,this.finishNode(u,"TSParameterProperty")}return r.length&&(c.decorators=r),l}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let r of e.params)r.type!=="Identifier"&&r.optional&&!this.state.isAmbientContext&&this.raise(F.PatternIsOptional,r)}setArrowFunctionParameters(e,r,i){super.setArrowFunctionParameters(e,r,i),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,r,i=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let s=r==="FunctionDeclaration"?"TSDeclareFunction":r==="ClassMethod"||r==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return s&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,s):s==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(F.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,s,i):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,r,i))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach(r=>{r?.type==="TSTypeCastExpression"&&this.raise(F.UnexpectedTypeAnnotation,r.typeAnnotation)})}toReferencedList(e,r){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,r,i){let s=super.parseArrayLike(e,r,i);return s.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(s.elements),s}parseSubscript(e,r,i,s){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(r);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(i)return s.stop=!0,e;s.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let o,d=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(e)){let p=this.tsTryParseGenericAsyncArrowFunction(r);if(p)return s.stop=!0,p}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){o=this.state.curPosition();return}if(ta(this.state.type)){let p=super.parseTaggedTemplateExpression(e,r,s);return p.typeParameters=c,p}if(!i&&this.eat(10)){let p=this.startNodeAt(r);return p.callee=e,p.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(p.arguments),p.typeParameters=c,s.optionalChainMember&&(p.optional=a),this.finishCallExpression(p,s.optionalChainMember)}let l=this.state.type;if(l===48||l===52||l!==10&&l!==93&&l!==120&&hi(l)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(r);return u.expression=e,u.typeParameters=c,this.finishNode(u,"TSInstantiationExpression")});if(o&&this.unexpected(o,10),d)return d.type==="TSInstantiationExpression"&&((this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40)&&this.raise(F.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(d.expression=super.stopParseSubscript(e,s))),d}return super.parseSubscript(e,r,i,s)}parseNewCallee(e){var r;super.parseNewCallee(e);let{callee:i}=e;i.type==="TSInstantiationExpression"&&!((r=i.extra)!=null&&r.parenthesized)&&(e.typeParameters=i.typeParameters,e.callee=i.expression)}parseExprOp(e,r,i){let s;if(Qs(58)>i&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(s=this.isContextual(120)))){let a=this.startNodeAt(r);return a.expression=e,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(s&&this.raise(b.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,s?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,r,i)}return super.parseExprOp(e,r,i)}checkReservedWord(e,r,i,s){this.state.isAmbientContext||super.checkReservedWord(e,r,i,s)}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(F.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){let r=this.lookaheadCharCode();return e?r===123||r===42:r!==61}return!e&&this.isContextual(87)}applyImportPhase(e,r,i,s){super.applyImportPhase(e,r,i,s),r?e.exportKind=i==="type"?"type":"value":e.importKind=i==="type"||i==="typeof"?i:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let r;if(se(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){let i=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,i);r=super.parseImportSpecifiersAndAfter(e,i)}else r=super.parseImport(e);return r.importKind==="type"&&r.specifiers.length>1&&r.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(F.TypeImportCannotSpecifyDefaultAndNamed,r),r}parseExport(e,r){if(this.match(83)){let i=e;this.next();let s=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?s=this.parseMaybeImportPhase(i,!1):i.importKind="value",this.tsParseImportEqualsDeclaration(i,s,!0)}else if(this.eat(29)){let i=e;return i.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(i,"TSExportAssignment")}else if(this.eatContextual(93)){let i=e;return this.expectContextual(128),i.id=this.parseIdentifier(),this.semicolon(),this.finishNode(i,"TSNamespaceExportDeclaration")}else return super.parseExport(e,r)}isAbstractClass(){return this.isContextual(124)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){let e=this.startNode();return this.next(),e.abstract=!0,this.parseClass(e,!0,!0)}if(this.match(129)){let e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseExportDefaultExpression()}parseVarStatement(e,r,i=!1){let{isAmbientContext:s}=this.state,a=super.parseVarStatement(e,r,i||s);if(!s)return a;if(!e.declare&&(r==="using"||r==="await using"))return this.raiseOverwrite(F.UsingDeclarationInAmbientContext,e,r),a;for(let{id:o,init:d}of a.declarations)d&&(r==="var"||r==="let"||o.typeAnnotation?this.raise(F.InitializerNotAllowedInAmbientContext,d):xR(d,this.hasPlugin("estree"))||this.raise(F.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,d));return a}parseStatementContent(e,r){if(!this.state.containsEsc)switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){let i=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(i,{const:!0})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){let i=this.state.type,s=this.startNode();this.next();let a=i===125?this.tsTryParseDeclare(s):this.tsParseAbstractDeclaration(s,r);return a?(i===125&&(a.declare=!0),a):(s.expression=this.createIdentifier(this.startNodeAt(s.loc.start),i===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(s,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let s=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(s)}break}case 129:{let i=this.tsParseInterfaceDeclaration(this.startNode());if(i)return i;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,127,!1,r)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,128,!1,r)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseTypeAliasDeclaration(i)}break}}return super.parseStatementContent(e,r)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,r){return r.some(i=>Bf(i)?e.accessibility===i:!!e[i])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(e,r,i){let s=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:s,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:F.InvalidModifierOnTypeParameterPositions},r);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(r,s)&&this.raise(F.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,r)):this.parseClassMemberWithIsStatic(e,r,i,!!r.static)};r.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(e,r,i,s){let a=this.tsTryParseIndexSignature(r);if(a){e.body.push(a),r.abstract&&this.raise(F.IndexSignatureHasAbstract,r),r.accessibility&&this.raise(F.IndexSignatureHasAccessibility,r,{modifier:r.accessibility}),r.declare&&this.raise(F.IndexSignatureHasDeclare,r),r.override&&this.raise(F.IndexSignatureHasOverride,r);return}!this.state.inAbstractClass&&r.abstract&&this.raise(F.NonAbstractClassHasAbstractMethod,r),r.override&&(i.hadSuperClass||this.raise(F.OverrideNotInSubClass,r)),super.parseClassMemberWithIsStatic(e,r,i,s)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(F.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(F.ClassMethodHasDeclare,e)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,r,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let s=this.lookaheadCharCode();if(s===44||s===61||s===58||s===41)return this.setOptionalParametersError(i),e}return super.parseConditional(e,r,i)}parseParenItem(e,r){let i=super.parseParenItem(e,r);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(r);return s.expression=e,s.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(s,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let r=this.state.startLoc,i=this.eatContextual(125);if(i&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(F.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=se(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||i)&&(e.exportKind="type"),i&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,r),a.declare=!0),a):null}parseClassId(e,r,i,s){if((!r||i)&&this.isContextual(113))return;super.parseClassId(e,r,i,e.declare?1024:8331);let a=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);a&&(e.typeParameters=a)}parseClassPropertyAnnotation(e){e.optional||(this.eat(35)?e.definite=!0:this.eat(17)&&(e.optional=!0));let r=this.tsTryParseTypeAnnotation();r&&(e.typeAnnotation=r)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(F.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){let{key:r}=e;this.raise(F.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:r.type==="Identifier"&&!e.computed?r.name:`[${this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end))}]`})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(F.PrivateElementHasAbstract,e),e.accessibility&&this.raise(F.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(F.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,r,i,s,a,o){let d=this.tsTryParseTypeParameters(this.tsParseConstModifier);d&&a&&this.raise(F.ConstructorHasTypeParameters,d);let{declare:c=!1,kind:l}=r;c&&(l==="get"||l==="set")&&this.raise(F.DeclareAccessor,r,{kind:l}),d&&(r.typeParameters=d),super.pushClassMethod(e,r,i,s,a,o)}pushClassPrivateMethod(e,r,i,s){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(r.typeParameters=a),super.pushClassPrivateMethod(e,r,i,s)}declareClassPrivateMethodInScope(e,r){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&e.value.body==null||super.declareClassPrivateMethodInScope(e,r))}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass)if(e.superClass.type==="TSInstantiationExpression"){let r=e.superClass,i=r.expression;this.takeSurroundingComments(i,i.start,i.end);let s=r.typeParameters;this.takeSurroundingComments(s,s.start,s.end),e.superClass=i,e.superTypeParameters=s}else(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,r,i,s,a,o,d){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(e.typeParameters=c),super.parseObjPropValue(e,r,i,s,a,o,d)}parseFunctionParams(e,r){let i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(e.typeParameters=i),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),e.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(e.definite=!0);let i=this.tsTryParseTypeAnnotation();i&&(e.id.typeAnnotation=i,this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,r)}parseMaybeAssign(e,r){var i,s,a,o,d;let c,l,u;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(c=this.state.clone(),l=this.tryParse(()=>super.parseMaybeAssign(e,r),c),!l.error)return l.node;let{context:h}=this.state,m=h[h.length-1];(m===ie.j_oTag||m===ie.j_expr)&&h.pop()}if(!((i=l)!=null&&i.error)&&!this.match(47))return super.parseMaybeAssign(e,r);(!c||c===this.state)&&(c=this.state.clone());let p,f=this.tryParse(h=>{var m,g;p=this.tsParseTypeParameters(this.tsParseConstModifier);let y=super.parseMaybeAssign(e,r);return(y.type!=="ArrowFunctionExpression"||(m=y.extra)!=null&&m.parenthesized)&&h(),((g=p)==null?void 0:g.params.length)!==0&&this.resetStartLocationFromNode(y,p),y.typeParameters=p,y},c);if(!f.error&&!f.aborted)return p&&this.reportReservedArrowTypeParam(p),f.node;if(!l&&(Ff(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,r),c),!u.error))return u.node;if((s=l)!=null&&s.node)return this.state=l.failState,l.node;if(f.node)return this.state=f.failState,p&&this.reportReservedArrowTypeParam(p),f.node;if((a=u)!=null&&a.node)return this.state=u.failState,u.node;throw((o=l)==null?void 0:o.error)||f.error||((d=u)==null?void 0:d.error)}reportReservedArrowTypeParam(e){var r;e.params.length===1&&!e.params[0].constraint&&!((r=e.extra)!=null&&r.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(F.ReservedArrowTypeParam,e)}parseMaybeUnary(e,r){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(i=>{let s=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&i(),s});if(r.aborted)return;r.thrown||(r.error&&(this.state=r.failState),e.returnType=r.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);let r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r),this.resetEndLocation(e),e}isAssignable(e,r){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,r);case"TSParameterProperty":return!0;default:return super.isAssignable(e,r)}}toAssignable(e,r=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,r);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":r?this.expressionScope.recordArrowParameterBindingError(F.UnexpectedTypeCastInParameter,e):this.raise(F.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,r);break;case"AssignmentExpression":!r&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,r)}}toAssignableParenthesizedExpression(e,r){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,r);break;default:super.toAssignable(e,r)}}checkToRestConversion(e,r){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,r)}}isValidLVal(e,r,i,s){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(s!==64||!i)&&["expression",!0];default:return super.isValidLVal(e,r,i,s)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,r){if(this.match(47)||this.match(51)){let i=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let s=super.parseMaybeDecoratorArguments(e,r);return s.typeParameters=i,s}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,r)}checkCommaAfterRest(e){return this.state.isAmbientContext&&this.match(12)&&this.lookaheadCharCode()===e?(this.next(),!1):super.checkCommaAfterRest(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(35)||this.match(14)||super.isClassProperty()}parseMaybeDefault(e,r){let i=super.parseMaybeDefault(e,r);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(F.TypeAnnotationAfterAssign,i.typeAnnotation),i}getTokenFromCode(e){if(this.state.inType){if(e===62){this.finishOp(48,1);return}if(e===60){this.finishOp(47,1);return}}super.getTokenFromCode(e)}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}toAssignableListItem(e,r,i){let s=e[r];s.type==="TSTypeCastExpression"&&(e[r]=this.typeCastToParameter(s)),super.toAssignableListItem(e,r,i)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}shouldParseArrow(e){return this.match(14)?e.every(r=>this.isAssignable(r,!0)):super.shouldParseArrow(e)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(e){if(this.match(47)||this.match(51)){let r=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());r&&(e.typeParameters=r)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let r=super.getGetterSetterExpectedParamCount(e),s=this.getObjectOrClassMethodParams(e)[0];return s&&this.isThisParam(s)?r+1:r}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r,this.resetEndLocation(e)),e}tsInAmbientContext(e){let{isAmbientContext:r,strict:i}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=r,this.state.strict=i}}parseClass(e,r,i){let s=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,r,i)}finally{this.state.inAbstractClass=s}}tsParseAbstractDeclaration(e,r){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(r,this.parseClass(e,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(e.abstract=!0,this.raise(F.NonClassMethodPropertyHasAbstractModifier,e),this.tsParseInterfaceDeclaration(e));throw this.unexpected(null,80)}parseMethod(e,r,i,s,a,o,d){let c=super.parseMethod(e,r,i,s,a,o,d);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:p}=c;this.raise(F.AbstractMethodHasImplementation,c,{methodName:p.type==="Identifier"&&!c.computed?p.name:`[${this.input.slice(this.offsetToSourcePos(p.start),this.offsetToSourcePos(p.end))}]`})}return c}tsParseTypeParameterName(){return this.parseIdentifier().name}shouldParseAsAmbientContext(){return!!this.getPluginOption("typescript","dts")}parse(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.parse()}getExpression(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.getExpression()}parseExportSpecifier(e,r,i,s){return!r&&s?(this.parseTypeOnlyImportExportSpecifier(e,!1,i),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,r,i,s))}parseImportSpecifier(e,r,i,s,a){return!r&&s?(this.parseTypeOnlyImportExportSpecifier(e,!0,i),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,r,i,s,i?4098:4096))}parseTypeOnlyImportExportSpecifier(e,r,i){let s=r?"imported":"local",a=r?"local":"exported",o=e[s],d,c=!1,l=!0,u=o.loc.start;if(this.isContextual(93)){let f=this.parseIdentifier();if(this.isContextual(93)){let h=this.parseIdentifier();dt(this.state.type)?(c=!0,o=f,d=r?this.parseIdentifier():this.parseModuleExportName(),l=!1):(d=h,l=!1)}else dt(this.state.type)?(l=!1,d=r?this.parseIdentifier():this.parseModuleExportName()):(c=!0,o=f)}else dt(this.state.type)&&(c=!0,r?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());c&&i&&this.raise(r?F.TypeModifierIsUsedInTypeImports:F.TypeModifierIsUsedInTypeExports,u),e[s]=o,e[a]=d;let p=r?"importKind":"exportKind";e[p]=c?"type":"value",l&&this.eatContextual(93)&&(e[a]=r?this.parseIdentifier():this.parseModuleExportName()),e[a]||(e[a]=this.cloneIdentifier(e[s])),r&&this.checkIdentifier(e[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(e){var r,i,s,a,o,d,c,l,u,p,f,h,m,g,y,w,x,v,R,P,C,E,M,A,N,T,I,$,D,k,S,_,q,K,te,le,Y,Ae,Ee,St,qt,ni,ri,Fs,ii,si,ai,mf,yf;switch(e.type){case"ImportDeclaration":(r=e.phase)!=null||(e.phase=null);return;case"ExpressionStatement":(i=e.directive)!=null||(e.directive=void 0);return;case"RestElement":e.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(s=e.decorators)!=null||(e.decorators=[]),(a=e.optional)!=null||(e.optional=!1),(o=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);return;case"TSParameterProperty":(d=e.accessibility)!=null||(e.accessibility=void 0),(c=e.decorators)!=null||(e.decorators=[]),(l=e.override)!=null||(e.override=!1),(u=e.readonly)!=null||(e.readonly=!1),(p=e.static)!=null||(e.static=!1);return;case"TSEmptyBodyFunctionExpression":e.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":(f=e.declare)!=null||(e.declare=!1),(h=e.returnType)!=null||(e.returnType=void 0),(m=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"Property":(g=e.optional)!=null||(e.optional=!1);return;case"TSMethodSignature":case"TSPropertySignature":(y=e.optional)!=null||(e.optional=!1);case"TSIndexSignature":(w=e.accessibility)!=null||(e.accessibility=void 0),(x=e.readonly)!=null||(e.readonly=!1),(v=e.static)!=null||(e.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(R=e.declare)!=null||(e.declare=!1),(P=e.definite)!=null||(e.definite=!1),(C=e.readonly)!=null||(e.readonly=!1),(E=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(M=e.accessibility)!=null||(e.accessibility=void 0),(A=e.decorators)!=null||(e.decorators=[]),(N=e.override)!=null||(e.override=!1),(T=e.optional)!=null||(e.optional=!1);return;case"ClassExpression":(I=e.id)!=null||(e.id=null);case"ClassDeclaration":($=e.abstract)!=null||(e.abstract=!1),(D=e.declare)!=null||(e.declare=!1),(k=e.decorators)!=null||(e.decorators=[]),(S=e.implements)!=null||(e.implements=[]),(_=e.superTypeArguments)!=null||(e.superTypeArguments=void 0),(q=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(K=e.declare)!=null||(e.declare=!1);return;case"VariableDeclarator":(te=e.definite)!=null||(e.definite=!1);return;case"TSEnumDeclaration":(le=e.const)!=null||(e.const=!1),(Y=e.declare)!=null||(e.declare=!1);return;case"TSEnumMember":(Ae=e.computed)!=null||(e.computed=!1);return;case"TSImportType":(Ee=e.qualifier)!=null||(e.qualifier=null),(St=e.options)!=null||(e.options=null);return;case"TSInterfaceDeclaration":(qt=e.declare)!=null||(e.declare=!1),(ni=e.extends)!=null||(e.extends=[]);return;case"TSMappedType":(ri=e.optional)!=null||(e.optional=!1),(Fs=e.readonly)!=null||(e.readonly=void 0);return;case"TSModuleDeclaration":(ii=e.declare)!=null||(e.declare=!1),(si=e.global)!=null||(e.global=e.kind==="global");return;case"TSTypeParameter":(ai=e.const)!=null||(e.const=!1),(mf=e.in)!=null||(e.in=!1),(yf=e.out)!=null||(e.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(e,r){if(bt(e)){if(qd.lastIndex=r,qd.test(this.input)){let i=this.codePointAtPos(qd.lastIndex);if(!wn(i)&&i!==92)return!1}return!0}else return e===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifierAndNotRelationalOperator(r,e)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifier(r,e)||r===34||r===39}};function bR(t){if(t.type!=="MemberExpression")return!1;let{computed:n,property:e}=t;return n&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:rh(t.object)}function xR(t,n){var e;let{type:r}=t;if((e=t.extra)!=null&&e.parenthesized)return!1;if(n){if(r==="Literal"){let{value:i}=t;if(typeof i=="string"||typeof i=="boolean")return!0}}else if(r==="StringLiteral"||r==="BooleanLiteral")return!0;return!!(nh(t,n)||vR(t,n)||r==="TemplateLiteral"&&t.expressions.length===0||bR(t))}function nh(t,n){return n?t.type==="Literal"&&(typeof t.value=="number"||"bigint"in t):t.type==="NumericLiteral"||t.type==="BigIntLiteral"}function vR(t,n){if(t.type==="UnaryExpression"){let{operator:e,argument:r}=t;if(e==="-"&&nh(r,n))return!0}return!1}function rh(t){return t.type==="Identifier"?!0:t.type!=="MemberExpression"||t.computed?!1:rh(t.object)}var Hf=ot`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),kR=t=>class extends t{parsePlaceholder(e){if(this.match(133)){let r=this.startNode();return this.next(),this.assertNoSpace(),r.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(r,e)}}finishPlaceholder(e,r){let i=e;return(!i.expectedNode||!i.type)&&(i=this.finishNode(i,"Placeholder")),i.expectedNode=r,i}getTokenFromCode(e){e===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(133,2):super.getTokenFromCode(e)}parseExprAtom(e){return this.parsePlaceholder("Expression")||super.parseExprAtom(e)}parseIdentifier(e){return this.parsePlaceholder("Identifier")||super.parseIdentifier(e)}checkReservedWord(e,r,i,s){e!==void 0&&super.checkReservedWord(e,r,i,s)}cloneIdentifier(e){let r=super.cloneIdentifier(e);return r.type==="Placeholder"&&(r.expectedNode=e.expectedNode),r}cloneStringLiteral(e){return e.type==="Placeholder"?this.cloneIdentifier(e):super.cloneStringLiteral(e)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,r,i,s){return e==="Placeholder"||super.isValidLVal(e,r,i,s)}toAssignable(e,r){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,r)}chStartsBindingIdentifier(e,r){if(super.chStartsBindingIdentifier(e,r))return!0;let i=this.nextTokenStart();return this.input.charCodeAt(i)===37&&this.input.charCodeAt(i+1)===37}verifyBreakContinue(e,r){var i;((i=e.label)==null?void 0:i.type)!=="Placeholder"&&super.verifyBreakContinue(e,r)}parseExpressionStatement(e,r){var i;if(r.type!=="Placeholder"||(i=r.extra)!=null&&i.parenthesized)return super.parseExpressionStatement(e,r);if(this.match(14)){let a=e;return a.label=this.finishPlaceholder(r,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let s=e;return s.name=r.name,this.finishPlaceholder(s,"Statement")}parseBlock(e,r,i){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,r,i)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,r,i){let s=r?"ClassDeclaration":"ClassExpression";this.next();let a=this.state.strict,o=this.parsePlaceholder("Identifier");if(o)if(this.match(81)||this.match(133)||this.match(5))e.id=o;else{if(i||!r)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,s);throw this.raise(Hf.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(e,r,i);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,a),this.finishNode(e,s)}parseExport(e,r){let i=this.parsePlaceholder("Identifier");if(!i)return super.parseExport(e,r);let s=e;if(!this.isContextual(98)&&!this.match(12))return s.specifiers=[],s.source=null,s.declaration=this.finishPlaceholder(i,"Declaration"),this.finishNode(s,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=i,s.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(s,r)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Yt(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,r){var i;return(i=e.specifiers)!=null&&i.length?!0:super.maybeParseExportDefaultSpecifier(e,r)}checkExport(e){let{specifiers:r}=e;r!=null&&r.length&&(e.specifiers=r.filter(i=>i.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=r}parseImport(e){let r=this.parsePlaceholder("Identifier");if(!r)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(r,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let i=this.startNodeAtNode(r);return i.local=r,e.specifiers.push(this.finishNode(i,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(e)||this.parseNamedImportSpecifiers(e)),this.expectContextual(98),e.source=this.parseImportSource(),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(Hf.UnexpectedSpace,this.state.lastTokEndLoc)}},RR=t=>class extends t{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,r=this.startNode();if(this.next(),se(this.state.type)){let i=this.parseIdentifierName(),s=this.createIdentifier(r,i);if(this.castNodeTo(s,"V8IntrinsicIdentifier"),this.match(10))return s}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},zf=["minimal","fsharp","hack","smart"],Vf=["^^","@@","^","%","#"];function IR(t){if(t.has("decorators")){if(t.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let r=t.get("decorators").decoratorsBeforeExport;if(r!=null&&typeof r!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let i=t.get("decorators").allowCallParenthesized;if(i!=null&&typeof i!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(t.has("flow")&&t.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(t.has("placeholders")&&t.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(t.has("pipelineOperator")){var n;let r=t.get("pipelineOperator").proposal;if(!zf.includes(r)){let i=zf.map(s=>`"${s}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${i}.`)}if(r==="hack"){var e;if(t.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(t.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let i=t.get("pipelineOperator").topicToken;if(!Vf.includes(i)){let s=Vf.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${s}.`)}if(i==="#"&&((e=t.get("recordAndTuple"))==null?void 0:e.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",t.get("recordAndTuple")])}\`.`)}else if(r==="smart"&&((n=t.get("recordAndTuple"))==null?void 0:n.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",t.get("recordAndTuple")])}\`.`)}if(t.has("moduleAttributes")){if(t.has("deprecatedImportAssert")||t.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(t.get("moduleAttributes").version!=="may-2020")throw new Error("The 'moduleAttributes' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is 'may-2020'.")}if(t.has("importAssertions")&&t.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(t.has("deprecatedImportAssert")||t.has("importAttributes")&&t.get("importAttributes").deprecatedAssertSyntax&&t.set("deprecatedImportAssert",{}),t.has("recordAndTuple")){let r=t.get("recordAndTuple").syntaxType;if(r!=null){let i=["hash","bar"];if(!i.includes(r))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+i.map(s=>`'${s}'`).join(", "))}}if(t.has("asyncDoExpressions")&&!t.has("doExpressions")){let r=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw r.missingPlugins="doExpressions",r}if(t.has("optionalChainingAssign")&&t.get("optionalChainingAssign").version!=="2023-07")throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.");if(t.has("discardBinding")&&t.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var ih={estree:Sk,jsx:aR,flow:nR,typescript:wR,v8intrinsic:RR,placeholders:kR},AR=Object.keys(ih),fc=class extends pc{checkProto(n,e,r,i){if(n.type==="SpreadElement"||this.isObjectMethod(n)||n.computed||n.shorthand)return r;let s=n.key;return(s.type==="Identifier"?s.name:s.value)==="__proto__"?e?(this.raise(b.RecordNoProto,s),!0):(r&&(i?i.doubleProtoLoc===null&&(i.doubleProtoLoc=s.loc.start):this.raise(b.DuplicateProto,s)),!0):r}shouldExitDescending(n,e){return n.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(n.start)===e}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(b.ParseExpressionEmptyInput,this.state.startLoc);let n=this.parseExpression();if(!this.match(140))throw this.raise(b.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),n.comments=this.comments,n.errors=this.state.errors,this.optionFlags&256&&(n.tokens=this.tokens),n}parseExpression(n,e){return n?this.disallowInAnd(()=>this.parseExpressionBase(e)):this.allowInAnd(()=>this.parseExpressionBase(e))}parseExpressionBase(n){let e=this.state.startLoc,r=this.parseMaybeAssign(n);if(this.match(12)){let i=this.startNodeAt(e);for(i.expressions=[r];this.eat(12);)i.expressions.push(this.parseMaybeAssign(n));return this.toReferencedList(i.expressions),this.finishNode(i,"SequenceExpression")}return r}parseMaybeAssignDisallowIn(n,e){return this.disallowInAnd(()=>this.parseMaybeAssign(n,e))}parseMaybeAssignAllowIn(n,e){return this.allowInAnd(()=>this.parseMaybeAssign(n,e))}setOptionalParametersError(n){n.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(n,e){let r=this.state.startLoc,i=this.isContextual(108);if(i&&this.prodParam.hasYield){this.next();let d=this.parseYield(r);return e&&(d=e.call(this,d,r)),d}let s;n?s=!1:(n=new or,s=!0);let{type:a}=this.state;(a===10||se(a))&&(this.state.potentialArrowAt=this.state.start);let o=this.parseMaybeConditional(n);if(e&&(o=e.call(this,o,r)),$k(this.state.type)){let d=this.startNodeAt(r),c=this.state.value;if(d.operator=c,this.match(29)){this.toAssignable(o,!0),d.left=o;let l=r.index;n.doubleProtoLoc!=null&&n.doubleProtoLoc.index>=l&&(n.doubleProtoLoc=null),n.shorthandAssignLoc!=null&&n.shorthandAssignLoc.index>=l&&(n.shorthandAssignLoc=null),n.privateKeyLoc!=null&&n.privateKeyLoc.index>=l&&(this.checkDestructuringPrivate(n),n.privateKeyLoc=null),n.voidPatternLoc!=null&&n.voidPatternLoc.index>=l&&(n.voidPatternLoc=null)}else d.left=o;return this.next(),d.right=this.parseMaybeAssign(),this.checkLVal(o,this.finishNode(d,"AssignmentExpression"),void 0,void 0,void 0,void 0,c==="||="||c==="&&="||c==="??="),d}else s&&this.checkExpressionErrors(n,!0);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?hi(d):hi(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.YieldNotInGeneratorFunction,r),this.parseYield(r)}return o}parseMaybeConditional(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,i=this.parseExprOps(n);return this.shouldExitDescending(i,r)?i:this.parseConditional(i,e,n)}parseConditional(n,e,r){if(this.eat(17)){let i=this.startNodeAt(e);return i.test=n,i.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),i.alternate=this.parseMaybeAssign(),this.finishNode(i,"ConditionalExpression")}return n}parseMaybeUnaryOrPrivate(n){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(n)}parseExprOps(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,i=this.parseMaybeUnaryOrPrivate(n);return this.shouldExitDescending(i,r)?i:this.parseExprOp(i,e,-1)}parseExprOp(n,e,r){if(this.isPrivateName(n)){let s=this.getPrivateNameSV(n);(r>=Qs(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(b.PrivateInExpectedIn,n,{identifierName:s}),this.classScope.usePrivateName(s,n.loc.start)}let i=this.state.type;if(Lk(i)&&(this.prodParam.hasIn||!this.match(58))){let s=Qs(i);if(s>r){if(i===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return n;this.checkPipelineAtInfixOperator(n,e)}let a=this.startNodeAt(e);a.left=n,a.operator=this.state.value;let o=i===41||i===42,d=i===40;if(d&&(s=Qs(42)),this.next(),i===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&this.state.type===96&&this.prodParam.hasAwait)throw this.raise(b.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);a.right=this.parseExprOpRightExpr(i,s);let c=this.finishNode(a,o||d?"LogicalExpression":"BinaryExpression"),l=this.state.type;if(d&&(l===41||l===42)||o&&l===40)throw this.raise(b.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(c,e,r)}}return n}parseExprOpRightExpr(n,e){let r=this.state.startLoc;switch(n){case 39:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>this.parseHackPipeBody());case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e))}if(this.getPluginOption("pipelineOperator","proposal")==="smart")return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(108))throw this.raise(b.PipeBodyIsTighter,this.state.startLoc);return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(n,e),r)});default:return this.parseExprOpBaseRightExpr(n,e)}}parseExprOpBaseRightExpr(n,e){let r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,Bk(n)?e-1:e)}parseHackPipeBody(){var n;let{startLoc:e}=this.state,r=this.parseMaybeAssign();return xk.has(r.type)&&!((n=r.extra)!=null&&n.parenthesized)&&this.raise(b.PipeUnparenthesizedBody,e,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipeTopicUnused,e),r}checkExponentialAfterUnary(n){this.match(57)&&this.raise(b.UnexpectedTokenUnaryExponentiation,n.argument)}parseMaybeUnary(n,e){let r=this.state.startLoc,i=this.isContextual(96);if(i&&this.recordAwaitIfAllowed()){this.next();let d=this.parseAwait(r);return e||this.checkExponentialAfterUnary(d),d}let s=this.match(34),a=this.startNode();if(_k(this.state.type)){a.operator=this.state.value,a.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");let d=this.match(89);if(this.next(),a.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(n,!0),this.state.strict&&d){let c=a.argument;c.type==="Identifier"?this.raise(b.StrictDelete,a):this.hasPropertyAsPrivateName(c)&&this.raise(b.DeletePrivateField,a)}if(!s)return e||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let o=this.parseUpdate(a,s,n);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?hi(d):hi(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.AwaitNotInAsyncContext,r),this.parseAwait(r)}return o}parseUpdate(n,e,r){if(e){let a=n;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),n}let i=this.state.startLoc,s=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return s;for(;Mk(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(i);a.operator=this.state.value,a.prefix=!1,a.argument=s,this.next(),this.checkLVal(s,s=this.finishNode(a,"UpdateExpression"))}return s}parseExprSubscripts(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,i=this.parseExprAtom(n);return this.shouldExitDescending(i,r)?i:this.parseSubscripts(i,e)}parseSubscripts(n,e,r){let i={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(n),stop:!1};do n=this.parseSubscript(n,e,r,i),i.maybeAsyncArrow=!1;while(!i.stop);return n}parseSubscript(n,e,r,i){let{type:s}=this.state;if(!r&&s===15)return this.parseBind(n,e,i);if(ta(s))return this.parseTaggedTemplateExpression(n,e,i);let a=!1;if(s===18){if(r&&(this.raise(b.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(n,i);i.optionalChainMember=a=!0,this.next()}if(!r&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(n,e,i,a);{let o=this.eat(0);return o||a||this.eat(16)?this.parseMember(n,e,i,o,a):this.stopParseSubscript(n,i)}}stopParseSubscript(n,e){return e.stop=!0,n}parseMember(n,e,r,i,s){let a=this.startNodeAt(e);return a.object=n,a.computed=i,i?(a.property=this.parseExpression(),this.expect(3)):this.match(139)?(n.type==="Super"&&this.raise(b.SuperPrivateField,e),this.classScope.usePrivateName(this.state.value,this.state.startLoc),a.property=this.parsePrivateName()):a.property=this.parseIdentifier(!0),r.optionalChainMember?(a.optional=s,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(n,e,r){let i=this.startNodeAt(e);i.object=n,this.next();let s=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||s&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(b.UnsupportedBindRHS,a);return i.callee=a,r.stop=!0,this.parseSubscripts(this.finishNode(i,"BindExpression"),e,!1)}parseCoverCallAndAsyncArrowHead(n,e,r,i){let s=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=n;let{maybeAsyncArrow:d,optionalChainMember:c}=r;d&&(this.expressionScope.enter(hR()),a=new or),c&&(o.optional=i),i?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(n.type!=="Super",o,a);let l=this.finishCallExpression(o,c);return d&&this.shouldParseAsyncArrow()&&!i?(r.stop=!0,this.checkDestructuringPrivate(a),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),l=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e),l)):(d&&(this.checkExpressionErrors(a,!0),this.expressionScope.exit()),this.toReferencedArguments(l)),this.state.maybeInArrowParameters=s,l}toReferencedArguments(n,e){this.toReferencedListDeep(n.arguments,e)}parseTaggedTemplateExpression(n,e,r){let i=this.startNodeAt(e);return i.tag=n,i.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(b.OptionalChainingNoTemplate,e),this.finishNode(i,"TaggedTemplateExpression")}atPossibleAsyncArrow(n){return n.type==="Identifier"&&n.name==="async"&&this.state.lastTokEndLoc.index===n.end&&!this.canInsertSemicolon()&&n.end-n.start===5&&this.offsetToSourcePos(n.start)===this.state.potentialArrowAt}finishCallExpression(n,e){if(n.callee.type==="Import")if(n.arguments.length===0||n.arguments.length>2)this.raise(b.ImportCallArity,n);else for(let r of n.arguments)r.type==="SpreadElement"&&this.raise(b.ImportCallSpreadArgument,r);return this.finishNode(n,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(n,e,r){let i=[],s=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(s)s=!1;else if(this.expect(12),this.match(11)){e&&this.addTrailingCommaExtraToNode(e),this.next();break}i.push(this.parseExprListItem(11,!1,r,n))}return this.state.inFSharpPipelineDirectBody=a,i}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(n,e){var r;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(n,e.arguments,!0,(r=e.extra)==null?void 0:r.trailingCommaLoc),e.innerComments&&bi(n,e.innerComments),e.callee.trailingComments&&bi(n,e.callee.trailingComments),n}parseNoCallExpr(){let n=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),n,!0)}parseExprAtom(n){let e,r=null,{type:i}=this.state;switch(i){case 79:return this.parseSuper();case 83:return e=this.startNode(),this.next(),this.match(16)?this.parseImportMetaPropertyOrPhaseCall(e):this.match(10)?this.optionFlags&512?this.parseImportCall(e):this.finishNode(e,"Import"):(this.raise(b.UnsupportedImport,this.state.lastTokStartLoc),this.finishNode(e,"Import"));case 78:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case 90:return this.parseDo(this.startNode(),!1);case 56:case 31:return this.readRegexp(),this.parseRegExpLiteral(this.state.value);case 135:return this.parseNumericLiteral(this.state.value);case 136:return this.parseBigIntLiteral(this.state.value);case 134:return this.parseStringLiteral(this.state.value);case 84:return this.parseNullLiteral();case 85:return this.parseBooleanLiteral(!0);case 86:return this.parseBooleanLiteral(!1);case 10:{let s=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(s)}case 0:return this.parseArrayLike(3,!1,n);case 5:return this.parseObjectLike(8,!1,!1,n);case 68:return this.parseFunctionOrFunctionSent();case 26:r=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(r,this.startNode()),!1);case 77:return this.parseNewOrNewTarget();case 25:case 24:return this.parseTemplate(!1);case 15:{e=this.startNode(),this.next(),e.object=null;let s=e.callee=this.parseNoCallExpr();if(s.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(b.UnsupportedBind,s)}case 139:return this.raise(b.PrivateInExpectedIn,this.state.startLoc,{identifierName:this.state.value}),this.parsePrivateName();case 33:return this.parseTopicReferenceThenEqualsSign(54,"%");case 32:return this.parseTopicReferenceThenEqualsSign(44,"^");case 37:case 38:return this.parseTopicReference("hack");case 44:case 54:case 27:{let s=this.getPluginOption("pipelineOperator","proposal");if(s)return this.parseTopicReference(s);throw this.unexpected()}case 47:{let s=this.input.codePointAt(this.nextTokenStart());throw bt(s)||s===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}default:if(i===137)return this.parseDecimalLiteral(this.state.value);if(i===2||i===1)return this.parseArrayLike(this.state.type===2?4:3,!0);if(i===6||i===7)return this.parseObjectLike(this.state.type===6?9:8,!1,!0);if(se(i)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let s=this.state.potentialArrowAt===this.state.start,a=this.state.containsEsc,o=this.parseIdentifier();if(!a&&o.name==="async"&&!this.canInsertSemicolon()){let{type:d}=this.state;if(d===68)return this.resetPreviousNodeTrailingComments(o),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(o));if(se(d))return s&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(d===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return s&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(n,e){let r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.state.type=n,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=_e(this.state.endLoc,-1),this.parseTopicReference(r);throw this.unexpected()}parseTopicReference(n){let e=this.startNode(),r=this.state.startLoc,i=this.state.type;return this.next(),this.finishTopicReference(e,r,n,i)}finishTopicReference(n,e,r,i){if(this.testTopicReferenceConfiguration(r,e,i))return r==="hack"?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PipeTopicUnbound,e),this.registerTopicReference(),this.finishNode(n,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PrimaryTopicNotAllowed,e),this.registerTopicReference(),this.finishNode(n,"PipelinePrimaryTopicReference"));throw this.raise(b.PipeTopicUnconfiguredToken,e,{token:Yt(i)})}testTopicReferenceConfiguration(n,e,r){switch(n){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Yt(r)}]);case"smart":return r===27;default:throw this.raise(b.PipeTopicRequiresHackPipes,e)}}parseAsyncArrowUnaryFunction(n){this.prodParam.enter(Zs(!0,this.prodParam.hasYield));let e=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(b.LineTerminatorBeforeArrow,this.state.curPosition()),this.expect(19),this.parseArrowExpression(n,e,!0)}parseDo(n,e){this.expectPlugin("doExpressions"),e&&this.expectPlugin("asyncDoExpressions"),n.async=e,this.next();let r=this.state.labels;return this.state.labels=[],e?(this.prodParam.enter(2),n.body=this.parseBlock(),this.prodParam.exit()):n.body=this.parseBlock(),this.state.labels=r,this.finishNode(n,"DoExpression")}parseSuper(){let n=this.startNode();return this.next(),this.match(10)&&!this.scope.allowDirectSuper?this.optionFlags&16||this.raise(b.SuperNotAllowed,n):this.scope.allowSuper||this.optionFlags&16||this.raise(b.UnexpectedSuper,n),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(b.UnsupportedSuper,n),this.finishNode(n,"Super")}parsePrivateName(){let n=this.startNode(),e=this.startNodeAt(_e(this.state.startLoc,1)),r=this.state.value;return this.next(),n.id=this.createIdentifier(e,r),this.finishNode(n,"PrivateName")}parseFunctionOrFunctionSent(){let n=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(n),"function");return this.next(),this.match(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(n,e,"sent")}return this.parseFunction(n)}parseMetaProperty(n,e,r){n.meta=e;let i=this.state.containsEsc;return n.property=this.parseIdentifier(!0),(n.property.name!==r||i)&&this.raise(b.UnsupportedMetaProperty,n.property,{target:e.name,onlyValidPropertyName:r}),this.finishNode(n,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(n){if(this.next(),this.isContextual(105)||this.isContextual(97)){let e=this.isContextual(105);return this.expectPlugin(e?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),n.phase=e?"source":"defer",this.parseImportCall(n)}else{let e=this.createIdentifierAt(this.startNodeAtNode(n),"import",this.state.lastTokStartLoc);return this.isContextual(101)&&(this.inModule||this.raise(b.ImportMetaOutsideModule,e),this.sawUnambiguousESM=!0),this.parseMetaProperty(n,e,"meta")}}parseLiteralAtNode(n,e,r){return this.addExtra(r,"rawValue",n),this.addExtra(r,"raw",this.input.slice(this.offsetToSourcePos(r.start),this.state.end)),r.value=n,this.next(),this.finishNode(r,e)}parseLiteral(n,e){let r=this.startNode();return this.parseLiteralAtNode(n,e,r)}parseStringLiteral(n){return this.parseLiteral(n,"StringLiteral")}parseNumericLiteral(n){return this.parseLiteral(n,"NumericLiteral")}parseBigIntLiteral(n){return this.parseLiteral(n,"BigIntLiteral")}parseDecimalLiteral(n){return this.parseLiteral(n,"DecimalLiteral")}parseRegExpLiteral(n){let e=this.startNode();return this.addExtra(e,"raw",this.input.slice(this.offsetToSourcePos(e.start),this.state.end)),e.pattern=n.pattern,e.flags=n.flags,this.next(),this.finishNode(e,"RegExpLiteral")}parseBooleanLiteral(n){let e=this.startNode();return e.value=n,this.next(),this.finishNode(e,"BooleanLiteral")}parseNullLiteral(){let n=this.startNode();return this.next(),this.finishNode(n,"NullLiteral")}parseParenAndDistinguishExpression(n){let e=this.state.startLoc,r;this.next(),this.expressionScope.enter(fR());let i=this.state.maybeInArrowParameters,s=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,o=[],d=new or,c=!0,l,u;for(;!this.match(11);){if(c)c=!1;else if(this.expect(12,d.optionalParametersLoc===null?null:d.optionalParametersLoc),this.match(11)){u=this.state.startLoc;break}if(this.match(21)){let h=this.state.startLoc;if(l=this.state.startLoc,o.push(this.parseParenItem(this.parseRestBinding(),h)),!this.checkCommaAfterRest(41))break}else o.push(this.parseMaybeAssignAllowInOrVoidPattern(11,d,this.parseParenItem))}let p=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=i,this.state.inFSharpPipelineDirectBody=s;let f=this.startNodeAt(e);return n&&this.shouldParseArrow(o)&&(f=this.parseArrow(f))?(this.checkDestructuringPrivate(d),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(f,o,!1),f):(this.expressionScope.exit(),o.length||this.unexpected(this.state.lastTokStartLoc),u&&this.unexpected(u),l&&this.unexpected(l),this.checkExpressionErrors(d,!0),this.toReferencedListDeep(o,!0),o.length>1?(r=this.startNodeAt(a),r.expressions=o,this.finishNode(r,"SequenceExpression"),this.resetEndLocation(r,p)):r=o[0],this.wrapParenthesis(e,r))}wrapParenthesis(n,e){if(!(this.optionFlags&1024))return this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",n.index),this.takeSurroundingComments(e,n.index,this.state.lastTokEndLoc.index),e;let r=this.startNodeAt(n);return r.expression=e,this.finishNode(r,"ParenthesizedExpression")}shouldParseArrow(n){return!this.canInsertSemicolon()}parseArrow(n){if(this.eat(19))return n}parseParenItem(n,e){return n}parseNewOrNewTarget(){let n=this.startNode();if(this.next(),this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(n),"new");this.next();let r=this.parseMetaProperty(n,e,"target");return this.scope.allowNewTarget||this.raise(b.UnexpectedNewTarget,r),r}return this.parseNew(n)}parseNew(n){if(this.parseNewCallee(n),this.eat(10)){let e=this.parseExprList(11);this.toReferencedList(e),n.arguments=e}else n.arguments=[];return this.finishNode(n,"NewExpression")}parseNewCallee(n){let e=this.match(83),r=this.parseNoCallExpr();n.callee=r,(e&&r.type==="ImportExpression"||r.type==="Import")&&this.raise(b.ImportCallNotNewExpression,r),r.type==="Super"&&this.raise(b.SuperCallNotNewExpression,r)}parseTemplateElement(n){let{start:e,startLoc:r,end:i,value:s}=this.state,a=e+1,o=this.startNodeAt(_e(r,1));s===null&&(n||this.raise(b.InvalidEscapeSequenceTemplate,_e(this.state.firstInvalidTemplateEscapePos,1)));let d=this.match(24),c=d?-1:-2,l=i+c;o.value={raw:this.input.slice(a,l).replace(/\r\n?/g,`
10
- `),cooked:s===null?null:s.slice(1,c)},o.tail=d,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,_e(this.state.lastTokEndLoc,c)),u}parseTemplate(n){let e=this.startNode(),r=this.parseTemplateElement(n),i=[r],s=[];for(;!r.tail;)s.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),i.push(r=this.parseTemplateElement(n));return e.expressions=s,e.quasis=i,this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(n,e,r,i){r&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,o=!0,d=this.startNode();for(d.properties=[],this.next();!this.match(n);){if(o)o=!1;else if(this.expect(12),this.match(n)){this.addTrailingCommaExtraToNode(d);break}let l;e?l=this.parseBindingProperty():(l=this.parsePropertyDefinition(i),a=this.checkProto(l,r,a,i)),r&&!this.isObjectProperty(l)&&l.type!=="SpreadElement"&&this.raise(b.InvalidRecordProperty,l),l.shorthand&&this.addExtra(l,"shorthand",!0),d.properties.push(l)}this.next(),this.state.inFSharpPipelineDirectBody=s;let c="ObjectExpression";return e?c="ObjectPattern":r&&(c="RecordExpression"),this.finishNode(d,c)}addTrailingCommaExtraToNode(n){this.addExtra(n,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(n,"trailingCommaLoc",this.state.lastTokStartLoc,!1)}maybeAsyncOrAccessorProp(n){return!n.computed&&n.key.type==="Identifier"&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))}parsePropertyDefinition(n){let e=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(b.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)e.push(this.parseDecorator());let r=this.startNode(),i=!1,s=!1,a;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(r.decorators=e,e=[]),r.method=!1,n&&(a=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(r);let d=this.state.containsEsc;if(this.parsePropertyName(r,n),!o&&!d&&this.maybeAsyncOrAccessorProp(r)){let{key:c}=r,l=c.name;l==="async"&&!this.hasPrecedingLineBreak()&&(i=!0,this.resetPreviousNodeTrailingComments(c),o=this.eat(55),this.parsePropertyName(r)),(l==="get"||l==="set")&&(s=!0,this.resetPreviousNodeTrailingComments(c),r.kind=l,this.match(55)&&(o=!0,this.raise(b.AccessorIsGenerator,this.state.curPosition(),{kind:l}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,a,o,i,!1,s,n)}getGetterSetterExpectedParamCount(n){return n.kind==="get"?0:1}getObjectOrClassMethodParams(n){return n.params}checkGetterSetterParams(n){var e;let r=this.getGetterSetterExpectedParamCount(n),i=this.getObjectOrClassMethodParams(n);i.length!==r&&this.raise(n.kind==="get"?b.BadGetterArity:b.BadSetterArity,n),n.kind==="set"&&((e=i[i.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(b.BadSetterRestParameter,n)}parseObjectMethod(n,e,r,i,s){if(s){let a=this.parseMethod(n,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(r||e||this.match(10))return i&&this.unexpected(),n.kind="method",n.method=!0,this.parseMethod(n,e,r,!1,!1,"ObjectMethod")}parseObjectProperty(n,e,r,i){if(n.shorthand=!1,this.eat(14))return n.value=r?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,i),this.finishObjectProperty(n);if(!n.computed&&n.key.type==="Identifier"){if(this.checkReservedWord(n.key.name,n.key.loc.start,!0,!1),r)n.value=this.parseMaybeDefault(e,this.cloneIdentifier(n.key));else if(this.match(29)){let s=this.state.startLoc;i!=null?i.shorthandAssignLoc===null&&(i.shorthandAssignLoc=s):this.raise(b.InvalidCoverInitializedName,s),n.value=this.parseMaybeDefault(e,this.cloneIdentifier(n.key))}else n.value=this.cloneIdentifier(n.key);return n.shorthand=!0,this.finishObjectProperty(n)}}finishObjectProperty(n){return this.finishNode(n,"ObjectProperty")}parseObjPropValue(n,e,r,i,s,a,o){let d=this.parseObjectMethod(n,r,i,s,a)||this.parseObjectProperty(n,e,s,o);return d||this.unexpected(),d}parsePropertyName(n,e){if(this.eat(0))n.computed=!0,n.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:r,value:i}=this.state,s;if(dt(r))s=this.parseIdentifier(!0);else switch(r){case 135:s=this.parseNumericLiteral(i);break;case 134:s=this.parseStringLiteral(i);break;case 136:s=this.parseBigIntLiteral(i);break;case 139:{let a=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=a):this.raise(b.UnexpectedPrivateField,a),s=this.parsePrivateName();break}default:if(r===137){s=this.parseDecimalLiteral(i);break}this.unexpected()}n.key=s,r!==139&&(n.computed=!1)}}initFunction(n,e){n.id=null,n.generator=!1,n.async=e}parseMethod(n,e,r,i,s,a,o=!1){this.initFunction(n,r),n.generator=e,this.scope.enter(530|(o?576:0)|(s?32:0)),this.prodParam.enter(Zs(r,n.generator)),this.parseFunctionParams(n,i);let d=this.parseFunctionBodyAndFinish(n,a,!0);return this.prodParam.exit(),this.scope.exit(),d}parseArrayLike(n,e,r){e&&this.expectPlugin("recordAndTuple");let i=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let s=this.startNode();return this.next(),s.elements=this.parseExprList(n,!e,r,s),this.state.inFSharpPipelineDirectBody=i,this.finishNode(s,e?"TupleExpression":"ArrayExpression")}parseArrowExpression(n,e,r,i){this.scope.enter(518);let s=Zs(r,!1);!this.match(5)&&this.prodParam.hasIn&&(s|=8),this.prodParam.enter(s),this.initFunction(n,r);let a=this.state.maybeInArrowParameters;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(n,e,i)),this.state.maybeInArrowParameters=!1,this.parseFunctionBody(n,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=a,this.finishNode(n,"ArrowFunctionExpression")}setArrowFunctionParameters(n,e,r){this.toAssignableList(e,r,!1),n.params=e}parseFunctionBodyAndFinish(n,e,r=!1){return this.parseFunctionBody(n,!1,r),this.finishNode(n,e)}parseFunctionBody(n,e,r=!1){let i=e&&!this.match(5);if(this.expressionScope.enter(th()),i)n.body=this.parseMaybeAssign(),this.checkParams(n,!1,e,!1);else{let s=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),n.body=this.parseBlock(!0,!1,o=>{let d=!this.isSimpleParamList(n.params);o&&d&&this.raise(b.IllegalLanguageModeDirective,(n.kind==="method"||n.kind==="constructor")&&n.key?n.key.loc.end:n);let c=!s&&this.state.strict;this.checkParams(n,!this.state.strict&&!e&&!r&&!d,e,c),this.state.strict&&n.id&&this.checkIdentifier(n.id,65,c)}),this.prodParam.exit(),this.state.labels=a}this.expressionScope.exit()}isSimpleParameter(n){return n.type==="Identifier"}isSimpleParamList(n){for(let e=0,r=n.length;e<r;e++)if(!this.isSimpleParameter(n[e]))return!1;return!0}checkParams(n,e,r,i=!0){let s=!e&&new Set,a={type:"FormalParameters"};for(let o of n.params)this.checkLVal(o,a,5,s,i)}parseExprList(n,e,r,i){let s=[],a=!0;for(;!this.eat(n);){if(a)a=!1;else if(this.expect(12),this.match(n)){i&&this.addTrailingCommaExtraToNode(i),this.next();break}s.push(this.parseExprListItem(n,e,r))}return s}parseExprListItem(n,e,r,i){let s;if(this.match(12))e||this.raise(b.UnexpectedToken,this.state.curPosition(),{unexpected:","}),s=null;else if(this.match(21)){let a=this.state.startLoc;s=this.parseParenItem(this.parseSpread(r),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),i||this.raise(b.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),s=this.finishNode(a,"ArgumentPlaceholder")}else s=this.parseMaybeAssignAllowInOrVoidPattern(n,r,this.parseParenItem);return s}parseIdentifier(n){let e=this.startNode(),r=this.parseIdentifierName(n);return this.createIdentifier(e,r)}createIdentifier(n,e){return n.name=e,n.loc.identifierName=e,this.finishNode(n,"Identifier")}createIdentifierAt(n,e,r){return n.name=e,n.loc.identifierName=e,this.finishNodeAt(n,"Identifier",r)}parseIdentifierName(n){let e,{startLoc:r,type:i}=this.state;dt(i)?e=this.state.value:this.unexpected();let s=Nk(i);return n?s&&this.replaceToken(132):this.checkReservedWord(e,r,s,!1),this.next(),e}checkReservedWord(n,e,r,i){if(n.length>10||!Yk(n))return;if(r&&Kk(n)){this.raise(b.UnexpectedKeyword,e,{keyword:n});return}if((this.state.strict?i?Xf:Jf:Wf)(n,this.inModule)){this.raise(b.UnexpectedReservedWord,e,{reservedWord:n});return}else if(n==="yield"){if(this.prodParam.hasYield){this.raise(b.YieldBindingIdentifier,e);return}}else if(n==="await"){if(this.prodParam.hasAwait){this.raise(b.AwaitBindingIdentifier,e);return}if(this.scope.inStaticBlock){this.raise(b.AwaitBindingIdentifierInStaticBlock,e);return}this.expressionScope.recordAsyncArrowParametersError(e)}else if(n==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(b.ArgumentsInClass,e);return}}recordAwaitIfAllowed(){let n=this.prodParam.hasAwait;return n&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),n}parseAwait(n){let e=this.startNodeAt(n);return this.expressionScope.recordParameterInitializerError(b.AwaitExpressionFormalParameter,e),this.eat(55)&&this.raise(b.ObsoleteAwaitStar,e),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(e.argument=this.parseMaybeUnary(null,!0)),this.finishNode(e,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;let{type:n}=this.state;return n===53||n===10||n===0||ta(n)||n===102&&!this.state.containsEsc||n===138||n===56||this.hasPlugin("v8intrinsic")&&n===54}parseYield(n){let e=this.startNodeAt(n);this.expressionScope.recordParameterInitializerError(b.YieldInParameter,e);let r=!1,i=null;if(!this.hasPrecedingLineBreak())switch(r=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!r)break;default:i=this.parseMaybeAssign()}return e.delegate=r,e.argument=i,this.finishNode(e,"YieldExpression")}parseImportCall(n){if(this.next(),n.source=this.parseMaybeAssignAllowIn(),n.options=null,this.eat(12)){if(this.match(11))this.addTrailingCommaExtraToNode(n.source);else if(n.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&(this.addTrailingCommaExtraToNode(n.options),!this.match(11))){do this.parseMaybeAssignAllowIn();while(this.eat(12)&&!this.match(11));this.raise(b.ImportCallArity,n)}}return this.expect(11),this.finishNode(n,"ImportExpression")}checkPipelineAtInfixOperator(n,e){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&n.type==="SequenceExpression"&&this.raise(b.PipelineHeadSequenceExpression,e)}parseSmartPipelineBodyInStyle(n,e){if(this.isSimpleReference(n)){let r=this.startNodeAt(e);return r.callee=n,this.finishNode(r,"PipelineBareFunction")}else{let r=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),r.expression=n,this.finishNode(r,"PipelineTopicExpression")}}isSimpleReference(n){switch(n.type){case"MemberExpression":return!n.computed&&this.isSimpleReference(n.object);case"Identifier":return!0;default:return!1}}checkSmartPipeTopicBodyEarlyErrors(n){if(this.match(19))throw this.raise(b.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipelineTopicUnused,n)}withTopicBindingContext(n){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return n()}finally{this.state.topicContext=e}}withSmartMixTopicForbiddingContext(n){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return n()}finally{this.state.topicContext=e}}else return n()}withSoloAwaitPermittingContext(n){let e=this.state.soloAwait;this.state.soloAwait=!0;try{return n()}finally{this.state.soloAwait=e}}allowInAnd(n){let e=this.prodParam.currentFlags();if(8&~e){this.prodParam.enter(e|8);try{return n()}finally{this.prodParam.exit()}}return n()}disallowInAnd(n){let e=this.prodParam.currentFlags();if(8&e){this.prodParam.enter(e&-9);try{return n()}finally{this.prodParam.exit()}}return n()}registerTopicReference(){this.state.topicContext.maxTopicIndex=0}topicReferenceIsAllowedInCurrentContext(){return this.state.topicContext.maxNumOfResolvableTopics>=1}topicReferenceWasUsedInCurrentContext(){return this.state.topicContext.maxTopicIndex!=null&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(n){let e=this.state.startLoc;this.state.potentialArrowAt=this.state.start;let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let i=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,n);return this.state.inFSharpPipelineDirectBody=r,i}parseModuleExpression(){this.expectPlugin("moduleBlocks");let n=this.startNode();this.next(),this.match(5)||this.unexpected(null,5);let e=this.startNodeAt(this.state.endLoc);this.next();let r=this.initializeScopes(!0);this.enterInitialScopes();try{n.body=this.parseProgram(e,8,"module")}finally{r()}return this.finishNode(n,"ModuleExpression")}parseVoidPattern(n){this.expectPlugin("discardBinding");let e=this.startNode();return n!=null&&(n.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(e,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(n,e,r){if(e!=null&&this.match(88)){let i=this.lookaheadCharCode();if(i===44||i===(n===3?93:n===8?125:41)||i===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(e))}return this.parseMaybeAssignAllowIn(e,r)}parsePropertyNamePrefixOperator(n){}},Gd={kind:1},TR={kind:2},PR=/[\uD800-\uDFFF]/u,Kd=/in(?:stanceof)?/y;function SR(t,n,e){for(let r=0;r<t.length;r++){let i=t[r],{type:s}=i;if(typeof s=="number"){if(s===139){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=_e(a.start,1);t.splice(r,1,new wt({type:Et(27),value:"#",start:o,end:l,startLoc:a.start,endLoc:u}),new wt({type:Et(132),value:d,start:l,end:c,startLoc:u,endLoc:a.end})),r++;continue}if(ta(s)){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=_e(a.start,1),p;n.charCodeAt(o-e)===96?p=new wt({type:Et(22),value:"`",start:o,end:l,startLoc:a.start,endLoc:u}):p=new wt({type:Et(8),value:"}",start:o,end:l,startLoc:a.start,endLoc:u});let f,h,m,g;s===24?(h=c-1,m=_e(a.end,-1),f=d===null?null:d.slice(1,-1),g=new wt({type:Et(22),value:"`",start:h,end:c,startLoc:m,endLoc:a.end})):(h=c-2,m=_e(a.end,-2),f=d===null?null:d.slice(1,-2),g=new wt({type:Et(23),value:"${",start:h,end:c,startLoc:m,endLoc:a.end})),t.splice(r,1,p,new wt({type:Et(20),value:f,start:l,end:h,startLoc:u,endLoc:m}),g),r+=2;continue}i.type=Et(s)}}return t}var hc=class extends fc{parseTopLevel(n,e){return n.program=this.parseProgram(e,140,this.options.sourceType==="module"?"module":"script"),n.comments=this.comments,this.optionFlags&256&&(n.tokens=SR(this.tokens,this.input,this.startIndex)),this.finishNode(n,"File")}parseProgram(n,e,r){if(n.sourceType=r,n.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(n,!0,!0,e),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[s,a]of Array.from(this.scope.undefinedExports))this.raise(b.ModuleExportUndefined,a,{localName:s});this.addExtra(n,"topLevelAwait",this.state.hasTopLevelAwait)}let i;return e===140?i=this.finishNode(n,"Program"):i=this.finishNodeAt(n,"Program",_e(this.state.startLoc,-1)),i}stmtToDirective(n){let e=this.castNodeTo(n,"Directive"),r=this.castNodeTo(n.expression,"DirectiveLiteral"),i=r.value,s=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),a=r.value=s.slice(1,-1);return this.addExtra(r,"raw",s),this.addExtra(r,"rawValue",a),this.addExtra(r,"expressionValue",i),e.value=r,delete n.expression,e}parseInterpreterDirective(){if(!this.match(28))return null;let n=this.startNode();return n.value=this.state.value,this.next(),this.finishNode(n,"InterpreterDirective")}isLet(){return this.isContextual(100)?this.hasFollowingBindingAtom():!1}isUsing(){return this.isContextual(107)?this.nextTokenIsIdentifierOnSameLine():!1}isForUsing(){if(!this.isContextual(107))return!1;let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);if(this.isUnparsedContextual(n,"of")){let r=this.lookaheadCharCodeSince(n+2);if(r!==61&&r!==58&&r!==59)return!1}return!!(this.chStartsBindingIdentifier(e,n)||this.isUnparsedContextual(n,"void"))}nextTokenIsIdentifierOnSameLine(){let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);return this.chStartsBindingIdentifier(e,n)}isAwaitUsing(){if(!this.isContextual(96))return!1;let n=this.nextTokenInLineStart();if(this.isUnparsedContextual(n,"using")){n=this.nextTokenInLineStartSince(n+5);let e=this.codePointAtPos(n);if(this.chStartsBindingIdentifier(e,n))return!0}return!1}chStartsBindingIdentifier(n,e){if(bt(n)){if(Kd.lastIndex=e,Kd.test(this.input)){let r=this.codePointAtPos(Kd.lastIndex);if(!wn(r)&&r!==92)return!1}return!0}else return n===92}chStartsBindingPattern(n){return n===91||n===123}hasFollowingBindingAtom(){let n=this.nextTokenStart(),e=this.codePointAtPos(n);return this.chStartsBindingPattern(e)||this.chStartsBindingIdentifier(e,n)}hasInLineFollowingBindingIdentifierOrBrace(){let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);return e===123||this.chStartsBindingIdentifier(e,n)}allowsUsing(){return(this.scope.inModule||!this.scope.inTopLevel)&&!this.scope.inBareCaseStatement}parseModuleItem(){return this.parseStatementLike(15)}parseStatementListItem(){return this.parseStatementLike(6|(!this.options.annexB||this.state.strict?0:8))}parseStatementOrSloppyAnnexBFunctionDeclaration(n=!1){let e=0;return this.options.annexB&&!this.state.strict&&(e|=4,n&&(e|=8)),this.parseStatementLike(e)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(n){let e=null;return this.match(26)&&(e=this.parseDecorators(!0)),this.parseStatementContent(n,e)}parseStatementContent(n,e){let r=this.state.type,i=this.startNode(),s=!!(n&2),a=!!(n&4),o=n&1;switch(r){case 60:return this.parseBreakContinueStatement(i,!0);case 63:return this.parseBreakContinueStatement(i,!1);case 64:return this.parseDebuggerStatement(i);case 90:return this.parseDoWhileStatement(i);case 91:return this.parseForStatement(i);case 68:if(this.lookaheadCharCode()===46)break;return a||this.raise(this.state.strict?b.StrictFunction:this.options.annexB?b.SloppyFunctionAnnexB:b.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(i,!1,!s&&a);case 80:return s||this.unexpected(),this.parseClass(this.maybeTakeDecorators(e,i),!0);case 69:return this.parseIfStatement(i);case 70:return this.parseReturnStatement(i);case 71:return this.parseSwitchStatement(i);case 72:return this.parseThrowStatement(i);case 73:return this.parseTryStatement(i);case 96:if(this.isAwaitUsing())return this.allowsUsing()?s?this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,i):this.raise(b.UnexpectedLexicalDeclaration,i):this.raise(b.UnexpectedUsingDeclaration,i),this.next(),this.parseVarStatement(i,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(b.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(i,"using");case 100:{if(this.state.containsEsc)break;let l=this.nextTokenStart(),u=this.codePointAtPos(l);if(u!==91&&(!s&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,l)&&u!==123))break}case 75:s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let l=this.state.value;return this.parseVarStatement(i,l)}case 92:return this.parseWhileStatement(i);case 76:return this.parseWithStatement(i);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(i);case 83:{let l=this.lookaheadCharCode();if(l===40||l===46)break}case 82:{!(this.optionFlags&8)&&!o&&this.raise(b.UnexpectedImportExport,this.state.startLoc),this.next();let l;return r===83?l=this.parseImport(i):l=this.parseExport(i,e),this.assertModuleNodeAllowed(l),l}default:if(this.isAsyncFunction())return s||this.raise(b.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(i,!0,!s&&a)}let d=this.state.value,c=this.parseExpression();return se(r)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(i,d,c,n):this.parseExpressionStatement(i,c,e)}assertModuleNodeAllowed(n){!(this.optionFlags&8)&&!this.inModule&&this.raise(b.ImportOutsideModule,n)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(n,e,r){if(n){var i;(i=e.decorators)!=null&&i.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(b.DecoratorsBeforeAfterExport,e.decorators[0]),e.decorators.unshift(...n)):e.decorators=n,this.resetStartLocationFromNode(e,n[0]),r&&this.resetStartLocationFromNode(r,e)}return e}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(n){let e=[];do e.push(this.parseDecorator());while(this.match(26));if(this.match(82))n||this.unexpected(),this.decoratorsEnabledBeforeExport()||this.raise(b.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(b.UnexpectedLeadingDecorator,this.state.startLoc);return e}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);let n=this.startNode();if(this.next(),this.hasPlugin("decorators")){let e=this.state.startLoc,r;if(this.match(10)){let i=this.state.startLoc;this.next(),r=this.parseExpression(),this.expect(11),r=this.wrapParenthesis(i,r);let s=this.state.startLoc;n.expression=this.parseMaybeDecoratorArguments(r,i),this.getPluginOption("decorators","allowCallParenthesized")===!1&&n.expression!==r&&this.raise(b.DecoratorArgumentsOutsideParentheses,s)}else{for(r=this.parseIdentifier(!1);this.eat(16);){let i=this.startNodeAt(e);i.object=r,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),i.computed=!1,r=this.finishNode(i,"MemberExpression")}n.expression=this.parseMaybeDecoratorArguments(r,e)}}else n.expression=this.parseExprSubscripts();return this.finishNode(n,"Decorator")}parseMaybeDecoratorArguments(n,e){if(this.eat(10)){let r=this.startNodeAt(e);return r.callee=n,r.arguments=this.parseCallExpressionArguments(),this.toReferencedList(r.arguments),this.finishNode(r,"CallExpression")}return n}parseBreakContinueStatement(n,e){return this.next(),this.isLineTerminator()?n.label=null:(n.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(n,e),this.finishNode(n,e?"BreakStatement":"ContinueStatement")}verifyBreakContinue(n,e){let r;for(r=0;r<this.state.labels.length;++r){let i=this.state.labels[r];if((n.label==null||i.name===n.label.name)&&(i.kind!=null&&(e||i.kind===1)||n.label&&e))break}if(r===this.state.labels.length){let i=e?"BreakStatement":"ContinueStatement";this.raise(b.IllegalBreakContinue,n,{type:i})}}parseDebuggerStatement(n){return this.next(),this.semicolon(),this.finishNode(n,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);let n=this.parseExpression();return this.expect(11),n}parseDoWhileStatement(n){return this.next(),this.state.labels.push(Gd),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.expect(92),n.test=this.parseHeaderExpression(),this.eat(13),this.finishNode(n,"DoWhileStatement")}parseForStatement(n){this.next(),this.state.labels.push(Gd);let e=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(e=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return e!==null&&this.unexpected(e),this.parseFor(n,null);let r=this.isContextual(100);{let d=this.isAwaitUsing(),c=d||this.isForUsing(),l=r&&this.hasFollowingBindingAtom()||c;if(this.match(74)||this.match(75)||l){let u=this.startNode(),p;d?(p="await using",this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):p=this.state.value,this.next(),this.parseVar(u,!0,p);let f=this.finishNode(u,"VariableDeclaration"),h=this.match(58);return h&&c&&this.raise(b.ForInUsing,f),(h||this.isContextual(102))&&f.declarations.length===1?this.parseForIn(n,f,e):(e!==null&&this.unexpected(e),this.parseFor(n,f))}}let i=this.isContextual(95),s=new or,a=this.parseExpression(!0,s),o=this.isContextual(102);if(o&&(r&&this.raise(b.ForOfLet,a),e===null&&i&&a.type==="Identifier"&&this.raise(b.ForOfAsync,a)),o||this.match(58)){this.checkDestructuringPrivate(s),this.toAssignable(a,!0);let d=o?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:d}),this.parseForIn(n,a,e)}else this.checkExpressionErrors(s,!0);return e!==null&&this.unexpected(e),this.parseFor(n,a)}parseFunctionStatement(n,e,r){return this.next(),this.parseFunction(n,1|(r?2:0)|(e?8:0))}parseIfStatement(n){return this.next(),n.test=this.parseHeaderExpression(),n.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration(),n.alternate=this.eat(66)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null,this.finishNode(n,"IfStatement")}parseReturnStatement(n){return this.prodParam.hasReturn||this.raise(b.IllegalReturn,this.state.startLoc),this.next(),this.isLineTerminator()?n.argument=null:(n.argument=this.parseExpression(),this.semicolon()),this.finishNode(n,"ReturnStatement")}parseSwitchStatement(n){this.next(),n.discriminant=this.parseHeaderExpression();let e=n.cases=[];this.expect(5),this.state.labels.push(TR),this.scope.enter(256);let r;for(let i;!this.match(8);)if(this.match(61)||this.match(65)){let s=this.match(61);r&&this.finishNode(r,"SwitchCase"),e.push(r=this.startNode()),r.consequent=[],this.next(),s?r.test=this.parseExpression():(i&&this.raise(b.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),i=!0,r.test=null),this.expect(14)}else r?r.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),r&&this.finishNode(r,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(n,"SwitchStatement")}parseThrowStatement(n){return this.next(),this.hasPrecedingLineBreak()&&this.raise(b.NewlineAfterThrow,this.state.lastTokEndLoc),n.argument=this.parseExpression(),this.semicolon(),this.finishNode(n,"ThrowStatement")}parseCatchClauseParam(){let n=this.parseBindingAtom();return this.scope.enter(this.options.annexB&&n.type==="Identifier"?8:0),this.checkLVal(n,{type:"CatchClause"},9),n}parseTryStatement(n){if(this.next(),n.block=this.parseBlock(),n.handler=null,this.match(62)){let e=this.startNode();this.next(),this.match(10)?(this.expect(10),e.param=this.parseCatchClauseParam(),this.expect(11)):(e.param=null,this.scope.enter(0)),e.body=this.withSmartMixTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),n.handler=this.finishNode(e,"CatchClause")}return n.finalizer=this.eat(67)?this.parseBlock():null,!n.handler&&!n.finalizer&&this.raise(b.NoCatchOrFinally,n),this.finishNode(n,"TryStatement")}parseVarStatement(n,e,r=!1){return this.next(),this.parseVar(n,!1,e,r),this.semicolon(),this.finishNode(n,"VariableDeclaration")}parseWhileStatement(n){return this.next(),n.test=this.parseHeaderExpression(),this.state.labels.push(Gd),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(n,"WhileStatement")}parseWithStatement(n){return this.state.strict&&this.raise(b.StrictWith,this.state.startLoc),this.next(),n.object=this.parseHeaderExpression(),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.finishNode(n,"WithStatement")}parseEmptyStatement(n){return this.next(),this.finishNode(n,"EmptyStatement")}parseLabeledStatement(n,e,r,i){for(let a of this.state.labels)a.name===e&&this.raise(b.LabelRedeclaration,r,{labelName:e});let s=Dk(this.state.type)?1:this.match(71)?2:null;for(let a=this.state.labels.length-1;a>=0;a--){let o=this.state.labels[a];if(o.statementStart===n.start)o.statementStart=this.sourceToOffsetPos(this.state.start),o.kind=s;else break}return this.state.labels.push({name:e,kind:s,statementStart:this.sourceToOffsetPos(this.state.start)}),n.body=i&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),n.label=r,this.finishNode(n,"LabeledStatement")}parseExpressionStatement(n,e,r){return n.expression=e,this.semicolon(),this.finishNode(n,"ExpressionStatement")}parseBlock(n=!1,e=!0,r){let i=this.startNode();return n&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(i,n,!1,8,r),e&&this.scope.exit(),this.finishNode(i,"BlockStatement")}isValidDirective(n){return n.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&!n.expression.extra.parenthesized}parseBlockBody(n,e,r,i,s){let a=n.body=[],o=n.directives=[];this.parseBlockOrModuleBlockBody(a,e?o:void 0,r,i,s)}parseBlockOrModuleBlockBody(n,e,r,i,s){let a=this.state.strict,o=!1,d=!1;for(;!this.match(i);){let c=r?this.parseModuleItem():this.parseStatementListItem();if(e&&!d){if(this.isValidDirective(c)){let l=this.stmtToDirective(c);e.push(l),!o&&l.value.value==="use strict"&&(o=!0,this.setStrict(!0));continue}d=!0,this.state.strictErrors.clear()}n.push(c)}s?.call(this,o),a||this.setStrict(!1),this.next()}parseFor(n,e){return n.init=e,this.semicolon(!1),n.test=this.match(13)?null:this.parseExpression(),this.semicolon(!1),n.update=this.match(11)?null:this.parseExpression(),this.expect(11),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(n,"ForStatement")}parseForIn(n,e,r){let i=this.match(58);return this.next(),i?r!==null&&this.unexpected(r):n.await=r!==null,e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!i||!this.options.annexB||this.state.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(b.ForInOfLoopInitializer,e,{type:i?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(b.InvalidLhs,e,{ancestor:{type:"ForStatement"}}),n.left=e,n.right=i?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(n,i?"ForInStatement":"ForOfStatement")}parseVar(n,e,r,i=!1){let s=n.declarations=[];for(n.kind=r;;){let a=this.startNode();if(this.parseVarId(a,r),a.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!i&&(a.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(102)))?this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(r==="const"||r==="using"||r==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r})),s.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return n}parseVarId(n,e){let r=this.parseBindingAtom();e==="using"||e==="await using"?(r.type==="ArrayPattern"||r.type==="ObjectPattern")&&this.raise(b.UsingDeclarationHasBindingPattern,r.loc.start):r.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},e==="var"?5:8201),n.id=r}parseAsyncFunctionExpression(n){return this.parseFunction(n,8)}parseFunction(n,e=0){let r=e&2,i=!!(e&1),s=i&&!(e&4),a=!!(e&8);this.initFunction(n,a),this.match(55)&&(r&&this.raise(b.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),n.generator=!0),i&&(n.id=this.parseFunctionId(s));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Zs(a,n.generator)),i||(n.id=this.parseFunctionId()),this.parseFunctionParams(n,!1),this.withSmartMixTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(n,i?"FunctionDeclaration":"FunctionExpression")}),this.prodParam.exit(),this.scope.exit(),i&&!r&&this.registerFunctionStatementId(n),this.state.maybeInArrowParameters=o,n}parseFunctionId(n){return n||se(this.state.type)?this.parseIdentifier():null}parseFunctionParams(n,e){this.expect(10),this.expressionScope.enter(pR()),n.params=this.parseBindingList(11,41,2|(e?4:0)),this.expressionScope.exit()}registerFunctionStatementId(n){n.id&&this.scope.declareName(n.id.name,!this.options.annexB||this.state.strict||n.generator||n.async?this.scope.treatFunctionsAsVar?5:8201:17,n.id.loc.start)}parseClass(n,e,r){this.next();let i=this.state.strict;return this.state.strict=!0,this.parseClassId(n,e,r),this.parseClassSuper(n),n.body=this.parseClassBody(!!n.superClass,i),this.finishNode(n,e?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(29)||this.match(13)||this.match(8)}isClassMethod(){return this.match(10)}nameIsConstructor(n){return n.type==="Identifier"&&n.name==="constructor"||n.type==="StringLiteral"&&n.value==="constructor"}isNonstaticConstructor(n){return!n.computed&&!n.static&&this.nameIsConstructor(n.key)}parseClassBody(n,e){this.classScope.enter();let r={hadConstructor:!1,hadSuperClass:n},i=[],s=this.startNode();if(s.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(i.length>0)throw this.raise(b.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){i.push(this.parseDecorator());continue}let a=this.startNode();i.length&&(a.decorators=i,this.resetStartLocationFromNode(a,i[0]),i=[]),this.parseClassMember(s,a,r),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(b.DecoratorConstructor,a)}}),this.state.strict=e,this.next(),i.length)throw this.raise(b.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(s,"ClassBody")}parseClassMemberFromModifier(n,e){let r=this.parseIdentifier(!0);if(this.isClassMethod()){let i=e;return i.kind="method",i.computed=!1,i.key=r,i.static=!1,this.pushClassMethod(n,i,!1,!1,!1,!1),!0}else if(this.isClassProperty()){let i=e;return i.computed=!1,i.key=r,i.static=!1,n.body.push(this.parseClassProperty(i)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(n,e,r){let i=this.isContextual(106);if(i){if(this.parseClassMemberFromModifier(n,e))return;if(this.eat(5)){this.parseClassStaticBlock(n,e);return}}this.parseClassMemberWithIsStatic(n,e,r,i)}parseClassMemberWithIsStatic(n,e,r,i){let s=e,a=e,o=e,d=e,c=e,l=s,u=s;if(e.static=i,this.parsePropertyNamePrefixOperator(e),this.eat(55)){l.kind="method";let y=this.match(139);if(this.parseClassElementName(l),this.parsePostMemberNameModifiers(l),y){this.pushClassPrivateMethod(n,a,!0,!1);return}this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsGenerator,s.key),this.pushClassMethod(n,s,!0,!1,!1,!1);return}let p=!this.state.containsEsc&&se(this.state.type),f=this.parseClassElementName(e),h=p?f.name:null,m=this.isPrivateName(f),g=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(l.kind="method",m){this.pushClassPrivateMethod(n,a,!1,!1);return}let y=this.isNonstaticConstructor(s),w=!1;y&&(s.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(b.DuplicateConstructor,f),y&&this.hasPlugin("typescript")&&e.override&&this.raise(b.OverrideOnConstructor,f),r.hadConstructor=!0,w=r.hadSuperClass),this.pushClassMethod(n,s,!1,!1,y,w)}else if(this.isClassProperty())m?this.pushClassPrivateProperty(n,d):this.pushClassProperty(n,o);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(f);let y=this.eat(55);u.optional&&this.unexpected(g),l.kind="method";let w=this.match(139);this.parseClassElementName(l),this.parsePostMemberNameModifiers(u),w?this.pushClassPrivateMethod(n,a,y,!0):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAsync,s.key),this.pushClassMethod(n,s,y,!0,!1,!1))}else if((h==="get"||h==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(f),l.kind=h;let y=this.match(139);this.parseClassElementName(s),y?this.pushClassPrivateMethod(n,a,!1,!1):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAccessor,s.key),this.pushClassMethod(n,s,!1,!1,!1,!1)),this.checkGetterSetterParams(s)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);let y=this.match(139);this.parseClassElementName(o),this.pushClassAccessorProperty(n,c,y)}else this.isLineTerminator()?m?this.pushClassPrivateProperty(n,d):this.pushClassProperty(n,o):this.unexpected()}parseClassElementName(n){let{type:e,value:r}=this.state;if((e===132||e===134)&&n.static&&r==="prototype"&&this.raise(b.StaticPrototype,this.state.startLoc),e===139){r==="constructor"&&this.raise(b.ConstructorClassPrivateField,this.state.startLoc);let i=this.parsePrivateName();return n.key=i,i}return this.parsePropertyName(n),n.key}parseClassStaticBlock(n,e){var r;this.scope.enter(720);let i=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let s=e.body=[];this.parseBlockOrModuleBlockBody(s,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=i,n.body.push(this.finishNode(e,"StaticBlock")),(r=e.decorators)!=null&&r.length&&this.raise(b.DecoratorStaticBlock,e)}pushClassProperty(n,e){!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key),n.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(n,e){let r=this.parseClassPrivateProperty(e);n.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(n,e,r){!r&&!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key);let i=this.parseClassAccessorProperty(e);n.body.push(i),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(i.key),0,i.key.loc.start)}pushClassMethod(n,e,r,i,s,a){n.body.push(this.parseMethod(e,r,i,s,a,"ClassMethod",!0))}pushClassPrivateMethod(n,e,r,i){let s=this.parseMethod(e,r,i,!1,!1,"ClassPrivateMethod",!0);n.body.push(s);let a=s.kind==="get"?s.static?6:2:s.kind==="set"?s.static?5:1:0;this.declareClassPrivateMethodInScope(s,a)}declareClassPrivateMethodInScope(n,e){this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),e,n.key.loc.start)}parsePostMemberNameModifiers(n){}parseClassPrivateProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassPrivateProperty")}parseClassProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassProperty")}parseClassAccessorProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassAccessorProperty")}parseInitializer(n){this.scope.enter(592),this.expressionScope.enter(th()),this.prodParam.enter(0),n.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(n,e,r,i=8331){if(se(this.state.type))n.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(n.id,i);else if(r||!e)n.id=null;else throw this.raise(b.MissingClassName,this.state.startLoc)}parseClassSuper(n){n.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(n,e){let r=this.parseMaybeImportPhase(n,!0),i=this.maybeParseExportDefaultSpecifier(n,r),s=!i||this.eat(12),a=s&&this.eatExportStar(n),o=a&&this.maybeParseExportNamespaceSpecifier(n),d=s&&(!o||this.eat(12)),c=i||a;if(a&&!o){if(i&&this.unexpected(),e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.parseExportFrom(n,!0),this.sawUnambiguousESM=!0,this.finishNode(n,"ExportAllDeclaration")}let l=this.maybeParseExportNamedSpecifiers(n);i&&s&&!a&&!l&&this.unexpected(null,5),o&&d&&this.unexpected(null,98);let u;if(c||l){if(u=!1,e)throw this.raise(b.UnsupportedDecoratorExport,n);this.parseExportFrom(n,c)}else u=this.maybeParseExportDeclaration(n);if(c||l||u){var p;let f=n;if(this.checkExport(f,!0,!1,!!f.source),((p=f.declaration)==null?void 0:p.type)==="ClassDeclaration")this.maybeTakeDecorators(e,f.declaration,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportNamedDeclaration")}if(this.eat(65)){let f=n,h=this.parseExportDefaultExpression();if(f.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(e,h,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(n){return this.eat(55)}maybeParseExportDefaultSpecifier(n,e){if(e||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",e?.loc.start);let r=e||this.parseIdentifier(!0),i=this.startNodeAtNode(r);return i.exported=r,n.specifiers=[this.finishNode(i,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(n){if(this.isContextual(93)){var e,r;(r=(e=n).specifiers)!=null||(e.specifiers=[]);let i=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),i.exported=this.parseModuleExportName(),n.specifiers.push(this.finishNode(i,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(n){if(this.match(5)){let e=n;e.specifiers||(e.specifiers=[]);let r=e.exportKind==="type";return e.specifiers.push(...this.parseExportSpecifiers(r)),e.source=null,this.hasPlugin("importAssertions")?e.assertions=[]:e.attributes=[],e.declaration=null,!0}return!1}maybeParseExportDeclaration(n){return this.shouldParseExportDeclaration()?(n.specifiers=[],n.source=null,this.hasPlugin("importAssertions")?n.assertions=[]:n.attributes=[],n.declaration=this.parseExportDeclaration(n),!0):!1}isAsyncFunction(){if(!this.isContextual(95))return!1;let n=this.nextTokenInLineStart();return this.isUnparsedContextual(n,"function")}parseExportDefaultExpression(){let n=this.startNode();if(this.match(68))return this.next(),this.parseFunction(n,5);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(n,13);if(this.match(80))return this.parseClass(n,!0,!0);if(this.match(26))return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")===!0&&this.raise(b.DecoratorBeforeExport,this.state.startLoc),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(b.UnsupportedDefaultExport,this.state.startLoc);let e=this.parseMaybeAssignAllowIn();return this.semicolon(),e}parseExportDeclaration(n){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){let{type:n}=this.state;if(se(n)){if(n===95&&!this.state.containsEsc||n===100)return!1;if((n===130||n===129)&&!this.state.containsEsc){let i=this.nextTokenStart(),s=this.input.charCodeAt(i);if(s===123||this.chStartsBindingIdentifier(s,i)&&!this.input.startsWith("from",i))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let e=this.nextTokenStart(),r=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||se(this.state.type)&&r)return!0;if(this.match(65)&&r){let i=this.input.charCodeAt(this.nextTokenStartSince(e+4));return i===34||i===39}return!1}parseExportFrom(n,e){this.eatContextual(98)?(n.source=this.parseImportSource(),this.checkExport(n),this.maybeParseImportAttributes(n),this.checkJSONModuleImport(n)):e&&this.unexpected(),this.semicolon()}shouldParseExportDeclaration(){let{type:n}=this.state;return n===26&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))?(this.getPluginOption("decorators","decoratorsBeforeExport")===!0&&this.raise(b.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):n===74||n===75||n===68||n===80||this.isLet()||this.isAsyncFunction()}checkExport(n,e,r,i){if(e){var s;if(r){if(this.checkDuplicateExports(n,"default"),this.hasPlugin("exportDefaultFrom")){var a;let o=n.declaration;o.type==="Identifier"&&o.name==="from"&&o.end-o.start===4&&!((a=o.extra)!=null&&a.parenthesized)&&this.raise(b.ExportDefaultFromAsIdentifier,o)}}else if((s=n.specifiers)!=null&&s.length)for(let o of n.specifiers){let{exported:d}=o,c=d.type==="Identifier"?d.name:d.value;if(this.checkDuplicateExports(o,c),!i&&o.local){let{local:l}=o;l.type!=="Identifier"?this.raise(b.ExportBindingIsString,o,{localName:l.value,exportName:c}):(this.checkReservedWord(l.name,l.loc.start,!0,!1),this.scope.checkLocalExport(l))}}else if(n.declaration){let o=n.declaration;if(o.type==="FunctionDeclaration"||o.type==="ClassDeclaration"){let{id:d}=o;if(!d)throw new Error("Assertion failure");this.checkDuplicateExports(n,d.name)}else if(o.type==="VariableDeclaration")for(let d of o.declarations)this.checkDeclaration(d.id)}}}checkDeclaration(n){if(n.type==="Identifier")this.checkDuplicateExports(n,n.name);else if(n.type==="ObjectPattern")for(let e of n.properties)this.checkDeclaration(e);else if(n.type==="ArrayPattern")for(let e of n.elements)e&&this.checkDeclaration(e);else n.type==="ObjectProperty"?this.checkDeclaration(n.value):n.type==="RestElement"?this.checkDeclaration(n.argument):n.type==="AssignmentPattern"&&this.checkDeclaration(n.left)}checkDuplicateExports(n,e){this.exportedIdentifiers.has(e)&&(e==="default"?this.raise(b.DuplicateDefaultExport,n):this.raise(b.DuplicateExport,n,{exportName:e})),this.exportedIdentifiers.add(e)}parseExportSpecifiers(n){let e=[],r=!0;for(this.expect(5);!this.eat(8);){if(r)r=!1;else if(this.expect(12),this.eat(8))break;let i=this.isContextual(130),s=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(a,s,n,i))}return e}parseExportSpecifier(n,e,r,i){return this.eatContextual(93)?n.exported=this.parseModuleExportName():e?n.exported=this.cloneStringLiteral(n.local):n.exported||(n.exported=this.cloneIdentifier(n.local)),this.finishNode(n,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){let n=this.parseStringLiteral(this.state.value),e=PR.exec(n.value);return e&&this.raise(b.ModuleExportNameHasLoneSurrogate,n,{surrogateCharCode:e[0].charCodeAt(0)}),n}return this.parseIdentifier(!0)}isJSONModuleImport(n){return n.assertions!=null?n.assertions.some(({key:e,value:r})=>r.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(n){let{specifiers:e}=n,r=e.length===1?e[0].type:null;if(n.phase==="source")r!=="ImportDefaultSpecifier"&&this.raise(b.SourcePhaseImportRequiresDefault,e[0].loc.start);else if(n.phase==="defer")r!=="ImportNamespaceSpecifier"&&this.raise(b.DeferImportRequiresNamespace,e[0].loc.start);else if(n.module){var i;r!=="ImportDefaultSpecifier"&&this.raise(b.ImportReflectionNotBinding,e[0].loc.start),((i=n.assertions)==null?void 0:i.length)>0&&this.raise(b.ImportReflectionHasAssertion,e[0].loc.start)}}checkJSONModuleImport(n){if(this.isJSONModuleImport(n)&&n.type!=="ExportAllDeclaration"){let{specifiers:e}=n;if(e!=null){let r=e.find(i=>{let s;if(i.type==="ExportSpecifier"?s=i.local:i.type==="ImportSpecifier"&&(s=i.imported),s!==void 0)return s.type==="Identifier"?s.name!=="default":s.value!=="default"});r!==void 0&&this.raise(b.ImportJSONBindingNotDefault,r.loc.start)}}}isPotentialImportPhase(n){return n?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(n,e,r,i){e||(r==="module"?(this.expectPlugin("importReflection",i),n.module=!0):this.hasPlugin("importReflection")&&(n.module=!1),r==="source"?(this.expectPlugin("sourcePhaseImports",i),n.phase="source"):r==="defer"?(this.expectPlugin("deferredImportEvaluation",i),n.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(n.phase=null))}parseMaybeImportPhase(n,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(n,e,null),null;let r=this.startNode(),i=this.parseIdentifierName(!0),{type:s}=this.state;return(dt(s)?s!==98||this.lookaheadCharCode()===102:s!==12)?(this.applyImportPhase(n,e,i,r.loc.start),null):(this.applyImportPhase(n,e,null),this.createIdentifier(r,i))}isPrecedingIdImportPhase(n){let{type:e}=this.state;return se(e)?e!==98||this.lookaheadCharCode()===102:e!==12}parseImport(n){return this.match(134)?this.parseImportSourceAndAttributes(n):this.parseImportSpecifiersAndAfter(n,this.parseMaybeImportPhase(n,!1))}parseImportSpecifiersAndAfter(n,e){n.specifiers=[];let i=!this.maybeParseDefaultImportSpecifier(n,e)||this.eat(12),s=i&&this.maybeParseStarImportSpecifier(n);return i&&!s&&this.parseNamedImportSpecifiers(n),this.expectContextual(98),this.parseImportSourceAndAttributes(n)}parseImportSourceAndAttributes(n){var e;return(e=n.specifiers)!=null||(n.specifiers=[]),n.source=this.parseImportSource(),this.maybeParseImportAttributes(n),this.checkImportReflection(n),this.checkJSONModuleImport(n),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(n,"ImportDeclaration")}parseImportSource(){return this.match(134)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(n,e,r){e.local=this.parseIdentifier(),n.specifiers.push(this.finishImportSpecifier(e,r))}finishImportSpecifier(n,e,r=8201){return this.checkLVal(n.local,{type:e},r),this.finishNode(n,e)}parseImportAttributes(){this.expect(5);let n=[],e=new Set;do{if(this.match(8))break;let r=this.startNode(),i=this.state.value;if(e.has(i)&&this.raise(b.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:i}),e.add(i),this.match(134)?r.key=this.parseStringLiteral(i):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),n.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return this.expect(8),n}parseModuleAttributes(){let n=[],e=new Set;do{let r=this.startNode();if(r.key=this.parseIdentifier(!0),r.key.name!=="type"&&this.raise(b.ModuleAttributeDifferentFromType,r.key),e.has(r.key.name)&&this.raise(b.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),e.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),n.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return n}maybeParseImportAttributes(n){let e;var r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(e=this.parseModuleAttributes(),this.addExtra(n,"deprecatedWithLegacySyntax",!0)):e=this.parseImportAttributes(),r=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")&&this.raise(b.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(n,"deprecatedAssertSyntax",!0),this.next(),e=this.parseImportAttributes()):e=[];!r&&this.hasPlugin("importAssertions")?n.assertions=e:n.attributes=e}maybeParseDefaultImportSpecifier(n,e){if(e){let r=this.startNodeAtNode(e);return r.local=e,n.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}else if(dt(this.state.type))return this.parseImportSpecifierLocal(n,this.startNode(),"ImportDefaultSpecifier"),!0;return!1}maybeParseStarImportSpecifier(n){if(this.match(55)){let e=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(n,e,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(n){let e=!0;for(this.expect(5);!this.eat(8);){if(e)e=!1;else{if(this.eat(14))throw this.raise(b.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}let r=this.startNode(),i=this.match(134),s=this.isContextual(130);r.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(r,i,n.importKind==="type"||n.importKind==="typeof",s,void 0);n.specifiers.push(a)}}parseImportSpecifier(n,e,r,i,s){if(this.eatContextual(93))n.local=this.parseIdentifier();else{let{imported:a}=n;if(e)throw this.raise(b.ImportBindingIsString,n,{importName:a.value});this.checkReservedWord(a.name,n.loc.start,!0,!0),n.local||(n.local=this.cloneIdentifier(a))}return this.finishImportSpecifier(n,"ImportSpecifier",s)}isThisParam(n){return n.type==="Identifier"&&n.name==="this"}},ra=class extends hc{constructor(n,e,r){let i=Tk(n);super(i,e),this.options=i,this.initializeScopes(),this.plugins=r,this.filename=i.sourceFilename,this.startIndex=i.startIndex;let s=0;i.allowAwaitOutsideFunction&&(s|=1),i.allowReturnOutsideFunction&&(s|=2),i.allowImportExportEverywhere&&(s|=8),i.allowSuperOutsideMethod&&(s|=16),i.allowUndeclaredExports&&(s|=64),i.allowNewTargetOutsideFunction&&(s|=4),i.allowYieldOutsideFunction&&(s|=32),i.ranges&&(s|=128),i.tokens&&(s|=256),i.createImportExpressions&&(s|=512),i.createParenthesizedExpressions&&(s|=1024),i.errorRecovery&&(s|=2048),i.attachComment&&(s|=4096),i.annexB&&(s|=8192),this.optionFlags=s}getScopeHandler(){return wi}parse(){this.enterInitialScopes();let n=this.startNode(),e=this.startNode();this.nextToken(),n.errors=null;let r=this.parseTopLevel(n,e);return r.errors=this.state.errors,r.comments.length=this.state.commentsLen,r}};function ER(t,n){var e;if(((e=n)==null?void 0:e.sourceType)==="unambiguous"){n=Object.assign({},n);try{n.sourceType="module";let r=mi(n,t),i=r.parse();if(r.sawUnambiguousESM)return i;if(r.ambiguousScriptDifferentAst)try{return n.sourceType="script",mi(n,t).parse()}catch{}else i.program.sourceType="script";return i}catch(r){try{return n.sourceType="script",mi(n,t).parse()}catch{}throw r}}else return mi(n,t).parse()}function CR(t,n){let e=mi(n,t);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function NR(t){let n={};for(let e of Object.keys(t))n[e]=Et(t[e]);return n}var OR=NR(Ck);function mi(t,n){let e=ra,r=new Map;if(t!=null&&t.plugins){for(let i of t.plugins){let s,a;typeof i=="string"?s=i:[s,a]=i,r.has(s)||r.set(s,a||{})}IR(r),e=$R(r)}return new e(t,n,r)}var Uf=new Map;function $R(t){let n=[];for(let i of AR)t.has(i)&&n.push(i);let e=n.join("|"),r=Uf.get(e);if(!r){r=ra;for(let i of n)r=ih[i](r);Uf.set(e,r)}return r}xi.parse=ER;xi.parseExpression=CR;xi.tokTypes=OR});import{parseArgs as LD}from"node:util";import{writeFile as Jv}from"node:fs/promises";import{join as Yv}from"node:path";function wf(t,n){try{let e=new URL(t);return n.includes(e.protocol)&&e.username===""&&e.password===""&&e.search===""&&e.hash===""?e.href.replace(/\/+$/,""):void 0}catch{return}}function st(t,n=""){return wf(t===void 0||t===""?n:t,["https:"])}function Ed(t){return wf(t??"",["https:","http:"])}var Xv=3e4,Qv="7.1",bf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vf="KwikQA.Ci",Zv=4,kf=/^\$\([\w.-]+\)$/;function $d(t){return Object.fromEntries(Object.entries(t).filter(([,n])=>n===void 0||!kf.test(n.trim())))}function ek(t){if(!(t===void 0||t===""))try{let n=new URL(t);return n.username="",n.password="",st(n.href)}catch{return}}function Cd(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function xf(t){if(!(t===void 0||t===""||t.startsWith("refs/pull/")))return t.replace(/^refs\/(?:heads|tags)\//,"")}function zs(t){if(t.TF_BUILD!=="True")return;let n=st(t.SYSTEM_COLLECTIONURI),e=t.SYSTEM_TEAMPROJECT??"",r=Cd(t.BUILD_BUILDID),i=t.BUILD_REPOSITORY_PROVIDER??"",s=i==="GitHub"||i==="GitHubEnterprise",a=i==="TfsGit"?"pullrequest":s?"pull":void 0,o=a===void 0?void 0:ek(t.BUILD_REPOSITORY_URI),d=Cd((s?t.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER:void 0)||t.SYSTEM_PULLREQUEST_PULLREQUESTID),c=/^[0-9a-f]{40}$/i.test(t.BUILD_SOURCEVERSION??"")?t.BUILD_SOURCEVERSION:void 0,l=xf(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)??xf(t.BUILD_SOURCEBRANCH),u=(t.SYSTEM_ACCESSTOKEN??"").trim(),p=Cd(t.SYSTEM_JOBATTEMPT),f=/^refs\/[^\s\0]+$/.test(t.BUILD_SOURCEBRANCH??"")?t.BUILD_SOURCEBRANCH:void 0,h=t.SYSTEM_PULLREQUEST_SOURCEBRANCH?.startsWith("refs/heads/")?t.SYSTEM_PULLREQUEST_SOURCEBRANCH.slice(11):void 0,m=/^[0-9a-f]{40}$/i.test(t.SYSTEM_PULLREQUEST_SOURCECOMMITID??"")?t.SYSTEM_PULLREQUEST_SOURCECOMMITID?.toLowerCase():void 0,g=bf.test(t.SYSTEM_TEAMPROJECTID??"")?t.SYSTEM_TEAMPROJECTID:void 0,y=bf.test(t.BUILD_REPOSITORY_ID??"")?t.BUILD_REPOSITORY_ID:void 0;return{...n===void 0?{}:{collectionUrl:n},...g===void 0?{}:{projectId:g},...y===void 0?{}:{repositoryId:y},provider:i,...t.BUILD_REPOSITORY_NAME?{repository:t.BUILD_REPOSITORY_NAME}:{},...n===void 0||e===""||r===void 0?{}:{runUrl:`${n}/${encodeURIComponent(e)}/_build/results?buildId=${r}`},pipeline:t.SYSTEM_DEFINITIONID||t.BUILD_DEFINITIONNAME||"",job:[t.SYSTEM_STAGENAME,t.SYSTEM_JOBNAME].filter(Boolean).join("."),...l===void 0?{}:{branch:l},...c===void 0?{}:{commit:{sha:c,...o===void 0?{}:{url:`${o}/commit/${c}`}}},...t.AGENT_TEMPDIRECTORY?{tempDirectory:t.AGENT_TEMPDIRECTORY}:{},...u===""||kf.test(u)?{}:{token:u},...r===void 0?{}:{buildId:String(r)},...p===void 0?{}:{jobAttempt:p},...f===void 0?{}:{ref:f},...d!==void 0&&h!==void 0&&m!==void 0?{pullRequestHead:{ref:h,sha:m}}:{},...d===void 0?{}:{pullRequest:{number:d,...o===void 0?{}:{url:`${o}/${a}/${d}`},fork:t.SYSTEM_PULLREQUEST_ISFORK==="True"}}}}function tk(t){return`kwikqa-ci pipeline=${encodeURIComponent(t.pipeline)} job=${encodeURIComponent(t.job)}`}function nk(t){return t.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function gt(t){return t.ok&&t.status!==203}async function Hs(t){let n=await t.json().catch(()=>{});return typeof n?.message=="string"?n.message.replace(/\s+/g," ").trim().slice(0,200):void 0}async function Nd(t){if(t.status===429)return"Azure DevOps's rate limit was reached";if(t.status===401||t.status===203)return"Azure DevOps refused the token";if(t.status===403){let e=await Hs(t);return`the build service can't comment on this pull request; give it "Contribute to pull requests" on the repository${e===void 0?"":` (${e})`}`}if(t.status===404)return"Azure DevOps found no such pull request with this token";let n=await Hs(t);return`Azure DevOps answered ${t.status}${n===void 0?"":`: ${n}`}`}var Od=class{constructor(n,e,r){this.send=n;this.base=e;this.token=r}send;base;token;call(n,e,r){return this.send(`${this.base}${e}?api-version=${Qv}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.token}`,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(Xv)})}},nr=class extends Error{};function rk(t){if(typeof t=="string")return t;let n=typeof t=="object"&&t!==null?t:{};return typeof n.$value=="string"?n.$value:void 0}async function ik(t,n){let e=await t.call("GET","/threads");if(!gt(e))throw new nr(await Nd(e));let r=(await e.json()).value??[];for(let i of r){if(i.isDeleted===!0||rk(i.properties?.[vf])!==n)continue;let s=i.comments?.find(a=>a.parentCommentId===0&&a.isDeleted!==!0);if(typeof i.id=="number"&&typeof s?.id=="number")return{thread:i.id,comment:s.id}}}async function Dd(t,n,e,r,i){let s=e.noun??"pull-request comment",a=`${s.charAt(0).toUpperCase()}${s.slice(1)}`,o=new Od(n,`${e.collectionUrl}/${e.projectId}/_apis/git/repositories/${e.repositoryId}/pullRequests/${e.pullRequest}`,e.token);try{let d=await ik(o,e.marker);if(d!==void 0){let l=await o.call("PATCH",`/threads/${d.thread}/comments/${d.comment}`,{content:r});if(gt(l))return t.print(`${a}: updated.`);if(l.status!==403&&l.status!==404)throw new nr(await Nd(l))}if(d===void 0&&!i)return t.print(`No ${s}: nothing failed, and there is no earlier comment to update.`);let c=await o.call("POST","/threads",{comments:[{parentCommentId:0,content:r,commentType:1}],status:Zv,properties:{[vf]:{$type:"System.String",$value:e.marker}}});if(!gt(c))throw new nr(await Nd(c));t.print(`${a}: posted.`)}catch(d){let c=d instanceof nr?d.message:`Azure DevOps couldn't be reached (${d instanceof Error?d.message:String(d)})`;t.error(`No ${s}: ${c}.`)}}async function sk(t,n,e,r,i){let s=o=>t.print(`No pull-request comment: ${o}.`),a=e.pullRequest;if(a===void 0)return s("this run isn't for a pull request");if(e.provider!=="TfsGit")return s(`the repository is on ${e.provider||"another host"}, and KwikQA comments from Azure Pipelines only on Azure Repos pull requests`);if(a.fork)return s("the pull request comes from a fork, and its build gets no secrets by default");if(e.token===void 0)return s("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env");if(e.collectionUrl===void 0||e.projectId===void 0||e.repositoryId===void 0)return s("System.CollectionUri, System.TeamProjectId, or Build.Repository.ID isn't what Azure Pipelines sets");await Dd(t,n,{collectionUrl:e.collectionUrl,projectId:e.projectId,repositoryId:e.repositoryId,pullRequest:a.number,token:e.token,marker:tk(e)},r,i)}async function Ld(t,n,e,r,i){if(e.tempDirectory===void 0)t.print("No build summary: AGENT_TEMPDIRECTORY isn't set.");else{let s=Yv(e.tempDirectory,"kwikqa-summary.md");try{await Jv(s,r);let a=`##vso[task.addattachment type=Distributedtask.Core.Summary;name=KwikQA;]${nk(s)}`;t.command===void 0?t.print(a):t.command(a),t.print("Build summary: written.")}catch(a){t.error(`No build summary: ${a.message}`)}}await sk(t,n,e,r,i.failures)}import{createHash as Dw}from"node:crypto";import{readFile as z1,stat as V1}from"node:fs/promises";import{join as U1,relative as q1,sep as G1}from"node:path";import{createHash as ak}from"node:crypto";function Md(t,n){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("canonical JSON cannot contain non-finite numbers");return t}if(Array.isArray(t))return t.map(e=>Md(e,n));if(typeof t!="object")throw new TypeError(`canonical JSON cannot contain ${typeof t}`);if(n.has(t))throw new TypeError("canonical JSON cannot contain cycles");n.add(t);try{let e=t,r={};for(let i of Object.keys(e).sort()){let s=e[i];if(s===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(i)}`);r[i]=Md(s,n)}return r}finally{n.delete(t)}}function ue(t){return JSON.stringify(Md(t,new Set))}function L(t){return ak("sha256").update(ue(t),"utf8").digest("hex")}function Rf(t){let n=new Map;for(let e of t){if(n.has(e.logicalTestId))throw new Error("Logical test observation is duplicated.");n.set(e.logicalTestId,e.status)}return n}function If(t){return t!==void 0&&t!=="passed"}function _d(t){let n=new Set(t.targetLogicalTestIds);if(n.size===0||n.size!==t.targetLogicalTestIds.length)throw new Error("Target logical test identities must be unique and nonempty.");let e=Rf(t.baseline),r=[],i=new Set;for(let l of t.blockingReasons??[]){if(l.length===0)throw new Error("Blocking validation reasons must be nonempty.");r.push({classification:"incomplete-check",message:l})}for(let l of[...t.commands].sort((u,p)=>u.commandId.localeCompare(p.commandId))){if(!l.required)continue;if(l.timing==="post-patch")for(let p of l.expectedLogicalTestIds)i.add(p);if(!l.fresh){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command evidence is not fresh."});continue}if(l.status==="unavailable"){r.push({classification:"unavailable-check",commandId:l.commandId,message:"Required command was unavailable."});continue}if(l.status==="incomplete"){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command did not produce authoritative evidence."});continue}if(l.timing==="baseline")continue;let u=Rf(l.observations);for(let p of l.expectedLogicalTestIds){let f=u.get(p);if(f===void 0){r.push({classification:"incomplete-check",logicalTestId:p,commandId:l.commandId,message:"An expected logical test is missing from post-patch evidence."});continue}if(n.has(p)){r.push({classification:f==="passed"?"fixed-target-failure":"still-failing-target",logicalTestId:p,commandId:l.commandId,message:f==="passed"?"The original target failure is fixed.":"The original target remains non-passing."});continue}let h=e.get(p);f!=="passed"&&r.push({classification:If(h)?"unchanged-pre-existing-failure":"newly-introduced-failure",logicalTestId:p,commandId:l.commandId,message:If(h)?"An affected test remains non-passing from its baseline.":"An affected test newly became non-passing."})}}for(let l of[...n].sort())i.has(l)||r.push({classification:"incomplete-check",logicalTestId:l,message:"No fresh focused evidence covers the target logical test."});let s=r.sort((l,u)=>`${l.classification}\0${l.logicalTestId??""}\0${l.commandId??""}`.localeCompare(`${u.classification}\0${u.logicalTestId??""}\0${u.commandId??""}`)),a=new Set(s.map(l=>l.classification)),o=[...n].every(l=>s.some(u=>u.classification==="fixed-target-failure"&&u.logicalTestId===l)),c={schemaVersion:"1.0",status:a.has("incomplete-check")?"incomplete":a.has("unavailable-check")?"unavailable":!o||a.has("still-failing-target")||a.has("unchanged-pre-existing-failure")||a.has("newly-introduced-failure")||t.commands.some(l=>l.required&&l.status==="failed")?"failed":"passed",classifications:s};return{...c,summaryHash:L(c)}}var Us="1.1",jd="1.0",qs="1.1";var Gs="1.0",Gt=/^[a-z][a-z0-9_-]{0,63}$/,rr=32*1024*1024,hn=16*1024*1024,di="report.json",Tf=["playwright-focused","playwright-affected","playwright-project","playwright-suite","cypress-focused","cypress-affected","cypress-project","cypress-suite","webdriverio-focused","webdriverio-affected","webdriverio-project","webdriverio-suite"];function ir(t){return Tf.includes(t)}var ke=/^[a-f0-9]{64}$/,ci=Gt;function Oe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Pf(t){return Array.isArray(t)&&t.every(n=>typeof n=="string")}function oi(t,n=!0){return Pf(t)&&(n||t.length>0)&&t.every(e=>e.length>0&&!e.includes("\0"))&&new Set(t).size===t.length}function Ce(t,n){let e=Object.keys(t).sort(),r=[...n].sort();return e.length===r.length&&e.every((i,s)=>i===r[s])}function ok(t){if(!Oe(t))return!1;let n=["outputDirectory","maxArtifacts","maxArtifactBytes"];return t.reportFile!==void 0&&n.push("reportFile"),Ce(t,n)&&typeof t.outputDirectory=="string"&&t.outputDirectory.length>0&&!t.outputDirectory.includes("\0")&&(t.reportFile===void 0||typeof t.reportFile=="string"&&t.reportFile.length>0&&!t.reportFile.includes("\0"))&&Number.isInteger(t.maxArtifacts)&&t.maxArtifacts>0&&Number.isInteger(t.maxArtifactBytes)&&t.maxArtifactBytes>0&&t.maxArtifactBytes<=rr}function dk(t){if(!Oe(t))return!1;let n=["kind","path","detail"];return t.sha256!==void 0&&n.push("sha256"),Ce(t,n)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation"].includes(String(t.kind))&&typeof t.path=="string"&&t.path.length>0&&!t.path.includes("\0")&&typeof t.detail=="string"&&t.detail.length>0&&(t.sha256===void 0||typeof t.sha256=="string"&&ke.test(t.sha256))}function Sf(t){return!Oe(t)||!ci.test(String(t.commandId))||!Ce(t,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(ir(String(t.kind))||["parse","format","typecheck","lint"].includes(String(t.kind)))||t.timing!=="baseline"&&t.timing!=="post-patch"||typeof t.executable!="string"||t.executable.length===0||!Pf(t.args)||t.args.some(n=>n.includes("\0"))||typeof t.workingDirectory!="string"||t.workingDirectory.length===0||t.workingDirectory.includes("\0")||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||t.required!==!0||typeof t.purpose!="string"||t.purpose.length===0||!oi(t.logicalTestIds)||!oi(t.projectIds)||!Oe(t.environmentDelta)||!ok(t.artifactPolicy)||!Array.isArray(t.resolutionEvidence)||!t.resolutionEvidence.every(dk)?!1:Object.entries(t.environmentDelta).every(([n,e])=>/^[A-Z][A-Z0-9_]*$/.test(n)&&typeof e=="string"&&!e.includes("\0"))}function Fd(t){return Oe(t)&&Ce(t,["path","sourceSha256","resultSha256"])&&typeof t.path=="string"&&t.path.length>0&&!t.path.includes("\0")&&typeof t.sourceSha256=="string"&&ke.test(t.sourceSha256)&&typeof t.resultSha256=="string"&&ke.test(t.resultSha256)}function ck(t){return Oe(t)&&Ce(t,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(t.baselineId))&&ci.test(String(t.commandId))&&oi(t.logicalTestIds,!1)&&typeof t.reason=="string"&&t.reason.length>0}function lk(t){if(!Oe(t))return!1;let n=["code","message"];return t.path!==void 0&&n.push("path"),Ce(t,n)&&["ambiguous-package-root","ambiguous-configuration","budget-exceeded","cancelled","entry-outside-workspace","invalid-artifact","invalid-command","malformed-manifest","missing-browser","missing-configuration","missing-dependency","missing-test-identity","package-mismatch","parse-failed","report-incomplete","resolution-failed","spawn-failed","symlink-escape","timeout","unsupported-layout"].includes(String(t.code))&&typeof t.message=="string"&&t.message.length>0&&(t.path===void 0||typeof t.path=="string"&&!t.path.includes("\0"))}function Ef(t){return L({purpose:"kwikqa-validation-baseline",...t})}function Ks(t){return L({purpose:"kwikqa-validation-run",...t})}function Vs(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function uk(t){if(!Oe(t)||typeof t.kind!="string")return!1;if(t.kind==="exit")return Ce(t,["kind","exitCode"])&&Number.isInteger(t.exitCode);if(t.kind==="signal")return Ce(t,["kind","signal"])&&typeof t.signal=="string";if(t.kind==="spawn-error"){let n=["kind",...t.code===void 0?[]:["code"]];return Ce(t,n)&&(t.code===void 0||typeof t.code=="string")}return(t.kind==="timeout"||t.kind==="cancelled")&&Ce(t,["kind"])}function Af(t){return Oe(t)&&Ce(t,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&ke.test(t.sha256)&&typeof t.storedSha256=="string"&&ke.test(t.storedSha256)&&Number.isInteger(t.observedBytes)&&t.observedBytes>=0&&Number.isInteger(t.storedBytes)&&t.storedBytes>=0&&typeof t.truncated=="boolean"&&typeof t.redacted=="boolean"}function pk(t){return Oe(t)&&Ce(t,["path","sha256","bytes"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&ke.test(t.sha256)&&Number.isInteger(t.bytes)&&t.bytes>=0}function Bd(t){if(!Hd(t))throw new Error("Validation command record is malformed or failed integrity validation.");return t}function fk(t){if(!Oe(t))return!1;let n=["classification",...t.logicalTestId===void 0?[]:["logicalTestId"],...t.commandId===void 0?[]:["commandId"],"message"];return Ce(t,n)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(t.classification))&&(t.logicalTestId===void 0||typeof t.logicalTestId=="string"&&t.logicalTestId.length>0)&&(t.commandId===void 0||typeof t.commandId=="string"&&ci.test(t.commandId))&&typeof t.message=="string"&&t.message.length>0}function Hd(t){if(!Oe(t))return!1;let n=t,{recordHash:e,...r}=n;return Ce(t,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])&&n.schemaVersion===jd&&/^vld_[a-f0-9]{24}$/.test(n.validationRunId)&&ci.test(n.commandId)&&ke.test(n.commandHash)&&ke.test(n.planHash)&&n.required===!0&&Sf({commandId:n.commandId,kind:n.kind,timing:n.timing,required:n.required,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:n.environmentDelta,timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,artifactPolicy:{outputDirectory:"artifacts",maxArtifacts:1,maxArtifactBytes:1},resolutionEvidence:[]})&&Vs(n.startedAt)&&Number.isInteger(n.durationMs)&&n.durationMs>=0&&uk(n.termination)&&Af(n.stdout)&&Af(n.stderr)&&Array.isArray(n.artifacts)&&n.artifacts.every(pk)&&["blocked","passed","failed","unavailable","incomplete"].includes(n.status)&&ke.test(e)&&L(r)===e}function li(t){if(!Oe(t))throw new Error("Baseline manifest is not an object.");let n=t,{baselineHash:e,...r}=n;if(!Ce(t,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||n.schemaVersion!==jd||!ke.test(n.planHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(Fd)||!Array.isArray(n.commandRecords)||!n.commandRecords.every(Hd)||!Oe(n.logicalTestOutcomes)||!Object.entries(n.logicalTestOutcomes).every(([i,s])=>i.length>0&&typeof s=="string"&&["passed","failed","skipped","interrupted"].includes(s))||!Vs(n.capturedAt)||!ke.test(e)||Ef(r)!==e)throw new Error("Baseline manifest is malformed or failed integrity validation.");return n}function Kt(t){if(!Oe(t))throw new Error("Validation run manifest is not an object.");let n=t,{manifestHash:e,...r}=n;if(!Ce(t,["schemaVersion","validationRunId","transactionId","planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||n.schemaVersion!==qs||!/^vld_[a-f0-9]{24}$/.test(n.validationRunId)||!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||!ke.test(n.planHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(Fd)||!oi(n.requiredCommandIds,!1)||!n.requiredCommandIds.every(i=>ci.test(i))||!Array.isArray(n.commandRecords)||!n.commandRecords.every(Hd)||!Array.isArray(n.classifications)||!n.classifications.every(fk)||!["blocked","passed","failed","unavailable","incomplete"].includes(n.status)||!Vs(n.startedAt)||!Vs(n.completedAt)||Date.parse(n.completedAt)<Date.parse(n.startedAt)||!ke.test(e)||Ks(r)!==e)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(n.targetHashes.map(i=>i.path)).size!==n.targetHashes.length||new Set(n.commandRecords.map(i=>i.commandId)).size!==n.commandRecords.length||n.commandRecords.some(i=>i.validationRunId!==n.validationRunId||i.planHash!==n.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!hk(n))throw new Error("Validation run manifest status is inconsistent with its evidence.");return n}function hk(t){let n=new Set(t.requiredCommandIds),e=new Set(t.commandRecords.map(i=>i.commandId)),r=new Set(t.classifications.map(i=>i.classification));if(t.commandRecords.some(i=>!n.has(i.commandId)||i.timing!=="post-patch")||t.requiredCommandIds.some(i=>!e.has(i)&&!t.classifications.some(s=>s.classification==="incomplete-check"&&s.commandId===i)))return!1;switch(t.status){case"passed":return t.classifications.length>0&&[...r].every(i=>i==="fixed-target-failure")&&e.size===n.size&&t.commandRecords.every(i=>i.status==="passed");case"incomplete":return r.has("incomplete-check");case"unavailable":return!r.has("incomplete-check")&&r.has("unavailable-check");case"failed":return!r.has("incomplete-check")&&!r.has("unavailable-check");default:return!0}}function Ws(t){return L({purpose:"kwikqa-resolved-validation-plan",...t})}function mn(t){if(!Oe(t))throw new Error("Resolved validation plan is not an object.");if(!Ce(t,["schemaVersion","policyVersion","status",...t.transactionId===void 0?[]:["transactionId"],"proposalHash","targetLogicalTestIds","targetHashes","advisoryPlanHash","repositoryFingerprint","commands","baselineRequirements","unresolvedReasons","planHash"]))throw new Error("Resolved validation plan contains unknown or missing fields.");let n=t,{planHash:e,...r}=n;if(n.schemaVersion!==Us||n.policyVersion!==Gs||n.status!=="resolved"&&n.status!=="unavailable"||!ke.test(n.proposalHash)||!oi(n.targetLogicalTestIds,!1)||!ke.test(n.advisoryPlanHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.commands)||!n.commands.every(Sf)||n.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(Fd)||!Array.isArray(n.baselineRequirements)||!n.baselineRequirements.every(ck)||!Array.isArray(n.unresolvedReasons)||!n.unresolvedReasons.every(lk)||!ke.test(e)||Ws(r)!==e)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(n.commands.map(s=>s.commandId)).size!==n.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(n.targetHashes.map(s=>s.path)).size!==n.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(n.baselineRequirements.map(s=>s.baselineId)).size!==n.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let i=new Map(n.commands.map(s=>[s.commandId,s]));if(n.baselineRequirements.some(s=>{let a=i.get(s.commandId);return a===void 0||a.timing!=="baseline"}))throw new Error("Resolved validation plan baseline references are invalid.");if(n.status==="resolved"&&n.unresolvedReasons.length>0||n.status==="unavailable"&&n.unresolvedReasons.length===0)throw new Error("Resolved validation plan status is inconsistent.");return n}var hh=Bs(vi(),1);import{readdir as FR,realpath as ph}from"node:fs/promises";import{extname as BR,isAbsolute as fh,join as HR,relative as zR,resolve as VR,sep as lh}from"node:path";import{dirname as UR,extname as Sc,join as uh}from"node:path/posix";import{open as jR}from"node:fs/promises";import{createHash as sh}from"node:crypto";function DR(t){return`${Buffer.byteLength(t,"utf8")}:${t}`}function Ne(t){return sh("sha256").update(t).digest("hex")}function B(t,n){let e=n.map(DR).join("|"),r=sh("sha256").update(e,"utf8").digest("hex");return`${t}_${r.slice(0,24)}`}import{realpath as ah,stat as LR}from"node:fs/promises";import{isAbsolute as ch,relative as MR,resolve as _R,sep as oh}from"node:path";function dh(t,n){let e=MR(t,n);if(e==="")return"";if(!(e===".."||e.startsWith(`..${oh}`)||ch(e)))return e.split(oh).join("/")}async function ki(t,n){if(n.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let e;try{e=await ah(t)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let r=ch(n)?n:_R(e,n);if(dh(e,r)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let i;try{i=await ah(r)}catch(a){return a.code==="ENOENT"?{kind:"unavailable",message:"Authorized artifact does not exist."}:{kind:"unreadable",message:"Authorized artifact could not be resolved."}}let s=dh(e,i);if(s===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await LR(i)).isFile())return{kind:"unreadable",message:"Authorized artifact is not a regular file."}}catch{return{kind:"unreadable",message:"Authorized artifact could not be inspected."}}return{kind:"authorized",absolutePath:i,relativePath:s}}function Ic(t){return t.length===0||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[A-Za-z]:/.test(t)?!1:t.split("/").every(e=>e!==".."&&e!==".")}async function X(t,n,e){let r=await ki(t,n);if(r.kind!=="authorized")return r;let i;try{i=await jR(r.absolutePath,"r");let s=await i.stat();if(s.size>e)return{kind:"over-budget",message:`Artifact exceeds the ${e}-byte limit.`,relativePath:r.relativePath};let a=new Uint8Array(s.size),o=0;for(;o<a.byteLength;){let d=await i.read(a,o,a.byteLength-o,o);if(d.bytesRead===0)break;o+=d.bytesRead}return o!==a.byteLength?{kind:"unreadable",message:"Artifact changed or ended while it was being read.",relativePath:r.relativePath}:{kind:"read",bytes:a,sha256:Ne(a),relativePath:r.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:r.relativePath}}finally{await i?.close()}}var Ac=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],mh=new Set(Ac),qR=new Set([".js",".mjs",".cjs"]),GR=[".ts",".tsx",".mts",".cts"],KR=/(?:^|\/)(?:[^/]+\.)?(?:spec|test|cy|e2e)\.(?:[cm]?[jt]sx?)$/i,WR=new Set([".git",".kwikqa","node_modules",".yarn",".pnpm-store","coverage","dist","build","out","test-results","playwright-report"]);function Ri(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function Tc(t,n,e=new Set){if(!e.has(t)){e.add(t),n(t);for(let[r,i]of Object.entries(t))if(r!=="loc")if(Array.isArray(i))for(let s of i)Ri(s)&&Tc(s,n,e);else Ri(i)&&Tc(i,n,e)}}function JR(t){let n=Sc(t).toLowerCase();return n===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(n)?["typescript"]:["jsx"]}function ia(t){return Ri(t)&&t.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function YR(t,n){try{let e=(0,hh.parse)(t,{sourceType:"unambiguous",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:JR(n)}),r=new Set,i=!1;return Tc(e,s=>{if(s.type==="ImportDeclaration"||s.type==="ExportNamedDeclaration"||s.type==="ExportAllDeclaration"){let c=ia(s.source);c!==void 0&&r.add(c),s.type==="ExportAllDeclaration"&&(i=!0);return}if(s.type==="ImportExpression"){let c=ia(s.source);c===void 0?i=!0:r.add(c);return}if(s.type!=="CallExpression")return;let a=s.callee,o=Array.isArray(s.arguments)?s.arguments:[];if(Ri(a)&&a.type==="Import"){let c=ia(o[0]);c===void 0?i=!0:r.add(c);return}if(!Ri(a)||a.type!=="Identifier"||a.name!=="require")return;let d=ia(o[0]);d===void 0?i=!0:r.add(d)}),{imports:[...r].sort(),ambiguous:i}}catch{return{code:"parse-failed",message:"Source could not be parsed for validation discovery.",path:n}}}function Pc(t){return t.length===0||t.includes("\0")||t.includes("\\")||fh(t)?!1:t.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function XR(t,n){return t.split("/").some(r=>WR.has(r))?!0:n.some(r=>t===r||t.startsWith(`${r}/`))}function QR(t,n){let e=zR(t,n);if(!(e===""||e===".."||e.startsWith(`..${lh}`)||fh(e)))return e.split(lh).join("/")}async function ZR(t,n,e){let r=await ph(t),i=[],s=!1;async function a(o){if(s)return;let d=(await FR(o,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name,"en"));for(let c of d){if(c.isSymbolicLink())continue;let l=HR(o,c.name),u=QR(r,l);if(!(u===void 0||XR(u,n))){if(c.isDirectory())await a(l);else if(c.isFile()&&mh.has(BR(c.name).toLowerCase())){if(i.length>=e){s=!0;return}i.push(u)}}}}return await a(r),{files:i.sort(),exhausted:s}}function eI(t,n){if(!t.startsWith("./")&&!t.startsWith("../"))return[];let e=uh(n,t),r=[e],i=Sc(e).toLowerCase();if(qR.has(i)){let s=e.slice(0,e.length-i.length);for(let a of GR)r.push(`${s}${a}`)}if(i===""){for(let s of Ac)r.push(`${e}${s}`);for(let s of Ac)r.push(uh(e,`index${s}`))}return r.filter(Pc)}function tI(t,n,e){return eI(t,UR(n)).find(r=>e.has(r))}async function nI(t){let n=[],e=await ZR(t.workspaceRoot,t.ignoredPaths??[],t.limits.maxFiles);e.exhausted&&n.push({code:"budget-exceeded",message:"Source file discovery exceeded its file limit."});let r=new Set(e.files),i=new Map,s=0,a=0,o=!e.exhausted,d=e.exhausted;for(let u of e.files){let p=await X(t.workspaceRoot,u,t.limits.maxFileBytes);if(p.kind!=="read"||p.relativePath!==u){o=!1,n.push({code:"unsafe-path",message:"Source could not be safely read.",path:u});continue}if(s+=p.bytes.byteLength,s>t.limits.maxTotalBytes){o=!1,d=!0,n.push({code:"budget-exceeded",message:"Source discovery exceeded its total byte limit."});break}let f=YR(new TextDecoder("utf-8",{fatal:!0}).decode(p.bytes),u);if("code"in f){o=!1,n.push(f),i.set(u,{path:u,imports:[],ambiguous:!0});continue}let h=[],m=f.ambiguous;for(let g of f.imports){if(!g.startsWith("./")&&!g.startsWith("../"))continue;let y=tI(g,u,r);if(y===void 0){m=!0,o=!1,n.push({code:"unresolved-local-import",message:`Local import ${JSON.stringify(g)} could not be resolved safely.`,path:u});continue}if(a+=1,a>t.limits.maxImportEdges){o=!1,d=!0,n.push({code:"budget-exceeded",message:"Import graph exceeded its edge limit."});break}h.push(y)}if(i.set(u,{path:u,imports:[...new Set(h)].sort(),ambiguous:m}),m&&(o=!1,n.push({code:"dynamic-import",message:"Module contains an import flow that cannot be bounded.",path:u})),d)break}let c=new Map;for(let u of i.values())for(let p of u.imports){let f=c.get(p)??[];f.push(u.path),c.set(p,f)}let l=new Map([...c].map(([u,p])=>[u,[...new Set(p)].sort()]));return{modules:i,reverse:l,edges:Math.min(a,t.limits.maxImportEdges),complete:o,exhausted:d,reasons:n}}function yh(t,n){return n.filter(e=>t===e.testDirectory||t.startsWith(`${e.testDirectory}/`)).sort((e,r)=>r.testDirectory.length-e.testDirectory.length||e.id.localeCompare(r.id))}function rI(t,n,e){let r=new Set,i=[];for(let s of[...t.map(a=>a.path),...n]){let o=yh(s,e)[0];o!==void 0&&!r.has(o.id)&&(r.add(o.id),i.push(o))}return i.sort((s,a)=>s.id.localeCompare(a.id))}function iI(t,n,e){let r=new Set,i=new Set(t),s=[...t].sort(),a=!0;for(let o=0;s.length>0;o+=1){if(o>=e){a=!1;break}let d=[];for(let c of s){n.modules.get(c)?.ambiguous===!0&&(a=!1);for(let u of n.reverse.get(c)??[])KR.test(u)&&r.add(u),i.has(u)||(i.add(u),d.push(u))}s=[...new Set(d)].sort()}return{tests:[...r].sort(),complete:a}}async function sa(t,n){for(let e of n){let r=await X(t,e,1e6);if(r.kind==="read"&&r.relativePath===e)return e}}async function gh(t,n){let e=[];n.some(o=>mh.has(Sc(o).toLowerCase()))&&e.push({kind:"parse",tool:"kwikqa-babel",required:!0});let r=await sa(t,["biome.json","biome.jsonc"]),i=await sa(t,[".prettierrc",".prettierrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs"]);r!==void 0?(e.push({kind:"format",tool:"biome",configPath:r,required:!0}),e.push({kind:"lint",tool:"biome",configPath:r,required:!0})):i!==void 0&&e.push({kind:"format",tool:"prettier",configPath:i,required:!0});let s=await sa(t,["tsconfig.json"]);s!==void 0&&e.push({kind:"typecheck",tool:"typescript",configPath:s,required:!0});let a=await sa(t,["eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json"]);return r===void 0&&a!==void 0&&e.push({kind:"lint",tool:"eslint",configPath:a,required:!0}),e}function sI(t,n,e){return t.some(r=>r.class==="playwright-config"||r.class==="framework-config")?n.length===1?"project":"suite":e?"affected":n.length===1?"project":"suite"}async function Ec(t){let n=await gh(t.workspaceRoot,t.targets.map(u=>u.path));if(t.targets.length===0||!Pc(t.originalTestPath)||t.targets.some(u=>!Pc(u.path))||t.limits.maxFiles<=0||t.limits.maxFileBytes<=0||t.limits.maxTotalBytes<=0||t.limits.maxImportEdges<=0||t.limits.maxImportDepth<=0)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:n,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Discovery input is unsafe or unbounded."}]};let e=await ph(t.workspaceRoot).catch(()=>{});if(e===void 0||VR(e,t.originalTestPath)===e)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:n,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Workspace could not be resolved safely."}]};let r=await nI(t),i=t.targets.filter(u=>u.class!=="spec");if(i.length===0)return{status:"resolved",scope:"focused",testPaths:[t.originalTestPath],projectIds:yh(t.originalTestPath,t.projects).slice(0,1).map(u=>u.id),staticChecks:n,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:r.complete,reasons:[]};let s=iI(i.map(u=>u.path),r,t.limits.maxImportDepth),a=r.complete&&s.complete&&!r.exhausted,o=rI(t.targets,s.tests,t.projects),d=sI(t.targets,o,a),c=d==="affected"?[...new Set([t.originalTestPath,...s.tests])].sort():d==="project"?[...new Set([t.originalTestPath,...s.tests])].sort():[t.originalTestPath],l=[...r.reasons];return d==="suite"&&t.projects.length>0&&o.length!==1&&l.push({code:"ambiguous-project",message:"Shared impact could not be partitioned to exactly one project; full-suite validation is required."}),{status:"resolved",scope:d,testPaths:c,projectIds:o.map(u=>u.id),staticChecks:n,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:a,reasons:l}}import{spawn as fI}from"node:child_process";import{createHash as ua,randomUUID as hI}from"node:crypto";import{lstat as Ti,mkdir as Ai,readdir as mI,readFile as yI,realpath as pa}from"node:fs/promises";import{isAbsolute as Eh,join as Ye,relative as fa,resolve as Ch,sep as ha}from"node:path";var aI=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function vt(t){return t.replace(aI,"")}function ce(t,n,e,r){let i=vt(t),s=[];for(let a of[...new Set(r.map(o=>o.toLowerCase()))].sort()){let o=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(`(["']?${o}["']?\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^,;&}\\r\\n]*?(?=\\s+(?:and\\s+)?[A-Za-z_$][\\w$.-]*\\s*[:=]|\\s*$|[,;&}]))`,"gim"),c=0;if(i=i.replace(d,(l,u)=>(c+=1,`${u}[REDACTED]`)),c===0){let l=new RegExp(`(${o}\\s*[:=]\\s*)\\S+`,"gi");i=i.replace(l,(u,p)=>(c+=1,`${p}[REDACTED]`))}c>0&&s.push({redactionId:B("red",[n,e,a]),ruleId:`sensitive-name:${a}`,channel:n,locator:e,action:"mask",count:c})}return{value:i,records:s}}function Ii(t,n){let e=t.toLowerCase();return n.map(r=>r.toLowerCase()).sort().find(r=>e===r||e.includes(r))}function aa(t,n,e,r){let i=[],s=new Map;for(let o of t){let d=Ii(o.name,r);if(d===void 0){i.push(o);continue}s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",[n,e,`header:${o}`]),ruleId:`sensitive-header:${o}`,channel:n,locator:e,action:"remove",count:d}));return{value:i,records:a}}function Xt(t,n,e,r){let i;try{i=new URL(t)}catch{return ce(t,n,e,r)}let s=[];(i.username!==""||i.password!=="")&&(i.username="",i.password="",s.push({redactionId:B("red",[n,e,"url-userinfo"]),ruleId:"url-userinfo",channel:n,locator:e,action:"remove",count:1}));let a=new Map;for(let o of[...i.searchParams.keys()]){let d=Ii(o,r);d!==void 0&&(i.searchParams.set(o,"[REDACTED]"),a.set(d,(a.get(d)??0)+1))}for(let[o,d]of[...a.entries()].sort(([c],[l])=>c.localeCompare(l)))s.push({redactionId:B("red",[n,e,`query:${o}`]),ruleId:`sensitive-query:${o}`,channel:n,locator:e,action:"mask",count:d});return{value:i.toString(),records:s}}var oI=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),wh=["type","name","id","autocomplete","placeholder","aria-label"];function Cc(t,n,e,r){if(t==="")return{value:t,records:[]};let i=n.filter(s=>wh.includes(s.name.toLowerCase())).map(s=>Ii(s.value,r)).find(s=>s!==void 0);return i===void 0?{value:t,records:[]}:{value:"[REDACTED]",records:[{redactionId:B("red",["dom",e,`text:${i}`]),ruleId:`sensitive-element-text:${i}`,channel:"dom",locator:e,action:"mask",count:1}]}}function Nc(t,n,e){let r=t.filter(o=>wh.includes(o.name.toLowerCase())).map(o=>Ii(o.value,e)).find(o=>o!==void 0),i=[],s=new Map;for(let o of t){let d=Ii(o.name,e),c=r!==void 0&&oI.has(o.name.toLowerCase())?r:void 0,l=d??c;if(l===void 0||o.value===""){i.push(o);continue}i.push({name:o.name,value:"[REDACTED]"});let u=d===void 0?`sensitive-element:${l}`:`sensitive-field:${l}`;s.set(u,(s.get(u)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",["dom",n,o]),ruleId:o,channel:"dom",locator:n,action:"mask",count:d}));return{value:i,records:a}}import{createHash as dI,randomUUID as da}from"node:crypto";import{constants as ur}from"node:fs";import{chmod as cI,link as lI,lstat as Ot,mkdir as vh,open as oa,readFile as kh,realpath as Nt,rename as Dc,rm as bh,unlink as Oc}from"node:fs/promises";import{dirname as $c,isAbsolute as uI,join as Qt,relative as Rh,resolve as Lc,sep as Ih}from"node:path";var pI=/^txn_[a-f0-9]{24}$/;function bn(t,n){let e=Rh(t,n);return e===""||!uI(e)&&e!==".."&&!e.startsWith(`..${Ih}`)}async function pr(t){if(process.platform==="win32")return;let n=await oa(t,"r");try{await n.sync()}finally{await n.close()}}function xh(t){return dI("sha256").update(t).digest("hex")}function Ah(){return`txn_${da().replaceAll("-","").slice(0,24)}`}function xn(t){return pI.test(t)}async function ca(t){let n=await Nt(t),e=Lc(n,".kwikqa","transactions");if(!bn(n,e))throw new Error("Transaction path escapes workspace.");return{root:n,transactionsDirectory:e}}async function ze(t,n){let e=await Nt(t),r=e;for(let i of n){if(!/^[A-Za-z0-9_.-]+$/.test(i)||i==="."||i==="..")throw new Error("Unsafe transaction directory segment.");let s=Qt(r,i),a=await Ot(s).catch(d=>{if(d.code!=="ENOENT")throw d});if(a===void 0)await vh(s,{mode:448}),await pr(r);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let o=await Nt(s);if(!bn(e,o))throw new Error("Transaction directory escapes workspace.");r=o}return r}async function Th(t,n,e){if(!/^\.staging-[a-f0-9]{24}$/.test(n)||!xn(e))throw new Error("Transaction publication name is invalid.");let r=await ca(t),i=await Nt(r.transactionsDirectory),s=Qt(i,n),a=Qt(i,e),o=await Ot(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await Ot(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await Dc(s,a),await pr(i)}async function ye(t,n,e){let r=await Nt($c(t)),i=Lc(r,t.slice($c(t).length+1));if(!bn(r,i))throw new Error("Write target escapes its directory.");if(!e.replace&&await Ot(i).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let s=Qt(r,`.kwikqa-${da()}.tmp`),a=await oa(s,"wx",e.mode),o=!1;try{await a.writeFile(n),await a.sync(),await a.close(),e.replace?await Dc(s,i):(await lI(s,i),await Oc(s)),o=!0,await pr(r)}finally{await a.close().catch(()=>{}),o||await Oc(s).catch(()=>{})}}async function la(t,n,e,r){let i=await Nt(t),s=Lc(i,n);if(!bn(i,s))throw new Error("Target escapes workspace.");let a=await Ot(s);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let o=await Nt($c(s)),d=await Nt(s);if(!bn(i,o)||!bn(i,d))throw new Error("Target escapes workspace.");if(Rh(i,d).split(Ih).join("/")!==n)throw new Error("Target canonical path changed during final authorization.");let l=await oa(d,ur.O_RDONLY|ur.O_NOFOLLOW);try{let m=await l.stat();if(!m.isFile()||m.dev!==a.dev||m.ino!==a.ino)throw new Error("Target changed during final authorization.");let g=await l.readFile();if(xh(g)!==e)throw new Error("Target content changed during final authorization.")}finally{await l.close()}let u=Qt(o,`.kwikqa-target-${da()}.tmp`),p=a.mode&511,f=await oa(u,ur.O_CREAT|ur.O_EXCL|ur.O_WRONLY|ur.O_NOFOLLOW,p),h=!1;try{await f.writeFile(r),await f.sync(),await f.close(),await cI(u,p);let m=await Nt(s);if(m!==d||!bn(i,m))throw new Error("Target path changed before replacement.");let g=await kh(m),y=await Ot(m);if(!y.isFile()||y.isSymbolicLink()||y.dev!==a.dev||y.ino!==a.ino||xh(g)!==e)throw new Error("Target changed before replacement.");await Dc(u,m),h=!0,await pr(o)}finally{await f.close().catch(()=>{}),h||await Oc(u).catch(()=>{})}}async function Je(t,n){let e=await ze(t,[".kwikqa","transactions"]),r=Qt(e,".lock"),i=da();await vh(r,{mode:448});let s=await Ot(r);try{await ye(Qt(r,"owner.json"),`${JSON.stringify({...n,nonce:i})}
11
- `,{mode:384,replace:!1})}catch(a){let o=await Ot(r).catch(()=>{});throw o?.dev===s.dev&&o.ino===s.ino&&await bh(r,{recursive:!0,force:!0}).catch(()=>{}),a}return await pr(e),{release:async()=>{let a=await Ot(r).catch(()=>{});if(a===void 0||a.dev!==s.dev||a.ino!==s.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await kh(Qt(r,"owner.json"),"utf8")).nonce!==i)throw new Error("Workspace lock ownership changed before release.");await bh(r,{recursive:!0,force:!1}),await pr(e)}}}var gI=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,wI=["authorization","cookie","password","passwd","secret","token","api_key","private_key"];function Mc(t,n){let e=fa(t,n);return e===""||!Eh(e)&&e!==".."&&!e.startsWith(`..${ha}`)}function bI(t){return/^[a-f0-9]{64}$/.test(t)}function xI(t){let n=mn(t.plan),e=n.commands.find(r=>r.commandId===t.commandId);if(!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||n.status!=="resolved"||!bI(n.planHash)||!Gt.test(t.commandId)||e===void 0||e.executable!==process.execPath||!Eh(e.workingDirectory)||e.args.some(r=>r.includes("\0"))||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||!Number.isInteger(t.limits.maxStreamBytes)||t.limits.maxStreamBytes<=0||t.limits.maxStreamBytes>hn||!Number.isInteger(t.limits.maxTotalStreamBytes)||t.limits.maxTotalStreamBytes<t.limits.maxStreamBytes||!Number.isInteger(t.limits.terminationGraceMs)||t.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[r,i]of Object.entries(e.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)||i.includes("\0"))throw new Error("Validation environment delta is invalid.");return e}async function vI(t,n){let e=await pa(t.workspaceRoot),r=Ch(e,".kwikqa","transactions",t.transactionId);if(!Mc(e,r))throw new Error("Validation transaction escapes workspace.");let i=await Ti(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Validation transaction is unsafe.");let s=t.validationRunId??`vld_${hI().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(s))throw new Error("Validation run id is invalid.");let a=Ye(r,"validation");await Ai(a,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let o=await Ti(a);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Validation directory is unsafe.");let d=Ye(a,s);await Ai(d,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let c=await Ti(d);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let l=Ye(d,"commands");await Ai(l,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let u=await Ti(l);if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let p=Ye(l,n.commandId);return await Ai(p,{mode:448}),await Ai(Ye(p,"artifacts"),{mode:448}),{root:d,commandDirectory:p,runId:s}}var ma=class{constructor(n,e){this.cap=n;this.consumeGlobal=e}cap;consumeGlobal;#e=ua("sha256");#n=[];#t=0;#r=0;add(n){this.#e.update(n),this.#t+=n.byteLength;let e=Math.max(0,this.cap-this.#r),r=this.consumeGlobal(Math.min(e,n.byteLength));r>0&&(this.#n.push(n.subarray(0,r)),this.#r+=r)}finish(){return{text:Buffer.concat(this.#n).toString("utf8"),observed:this.#t,hash:this.#e.digest("hex"),truncated:this.#r<this.#t}}};function Ph(t,n){let e=Buffer.from(t,"utf8");if(e.byteLength<=n)return{text:t,truncated:!1};let r=n;for(;r>0&&(e[r]??0)>=128&&(e[r]??0)<192;)r-=1;return{text:e.subarray(0,r).toString("utf8"),truncated:!0}}function Sh(t){return Object.fromEntries(Object.entries(t).sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>[n,gI.test(n)?"[REDACTED]":e]))}function kI(t){return t.kind==="timeout"||t.kind==="cancelled"?"incomplete":t.kind==="spawn-error"?"unavailable":t.kind==="signal"?"incomplete":t.exitCode===0?"passed":"failed"}function RI(t){return new Promise(n=>setTimeout(n,t))}async function II(t,n,e,r){let i=await mI(n,{withFileTypes:!0}),s=[],a=0;for(let o of i.sort((d,c)=>d.name.localeCompare(c.name))){if(!o.isFile()||o.isSymbolicLink())throw new Error("Validation artifact output contains an unsafe entry.");let d=Ye(n,o.name),c=await Ti(d),l=await pa(d);if(!c.isFile()||c.isSymbolicLink()||!Mc(n,l)||c.mtimeMs+1<r)throw new Error("Validation artifact is stale or unsafe.");let u=await yI(l);if(a+=u.byteLength,s.push({path:fa(t,l).split(ha).join("/"),sha256:ua("sha256").update(u).digest("hex"),bytes:u.byteLength}),s.length>e.artifactPolicy.maxArtifacts||a>e.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(e.artifactPolicy.reportFile!==void 0&&!s.some(o=>o.path.split("/").at(-1)===e.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return s}async function _c(t){let n=xI(t),e=await pa(t.workspaceRoot),r=await pa(n.workingDirectory);if(!Mc(e,r))throw new Error("Validation working directory escapes workspace.");let i=t.repositoryRoot??e;for(let K of n.resolutionEvidence){if(K.sha256===void 0)continue;let te=await X(i,Ch(e,K.path),16*1024*1024);if(te.kind!=="read"||te.sha256!==K.sha256)throw new Error("Validation resolution evidence changed after approval.")}let s=await vI(t,n),a=t.now??(()=>new Date),o=a(),d=t.limits.maxTotalStreamBytes,c=K=>{let te=Math.min(K,d);return d-=te,te},l=new ma(t.limits.maxStreamBytes,c),u=new ma(t.limits.maxStreamBytes,c),p=Ye(s.commandDirectory,"artifacts"),f={...t.inheritedEnvironment??process.env,...n.environmentDelta,...n.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Ye(p,n.artifactPolicy.reportFile??di)}:{},...ir(n.kind)&&!n.kind.startsWith("playwright-")?{KWIKQA_REPORT_DIR:p}:{}},h=fI(n.executable,[...n.args],{cwd:n.workingDirectory,env:f,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]});h.stdout.on("data",K=>l.add(K)),h.stderr.on("data",K=>u.add(K));let m,g,y=K=>{m===void 0&&(m=K,h.kill(),g=setTimeout(()=>h.kill("SIGKILL"),t.limits.terminationGraceMs))},w=()=>y("cancelled");t.signal?.addEventListener("abort",w,{once:!0}),t.signal?.aborted&&y("cancelled");let x=setTimeout(()=>y("timeout"),n.timeoutMs),v=await new Promise(K=>{let te=!1;h.once("error",le=>{te||(te=!0,K({kind:"spawn-error",...le.code===void 0?{}:{code:le.code}}))}),h.once("close",(le,Y)=>{te||(te=!0,K(m!==void 0?{kind:m}:Y!==null?{kind:"signal",signal:Y}:{kind:"exit",exitCode:le??1}))})});x!==void 0&&clearTimeout(x),g!==void 0&&clearTimeout(g),t.signal?.removeEventListener("abort",w),await RI(0);let R=t.sensitiveNames??wI,P=l.finish(),C=u.finish(),E=ce(P.text,"report","validation:stdout",R).value,M=Ph(E,t.limits.maxStreamBytes),A=ce(C.text,"report","validation:stderr",R).value,N=Ph(A,t.limits.maxStreamBytes),T=M.text,I=N.text,$=Ye(s.commandDirectory,"stdout.log"),D=Ye(s.commandDirectory,"stderr.log");await ye($,T,{mode:384,replace:!1}),await ye(D,I,{mode:384,replace:!1});let k=await II(s.root,p,n,o.getTime()),S=a(),_={schemaVersion:"1.0",validationRunId:s.runId,commandId:n.commandId,commandHash:L(n),planHash:t.plan.planHash,kind:n.kind,timing:n.timing,required:n.required,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:Sh(n.environmentDelta),timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,startedAt:o.toISOString(),durationMs:Math.max(0,S.getTime()-o.getTime()),termination:v,stdout:{path:fa(s.root,$).split(ha).join("/"),observedBytes:P.observed,storedBytes:Buffer.byteLength(T),sha256:P.hash,storedSha256:ua("sha256").update(T).digest("hex"),truncated:P.truncated||M.truncated,redacted:E!==P.text},stderr:{path:fa(s.root,D).split(ha).join("/"),observedBytes:C.observed,storedBytes:Buffer.byteLength(I),sha256:C.hash,storedSha256:ua("sha256").update(I).digest("hex"),truncated:C.truncated||N.truncated,redacted:A!==C.text},artifacts:k,status:kI(v)},q={..._,recordHash:L(_)};return await ye(Ye(s.commandDirectory,"command.json"),`${ue({commandId:n.commandId,planHash:t.plan.planHash,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:Sh(n.environmentDelta)})}
9
+ `);case 114:return o("\r");case 120:{let c;return{code:c,pos:n}=rc(t,n,e,r,2,!1,a,s),o(c===null?null:String.fromCharCode(c))}case 117:{let c;return{code:c,pos:n}=eh(t,n,e,r,a,s),o(c===null?null:String.fromCodePoint(c))}case 116:return o(" ");case 98:return o("\b");case 118:return o("\v");case 102:return o("\f");case 13:t.charCodeAt(n)===10&&++n;case 10:e=n,++r;case 8232:case 8233:return o("");case 56:case 57:if(i)return o(null);s.strictNumericEscape(n-1,e,r);default:if(d>=48&&d<=55){let c=n-1,u=/^[0-7]+/.exec(t.slice(c,n+2))[0],p=parseInt(u,8);p>255&&(u=u.slice(0,-1),p=parseInt(u,8)),n+=u.length-1;let f=t.charCodeAt(n);if(u!=="0"||f===56||f===57){if(i)return o(null);s.strictNumericEscape(c,e,r)}return o(String.fromCharCode(p))}return o(String.fromCharCode(d))}}function rc(t,n,e,r,i,s,a,o){let d=n,c;return{n:c,pos:n}=Zf(t,n,e,r,16,i,s,!1,o,!a),c===null&&(a?o.invalidEscapeSequence(d,e,r):n=d-1),{code:c,pos:n}}function Zf(t,n,e,r,i,s,a,o,d,c){let l=n,u=i===16?_f.hex:_f.decBinOct,p=i===16?Ys.hex:i===10?Ys.dec:i===8?Ys.oct:Ys.bin,f=!1,h=0;for(let m=0,g=s??1/0;m<g;++m){let y=t.charCodeAt(n),w;if(y===95&&o!=="bail"){let x=t.charCodeAt(n-1),v=t.charCodeAt(n+1);if(o){if(Number.isNaN(v)||!p(v)||u.has(x)||u.has(v)){if(c)return{n:null,pos:n};d.unexpectedNumericSeparator(n,e,r)}}else{if(c)return{n:null,pos:n};d.numericSeparatorInEscapeSequence(n,e,r)}++n;continue}if(y>=97?w=y-97+10:y>=65?w=y-65+10:dR(y)?w=y-48:w=1/0,w>=i){if(w<=9&&c)return{n:null,pos:n};if(w<=9&&d.invalidDigit(n,e,r,i))w=0;else if(a)w=0,f=!0;else break}++n,h=h*i+w}return n===l||s!=null&&n-l!==s||f?{n:null,pos:n}:{n:h,pos:n}}function eh(t,n,e,r,i,s){let a=t.charCodeAt(n),o;if(a===123){if(++n,{code:o,pos:n}=rc(t,n,e,r,t.indexOf("}",n)-n,!0,i,s),++n,o!==null&&o>1114111)if(i)s.invalidCodePoint(n,e,r);else return{code:null,pos:n}}else({code:o,pos:n}=rc(t,n,e,r,4,!1,i,s));return{code:o,pos:n}}function fi(t,n,e){return new xt(e,t-n,t)}var uR=new Set([103,109,115,105,121,117,100,118]),wt=class{constructor(n){let e=n.startIndex||0;this.type=n.type,this.value=n.value,this.start=e+n.start,this.end=e+n.end,this.loc=new cr(n.startLoc,n.endLoc)}},ic=class extends tc{constructor(n,e){super(),this.isLookahead=void 0,this.tokens=[],this.errorHandlers_readInt={invalidDigit:(r,i,s,a)=>this.optionFlags&2048?(this.raise(b.InvalidDigit,fi(r,i,s),{radix:a}),!0):!1,numericSeparatorInEscapeSequence:this.errorBuilder(b.NumericSeparatorInEscapeSequence),unexpectedNumericSeparator:this.errorBuilder(b.UnexpectedNumericSeparator)},this.errorHandlers_readCodePoint=Object.assign({},this.errorHandlers_readInt,{invalidEscapeSequence:this.errorBuilder(b.InvalidEscapeSequence),invalidCodePoint:this.errorBuilder(b.InvalidCodePoint)}),this.errorHandlers_readStringContents_string=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:(r,i,s)=>{this.recordStrictModeErrors(b.StrictNumericEscape,fi(r,i,s))},unterminated:(r,i,s)=>{throw this.raise(b.UnterminatedString,fi(r-1,i,s))}}),this.errorHandlers_readStringContents_template=Object.assign({},this.errorHandlers_readCodePoint,{strictNumericEscape:this.errorBuilder(b.StrictNumericEscape),unterminated:(r,i,s)=>{throw this.raise(b.UnterminatedTemplate,fi(r,i,s))}}),this.state=new nc,this.state.init(n),this.input=e,this.length=e.length,this.comments=[],this.isLookahead=!1}pushToken(n){this.tokens.length=this.state.tokensLength,this.tokens.push(n),++this.state.tokensLength}next(){this.checkKeywordEscapes(),this.optionFlags&256&&this.pushToken(new wt(this.state)),this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(n){return this.match(n)?(this.next(),!0):!1}match(n){return this.state.type===n}createLookaheadState(n){return{pos:n.pos,value:null,type:n.type,start:n.start,end:n.end,context:[this.curContext()],inType:n.inType,startLoc:n.startLoc,lastTokEndLoc:n.lastTokEndLoc,curLine:n.curLine,lineStart:n.lineStart,curPosition:n.curPosition}}lookahead(){let n=this.state;this.state=this.createLookaheadState(n),this.isLookahead=!0,this.nextToken(),this.isLookahead=!1;let e=this.state;return this.state=n,e}nextTokenStart(){return this.nextTokenStartSince(this.state.pos)}nextTokenStartSince(n){return Vd.lastIndex=n,Vd.test(this.input)?Vd.lastIndex:n}lookaheadCharCode(){return this.lookaheadCharCodeSince(this.state.pos)}lookaheadCharCodeSince(n){return this.input.charCodeAt(this.nextTokenStartSince(n))}nextTokenInLineStart(){return this.nextTokenInLineStartSince(this.state.pos)}nextTokenInLineStartSince(n){return Ud.lastIndex=n,Ud.test(this.input)?Ud.lastIndex:n}lookaheadInLineCharCode(){return this.input.charCodeAt(this.nextTokenInLineStart())}codePointAtPos(n){let e=this.input.charCodeAt(n);if((e&64512)===55296&&++n<this.input.length){let r=this.input.charCodeAt(n);(r&64512)===56320&&(e=65536+((e&1023)<<10)+(r&1023))}return e}setStrict(n){this.state.strict=n,n&&(this.state.strictErrors.forEach(([e,r])=>this.raise(e,r)),this.state.strictErrors.clear())}curContext(){return this.state.context[this.state.context.length-1]}nextToken(){if(this.skipSpace(),this.state.start=this.state.pos,this.isLookahead||(this.state.startLoc=this.state.curPosition()),this.state.pos>=this.length){this.finishToken(140);return}this.getTokenFromCode(this.codePointAtPos(this.state.pos))}skipBlockComment(n){let e;this.isLookahead||(e=this.state.curPosition());let r=this.state.pos,i=this.input.indexOf(n,r+2);if(i===-1)throw this.raise(b.UnterminatedComment,this.state.curPosition());for(this.state.pos=i+n.length,Js.lastIndex=r+2;Js.test(this.input)&&Js.lastIndex<=i;)++this.state.curLine,this.state.lineStart=Js.lastIndex;if(this.isLookahead)return;let s={type:"CommentBlock",value:this.input.slice(r+2,i),start:this.sourceToOffsetPos(r),end:this.sourceToOffsetPos(i+n.length),loc:new cr(e,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(s),s}skipLineComment(n){let e=this.state.pos,r;this.isLookahead||(r=this.state.curPosition());let i=this.input.charCodeAt(this.state.pos+=n);if(this.state.pos<this.length)for(;!or(i)&&++this.state.pos<this.length;)i=this.input.charCodeAt(this.state.pos);if(this.isLookahead)return;let s=this.state.pos,o={type:"CommentLine",value:this.input.slice(e+n,s),start:this.sourceToOffsetPos(e),end:this.sourceToOffsetPos(s),loc:new cr(r,this.state.curPosition())};return this.optionFlags&256&&this.pushToken(o),o}skipSpace(){let n=this.state.pos,e=this.optionFlags&4096?[]:null;e:for(;this.state.pos<this.length;){let r=this.input.charCodeAt(this.state.pos);switch(r){case 32:case 160:case 9:++this.state.pos;break;case 13:this.input.charCodeAt(this.state.pos+1)===10&&++this.state.pos;case 10:case 8232:case 8233:++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;break;case 47:switch(this.input.charCodeAt(this.state.pos+1)){case 42:{let i=this.skipBlockComment("*/");i!==void 0&&(this.addComment(i),e?.push(i));break}case 47:{let i=this.skipLineComment(2);i!==void 0&&(this.addComment(i),e?.push(i));break}default:break e}break;default:if(sR(r))++this.state.pos;else if(r===45&&!this.inModule&&this.optionFlags&8192){let i=this.state.pos;if(this.input.charCodeAt(i+1)===45&&this.input.charCodeAt(i+2)===62&&(n===0||this.state.lineStart>n)){let s=this.skipLineComment(3);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else if(r===60&&!this.inModule&&this.optionFlags&8192){let i=this.state.pos;if(this.input.charCodeAt(i+1)===33&&this.input.charCodeAt(i+2)===45&&this.input.charCodeAt(i+3)===45){let s=this.skipLineComment(4);s!==void 0&&(this.addComment(s),e?.push(s))}else break e}else break e}}if(e?.length>0){let r=this.state.pos,i={start:this.sourceToOffsetPos(n),end:this.sourceToOffsetPos(r),comments:e,leadingNode:null,trailingNode:null,containingNode:null};this.state.commentStack.push(i)}}finishToken(n,e){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();let r=this.state.type;this.state.type=n,this.state.value=e,this.isLookahead||this.updateContext(r)}replaceToken(n){this.state.type=n,this.updateContext()}readToken_numberSign(){if(this.state.pos===0&&this.readToken_interpreter())return;let n=this.state.pos+1,e=this.codePointAtPos(n);if(e>=48&&e<=57)throw this.raise(b.UnexpectedDigitAfterHash,this.state.curPosition());if(e===123||e===91&&this.hasPlugin("recordAndTuple")){if(this.expectPlugin("recordAndTuple"),this.getPluginOption("recordAndTuple","syntaxType")==="bar")throw this.raise(e===123?b.RecordExpressionHashIncorrectStartSyntaxType:b.TupleExpressionHashIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,e===123?this.finishToken(7):this.finishToken(1)}else bt(e)?(++this.state.pos,this.finishToken(139,this.readWord1(e))):e===92?(++this.state.pos,this.finishToken(139,this.readWord1())):this.finishOp(27,1)}readToken_dot(){let n=this.input.charCodeAt(this.state.pos+1);if(n>=48&&n<=57){this.readNumber(!0);return}n===46&&this.input.charCodeAt(this.state.pos+2)===46?(this.state.pos+=3,this.finishToken(21)):(++this.state.pos,this.finishToken(16))}readToken_slash(){this.input.charCodeAt(this.state.pos+1)===61?this.finishOp(31,2):this.finishOp(56,1)}readToken_interpreter(){if(this.state.pos!==0||this.length<2)return!1;let n=this.input.charCodeAt(this.state.pos+1);if(n!==33)return!1;let e=this.state.pos;for(this.state.pos+=1;!or(n)&&++this.state.pos<this.length;)n=this.input.charCodeAt(this.state.pos);let r=this.input.slice(e+2,this.state.pos);return this.finishToken(28,r),!0}readToken_mult_modulo(n){let e=n===42?55:54,r=1,i=this.input.charCodeAt(this.state.pos+1);n===42&&i===42&&(r++,i=this.input.charCodeAt(this.state.pos+2),e=57),i===61&&!this.state.inType&&(r++,e=n===37?33:30),this.finishOp(e,r)}readToken_pipe_amp(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===n){this.input.charCodeAt(this.state.pos+2)===61?this.finishOp(30,3):this.finishOp(n===124?41:42,2);return}if(n===124){if(e===62){this.finishOp(39,2);return}if(this.hasPlugin("recordAndTuple")&&e===125){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.RecordExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(9);return}if(this.hasPlugin("recordAndTuple")&&e===93){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.TupleExpressionBarIncorrectEndSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(4);return}}if(e===61){this.finishOp(30,2);return}this.finishOp(n===124?43:45,1)}readToken_caret(){let n=this.input.charCodeAt(this.state.pos+1);n===61&&!this.state.inType?this.finishOp(32,2):n===94&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"^^"}])?(this.finishOp(37,2),this.input.codePointAt(this.state.pos)===94&&this.unexpected()):this.finishOp(44,1)}readToken_atSign(){this.input.charCodeAt(this.state.pos+1)===64&&this.hasPlugin(["pipelineOperator",{proposal:"hack",topicToken:"@@"}])?this.finishOp(38,2):this.finishOp(26,1)}readToken_plus_min(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===n){this.finishOp(34,2);return}e===61?this.finishOp(30,2):this.finishOp(53,1)}readToken_lt(){let{pos:n}=this.state,e=this.input.charCodeAt(n+1);if(e===60){if(this.input.charCodeAt(n+2)===61){this.finishOp(30,3);return}this.finishOp(51,2);return}if(e===61){this.finishOp(49,2);return}this.finishOp(47,1)}readToken_gt(){let{pos:n}=this.state,e=this.input.charCodeAt(n+1);if(e===62){let r=this.input.charCodeAt(n+2)===62?3:2;if(this.input.charCodeAt(n+r)===61){this.finishOp(30,r+1);return}this.finishOp(52,r);return}if(e===61){this.finishOp(49,2);return}this.finishOp(48,1)}readToken_eq_excl(n){let e=this.input.charCodeAt(this.state.pos+1);if(e===61){this.finishOp(46,this.input.charCodeAt(this.state.pos+2)===61?3:2);return}if(n===61&&e===62){this.state.pos+=2,this.finishToken(19);return}this.finishOp(n===61?29:35,1)}readToken_question(){let n=this.input.charCodeAt(this.state.pos+1),e=this.input.charCodeAt(this.state.pos+2);n===63?e===61?this.finishOp(30,3):this.finishOp(40,2):n===46&&!(e>=48&&e<=57)?(this.state.pos+=2,this.finishToken(18)):(++this.state.pos,this.finishToken(17))}getTokenFromCode(n){switch(n){case 46:this.readToken_dot();return;case 40:++this.state.pos,this.finishToken(10);return;case 41:++this.state.pos,this.finishToken(11);return;case 59:++this.state.pos,this.finishToken(13);return;case 44:++this.state.pos,this.finishToken(12);return;case 91:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.TupleExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(2)}else++this.state.pos,this.finishToken(0);return;case 93:++this.state.pos,this.finishToken(3);return;case 123:if(this.hasPlugin("recordAndTuple")&&this.input.charCodeAt(this.state.pos+1)===124){if(this.getPluginOption("recordAndTuple","syntaxType")!=="bar")throw this.raise(b.RecordExpressionBarIncorrectStartSyntaxType,this.state.curPosition());this.state.pos+=2,this.finishToken(6)}else++this.state.pos,this.finishToken(5);return;case 125:++this.state.pos,this.finishToken(8);return;case 58:this.hasPlugin("functionBind")&&this.input.charCodeAt(this.state.pos+1)===58?this.finishOp(15,2):(++this.state.pos,this.finishToken(14));return;case 63:this.readToken_question();return;case 96:this.readTemplateToken();return;case 48:{let e=this.input.charCodeAt(this.state.pos+1);if(e===120||e===88){this.readRadixNumber(16);return}if(e===111||e===79){this.readRadixNumber(8);return}if(e===98||e===66){this.readRadixNumber(2);return}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:this.readNumber(!1);return;case 34:case 39:this.readString(n);return;case 47:this.readToken_slash();return;case 37:case 42:this.readToken_mult_modulo(n);return;case 124:case 38:this.readToken_pipe_amp(n);return;case 94:this.readToken_caret();return;case 43:case 45:this.readToken_plus_min(n);return;case 60:this.readToken_lt();return;case 62:this.readToken_gt();return;case 61:case 33:this.readToken_eq_excl(n);return;case 126:this.finishOp(36,1);return;case 64:this.readToken_atSign();return;case 35:this.readToken_numberSign();return;case 92:this.readWord();return;default:if(bt(n)){this.readWord(n);return}}throw this.raise(b.InvalidOrUnexpectedToken,this.state.curPosition(),{unexpected:String.fromCodePoint(n)})}finishOp(n,e){let r=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(n,r)}readRegexp(){let n=this.state.startLoc,e=this.state.start+1,r,i,{pos:s}=this.state;for(;;++s){if(s>=this.length)throw this.raise(b.UnterminatedRegExp,_e(n,1));let c=this.input.charCodeAt(s);if(or(c))throw this.raise(b.UnterminatedRegExp,_e(n,1));if(r)r=!1;else{if(c===91)i=!0;else if(c===93&&i)i=!1;else if(c===47&&!i)break;r=c===92}}let a=this.input.slice(e,s);++s;let o="",d=()=>_e(n,s+2-e);for(;s<this.length;){let c=this.codePointAtPos(s),l=String.fromCharCode(c);if(uR.has(c))c===118?o.includes("u")&&this.raise(b.IncompatibleRegExpUVFlags,d()):c===117&&o.includes("v")&&this.raise(b.IncompatibleRegExpUVFlags,d()),o.includes(l)&&this.raise(b.DuplicateRegExpFlags,d());else if(wn(c)||c===92)this.raise(b.MalformedRegExpFlags,d());else break;++s,o+=l}this.state.pos=s,this.finishToken(138,{pattern:a,flags:o})}readInt(n,e,r=!1,i=!0){let{n:s,pos:a}=Zf(this.input,this.state.pos,this.state.lineStart,this.state.curLine,n,e,r,i,this.errorHandlers_readInt,!1);return this.state.pos=a,s}readRadixNumber(n){let e=this.state.pos,r=this.state.curPosition(),i=!1;this.state.pos+=2;let s=this.readInt(n);s==null&&this.raise(b.InvalidDigit,_e(r,2),{radix:n});let a=this.input.charCodeAt(this.state.pos);if(a===110)++this.state.pos,i=!0;else if(a===109)throw this.raise(b.InvalidDecimal,r);if(bt(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());if(i){let o=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(136,o);return}this.finishToken(135,s)}readNumber(n){let e=this.state.pos,r=this.state.curPosition(),i=!1,s=!1,a=!1,o=!1;!n&&this.readInt(10)===null&&this.raise(b.InvalidNumber,this.state.curPosition());let d=this.state.pos-e>=2&&this.input.charCodeAt(e)===48;if(d){let f=this.input.slice(e,this.state.pos);if(this.recordStrictModeErrors(b.StrictOctalLiteral,r),!this.state.strict){let h=f.indexOf("_");h>0&&this.raise(b.ZeroDigitNumericSeparator,_e(r,h))}o=d&&!/[89]/.test(f)}let c=this.input.charCodeAt(this.state.pos);if(c===46&&!o&&(++this.state.pos,this.readInt(10),i=!0,c=this.input.charCodeAt(this.state.pos)),(c===69||c===101)&&!o&&(c=this.input.charCodeAt(++this.state.pos),(c===43||c===45)&&++this.state.pos,this.readInt(10)===null&&this.raise(b.InvalidOrMissingExponent,r),i=!0,a=!0,c=this.input.charCodeAt(this.state.pos)),c===110&&((i||d)&&this.raise(b.InvalidBigIntLiteral,r),++this.state.pos,s=!0),c===109){this.expectPlugin("decimal",this.state.curPosition()),(a||d)&&this.raise(b.InvalidDecimal,r),++this.state.pos;var l=!0}if(bt(this.codePointAtPos(this.state.pos)))throw this.raise(b.NumberIdentifier,this.state.curPosition());let u=this.input.slice(e,this.state.pos).replace(/[_mn]/g,"");if(s){this.finishToken(136,u);return}if(l){this.finishToken(137,u);return}let p=o?parseInt(u,8):parseFloat(u);this.finishToken(135,p)}readCodePoint(n){let{code:e,pos:r}=eh(this.input,this.state.pos,this.state.lineStart,this.state.curLine,n,this.errorHandlers_readCodePoint);return this.state.pos=r,e}readString(n){let{str:e,pos:r,curLine:i,lineStart:s}=jf(n===34?"double":"single",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_string);this.state.pos=r+1,this.state.lineStart=s,this.state.curLine=i,this.finishToken(134,e)}readTemplateContinuation(){this.match(8)||this.unexpected(null,8),this.state.pos--,this.readTemplateToken()}readTemplateToken(){let n=this.input[this.state.pos],{str:e,firstInvalidLoc:r,pos:i,curLine:s,lineStart:a}=jf("template",this.input,this.state.pos+1,this.state.lineStart,this.state.curLine,this.errorHandlers_readStringContents_template);this.state.pos=i+1,this.state.lineStart=a,this.state.curLine=s,r&&(this.state.firstInvalidTemplateEscapePos=new xt(r.curLine,r.pos-r.lineStart,this.sourceToOffsetPos(r.pos))),this.input.codePointAt(i)===96?this.finishToken(24,r?null:n+e+"`"):(this.state.pos++,this.finishToken(25,r?null:n+e+"${"))}recordStrictModeErrors(n,e){let r=e.index;this.state.strict&&!this.state.strictErrors.has(r)?this.raise(n,e):this.state.strictErrors.set(r,[n,e])}readWord1(n){this.state.containsEsc=!1;let e="",r=this.state.pos,i=this.state.pos;for(n!==void 0&&(this.state.pos+=n<=65535?1:2);this.state.pos<this.length;){let s=this.codePointAtPos(this.state.pos);if(wn(s))this.state.pos+=s<=65535?1:2;else if(s===92){this.state.containsEsc=!0,e+=this.input.slice(i,this.state.pos);let a=this.state.curPosition(),o=this.state.pos===r?bt:wn;if(this.input.charCodeAt(++this.state.pos)!==117){this.raise(b.MissingUnicodeEscape,this.state.curPosition()),i=this.state.pos-1;continue}++this.state.pos;let d=this.readCodePoint(!0);d!==null&&(o(d)||this.raise(b.EscapedCharNotAnIdentifier,a),e+=String.fromCodePoint(d)),i=this.state.pos}else break}return e+this.input.slice(i,this.state.pos)}readWord(n){let e=this.readWord1(n),r=mc.get(e);r!==void 0?this.finishToken(r,Yt(r)):this.finishToken(132,e)}checkKeywordEscapes(){let{type:n}=this.state;vc(n)&&this.state.containsEsc&&this.raise(b.InvalidEscapedReservedWord,this.state.startLoc,{reservedWord:Yt(n)})}raise(n,e,r={}){let i=e instanceof xt?e:e.loc.start,s=n(i,r);if(!(this.optionFlags&2048))throw s;return this.isLookahead||this.state.errors.push(s),s}raiseOverwrite(n,e,r={}){let i=e instanceof xt?e:e.loc.start,s=i.index,a=this.state.errors;for(let o=a.length-1;o>=0;o--){let d=a[o];if(d.loc.index===s)return a[o]=n(i,r);if(d.loc.index<s)break}return this.raise(n,e,r)}updateContext(n){}unexpected(n,e){throw this.raise(b.UnexpectedToken,n??this.state.startLoc,{expected:e?Yt(e):null})}expectPlugin(n,e){if(this.hasPlugin(n))return!0;throw this.raise(b.MissingPlugin,e??this.state.startLoc,{missingPlugin:[n]})}expectOnePlugin(n){if(!n.some(e=>this.hasPlugin(e)))throw this.raise(b.MissingOneOfPlugins,this.state.startLoc,{missingPlugin:n})}errorBuilder(n){return(e,r,i)=>{this.raise(n,fi(e,r,i))}}},sc=class{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}},ac=class{constructor(n){this.parser=void 0,this.stack=[],this.undefinedPrivateNames=new Map,this.parser=n}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new sc)}exit(){let n=this.stack.pop(),e=this.current();for(let[r,i]of Array.from(n.undefinedPrivateNames))e?e.undefinedPrivateNames.has(r)||e.undefinedPrivateNames.set(r,i):this.parser.raise(b.InvalidPrivateFieldResolution,i,{identifierName:r})}declarePrivateName(n,e,r){let{privateNames:i,loneAccessors:s,undefinedPrivateNames:a}=this.current(),o=i.has(n);if(e&3){let d=o&&s.get(n);if(d){let c=d&4,l=e&4,u=d&3,p=e&3;o=u===p||c!==l,o||s.delete(n)}else o||s.set(n,e)}o&&this.parser.raise(b.PrivateNameRedeclaration,r,{identifierName:n}),i.add(n),a.delete(n)}usePrivateName(n,e){let r;for(r of this.stack)if(r.privateNames.has(n))return;r?r.undefinedPrivateNames.set(n,e):this.parser.raise(b.InvalidPrivateFieldResolution,e,{identifierName:n})}},lr=class{constructor(n=0){this.type=n}canBeArrowParameterDeclaration(){return this.type===2||this.type===1}isCertainlyParameterDeclaration(){return this.type===3}},na=class extends lr{constructor(n){super(n),this.declarationErrors=new Map}recordDeclarationError(n,e){let r=e.index;this.declarationErrors.set(r,[n,e])}clearDeclarationError(n){this.declarationErrors.delete(n)}iterateErrors(n){this.declarationErrors.forEach(n)}},oc=class{constructor(n){this.parser=void 0,this.stack=[new lr],this.parser=n}enter(n){this.stack.push(n)}exit(){this.stack.pop()}recordParameterInitializerError(n,e){let r=e.loc.start,{stack:i}=this,s=i.length-1,a=i[s];for(;!a.isCertainlyParameterDeclaration();){if(a.canBeArrowParameterDeclaration())a.recordDeclarationError(n,r);else return;a=i[--s]}this.parser.raise(n,r)}recordArrowParameterBindingError(n,e){let{stack:r}=this,i=r[r.length-1],s=e.loc.start;if(i.isCertainlyParameterDeclaration())this.parser.raise(n,s);else if(i.canBeArrowParameterDeclaration())i.recordDeclarationError(n,s);else return}recordAsyncArrowParametersError(n){let{stack:e}=this,r=e.length-1,i=e[r];for(;i.canBeArrowParameterDeclaration();)i.type===2&&i.recordDeclarationError(b.AwaitBindingIdentifier,n),i=e[--r]}validateAsPattern(){let{stack:n}=this,e=n[n.length-1];e.canBeArrowParameterDeclaration()&&e.iterateErrors(([r,i])=>{this.parser.raise(r,i);let s=n.length-2,a=n[s];for(;a.canBeArrowParameterDeclaration();)a.clearDeclarationError(i.index),a=n[--s]})}};function pR(){return new lr(3)}function fR(){return new na(1)}function hR(){return new na(2)}function th(){return new lr}var dc=class extends ic{addExtra(n,e,r,i=!0){if(!n)return;let{extra:s}=n;s==null&&(s={},n.extra=s),i?s[e]=r:Object.defineProperty(s,e,{enumerable:i,value:r})}isContextual(n){return this.state.type===n&&!this.state.containsEsc}isUnparsedContextual(n,e){if(this.input.startsWith(e,n)){let r=this.input.charCodeAt(n+e.length);return!(wn(r)||(r&64512)===55296)}return!1}isLookaheadContextual(n){let e=this.nextTokenStart();return this.isUnparsedContextual(e,n)}eatContextual(n){return this.isContextual(n)?(this.next(),!0):!1}expectContextual(n,e){if(!this.eatContextual(n)){if(e!=null)throw this.raise(e,this.state.startLoc);this.unexpected(null,n)}}canInsertSemicolon(){return this.match(140)||this.match(8)||this.hasPrecedingLineBreak()}hasPrecedingLineBreak(){return Mf(this.input,this.offsetToSourcePos(this.state.lastTokEndLoc.index),this.state.start)}hasFollowingLineBreak(){return Mf(this.input,this.state.end,this.nextTokenStart())}isLineTerminator(){return this.eat(13)||this.canInsertSemicolon()}semicolon(n=!0){(n?this.isLineTerminator():this.eat(13))||this.raise(b.MissingSemicolon,this.state.lastTokEndLoc)}expect(n,e){this.eat(n)||this.unexpected(e,n)}tryParse(n,e=this.state.clone()){let r={node:null};try{let i=n((s=null)=>{throw r.node=s,r});if(this.state.errors.length>e.errors.length){let s=this.state;return this.state=e,this.state.tokensLength=s.tokensLength,{node:i,error:s.errors[e.errors.length],thrown:!1,aborted:!1,failState:s}}return{node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(i){let s=this.state;if(this.state=e,i instanceof SyntaxError)return{node:null,error:i,thrown:!0,aborted:!1,failState:s};if(i===r)return{node:r.node,error:null,thrown:!1,aborted:!0,failState:s};throw i}}checkExpressionErrors(n,e){if(!n)return!1;let{shorthandAssignLoc:r,doubleProtoLoc:i,privateKeyLoc:s,optionalParametersLoc:a,voidPatternLoc:o}=n,d=!!r||!!i||!!a||!!s||!!o;if(!e)return d;r!=null&&this.raise(b.InvalidCoverInitializedName,r),i!=null&&this.raise(b.DuplicateProto,i),s!=null&&this.raise(b.UnexpectedPrivateField,s),a!=null&&this.unexpected(a),o!=null&&this.raise(b.InvalidCoverDiscardElement,o)}isLiteralPropertyName(){return qf(this.state.type)}isPrivateName(n){return n.type==="PrivateName"}getPrivateNameSV(n){return n.id.name}hasPropertyAsPrivateName(n){return(n.type==="MemberExpression"||n.type==="OptionalMemberExpression")&&this.isPrivateName(n.property)}isObjectProperty(n){return n.type==="ObjectProperty"}isObjectMethod(n){return n.type==="ObjectMethod"}initializeScopes(n=this.options.sourceType==="module"){let e=this.state.labels;this.state.labels=[];let r=this.exportedIdentifiers;this.exportedIdentifiers=new Set;let i=this.inModule;this.inModule=n;let s=this.scope,a=this.getScopeHandler();this.scope=new a(this,n);let o=this.prodParam;this.prodParam=new Zd;let d=this.classScope;this.classScope=new ac(this);let c=this.expressionScope;return this.expressionScope=new oc(this),()=>{this.state.labels=e,this.exportedIdentifiers=r,this.inModule=i,this.scope=s,this.prodParam=o,this.classScope=d,this.expressionScope=c}}enterInitialScopes(){let n=0;(this.inModule||this.optionFlags&1)&&(n|=2),this.optionFlags&32&&(n|=1);let e=!this.inModule&&this.options.sourceType==="commonjs";(e||this.optionFlags&2)&&(n|=4),this.prodParam.enter(n);let r=e?514:1;this.optionFlags&4&&(r|=512),this.scope.enter(r)}checkDestructuringPrivate(n){let{privateKeyLoc:e}=n;e!==null&&this.expectPlugin("destructuringPrivate",e)}},dr=class{constructor(){this.shorthandAssignLoc=null,this.doubleProtoLoc=null,this.privateKeyLoc=null,this.optionalParametersLoc=null,this.voidPatternLoc=null}},ur=class{constructor(n,e,r){this.type="",this.start=e,this.end=0,this.loc=new cr(r),n?.optionFlags&128&&(this.range=[e,0]),n!=null&&n.filename&&(this.loc.filename=n.filename)}},cc=ur.prototype;cc.__clone=function(){let t=new ur(void 0,this.start,this.loc.start),n=Object.keys(this);for(let e=0,r=n.length;e<r;e++){let i=n[e];i!=="leadingComments"&&i!=="trailingComments"&&i!=="innerComments"&&(t[i]=this[i])}return t};var lc=class extends dc{startNode(){let n=this.state.startLoc;return new ur(this,n.index,n)}startNodeAt(n){return new ur(this,n.index,n)}startNodeAtNode(n){return this.startNodeAt(n.loc.start)}finishNode(n,e){return this.finishNodeAt(n,e,this.state.lastTokEndLoc)}finishNodeAt(n,e,r){return n.type=e,n.end=r.index,n.loc.end=r,this.optionFlags&128&&(n.range[1]=r.index),this.optionFlags&4096&&this.processComment(n),n}resetStartLocation(n,e){n.start=e.index,n.loc.start=e,this.optionFlags&128&&(n.range[0]=e.index)}resetEndLocation(n,e=this.state.lastTokEndLoc){n.end=e.index,n.loc.end=e,this.optionFlags&128&&(n.range[1]=e.index)}resetStartLocationFromNode(n,e){this.resetStartLocation(n,e.loc.start)}castNodeTo(n,e){return n.type=e,n}cloneIdentifier(n){let{type:e,start:r,end:i,loc:s,range:a,name:o}=n,d=Object.create(cc);return d.type=e,d.start=r,d.end=i,d.loc=s,d.range=a,d.name=o,n.extra&&(d.extra=n.extra),d}cloneStringLiteral(n){let{type:e,start:r,end:i,loc:s,range:a,extra:o}=n,d=Object.create(cc);return d.type=e,d.start=r,d.end=i,d.loc=s,d.range=a,d.extra=o,d.value=n.value,d}},uc=t=>t.type==="ParenthesizedExpression"?uc(t.expression):t,pc=class extends lc{toAssignable(n,e=!1){var r,i;let s;switch((n.type==="ParenthesizedExpression"||(r=n.extra)!=null&&r.parenthesized)&&(s=uc(n),e?s.type==="Identifier"?this.expressionScope.recordArrowParameterBindingError(b.InvalidParenthesizedAssignment,n):s.type!=="CallExpression"&&s.type!=="MemberExpression"&&!this.isOptionalMemberExpression(s)&&this.raise(b.InvalidParenthesizedAssignment,n):this.raise(b.InvalidParenthesizedAssignment,n)),n.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":break;case"ObjectExpression":this.castNodeTo(n,"ObjectPattern");for(let o=0,d=n.properties.length,c=d-1;o<d;o++){var a;let l=n.properties[o],u=o===c;this.toAssignableObjectExpressionProp(l,u,e),u&&l.type==="RestElement"&&(a=n.extra)!=null&&a.trailingCommaLoc&&this.raise(b.RestTrailingComma,n.extra.trailingCommaLoc)}break;case"ObjectProperty":{let{key:o,value:d}=n;this.isPrivateName(o)&&this.classScope.usePrivateName(this.getPrivateNameSV(o),o.loc.start),this.toAssignable(d,e);break}case"SpreadElement":throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");case"ArrayExpression":this.castNodeTo(n,"ArrayPattern"),this.toAssignableList(n.elements,(i=n.extra)==null?void 0:i.trailingCommaLoc,e);break;case"AssignmentExpression":n.operator!=="="&&this.raise(b.MissingEqInAssignment,n.left.loc.end),this.castNodeTo(n,"AssignmentPattern"),delete n.operator,n.left.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,n.left),this.toAssignable(n.left,e);break;case"ParenthesizedExpression":this.toAssignable(s,e);break}}toAssignableObjectExpressionProp(n,e,r){if(n.type==="ObjectMethod")this.raise(n.kind==="get"||n.kind==="set"?b.PatternHasAccessor:b.PatternHasMethod,n.key);else if(n.type==="SpreadElement"){this.castNodeTo(n,"RestElement");let i=n.argument;this.checkToRestConversion(i,!1),this.toAssignable(i,r),e||this.raise(b.RestTrailingComma,n)}else this.toAssignable(n,r)}toAssignableList(n,e,r){let i=n.length-1;for(let s=0;s<=i;s++){let a=n[s];a&&(this.toAssignableListItem(n,s,r),a.type==="RestElement"&&(s<i?this.raise(b.RestTrailingComma,a):e&&this.raise(b.RestTrailingComma,e)))}}toAssignableListItem(n,e,r){let i=n[e];if(i.type==="SpreadElement"){this.castNodeTo(i,"RestElement");let s=i.argument;this.checkToRestConversion(s,!0),this.toAssignable(s,r)}else this.toAssignable(i,r)}isAssignable(n,e){switch(n.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":case"VoidPattern":return!0;case"ObjectExpression":{let r=n.properties.length-1;return n.properties.every((i,s)=>i.type!=="ObjectMethod"&&(s===r||i.type!=="SpreadElement")&&this.isAssignable(i))}case"ObjectProperty":return this.isAssignable(n.value);case"SpreadElement":return this.isAssignable(n.argument);case"ArrayExpression":return n.elements.every(r=>r===null||this.isAssignable(r));case"AssignmentExpression":return n.operator==="=";case"ParenthesizedExpression":return this.isAssignable(n.expression);case"MemberExpression":case"OptionalMemberExpression":return!e;default:return!1}}toReferencedList(n,e){return n}toReferencedListDeep(n,e){this.toReferencedList(n,e);for(let r of n)r?.type==="ArrayExpression"&&this.toReferencedListDeep(r.elements)}parseSpread(n){let e=this.startNode();return this.next(),e.argument=this.parseMaybeAssignAllowIn(n,void 0),this.finishNode(e,"SpreadElement")}parseRestBinding(){let n=this.startNode();this.next();let e=this.parseBindingAtom();return e.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,e),n.argument=e,this.finishNode(n,"RestElement")}parseBindingAtom(){switch(this.state.type){case 0:{let n=this.startNode();return this.next(),n.elements=this.parseBindingList(3,93,1),this.finishNode(n,"ArrayPattern")}case 5:return this.parseObjectLike(8,!0);case 88:return this.parseVoidPattern(null)}return this.parseIdentifier()}parseBindingList(n,e,r){let i=r&1,s=[],a=!0;for(;!this.eat(n);)if(a?a=!1:this.expect(12),i&&this.match(12))s.push(null);else{if(this.eat(n))break;if(this.match(21)){let o=this.parseRestBinding();if((this.hasPlugin("flow")||r&2)&&(o=this.parseFunctionParamType(o)),s.push(o),!this.checkCommaAfterRest(e)){this.expect(n);break}}else{let o=[];if(r&2)for(this.match(26)&&this.hasPlugin("decorators")&&this.raise(b.UnsupportedParameterDecorator,this.state.startLoc);this.match(26);)o.push(this.parseDecorator());s.push(this.parseBindingElement(r,o))}}return s}parseBindingRestProperty(n){return this.next(),this.hasPlugin("discardBinding")&&this.match(88)?(n.argument=this.parseVoidPattern(null),this.raise(b.UnexpectedVoidPattern,n.argument)):n.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(n,"RestElement")}parseBindingProperty(){let{type:n,startLoc:e}=this.state;if(n===21)return this.parseBindingRestProperty(this.startNode());let r=this.startNode();return n===139?(this.expectPlugin("destructuringPrivate",e),this.classScope.usePrivateName(this.state.value,e),r.key=this.parsePrivateName()):this.parsePropertyName(r),r.method=!1,this.parseObjPropValue(r,e,!1,!1,!0,!1)}parseBindingElement(n,e){let r=this.parseMaybeDefault();return(this.hasPlugin("flow")||n&2)&&this.parseFunctionParamType(r),e.length&&(r.decorators=e,this.resetStartLocationFromNode(r,e[0])),this.parseMaybeDefault(r.loc.start,r)}parseFunctionParamType(n){return n}parseMaybeDefault(n,e){if(n??(n=this.state.startLoc),e=e??this.parseBindingAtom(),!this.eat(29))return e;let r=this.startNodeAt(n);return e.type==="VoidPattern"&&this.raise(b.VoidPatternInitializer,e),r.left=e,r.right=this.parseMaybeAssignAllowIn(),this.finishNode(r,"AssignmentPattern")}isValidLVal(n,e,r,i){switch(n){case"AssignmentPattern":return"left";case"RestElement":return"argument";case"ObjectProperty":return"value";case"ParenthesizedExpression":return"expression";case"ArrayPattern":return"elements";case"ObjectPattern":return"properties";case"VoidPattern":return!0;case"CallExpression":if(!e&&!this.state.strict&&this.optionFlags&8192)return!0}return!1}isOptionalMemberExpression(n){return n.type==="OptionalMemberExpression"}checkLVal(n,e,r=64,i=!1,s=!1,a=!1,o=!1){var d;let c=n.type;if(this.isObjectMethod(n))return;let l=this.isOptionalMemberExpression(n);if(l||c==="MemberExpression"){l&&(this.expectPlugin("optionalChainingAssign",n.loc.start),e.type!=="AssignmentExpression"&&this.raise(b.InvalidLhsOptionalChaining,n,{ancestor:e})),r!==64&&this.raise(b.InvalidPropertyBindingPattern,n);return}if(c==="Identifier"){this.checkIdentifier(n,r,s);let{name:y}=n;i&&(i.has(y)?this.raise(b.ParamDupe,n):i.add(y));return}else c==="VoidPattern"&&e.type==="CatchClause"&&this.raise(b.VoidPatternCatchClauseParam,n);let u=uc(n);o||(o=u.type==="CallExpression"&&(u.callee.type==="Import"||u.callee.type==="Super"));let p=this.isValidLVal(c,o,!(a||(d=n.extra)!=null&&d.parenthesized)&&e.type==="AssignmentExpression",r);if(p===!0)return;if(p===!1){let y=r===64?b.InvalidLhs:b.InvalidLhsBinding;this.raise(y,n,{ancestor:e});return}let f,h;typeof p=="string"?(f=p,h=c==="ParenthesizedExpression"):[f,h]=p;let m=c==="ArrayPattern"||c==="ObjectPattern"?{type:c}:e,g=n[f];if(Array.isArray(g))for(let y of g)y&&this.checkLVal(y,m,r,i,s,h,!0);else g&&this.checkLVal(g,m,r,i,s,h,o)}checkIdentifier(n,e,r=!1){this.state.strict&&(r?Xf(n.name,this.inModule):Yf(n.name))&&(e===64?this.raise(b.StrictEvalArguments,n,{referenceName:n.name}):this.raise(b.StrictEvalArgumentsBinding,n,{bindingName:n.name})),e&8192&&n.name==="let"&&this.raise(b.LetInLexicalBinding,n),e&64||this.declareNameFromIdentifier(n,e)}declareNameFromIdentifier(n,e){this.scope.declareName(n.name,e,n.loc.start)}checkToRestConversion(n,e){switch(n.type){case"ParenthesizedExpression":this.checkToRestConversion(n.expression,e);break;case"Identifier":case"MemberExpression":break;case"ArrayExpression":case"ObjectExpression":if(e)break;default:this.raise(b.InvalidRestAssignmentPattern,n)}}checkCommaAfterRest(n){return this.match(12)?(this.raise(this.lookaheadCharCode()===n?b.RestTrailingComma:b.ElementAfterRest,this.state.startLoc),!0):!1}},qd=/in(?:stanceof)?|as|satisfies/y;function mR(t){if(t==null)throw new Error(`Unexpected ${t} value.`);return t}function Ff(t){if(!t)throw new Error("Assert fail")}var F=ot`typescript`({AbstractMethodHasImplementation:({methodName:t})=>`Method '${t}' cannot have an implementation because it is marked abstract.`,AbstractPropertyHasInitializer:({propertyName:t})=>`Property '${t}' cannot have an initializer because it is marked abstract.`,AccessorCannotBeOptional:"An 'accessor' property cannot be declared optional.",AccessorCannotDeclareThisParameter:"'get' and 'set' accessors cannot declare 'this' parameters.",AccessorCannotHaveTypeParameters:"An accessor cannot have type parameters.",ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier.",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier.",ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",ConstructorHasTypeParameters:"Type parameters cannot appear on a constructor declaration.",DeclareAccessor:({kind:t})=>`'declare' is not allowed in ${t}ters.`,DeclareClassFieldHasInitializer:"Initializers are not allowed in ambient contexts.",DeclareFunctionHasImplementation:"An implementation cannot be declared in ambient contexts.",DuplicateAccessibilityModifier:({modifier:t})=>`Accessibility modifier already seen: '${t}'.`,DuplicateModifier:({modifier:t})=>`Duplicate modifier: '${t}'.`,EmptyHeritageClauseType:({token:t})=>`'${t}' list cannot be empty.`,EmptyTypeArguments:"Type argument list cannot be empty.",EmptyTypeParameters:"Type parameter list cannot be empty.",ExpectedAmbientAfterExportDeclare:"'export declare' must be followed by an ambient declaration.",ImportAliasHasImportType:"An import alias can not use 'import type'.",ImportReflectionHasImportType:"An `import module` declaration can not use `type` modifier",IncompatibleModifiers:({modifiers:t})=>`'${t[0]}' modifier cannot be used with '${t[1]}' modifier.`,IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier.",IndexSignatureHasAccessibility:({modifier:t})=>`Index signatures cannot have an accessibility modifier ('${t}').`,IndexSignatureHasDeclare:"Index signatures cannot have the 'declare' modifier.",IndexSignatureHasOverride:"'override' modifier cannot appear on an index signature.",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier.",InitializerNotAllowedInAmbientContext:"Initializers are not allowed in ambient contexts.",InvalidHeritageClauseType:({token:t})=>`'${t}' list can only include identifiers or qualified-names with optional type arguments.`,InvalidModifierOnAwaitUsingDeclaration:t=>`'${t}' modifier cannot appear on an await using declaration.`,InvalidModifierOnTypeMember:({modifier:t})=>`'${t}' modifier cannot appear on a type member.`,InvalidModifierOnTypeParameter:({modifier:t})=>`'${t}' modifier cannot appear on a type parameter.`,InvalidModifierOnTypeParameterPositions:({modifier:t})=>`'${t}' modifier can only appear on a type parameter of a class, interface or type alias.`,InvalidModifierOnUsingDeclaration:t=>`'${t}' modifier cannot appear on a using declaration.`,InvalidModifiersOrder:({orderedModifiers:t})=>`'${t[0]}' modifier must precede '${t[1]}' modifier.`,InvalidPropertyAccessAfterInstantiationExpression:"Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",InvalidTupleMemberLabel:"Tuple members must be labeled with a simple identifier.",MissingInterfaceName:"'interface' declarations must be followed by an identifier.",NonAbstractClassHasAbstractMethod:"Abstract methods can only appear within an abstract class.",NonClassMethodPropertyHasAbstractModifier:"'abstract' modifier can only appear on a class, method, or property declaration.",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",OverrideNotInSubClass:"This member cannot have an 'override' modifier because its containing class does not extend another class.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:({modifier:t})=>`Private elements cannot have an accessibility modifier ('${t}').`,ReadonlyForMethodSignature:"'readonly' modifier can only appear on a property declaration or index signature.",ReservedArrowTypeParam:"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",ReservedTypeAssertion:"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",SetAccessorCannotHaveOptionalParameter:"A 'set' accessor cannot have an optional parameter.",SetAccessorCannotHaveRestParameter:"A 'set' accessor cannot have rest parameter.",SetAccessorCannotHaveReturnType:"A 'set' accessor cannot have a return type annotation.",SingleTypeParameterWithoutTrailingComma:({typeParameterName:t})=>`Single type parameter ${t} should have a trailing comma. Example usage: <${t},>.`,StaticBlockCannotHaveModifier:"Static class blocks cannot have any modifier.",TupleOptionalAfterType:"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",TypeImportCannotSpecifyDefaultAndNamed:"A type-only import can specify a default import or named bindings, but not both.",TypeModifierIsUsedInTypeExports:"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",TypeModifierIsUsedInTypeImports:"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",UnexpectedParameterModifier:"A parameter property is only allowed in a constructor implementation.",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal.",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:({type:t})=>`Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${t}.`,UsingDeclarationInAmbientContext:t=>`'${t}' declarations are not allowed in ambient contexts.`});function yR(t){switch(t){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}function Bf(t){return t==="private"||t==="public"||t==="protected"}function gR(t){return t==="in"||t==="out"}var wR=t=>class extends t{constructor(...e){super(...e),this.tsParseInOutModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out"],disallowedModifiers:["const","public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter}),this.tsParseConstModifier=this.tsParseModifiers.bind(this,{allowedModifiers:["const"],disallowedModifiers:["in","out"],errorTemplate:F.InvalidModifierOnTypeParameterPositions}),this.tsParseInOutConstModifiers=this.tsParseModifiers.bind(this,{allowedModifiers:["in","out","const"],disallowedModifiers:["public","private","protected","readonly","declare","abstract","override"],errorTemplate:F.InvalidModifierOnTypeParameter})}getScopeHandler(){return Qd}tsIsIdentifier(){return se(this.state.type)}tsTokenCanFollowModifier(){return this.match(0)||this.match(5)||this.match(55)||this.match(21)||this.match(139)||this.isLiteralPropertyName()}tsNextTokenOnSameLineAndCanFollowModifier(){return this.next(),this.hasPrecedingLineBreak()?!1:this.tsTokenCanFollowModifier()}tsNextTokenCanFollowModifier(){return this.match(106)?(this.next(),this.tsTokenCanFollowModifier()):this.tsNextTokenOnSameLineAndCanFollowModifier()}tsParseModifier(e,r,i){if(!se(this.state.type)&&this.state.type!==58&&this.state.type!==75)return;let s=this.state.value;if(e.includes(s)){if(i&&this.match(106)||r&&this.tsIsStartOfStaticBlocks())return;if(this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this)))return s}}tsParseModifiers({allowedModifiers:e,disallowedModifiers:r,stopOnStartOfClassStaticBlock:i,errorTemplate:s=F.InvalidModifierOnTypeMember},a){let o=(c,l,u,p)=>{l===u&&a[p]&&this.raise(F.InvalidModifiersOrder,c,{orderedModifiers:[u,p]})},d=(c,l,u,p)=>{(a[u]&&l===p||a[p]&&l===u)&&this.raise(F.IncompatibleModifiers,c,{modifiers:[u,p]})};for(;;){let{startLoc:c}=this.state,l=this.tsParseModifier(e.concat(r??[]),i,a.static);if(!l)break;Bf(l)?a.accessibility?this.raise(F.DuplicateAccessibilityModifier,c,{modifier:l}):(o(c,l,l,"override"),o(c,l,l,"static"),o(c,l,l,"readonly"),a.accessibility=l):gR(l)?(a[l]&&this.raise(F.DuplicateModifier,c,{modifier:l}),a[l]=!0,o(c,l,"in","out")):(hasOwnProperty.call(a,l)?this.raise(F.DuplicateModifier,c,{modifier:l}):(o(c,l,"static","readonly"),o(c,l,"static","override"),o(c,l,"override","readonly"),o(c,l,"abstract","override"),d(c,l,"declare","override"),d(c,l,"static","abstract")),a[l]=!0),r!=null&&r.includes(l)&&this.raise(s,c,{modifier:l})}}tsIsListTerminator(e){switch(e){case"EnumMembers":case"TypeMembers":return this.match(8);case"HeritageClauseElement":return this.match(5);case"TupleElementTypes":return this.match(3);case"TypeParametersOrArguments":return this.match(48)}}tsParseList(e,r){let i=[];for(;!this.tsIsListTerminator(e);)i.push(r());return i}tsParseDelimitedList(e,r,i){return mR(this.tsParseDelimitedListWorker(e,r,!0,i))}tsParseDelimitedListWorker(e,r,i,s){let a=[],o=-1;for(;!this.tsIsListTerminator(e);){o=-1;let d=r();if(d==null)return;if(a.push(d),this.eat(12)){o=this.state.lastTokStartLoc.index;continue}if(this.tsIsListTerminator(e))break;i&&this.expect(12);return}return s&&(s.value=o),a}tsParseBracketedList(e,r,i,s,a){s||(i?this.expect(0):this.expect(47));let o=this.tsParseDelimitedList(e,r,a);return i?this.expect(3):this.expect(48),o}tsParseImportType(){let e=this.startNode();return this.expect(83),this.expect(10),this.match(134)?e.argument=this.parseStringLiteral(this.state.value):(this.raise(F.UnsupportedImportTypeArgument,this.state.startLoc),e.argument=super.parseExprAtom()),this.eat(12)?e.options=this.tsParseImportTypeOptions():e.options=null,this.expect(11),this.eat(16)&&(e.qualifier=this.tsParseEntityName(3)),this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSImportType")}tsParseImportTypeOptions(){let e=this.startNode();this.expect(5);let r=this.startNode();return this.isContextual(76)?(r.method=!1,r.key=this.parseIdentifier(!0),r.computed=!1,r.shorthand=!1):this.unexpected(null,76),this.expect(14),r.value=this.tsParseImportTypeWithPropertyValue(),e.properties=[this.finishObjectProperty(r)],this.eat(12),this.expect(8),this.finishNode(e,"ObjectExpression")}tsParseImportTypeWithPropertyValue(){let e=this.startNode(),r=[];for(this.expect(5);!this.match(8);){let i=this.state.type;se(i)||i===134?r.push(super.parsePropertyDefinition(null)):this.unexpected(),this.eat(12)}return e.properties=r,this.next(),this.finishNode(e,"ObjectExpression")}tsParseEntityName(e){let r;if(e&1&&this.match(78))if(e&2)r=this.parseIdentifier(!0);else{let i=this.startNode();this.next(),r=this.finishNode(i,"ThisExpression")}else r=this.parseIdentifier(!!(e&1));for(;this.eat(16);){let i=this.startNodeAtNode(r);i.left=r,i.right=this.parseIdentifier(!!(e&1)),r=this.finishNode(i,"TSQualifiedName")}return r}tsParseTypeReference(){let e=this.startNode();return e.typeName=this.tsParseEntityName(1),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeReference")}tsParseThisTypePredicate(e){this.next();let r=this.startNodeAtNode(e);return r.parameterName=e,r.typeAnnotation=this.tsParseTypeAnnotation(!1),r.asserts=!1,this.finishNode(r,"TSTypePredicate")}tsParseThisTypeNode(){let e=this.startNode();return this.next(),this.finishNode(e,"TSThisType")}tsParseTypeQuery(){let e=this.startNode();return this.expect(87),this.match(83)?e.exprName=this.tsParseImportType():e.exprName=this.tsParseEntityName(3),!this.hasPrecedingLineBreak()&&this.match(47)&&(e.typeParameters=this.tsParseTypeArguments()),this.finishNode(e,"TSTypeQuery")}tsParseTypeParameter(e){let r=this.startNode();return e(r),r.name=this.tsParseTypeParameterName(),r.constraint=this.tsEatThenParseType(81),r.default=this.tsEatThenParseType(29),this.finishNode(r,"TSTypeParameter")}tsTryParseTypeParameters(e){if(this.match(47))return this.tsParseTypeParameters(e)}tsParseTypeParameters(e){let r=this.startNode();this.match(47)||this.match(143)?this.next():this.unexpected();let i={value:-1};return r.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this,e),!1,!0,i),r.params.length===0&&this.raise(F.EmptyTypeParameters,r),i.value!==-1&&this.addExtra(r,"trailingComma",i.value),this.finishNode(r,"TSTypeParameterDeclaration")}tsFillSignature(e,r){let i=e===19,s="parameters",a="typeAnnotation";r.typeParameters=this.tsTryParseTypeParameters(this.tsParseConstModifier),this.expect(10),r[s]=this.tsParseBindingListForSignature(),i?r[a]=this.tsParseTypeOrTypePredicateAnnotation(e):this.match(e)&&(r[a]=this.tsParseTypeOrTypePredicateAnnotation(e))}tsParseBindingListForSignature(){let e=super.parseBindingList(11,41,2);for(let r of e){let{type:i}=r;(i==="AssignmentPattern"||i==="TSParameterProperty")&&this.raise(F.UnsupportedSignatureParameterKind,r,{type:i})}return e}tsParseTypeMemberSemicolon(){!this.eat(12)&&!this.isLineTerminator()&&this.expect(13)}tsParseSignatureMember(e,r){return this.tsFillSignature(14,r),this.tsParseTypeMemberSemicolon(),this.finishNode(r,e)}tsIsUnambiguouslyIndexSignature(){return this.next(),se(this.state.type)?(this.next(),this.match(14)):!1}tsTryParseIndexSignature(e){if(!(this.match(0)&&this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))))return;this.expect(0);let r=this.parseIdentifier();r.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(r),this.expect(3),e.parameters=[r];let i=this.tsTryParseTypeAnnotation();return i&&(e.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(e,"TSIndexSignature")}tsParsePropertyOrMethodSignature(e,r){if(this.eat(17)&&(e.optional=!0),this.match(10)||this.match(47)){r&&this.raise(F.ReadonlyForMethodSignature,e);let i=e;i.kind&&this.match(47)&&this.raise(F.AccessorCannotHaveTypeParameters,this.state.curPosition()),this.tsFillSignature(14,i),this.tsParseTypeMemberSemicolon();let s="parameters",a="typeAnnotation";if(i.kind==="get")i[s].length>0&&(this.raise(b.BadGetterArity,this.state.curPosition()),this.isThisParam(i[s][0])&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()));else if(i.kind==="set"){if(i[s].length!==1)this.raise(b.BadSetterArity,this.state.curPosition());else{let o=i[s][0];this.isThisParam(o)&&this.raise(F.AccessorCannotDeclareThisParameter,this.state.curPosition()),o.type==="Identifier"&&o.optional&&this.raise(F.SetAccessorCannotHaveOptionalParameter,this.state.curPosition()),o.type==="RestElement"&&this.raise(F.SetAccessorCannotHaveRestParameter,this.state.curPosition())}i[a]&&this.raise(F.SetAccessorCannotHaveReturnType,i[a])}else i.kind="method";return this.finishNode(i,"TSMethodSignature")}else{let i=e;r&&(i.readonly=!0);let s=this.tsTryParseTypeAnnotation();return s&&(i.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(i,"TSPropertySignature")}}tsParseTypeMember(){let e=this.startNode();if(this.match(10)||this.match(47))return this.tsParseSignatureMember("TSCallSignatureDeclaration",e);if(this.match(77)){let i=this.startNode();return this.next(),this.match(10)||this.match(47)?this.tsParseSignatureMember("TSConstructSignatureDeclaration",e):(e.key=this.createIdentifier(i,"new"),this.tsParsePropertyOrMethodSignature(e,!1))}this.tsParseModifiers({allowedModifiers:["readonly"],disallowedModifiers:["declare","abstract","private","protected","public","static","override"]},e);let r=this.tsTryParseIndexSignature(e);return r||(super.parsePropertyName(e),!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&this.tsTokenCanFollowModifier()&&(e.kind=e.key.name,super.parsePropertyName(e),!this.match(10)&&!this.match(47)&&this.unexpected(null,10)),this.tsParsePropertyOrMethodSignature(e,!!e.readonly))}tsParseTypeLiteral(){let e=this.startNode();return e.members=this.tsParseObjectTypeMembers(),this.finishNode(e,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(5);let e=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(8),e}tsIsStartOfMappedType(){return this.next(),this.eat(53)?this.isContextual(122):(this.isContextual(122)&&this.next(),!this.match(0)||(this.next(),!this.tsIsIdentifier())?!1:(this.next(),this.match(58)))}tsParseMappedType(){let e=this.startNode();this.expect(5),this.match(53)?(e.readonly=this.state.value,this.next(),this.expectContextual(122)):this.eatContextual(122)&&(e.readonly=!0),this.expect(0);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsExpectThenParseType(58),e.typeParameter=this.finishNode(r,"TSTypeParameter"),e.nameType=this.eatContextual(93)?this.tsParseType():null,this.expect(3),this.match(53)?(e.optional=this.state.value,this.next(),this.expect(17)):this.eat(17)&&(e.optional=!0),e.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(8),this.finishNode(e,"TSMappedType")}tsParseTupleType(){let e=this.startNode();e.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let r=!1;return e.elementTypes.forEach(i=>{let{type:s}=i;r&&s!=="TSRestType"&&s!=="TSOptionalType"&&!(s==="TSNamedTupleMember"&&i.optional)&&this.raise(F.OptionalTypeBeforeRequired,i),r||(r=s==="TSNamedTupleMember"&&i.optional||s==="TSOptionalType")}),this.finishNode(e,"TSTupleType")}tsParseTupleElementType(){let e=this.state.startLoc,r=this.eat(21),{startLoc:i}=this.state,s,a,o,d,l=dt(this.state.type)?this.lookaheadCharCode():null;if(l===58)s=!0,o=!1,a=this.parseIdentifier(!0),this.expect(14),d=this.tsParseType();else if(l===63){o=!0;let u=this.state.value,p=this.tsParseNonArrayType();this.lookaheadCharCode()===58?(s=!0,a=this.createIdentifier(this.startNodeAt(i),u),this.expect(17),this.expect(14),d=this.tsParseType()):(s=!1,d=p,this.expect(17))}else d=this.tsParseType(),o=this.eat(17),s=this.eat(14);if(s){let u;a?(u=this.startNodeAt(i),u.optional=o,u.label=a,u.elementType=d,this.eat(17)&&(u.optional=!0,this.raise(F.TupleOptionalAfterType,this.state.lastTokStartLoc))):(u=this.startNodeAt(i),u.optional=o,this.raise(F.InvalidTupleMemberLabel,d),u.label=d,u.elementType=this.tsParseType()),d=this.finishNode(u,"TSNamedTupleMember")}else if(o){let u=this.startNodeAt(i);u.typeAnnotation=d,d=this.finishNode(u,"TSOptionalType")}if(r){let u=this.startNodeAt(e);u.typeAnnotation=d,d=this.finishNode(u,"TSRestType")}return d}tsParseParenthesizedType(){let e=this.startNode();return this.expect(10),e.typeAnnotation=this.tsParseType(),this.expect(11),this.finishNode(e,"TSParenthesizedType")}tsParseFunctionOrConstructorType(e,r){let i=this.startNode();return e==="TSConstructorType"&&(i.abstract=!!r,r&&this.next(),this.next()),this.tsInAllowConditionalTypesContext(()=>this.tsFillSignature(19,i)),this.finishNode(i,e)}tsParseLiteralTypeNode(){let e=this.startNode();switch(this.state.type){case 135:case 136:case 134:case 85:case 86:e.literal=super.parseExprAtom();break;default:this.unexpected()}return this.finishNode(e,"TSLiteralType")}tsParseTemplateLiteralType(){let e=this.startNode();return e.literal=super.parseTemplate(!1),this.finishNode(e,"TSLiteralType")}parseTemplateSubstitution(){return this.state.inType?this.tsParseType():super.parseTemplateSubstitution()}tsParseThisTypeOrThisTypePredicate(){let e=this.tsParseThisTypeNode();return this.isContextual(116)&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(e):e}tsParseNonArrayType(){switch(this.state.type){case 134:case 135:case 136:case 85:case 86:return this.tsParseLiteralTypeNode();case 53:if(this.state.value==="-"){let e=this.startNode(),r=this.lookahead();return r.type!==135&&r.type!==136&&this.unexpected(),e.literal=this.parseMaybeUnary(),this.finishNode(e,"TSLiteralType")}break;case 78:return this.tsParseThisTypeOrThisTypePredicate();case 87:return this.tsParseTypeQuery();case 83:return this.tsParseImportType();case 5:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case 0:return this.tsParseTupleType();case 10:return this.tsParseParenthesizedType();case 25:case 24:return this.tsParseTemplateLiteralType();default:{let{type:e}=this.state;if(se(e)||e===88||e===84){let r=e===88?"TSVoidKeyword":e===84?"TSNullKeyword":yR(this.state.value);if(r!==void 0&&this.lookaheadCharCode()!==46){let i=this.startNode();return this.next(),this.finishNode(i,r)}return this.tsParseTypeReference()}}}throw this.unexpected()}tsParseArrayTypeOrHigher(){let{startLoc:e}=this.state,r=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(0);)if(this.match(3)){let i=this.startNodeAt(e);i.elementType=r,this.expect(3),r=this.finishNode(i,"TSArrayType")}else{let i=this.startNodeAt(e);i.objectType=r,i.indexType=this.tsParseType(),this.expect(3),r=this.finishNode(i,"TSIndexedAccessType")}return r}tsParseTypeOperator(){let e=this.startNode(),r=this.state.value;return this.next(),e.operator=r,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),r==="readonly"&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(e){switch(e.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(F.UnexpectedReadonly,e)}}tsParseInferType(){let e=this.startNode();this.expectContextual(115);let r=this.startNode();return r.name=this.tsParseTypeParameterName(),r.constraint=this.tsTryParse(()=>this.tsParseConstraintForInferType()),e.typeParameter=this.finishNode(r,"TSTypeParameter"),this.finishNode(e,"TSInferType")}tsParseConstraintForInferType(){if(this.eat(81)){let e=this.tsInDisallowConditionalTypesContext(()=>this.tsParseType());if(this.state.inDisallowConditionalTypesContext||!this.match(17))return e}}tsParseTypeOperatorOrHigher(){return jk(this.state.type)&&!this.state.containsEsc?this.tsParseTypeOperator():this.isContextual(115)?this.tsParseInferType():this.tsInAllowConditionalTypesContext(()=>this.tsParseArrayTypeOrHigher())}tsParseUnionOrIntersectionType(e,r,i){let s=this.startNode(),a=this.eat(i),o=[];do o.push(r());while(this.eat(i));return o.length===1&&!a?o[0]:(s.types=o,this.finishNode(s,e))}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),45)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),43)}tsIsStartOfFunctionType(){return this.match(47)?!0:this.match(10)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(se(this.state.type)||this.match(78))return this.next(),!0;if(this.match(5)){let{errors:e}=this.state,r=e.length;try{return this.parseObjectLike(8,!0),e.length===r}catch{return!1}}if(this.match(0)){this.next();let{errors:e}=this.state,r=e.length;try{return super.parseBindingList(3,93,1),e.length===r}catch{return!1}}return!1}tsIsUnambiguouslyStartOfFunctionType(){return this.next(),!!(this.match(11)||this.match(21)||this.tsSkipParameterStart()&&(this.match(14)||this.match(12)||this.match(17)||this.match(29)||this.match(11)&&(this.next(),this.match(19))))}tsParseTypeOrTypePredicateAnnotation(e){return this.tsInType(()=>{let r=this.startNode();this.expect(e);let i=this.startNode(),s=!!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(s&&this.match(78)){let d=this.tsParseThisTypeOrThisTypePredicate();return d.type==="TSThisType"?(i.parameterName=d,i.asserts=!0,i.typeAnnotation=null,d=this.finishNode(i,"TSTypePredicate")):(this.resetStartLocationFromNode(d,i),d.asserts=!0),r.typeAnnotation=d,this.finishNode(r,"TSTypeAnnotation")}let a=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!a)return s?(i.parameterName=this.parseIdentifier(),i.asserts=s,i.typeAnnotation=null,r.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")):this.tsParseTypeAnnotation(!1,r);let o=this.tsParseTypeAnnotation(!1);return i.parameterName=a,i.typeAnnotation=o,i.asserts=s,r.typeAnnotation=this.finishNode(i,"TSTypePredicate"),this.finishNode(r,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){if(this.match(14))return this.tsParseTypeOrTypePredicateAnnotation(14)}tsTryParseTypeAnnotation(){if(this.match(14))return this.tsParseTypeAnnotation()}tsTryParseType(){return this.tsEatThenParseType(14)}tsParseTypePredicatePrefix(){let e=this.parseIdentifier();if(this.isContextual(116)&&!this.hasPrecedingLineBreak())return this.next(),e}tsParseTypePredicateAsserts(){if(this.state.type!==109)return!1;let e=this.state.containsEsc;return this.next(),!se(this.state.type)&&!this.match(78)?!1:(e&&this.raise(b.InvalidEscapedReservedWord,this.state.lastTokStartLoc,{reservedWord:"asserts"}),!0)}tsParseTypeAnnotation(e=!0,r=this.startNode()){return this.tsInType(()=>{e&&this.expect(14),r.typeAnnotation=this.tsParseType()}),this.finishNode(r,"TSTypeAnnotation")}tsParseType(){Ff(this.state.inType);let e=this.tsParseNonConditionalType();if(this.state.inDisallowConditionalTypesContext||this.hasPrecedingLineBreak()||!this.eat(81))return e;let r=this.startNodeAtNode(e);return r.checkType=e,r.extendsType=this.tsInDisallowConditionalTypesContext(()=>this.tsParseNonConditionalType()),this.expect(17),r.trueType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.expect(14),r.falseType=this.tsInAllowConditionalTypesContext(()=>this.tsParseType()),this.finishNode(r,"TSConditionalType")}isAbstractConstructorSignature(){return this.isContextual(124)&&this.isLookaheadContextual("new")}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(77)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.isAbstractConstructorSignature()?this.tsParseFunctionOrConstructorType("TSConstructorType",!0):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(F.ReservedTypeAssertion,this.state.startLoc);let e=this.startNode();return e.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?this.tsParseTypeReference():this.tsParseType())),this.expect(48),e.expression=this.parseMaybeUnary(),this.finishNode(e,"TSTypeAssertion")}tsParseHeritageClause(e){let r=this.state.startLoc,i=this.tsParseDelimitedList("HeritageClauseElement",()=>{let s=this.startNode();return s.expression=this.tsParseEntityName(3),this.match(47)&&(s.typeParameters=this.tsParseTypeArguments()),this.finishNode(s,"TSExpressionWithTypeArguments")});return i.length||this.raise(F.EmptyHeritageClauseType,r,{token:e}),i}tsParseInterfaceDeclaration(e,r={}){if(this.hasFollowingLineBreak())return null;this.expectContextual(129),r.declare&&(e.declare=!0),se(this.state.type)?(e.id=this.parseIdentifier(),this.checkIdentifier(e.id,130)):(e.id=null,this.raise(F.MissingInterfaceName,this.state.startLoc)),e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers),this.eat(81)&&(e.extends=this.tsParseHeritageClause("extends"));let i=this.startNode();return i.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),e.body=this.finishNode(i,"TSInterfaceBody"),this.finishNode(e,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(e){return e.id=this.parseIdentifier(),this.checkIdentifier(e.id,2),e.typeAnnotation=this.tsInType(()=>{if(e.typeParameters=this.tsTryParseTypeParameters(this.tsParseInOutModifiers),this.expect(29),this.isContextual(114)&&this.lookaheadCharCode()!==46){let r=this.startNode();return this.next(),this.finishNode(r,"TSIntrinsicKeyword")}return this.tsParseType()}),this.semicolon(),this.finishNode(e,"TSTypeAliasDeclaration")}tsInTopLevelContext(e){if(this.curContext()!==ie.brace){let r=this.state.context;this.state.context=[r[0]];try{return e()}finally{this.state.context=r}}else return e()}tsInType(e){let r=this.state.inType;this.state.inType=!0;try{return e()}finally{this.state.inType=r}}tsInDisallowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!0;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}tsInAllowConditionalTypesContext(e){let r=this.state.inDisallowConditionalTypesContext;this.state.inDisallowConditionalTypesContext=!1;try{return e()}finally{this.state.inDisallowConditionalTypesContext=r}}tsEatThenParseType(e){if(this.match(e))return this.tsNextThenParseType()}tsExpectThenParseType(e){return this.tsInType(()=>(this.expect(e),this.tsParseType()))}tsNextThenParseType(){return this.tsInType(()=>(this.next(),this.tsParseType()))}tsParseEnumMember(){let e=this.startNode();return e.id=this.match(134)?super.parseStringLiteral(this.state.value):this.parseIdentifier(!0),this.eat(29)&&(e.initializer=super.parseMaybeAssignAllowIn()),this.finishNode(e,"TSEnumMember")}tsParseEnumDeclaration(e,r={}){return r.const&&(e.const=!0),r.declare&&(e.declare=!0),this.expectContextual(126),e.id=this.parseIdentifier(),this.checkIdentifier(e.id,e.const?8971:8459),this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumDeclaration")}tsParseEnumBody(){let e=this.startNode();return this.expect(5),e.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(8),this.finishNode(e,"TSEnumBody")}tsParseModuleBlock(){let e=this.startNode();return this.scope.enter(0),this.expect(5),super.parseBlockOrModuleBlockBody(e.body=[],void 0,!0,8),this.scope.exit(),this.finishNode(e,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(e,r=!1){if(e.id=this.parseIdentifier(),r||this.checkIdentifier(e.id,1024),this.eat(16)){let i=this.startNode();this.tsParseModuleOrNamespaceDeclaration(i,!0),e.body=i}else this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(e,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(e){return this.isContextual(112)?(e.kind="global",e.global=!0,e.id=this.parseIdentifier()):this.match(134)?(e.kind="module",e.id=super.parseStringLiteral(this.state.value)):this.unexpected(),this.match(5)?(this.scope.enter(1024),this.prodParam.enter(0),e.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(e,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(e,r,i){e.isExport=i||!1,e.id=r||this.parseIdentifier(),this.checkIdentifier(e.id,4096),this.expect(29);let s=this.tsParseModuleReference();return e.importKind==="type"&&s.type!=="TSExternalModuleReference"&&this.raise(F.ImportAliasHasImportType,s),e.moduleReference=s,this.semicolon(),this.finishNode(e,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual(119)&&this.lookaheadCharCode()===40}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(0)}tsParseExternalModuleReference(){let e=this.startNode();return this.expectContextual(119),this.expect(10),this.match(134)||this.unexpected(),e.expression=super.parseExprAtom(),this.expect(11),this.sawUnambiguousESM=!0,this.finishNode(e,"TSExternalModuleReference")}tsLookAhead(e){let r=this.state.clone(),i=e();return this.state=r,i}tsTryParseAndCatch(e){let r=this.tryParse(i=>e()||i());if(!(r.aborted||!r.node))return r.error&&(this.state=r.failState),r.node}tsTryParse(e){let r=this.state.clone(),i=e();if(i!==void 0&&i!==!1)return i;this.state=r}tsTryParseDeclare(e){if(this.isLineTerminator())return;let r=this.state.type;return this.tsInAmbientContext(()=>{switch(r){case 68:return e.declare=!0,super.parseFunctionStatement(e,!1,!1);case 80:return e.declare=!0,this.parseClass(e,!0,!1);case 126:return this.tsParseEnumDeclaration(e,{declare:!0});case 112:return this.tsParseAmbientExternalModuleDeclaration(e);case 100:if(this.state.containsEsc)return;case 75:case 74:return!this.match(75)||!this.isLookaheadContextual("enum")?(e.declare=!0,this.parseVarStatement(e,this.state.value,!0)):(this.expect(75),this.tsParseEnumDeclaration(e,{const:!0,declare:!0}));case 107:if(this.isUsing())return this.raise(F.InvalidModifierOnUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.parseVarStatement(e,"using",!0);break;case 96:if(this.isAwaitUsing())return this.raise(F.InvalidModifierOnAwaitUsingDeclaration,this.state.startLoc,"declare"),e.declare=!0,this.next(),this.parseVarStatement(e,"await using",!0);break;case 129:{let i=this.tsParseInterfaceDeclaration(e,{declare:!0});if(i)return i}default:if(se(r))return this.tsParseDeclaration(e,this.state.type,!0,null)}})}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.type,!0,null)}tsParseDeclaration(e,r,i,s){switch(r){case 124:if(this.tsCheckLineTerminator(i)&&(this.match(80)||se(this.state.type)))return this.tsParseAbstractDeclaration(e,s);break;case 127:if(this.tsCheckLineTerminator(i)){if(this.match(134))return this.tsParseAmbientExternalModuleDeclaration(e);if(se(this.state.type))return e.kind="module",this.tsParseModuleOrNamespaceDeclaration(e)}break;case 128:if(this.tsCheckLineTerminator(i)&&se(this.state.type))return e.kind="namespace",this.tsParseModuleOrNamespaceDeclaration(e);break;case 130:if(this.tsCheckLineTerminator(i)&&se(this.state.type))return this.tsParseTypeAliasDeclaration(e);break}}tsCheckLineTerminator(e){return e?this.hasFollowingLineBreak()?!1:(this.next(),!0):!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(e){if(!this.match(47))return;let r=this.state.maybeInArrowParameters;this.state.maybeInArrowParameters=!0;let i=this.tsTryParseAndCatch(()=>{let s=this.startNodeAt(e);return s.typeParameters=this.tsParseTypeParameters(this.tsParseConstModifier),super.parseFunctionParams(s),s.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(19),s});if(this.state.maybeInArrowParameters=r,!!i)return super.parseArrowExpression(i,null,!0)}tsParseTypeArgumentsInExpression(){if(this.reScan_lt()===47)return this.tsParseTypeArguments()}tsParseTypeArguments(){let e=this.startNode();return e.params=this.tsInType(()=>this.tsInTopLevelContext(()=>(this.expect(47),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),e.params.length===0?this.raise(F.EmptyTypeArguments,e):!this.state.inType&&this.curContext()===ie.brace&&this.reScan_lt_gt(),this.expect(48),this.finishNode(e,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){return Fk(this.state.type)}isExportDefaultSpecifier(){return this.tsIsDeclarationStart()?!1:super.isExportDefaultSpecifier()}parseBindingElement(e,r){let i=r.length?r[0].loc.start:this.state.startLoc,s={};this.tsParseModifiers({allowedModifiers:["public","private","protected","override","readonly"]},s);let a=s.accessibility,o=s.override,d=s.readonly;!(e&4)&&(a||d||o)&&this.raise(F.UnexpectedParameterModifier,i);let c=this.parseMaybeDefault();e&2&&this.parseFunctionParamType(c);let l=this.parseMaybeDefault(c.loc.start,c);if(a||d||o){let u=this.startNodeAt(i);return r.length&&(u.decorators=r),a&&(u.accessibility=a),d&&(u.readonly=d),o&&(u.override=o),l.type!=="Identifier"&&l.type!=="AssignmentPattern"&&this.raise(F.UnsupportedParameterPropertyKind,u),u.parameter=l,this.finishNode(u,"TSParameterProperty")}return r.length&&(c.decorators=r),l}isSimpleParameter(e){return e.type==="TSParameterProperty"&&super.isSimpleParameter(e.parameter)||super.isSimpleParameter(e)}tsDisallowOptionalPattern(e){for(let r of e.params)r.type!=="Identifier"&&r.optional&&!this.state.isAmbientContext&&this.raise(F.PatternIsOptional,r)}setArrowFunctionParameters(e,r,i){super.setArrowFunctionParameters(e,r,i),this.tsDisallowOptionalPattern(e)}parseFunctionBodyAndFinish(e,r,i=!1){this.match(14)&&(e.returnType=this.tsParseTypeOrTypePredicateAnnotation(14));let s=r==="FunctionDeclaration"?"TSDeclareFunction":r==="ClassMethod"||r==="ClassPrivateMethod"?"TSDeclareMethod":void 0;return s&&!this.match(5)&&this.isLineTerminator()?this.finishNode(e,s):s==="TSDeclareFunction"&&this.state.isAmbientContext&&(this.raise(F.DeclareFunctionHasImplementation,e),e.declare)?super.parseFunctionBodyAndFinish(e,s,i):(this.tsDisallowOptionalPattern(e),super.parseFunctionBodyAndFinish(e,r,i))}registerFunctionStatementId(e){!e.body&&e.id?this.checkIdentifier(e.id,1024):super.registerFunctionStatementId(e)}tsCheckForInvalidTypeCasts(e){e.forEach(r=>{r?.type==="TSTypeCastExpression"&&this.raise(F.UnexpectedTypeAnnotation,r.typeAnnotation)})}toReferencedList(e,r){return this.tsCheckForInvalidTypeCasts(e),e}parseArrayLike(e,r,i){let s=super.parseArrayLike(e,r,i);return s.type==="ArrayExpression"&&this.tsCheckForInvalidTypeCasts(s.elements),s}parseSubscript(e,r,i,s){if(!this.hasPrecedingLineBreak()&&this.match(35)){this.state.canStartJSXElement=!1,this.next();let o=this.startNodeAt(r);return o.expression=e,this.finishNode(o,"TSNonNullExpression")}let a=!1;if(this.match(18)&&this.lookaheadCharCode()===60){if(i)return s.stop=!0,e;s.optionalChainMember=a=!0,this.next()}if(this.match(47)||this.match(51)){let o,d=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(e)){let p=this.tsTryParseGenericAsyncArrowFunction(r);if(p)return s.stop=!0,p}let c=this.tsParseTypeArgumentsInExpression();if(!c)return;if(a&&!this.match(10)){o=this.state.curPosition();return}if(ta(this.state.type)){let p=super.parseTaggedTemplateExpression(e,r,s);return p.typeParameters=c,p}if(!i&&this.eat(10)){let p=this.startNodeAt(r);return p.callee=e,p.arguments=this.parseCallExpressionArguments(),this.tsCheckForInvalidTypeCasts(p.arguments),p.typeParameters=c,s.optionalChainMember&&(p.optional=a),this.finishCallExpression(p,s.optionalChainMember)}let l=this.state.type;if(l===48||l===52||l!==10&&l!==93&&l!==120&&hi(l)&&!this.hasPrecedingLineBreak())return;let u=this.startNodeAt(r);return u.expression=e,u.typeParameters=c,this.finishNode(u,"TSInstantiationExpression")});if(o&&this.unexpected(o,10),d)return d.type==="TSInstantiationExpression"&&((this.match(16)||this.match(18)&&this.lookaheadCharCode()!==40)&&this.raise(F.InvalidPropertyAccessAfterInstantiationExpression,this.state.startLoc),!this.match(16)&&!this.match(18)&&(d.expression=super.stopParseSubscript(e,s))),d}return super.parseSubscript(e,r,i,s)}parseNewCallee(e){var r;super.parseNewCallee(e);let{callee:i}=e;i.type==="TSInstantiationExpression"&&!((r=i.extra)!=null&&r.parenthesized)&&(e.typeParameters=i.typeParameters,e.callee=i.expression)}parseExprOp(e,r,i){let s;if(Qs(58)>i&&!this.hasPrecedingLineBreak()&&(this.isContextual(93)||(s=this.isContextual(120)))){let a=this.startNodeAt(r);return a.expression=e,a.typeAnnotation=this.tsInType(()=>(this.next(),this.match(75)?(s&&this.raise(b.UnexpectedKeyword,this.state.startLoc,{keyword:"const"}),this.tsParseTypeReference()):this.tsParseType())),this.finishNode(a,s?"TSSatisfiesExpression":"TSAsExpression"),this.reScan_lt_gt(),this.parseExprOp(a,r,i)}return super.parseExprOp(e,r,i)}checkReservedWord(e,r,i,s){this.state.isAmbientContext||super.checkReservedWord(e,r,i,s)}checkImportReflection(e){super.checkImportReflection(e),e.module&&e.importKind!=="value"&&this.raise(F.ImportReflectionHasImportType,e.specifiers[0].loc.start)}checkDuplicateExports(){}isPotentialImportPhase(e){if(super.isPotentialImportPhase(e))return!0;if(this.isContextual(130)){let r=this.lookaheadCharCode();return e?r===123||r===42:r!==61}return!e&&this.isContextual(87)}applyImportPhase(e,r,i,s){super.applyImportPhase(e,r,i,s),r?e.exportKind=i==="type"?"type":"value":e.importKind=i==="type"||i==="typeof"?i:"value"}parseImport(e){if(this.match(134))return e.importKind="value",super.parseImport(e);let r;if(se(this.state.type)&&this.lookaheadCharCode()===61)return e.importKind="value",this.tsParseImportEqualsDeclaration(e);if(this.isContextual(130)){let i=this.parseMaybeImportPhase(e,!1);if(this.lookaheadCharCode()===61)return this.tsParseImportEqualsDeclaration(e,i);r=super.parseImportSpecifiersAndAfter(e,i)}else r=super.parseImport(e);return r.importKind==="type"&&r.specifiers.length>1&&r.specifiers[0].type==="ImportDefaultSpecifier"&&this.raise(F.TypeImportCannotSpecifyDefaultAndNamed,r),r}parseExport(e,r){if(this.match(83)){let i=e;this.next();let s=null;return this.isContextual(130)&&this.isPotentialImportPhase(!1)?s=this.parseMaybeImportPhase(i,!1):i.importKind="value",this.tsParseImportEqualsDeclaration(i,s,!0)}else if(this.eat(29)){let i=e;return i.expression=super.parseExpression(),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(i,"TSExportAssignment")}else if(this.eatContextual(93)){let i=e;return this.expectContextual(128),i.id=this.parseIdentifier(),this.semicolon(),this.finishNode(i,"TSNamespaceExportDeclaration")}else return super.parseExport(e,r)}isAbstractClass(){return this.isContextual(124)&&this.isLookaheadContextual("class")}parseExportDefaultExpression(){if(this.isAbstractClass()){let e=this.startNode();return this.next(),e.abstract=!0,this.parseClass(e,!0,!0)}if(this.match(129)){let e=this.tsParseInterfaceDeclaration(this.startNode());if(e)return e}return super.parseExportDefaultExpression()}parseVarStatement(e,r,i=!1){let{isAmbientContext:s}=this.state,a=super.parseVarStatement(e,r,i||s);if(!s)return a;if(!e.declare&&(r==="using"||r==="await using"))return this.raiseOverwrite(F.UsingDeclarationInAmbientContext,e,r),a;for(let{id:o,init:d}of a.declarations)d&&(r==="var"||r==="let"||o.typeAnnotation?this.raise(F.InitializerNotAllowedInAmbientContext,d):xR(d,this.hasPlugin("estree"))||this.raise(F.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,d));return a}parseStatementContent(e,r){if(!this.state.containsEsc)switch(this.state.type){case 75:{if(this.isLookaheadContextual("enum")){let i=this.startNode();return this.expect(75),this.tsParseEnumDeclaration(i,{const:!0})}break}case 124:case 125:{if(this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()){let i=this.state.type,s=this.startNode();this.next();let a=i===125?this.tsTryParseDeclare(s):this.tsParseAbstractDeclaration(s,r);return a?(i===125&&(a.declare=!0),a):(s.expression=this.createIdentifier(this.startNodeAt(s.loc.start),i===125?"declare":"abstract"),this.semicolon(!1),this.finishNode(s,"ExpressionStatement"))}break}case 126:return this.tsParseEnumDeclaration(this.startNode());case 112:{if(this.lookaheadCharCode()===123){let s=this.startNode();return this.tsParseAmbientExternalModuleDeclaration(s)}break}case 129:{let i=this.tsParseInterfaceDeclaration(this.startNode());if(i)return i;break}case 127:{if(this.nextTokenIsIdentifierOrStringLiteralOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,127,!1,r)}break}case 128:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseDeclaration(i,128,!1,r)}break}case 130:{if(this.nextTokenIsIdentifierOnSameLine()){let i=this.startNode();return this.next(),this.tsParseTypeAliasDeclaration(i)}break}}return super.parseStatementContent(e,r)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}tsHasSomeModifiers(e,r){return r.some(i=>Bf(i)?e.accessibility===i:!!e[i])}tsIsStartOfStaticBlocks(){return this.isContextual(106)&&this.lookaheadCharCode()===123}parseClassMember(e,r,i){let s=["declare","private","public","protected","override","abstract","readonly","static"];this.tsParseModifiers({allowedModifiers:s,disallowedModifiers:["in","out"],stopOnStartOfClassStaticBlock:!0,errorTemplate:F.InvalidModifierOnTypeParameterPositions},r);let a=()=>{this.tsIsStartOfStaticBlocks()?(this.next(),this.next(),this.tsHasSomeModifiers(r,s)&&this.raise(F.StaticBlockCannotHaveModifier,this.state.curPosition()),super.parseClassStaticBlock(e,r)):this.parseClassMemberWithIsStatic(e,r,i,!!r.static)};r.declare?this.tsInAmbientContext(a):a()}parseClassMemberWithIsStatic(e,r,i,s){let a=this.tsTryParseIndexSignature(r);if(a){e.body.push(a),r.abstract&&this.raise(F.IndexSignatureHasAbstract,r),r.accessibility&&this.raise(F.IndexSignatureHasAccessibility,r,{modifier:r.accessibility}),r.declare&&this.raise(F.IndexSignatureHasDeclare,r),r.override&&this.raise(F.IndexSignatureHasOverride,r);return}!this.state.inAbstractClass&&r.abstract&&this.raise(F.NonAbstractClassHasAbstractMethod,r),r.override&&(i.hadSuperClass||this.raise(F.OverrideNotInSubClass,r)),super.parseClassMemberWithIsStatic(e,r,i,s)}parsePostMemberNameModifiers(e){this.eat(17)&&(e.optional=!0),e.readonly&&this.match(10)&&this.raise(F.ClassMethodHasReadonly,e),e.declare&&this.match(10)&&this.raise(F.ClassMethodHasDeclare,e)}shouldParseExportDeclaration(){return this.tsIsDeclarationStart()?!0:super.shouldParseExportDeclaration()}parseConditional(e,r,i){if(!this.match(17))return e;if(this.state.maybeInArrowParameters){let s=this.lookaheadCharCode();if(s===44||s===61||s===58||s===41)return this.setOptionalParametersError(i),e}return super.parseConditional(e,r,i)}parseParenItem(e,r){let i=super.parseParenItem(e,r);if(this.eat(17)&&(i.optional=!0,this.resetEndLocation(e)),this.match(14)){let s=this.startNodeAt(r);return s.expression=e,s.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(s,"TSTypeCastExpression")}return e}parseExportDeclaration(e){if(!this.state.isAmbientContext&&this.isContextual(125))return this.tsInAmbientContext(()=>this.parseExportDeclaration(e));let r=this.state.startLoc,i=this.eatContextual(125);if(i&&(this.isContextual(125)||!this.shouldParseExportDeclaration()))throw this.raise(F.ExpectedAmbientAfterExportDeclare,this.state.startLoc);let a=se(this.state.type)&&this.tsTryParseExportDeclaration()||super.parseExportDeclaration(e);return a?((a.type==="TSInterfaceDeclaration"||a.type==="TSTypeAliasDeclaration"||i)&&(e.exportKind="type"),i&&a.type!=="TSImportEqualsDeclaration"&&(this.resetStartLocation(a,r),a.declare=!0),a):null}parseClassId(e,r,i,s){if((!r||i)&&this.isContextual(113))return;super.parseClassId(e,r,i,e.declare?1024:8331);let a=this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);a&&(e.typeParameters=a)}parseClassPropertyAnnotation(e){e.optional||(this.eat(35)?e.definite=!0:this.eat(17)&&(e.optional=!0));let r=this.tsTryParseTypeAnnotation();r&&(e.typeAnnotation=r)}parseClassProperty(e){if(this.parseClassPropertyAnnotation(e),this.state.isAmbientContext&&!(e.readonly&&!e.typeAnnotation)&&this.match(29)&&this.raise(F.DeclareClassFieldHasInitializer,this.state.startLoc),e.abstract&&this.match(29)){let{key:r}=e;this.raise(F.AbstractPropertyHasInitializer,this.state.startLoc,{propertyName:r.type==="Identifier"&&!e.computed?r.name:`[${this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end))}]`})}return super.parseClassProperty(e)}parseClassPrivateProperty(e){return e.abstract&&this.raise(F.PrivateElementHasAbstract,e),e.accessibility&&this.raise(F.PrivateElementHasAccessibility,e,{modifier:e.accessibility}),this.parseClassPropertyAnnotation(e),super.parseClassPrivateProperty(e)}parseClassAccessorProperty(e){return this.parseClassPropertyAnnotation(e),e.optional&&this.raise(F.AccessorCannotBeOptional,e),super.parseClassAccessorProperty(e)}pushClassMethod(e,r,i,s,a,o){let d=this.tsTryParseTypeParameters(this.tsParseConstModifier);d&&a&&this.raise(F.ConstructorHasTypeParameters,d);let{declare:c=!1,kind:l}=r;c&&(l==="get"||l==="set")&&this.raise(F.DeclareAccessor,r,{kind:l}),d&&(r.typeParameters=d),super.pushClassMethod(e,r,i,s,a,o)}pushClassPrivateMethod(e,r,i,s){let a=this.tsTryParseTypeParameters(this.tsParseConstModifier);a&&(r.typeParameters=a),super.pushClassPrivateMethod(e,r,i,s)}declareClassPrivateMethodInScope(e,r){e.type!=="TSDeclareMethod"&&(e.type==="MethodDefinition"&&e.value.body==null||super.declareClassPrivateMethodInScope(e,r))}parseClassSuper(e){if(super.parseClassSuper(e),e.superClass)if(e.superClass.type==="TSInstantiationExpression"){let r=e.superClass,i=r.expression;this.takeSurroundingComments(i,i.start,i.end);let s=r.typeParameters;this.takeSurroundingComments(s,s.start,s.end),e.superClass=i,e.superTypeParameters=s}else(this.match(47)||this.match(51))&&(e.superTypeParameters=this.tsParseTypeArgumentsInExpression());this.eatContextual(113)&&(e.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(e,r,i,s,a,o,d){let c=this.tsTryParseTypeParameters(this.tsParseConstModifier);return c&&(e.typeParameters=c),super.parseObjPropValue(e,r,i,s,a,o,d)}parseFunctionParams(e,r){let i=this.tsTryParseTypeParameters(this.tsParseConstModifier);i&&(e.typeParameters=i),super.parseFunctionParams(e,r)}parseVarId(e,r){super.parseVarId(e,r),e.id.type==="Identifier"&&!this.hasPrecedingLineBreak()&&this.eat(35)&&(e.definite=!0);let i=this.tsTryParseTypeAnnotation();i&&(e.id.typeAnnotation=i,this.resetEndLocation(e.id))}parseAsyncArrowFromCallExpression(e,r){return this.match(14)&&(e.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(e,r)}parseMaybeAssign(e,r){var i,s,a,o,d;let c,l,u;if(this.hasPlugin("jsx")&&(this.match(143)||this.match(47))){if(c=this.state.clone(),l=this.tryParse(()=>super.parseMaybeAssign(e,r),c),!l.error)return l.node;let{context:h}=this.state,m=h[h.length-1];(m===ie.j_oTag||m===ie.j_expr)&&h.pop()}if(!((i=l)!=null&&i.error)&&!this.match(47))return super.parseMaybeAssign(e,r);(!c||c===this.state)&&(c=this.state.clone());let p,f=this.tryParse(h=>{var m,g;p=this.tsParseTypeParameters(this.tsParseConstModifier);let y=super.parseMaybeAssign(e,r);return(y.type!=="ArrowFunctionExpression"||(m=y.extra)!=null&&m.parenthesized)&&h(),((g=p)==null?void 0:g.params.length)!==0&&this.resetStartLocationFromNode(y,p),y.typeParameters=p,y},c);if(!f.error&&!f.aborted)return p&&this.reportReservedArrowTypeParam(p),f.node;if(!l&&(Ff(!this.hasPlugin("jsx")),u=this.tryParse(()=>super.parseMaybeAssign(e,r),c),!u.error))return u.node;if((s=l)!=null&&s.node)return this.state=l.failState,l.node;if(f.node)return this.state=f.failState,p&&this.reportReservedArrowTypeParam(p),f.node;if((a=u)!=null&&a.node)return this.state=u.failState,u.node;throw((o=l)==null?void 0:o.error)||f.error||((d=u)==null?void 0:d.error)}reportReservedArrowTypeParam(e){var r;e.params.length===1&&!e.params[0].constraint&&!((r=e.extra)!=null&&r.trailingComma)&&this.getPluginOption("typescript","disallowAmbiguousJSXLike")&&this.raise(F.ReservedArrowTypeParam,e)}parseMaybeUnary(e,r){return!this.hasPlugin("jsx")&&this.match(47)?this.tsParseTypeAssertion():super.parseMaybeUnary(e,r)}parseArrow(e){if(this.match(14)){let r=this.tryParse(i=>{let s=this.tsParseTypeOrTypePredicateAnnotation(14);return(this.canInsertSemicolon()||!this.match(19))&&i(),s});if(r.aborted)return;r.thrown||(r.error&&(this.state=r.failState),e.returnType=r.node)}return super.parseArrow(e)}parseFunctionParamType(e){this.eat(17)&&(e.optional=!0);let r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r),this.resetEndLocation(e),e}isAssignable(e,r){switch(e.type){case"TSTypeCastExpression":return this.isAssignable(e.expression,r);case"TSParameterProperty":return!0;default:return super.isAssignable(e,r)}}toAssignable(e,r=!1){switch(e.type){case"ParenthesizedExpression":this.toAssignableParenthesizedExpression(e,r);break;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":r?this.expressionScope.recordArrowParameterBindingError(F.UnexpectedTypeCastInParameter,e):this.raise(F.UnexpectedTypeCastInParameter,e),this.toAssignable(e.expression,r);break;case"AssignmentExpression":!r&&e.left.type==="TSTypeCastExpression"&&(e.left=this.typeCastToParameter(e.left));default:super.toAssignable(e,r)}}toAssignableParenthesizedExpression(e,r){switch(e.expression.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"ParenthesizedExpression":this.toAssignable(e.expression,r);break;default:super.toAssignable(e,r)}}checkToRestConversion(e,r){switch(e.type){case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":case"TSNonNullExpression":this.checkToRestConversion(e.expression,!1);break;default:super.checkToRestConversion(e,r)}}isValidLVal(e,r,i,s){switch(e){case"TSTypeCastExpression":return!0;case"TSParameterProperty":return"parameter";case"TSNonNullExpression":return"expression";case"TSAsExpression":case"TSSatisfiesExpression":case"TSTypeAssertion":return(s!==64||!i)&&["expression",!0];default:return super.isValidLVal(e,r,i,s)}}parseBindingAtom(){return this.state.type===78?this.parseIdentifier(!0):super.parseBindingAtom()}parseMaybeDecoratorArguments(e,r){if(this.match(47)||this.match(51)){let i=this.tsParseTypeArgumentsInExpression();if(this.match(10)){let s=super.parseMaybeDecoratorArguments(e,r);return s.typeParameters=i,s}this.unexpected(null,10)}return super.parseMaybeDecoratorArguments(e,r)}checkCommaAfterRest(e){return this.state.isAmbientContext&&this.match(12)&&this.lookaheadCharCode()===e?(this.next(),!1):super.checkCommaAfterRest(e)}isClassMethod(){return this.match(47)||super.isClassMethod()}isClassProperty(){return this.match(35)||this.match(14)||super.isClassProperty()}parseMaybeDefault(e,r){let i=super.parseMaybeDefault(e,r);return i.type==="AssignmentPattern"&&i.typeAnnotation&&i.right.start<i.typeAnnotation.start&&this.raise(F.TypeAnnotationAfterAssign,i.typeAnnotation),i}getTokenFromCode(e){if(this.state.inType){if(e===62){this.finishOp(48,1);return}if(e===60){this.finishOp(47,1);return}}super.getTokenFromCode(e)}reScan_lt_gt(){let{type:e}=this.state;e===47?(this.state.pos-=1,this.readToken_lt()):e===48&&(this.state.pos-=1,this.readToken_gt())}reScan_lt(){let{type:e}=this.state;return e===51?(this.state.pos-=2,this.finishOp(47,1),47):e}toAssignableListItem(e,r,i){let s=e[r];s.type==="TSTypeCastExpression"&&(e[r]=this.typeCastToParameter(s)),super.toAssignableListItem(e,r,i)}typeCastToParameter(e){return e.expression.typeAnnotation=e.typeAnnotation,this.resetEndLocation(e.expression,e.typeAnnotation.loc.end),e.expression}shouldParseArrow(e){return this.match(14)?e.every(r=>this.isAssignable(r,!0)):super.shouldParseArrow(e)}shouldParseAsyncArrow(){return this.match(14)||super.shouldParseAsyncArrow()}canHaveLeadingDecorator(){return super.canHaveLeadingDecorator()||this.isAbstractClass()}jsxParseOpeningElementAfterName(e){if(this.match(47)||this.match(51)){let r=this.tsTryParseAndCatch(()=>this.tsParseTypeArgumentsInExpression());r&&(e.typeParameters=r)}return super.jsxParseOpeningElementAfterName(e)}getGetterSetterExpectedParamCount(e){let r=super.getGetterSetterExpectedParamCount(e),s=this.getObjectOrClassMethodParams(e)[0];return s&&this.isThisParam(s)?r+1:r}parseCatchClauseParam(){let e=super.parseCatchClauseParam(),r=this.tsTryParseTypeAnnotation();return r&&(e.typeAnnotation=r,this.resetEndLocation(e)),e}tsInAmbientContext(e){let{isAmbientContext:r,strict:i}=this.state;this.state.isAmbientContext=!0,this.state.strict=!1;try{return e()}finally{this.state.isAmbientContext=r,this.state.strict=i}}parseClass(e,r,i){let s=this.state.inAbstractClass;this.state.inAbstractClass=!!e.abstract;try{return super.parseClass(e,r,i)}finally{this.state.inAbstractClass=s}}tsParseAbstractDeclaration(e,r){if(this.match(80))return e.abstract=!0,this.maybeTakeDecorators(r,this.parseClass(e,!0,!1));if(this.isContextual(129))return this.hasFollowingLineBreak()?null:(e.abstract=!0,this.raise(F.NonClassMethodPropertyHasAbstractModifier,e),this.tsParseInterfaceDeclaration(e));throw this.unexpected(null,80)}parseMethod(e,r,i,s,a,o,d){let c=super.parseMethod(e,r,i,s,a,o,d);if((c.abstract||c.type==="TSAbstractMethodDefinition")&&(this.hasPlugin("estree")?c.value:c).body){let{key:p}=c;this.raise(F.AbstractMethodHasImplementation,c,{methodName:p.type==="Identifier"&&!c.computed?p.name:`[${this.input.slice(this.offsetToSourcePos(p.start),this.offsetToSourcePos(p.end))}]`})}return c}tsParseTypeParameterName(){return this.parseIdentifier().name}shouldParseAsAmbientContext(){return!!this.getPluginOption("typescript","dts")}parse(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.parse()}getExpression(){return this.shouldParseAsAmbientContext()&&(this.state.isAmbientContext=!0),super.getExpression()}parseExportSpecifier(e,r,i,s){return!r&&s?(this.parseTypeOnlyImportExportSpecifier(e,!1,i),this.finishNode(e,"ExportSpecifier")):(e.exportKind="value",super.parseExportSpecifier(e,r,i,s))}parseImportSpecifier(e,r,i,s,a){return!r&&s?(this.parseTypeOnlyImportExportSpecifier(e,!0,i),this.finishNode(e,"ImportSpecifier")):(e.importKind="value",super.parseImportSpecifier(e,r,i,s,i?4098:4096))}parseTypeOnlyImportExportSpecifier(e,r,i){let s=r?"imported":"local",a=r?"local":"exported",o=e[s],d,c=!1,l=!0,u=o.loc.start;if(this.isContextual(93)){let f=this.parseIdentifier();if(this.isContextual(93)){let h=this.parseIdentifier();dt(this.state.type)?(c=!0,o=f,d=r?this.parseIdentifier():this.parseModuleExportName(),l=!1):(d=h,l=!1)}else dt(this.state.type)?(l=!1,d=r?this.parseIdentifier():this.parseModuleExportName()):(c=!0,o=f)}else dt(this.state.type)&&(c=!0,r?(o=this.parseIdentifier(!0),this.isContextual(93)||this.checkReservedWord(o.name,o.loc.start,!0,!0)):o=this.parseModuleExportName());c&&i&&this.raise(r?F.TypeModifierIsUsedInTypeImports:F.TypeModifierIsUsedInTypeExports,u),e[s]=o,e[a]=d;let p=r?"importKind":"exportKind";e[p]=c?"type":"value",l&&this.eatContextual(93)&&(e[a]=r?this.parseIdentifier():this.parseModuleExportName()),e[a]||(e[a]=this.cloneIdentifier(e[s])),r&&this.checkIdentifier(e[a],c?4098:4096)}fillOptionalPropertiesForTSESLint(e){var r,i,s,a,o,d,c,l,u,p,f,h,m,g,y,w,x,v,R,P,C,E,M,A,N,T,I,$,D,k,S,_,q,K,te,le,Y,Ae,Ee,St,qt,ni,ri,Fs,ii,si,ai,mf,yf;switch(e.type){case"ImportDeclaration":(r=e.phase)!=null||(e.phase=null);return;case"ExpressionStatement":(i=e.directive)!=null||(e.directive=void 0);return;case"RestElement":e.value=void 0;case"Identifier":case"ArrayPattern":case"AssignmentPattern":case"ObjectPattern":(s=e.decorators)!=null||(e.decorators=[]),(a=e.optional)!=null||(e.optional=!1),(o=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);return;case"TSParameterProperty":(d=e.accessibility)!=null||(e.accessibility=void 0),(c=e.decorators)!=null||(e.decorators=[]),(l=e.override)!=null||(e.override=!1),(u=e.readonly)!=null||(e.readonly=!1),(p=e.static)!=null||(e.static=!1);return;case"TSEmptyBodyFunctionExpression":e.body=null;case"TSDeclareFunction":case"FunctionDeclaration":case"FunctionExpression":case"ClassMethod":case"ClassPrivateMethod":(f=e.declare)!=null||(e.declare=!1),(h=e.returnType)!=null||(e.returnType=void 0),(m=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"Property":(g=e.optional)!=null||(e.optional=!1);return;case"TSMethodSignature":case"TSPropertySignature":(y=e.optional)!=null||(e.optional=!1);case"TSIndexSignature":(w=e.accessibility)!=null||(e.accessibility=void 0),(x=e.readonly)!=null||(e.readonly=!1),(v=e.static)!=null||(e.static=!1);return;case"TSAbstractPropertyDefinition":case"PropertyDefinition":case"TSAbstractAccessorProperty":case"AccessorProperty":(R=e.declare)!=null||(e.declare=!1),(P=e.definite)!=null||(e.definite=!1),(C=e.readonly)!=null||(e.readonly=!1),(E=e.typeAnnotation)!=null||(e.typeAnnotation=void 0);case"TSAbstractMethodDefinition":case"MethodDefinition":(M=e.accessibility)!=null||(e.accessibility=void 0),(A=e.decorators)!=null||(e.decorators=[]),(N=e.override)!=null||(e.override=!1),(T=e.optional)!=null||(e.optional=!1);return;case"ClassExpression":(I=e.id)!=null||(e.id=null);case"ClassDeclaration":($=e.abstract)!=null||(e.abstract=!1),(D=e.declare)!=null||(e.declare=!1),(k=e.decorators)!=null||(e.decorators=[]),(S=e.implements)!=null||(e.implements=[]),(_=e.superTypeArguments)!=null||(e.superTypeArguments=void 0),(q=e.typeParameters)!=null||(e.typeParameters=void 0);return;case"TSTypeAliasDeclaration":case"VariableDeclaration":(K=e.declare)!=null||(e.declare=!1);return;case"VariableDeclarator":(te=e.definite)!=null||(e.definite=!1);return;case"TSEnumDeclaration":(le=e.const)!=null||(e.const=!1),(Y=e.declare)!=null||(e.declare=!1);return;case"TSEnumMember":(Ae=e.computed)!=null||(e.computed=!1);return;case"TSImportType":(Ee=e.qualifier)!=null||(e.qualifier=null),(St=e.options)!=null||(e.options=null);return;case"TSInterfaceDeclaration":(qt=e.declare)!=null||(e.declare=!1),(ni=e.extends)!=null||(e.extends=[]);return;case"TSMappedType":(ri=e.optional)!=null||(e.optional=!1),(Fs=e.readonly)!=null||(e.readonly=void 0);return;case"TSModuleDeclaration":(ii=e.declare)!=null||(e.declare=!1),(si=e.global)!=null||(e.global=e.kind==="global");return;case"TSTypeParameter":(ai=e.const)!=null||(e.const=!1),(mf=e.in)!=null||(e.in=!1),(yf=e.out)!=null||(e.out=!1);return}}chStartsBindingIdentifierAndNotRelationalOperator(e,r){if(bt(e)){if(qd.lastIndex=r,qd.test(this.input)){let i=this.codePointAtPos(qd.lastIndex);if(!wn(i)&&i!==92)return!1}return!0}else return e===92}nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifierAndNotRelationalOperator(r,e)}nextTokenIsIdentifierOrStringLiteralOnSameLine(){let e=this.nextTokenInLineStart(),r=this.codePointAtPos(e);return this.chStartsBindingIdentifier(r,e)||r===34||r===39}};function bR(t){if(t.type!=="MemberExpression")return!1;let{computed:n,property:e}=t;return n&&e.type!=="StringLiteral"&&(e.type!=="TemplateLiteral"||e.expressions.length>0)?!1:rh(t.object)}function xR(t,n){var e;let{type:r}=t;if((e=t.extra)!=null&&e.parenthesized)return!1;if(n){if(r==="Literal"){let{value:i}=t;if(typeof i=="string"||typeof i=="boolean")return!0}}else if(r==="StringLiteral"||r==="BooleanLiteral")return!0;return!!(nh(t,n)||vR(t,n)||r==="TemplateLiteral"&&t.expressions.length===0||bR(t))}function nh(t,n){return n?t.type==="Literal"&&(typeof t.value=="number"||"bigint"in t):t.type==="NumericLiteral"||t.type==="BigIntLiteral"}function vR(t,n){if(t.type==="UnaryExpression"){let{operator:e,argument:r}=t;if(e==="-"&&nh(r,n))return!0}return!1}function rh(t){return t.type==="Identifier"?!0:t.type!=="MemberExpression"||t.computed?!1:rh(t.object)}var Hf=ot`placeholders`({ClassNameIsRequired:"A class name is required.",UnexpectedSpace:"Unexpected space in placeholder."}),kR=t=>class extends t{parsePlaceholder(e){if(this.match(133)){let r=this.startNode();return this.next(),this.assertNoSpace(),r.name=super.parseIdentifier(!0),this.assertNoSpace(),this.expect(133),this.finishPlaceholder(r,e)}}finishPlaceholder(e,r){let i=e;return(!i.expectedNode||!i.type)&&(i=this.finishNode(i,"Placeholder")),i.expectedNode=r,i}getTokenFromCode(e){e===37&&this.input.charCodeAt(this.state.pos+1)===37?this.finishOp(133,2):super.getTokenFromCode(e)}parseExprAtom(e){return this.parsePlaceholder("Expression")||super.parseExprAtom(e)}parseIdentifier(e){return this.parsePlaceholder("Identifier")||super.parseIdentifier(e)}checkReservedWord(e,r,i,s){e!==void 0&&super.checkReservedWord(e,r,i,s)}cloneIdentifier(e){let r=super.cloneIdentifier(e);return r.type==="Placeholder"&&(r.expectedNode=e.expectedNode),r}cloneStringLiteral(e){return e.type==="Placeholder"?this.cloneIdentifier(e):super.cloneStringLiteral(e)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom()}isValidLVal(e,r,i,s){return e==="Placeholder"||super.isValidLVal(e,r,i,s)}toAssignable(e,r){e&&e.type==="Placeholder"&&e.expectedNode==="Expression"?e.expectedNode="Pattern":super.toAssignable(e,r)}chStartsBindingIdentifier(e,r){if(super.chStartsBindingIdentifier(e,r))return!0;let i=this.nextTokenStart();return this.input.charCodeAt(i)===37&&this.input.charCodeAt(i+1)===37}verifyBreakContinue(e,r){var i;((i=e.label)==null?void 0:i.type)!=="Placeholder"&&super.verifyBreakContinue(e,r)}parseExpressionStatement(e,r){var i;if(r.type!=="Placeholder"||(i=r.extra)!=null&&i.parenthesized)return super.parseExpressionStatement(e,r);if(this.match(14)){let a=e;return a.label=this.finishPlaceholder(r,"Identifier"),this.next(),a.body=super.parseStatementOrSloppyAnnexBFunctionDeclaration(),this.finishNode(a,"LabeledStatement")}this.semicolon();let s=e;return s.name=r.name,this.finishPlaceholder(s,"Statement")}parseBlock(e,r,i){return this.parsePlaceholder("BlockStatement")||super.parseBlock(e,r,i)}parseFunctionId(e){return this.parsePlaceholder("Identifier")||super.parseFunctionId(e)}parseClass(e,r,i){let s=r?"ClassDeclaration":"ClassExpression";this.next();let a=this.state.strict,o=this.parsePlaceholder("Identifier");if(o)if(this.match(81)||this.match(133)||this.match(5))e.id=o;else{if(i||!r)return e.id=null,e.body=this.finishPlaceholder(o,"ClassBody"),this.finishNode(e,s);throw this.raise(Hf.ClassNameIsRequired,this.state.startLoc)}else this.parseClassId(e,r,i);return super.parseClassSuper(e),e.body=this.parsePlaceholder("ClassBody")||super.parseClassBody(!!e.superClass,a),this.finishNode(e,s)}parseExport(e,r){let i=this.parsePlaceholder("Identifier");if(!i)return super.parseExport(e,r);let s=e;if(!this.isContextual(98)&&!this.match(12))return s.specifiers=[],s.source=null,s.declaration=this.finishPlaceholder(i,"Declaration"),this.finishNode(s,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");let a=this.startNode();return a.exported=i,s.specifiers=[this.finishNode(a,"ExportDefaultSpecifier")],super.parseExport(s,r)}isExportDefaultSpecifier(){if(this.match(65)){let e=this.nextTokenStart();if(this.isUnparsedContextual(e,"from")&&this.input.startsWith(Yt(133),this.nextTokenStartSince(e+4)))return!0}return super.isExportDefaultSpecifier()}maybeParseExportDefaultSpecifier(e,r){var i;return(i=e.specifiers)!=null&&i.length?!0:super.maybeParseExportDefaultSpecifier(e,r)}checkExport(e){let{specifiers:r}=e;r!=null&&r.length&&(e.specifiers=r.filter(i=>i.exported.type==="Placeholder")),super.checkExport(e),e.specifiers=r}parseImport(e){let r=this.parsePlaceholder("Identifier");if(!r)return super.parseImport(e);if(e.specifiers=[],!this.isContextual(98)&&!this.match(12))return e.source=this.finishPlaceholder(r,"StringLiteral"),this.semicolon(),this.finishNode(e,"ImportDeclaration");let i=this.startNodeAtNode(r);return i.local=r,e.specifiers.push(this.finishNode(i,"ImportDefaultSpecifier")),this.eat(12)&&(this.maybeParseStarImportSpecifier(e)||this.parseNamedImportSpecifiers(e)),this.expectContextual(98),e.source=this.parseImportSource(),this.semicolon(),this.finishNode(e,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource()}assertNoSpace(){this.state.start>this.offsetToSourcePos(this.state.lastTokEndLoc.index)&&this.raise(Hf.UnexpectedSpace,this.state.lastTokEndLoc)}},RR=t=>class extends t{parseV8Intrinsic(){if(this.match(54)){let e=this.state.startLoc,r=this.startNode();if(this.next(),se(this.state.type)){let i=this.parseIdentifierName(),s=this.createIdentifier(r,i);if(this.castNodeTo(s,"V8IntrinsicIdentifier"),this.match(10))return s}this.unexpected(e)}}parseExprAtom(e){return this.parseV8Intrinsic()||super.parseExprAtom(e)}},zf=["minimal","fsharp","hack","smart"],Vf=["^^","@@","^","%","#"];function IR(t){if(t.has("decorators")){if(t.has("decorators-legacy"))throw new Error("Cannot use the decorators and decorators-legacy plugin together");let r=t.get("decorators").decoratorsBeforeExport;if(r!=null&&typeof r!="boolean")throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");let i=t.get("decorators").allowCallParenthesized;if(i!=null&&typeof i!="boolean")throw new Error("'allowCallParenthesized' must be a boolean.")}if(t.has("flow")&&t.has("typescript"))throw new Error("Cannot combine flow and typescript plugins.");if(t.has("placeholders")&&t.has("v8intrinsic"))throw new Error("Cannot combine placeholders and v8intrinsic plugins.");if(t.has("pipelineOperator")){var n;let r=t.get("pipelineOperator").proposal;if(!zf.includes(r)){let i=zf.map(s=>`"${s}"`).join(", ");throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${i}.`)}if(r==="hack"){var e;if(t.has("placeholders"))throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");if(t.has("v8intrinsic"))throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");let i=t.get("pipelineOperator").topicToken;if(!Vf.includes(i)){let s=Vf.map(a=>`"${a}"`).join(", ");throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${s}.`)}if(i==="#"&&((e=t.get("recordAndTuple"))==null?void 0:e.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple",t.get("recordAndTuple")])}\`.`)}else if(r==="smart"&&((n=t.get("recordAndTuple"))==null?void 0:n.syntaxType)==="hash")throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple",t.get("recordAndTuple")])}\`.`)}if(t.has("moduleAttributes")){if(t.has("deprecatedImportAssert")||t.has("importAssertions"))throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");if(t.get("moduleAttributes").version!=="may-2020")throw new Error("The 'moduleAttributes' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is 'may-2020'.")}if(t.has("importAssertions")&&t.has("deprecatedImportAssert"))throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");if(t.has("deprecatedImportAssert")||t.has("importAttributes")&&t.get("importAttributes").deprecatedAssertSyntax&&t.set("deprecatedImportAssert",{}),t.has("recordAndTuple")){let r=t.get("recordAndTuple").syntaxType;if(r!=null){let i=["hash","bar"];if(!i.includes(r))throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: "+i.map(s=>`'${s}'`).join(", "))}}if(t.has("asyncDoExpressions")&&!t.has("doExpressions")){let r=new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");throw r.missingPlugins="doExpressions",r}if(t.has("optionalChainingAssign")&&t.get("optionalChainingAssign").version!=="2023-07")throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'.");if(t.has("discardBinding")&&t.get("discardBinding").syntaxType!=="void")throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.")}var ih={estree:Sk,jsx:aR,flow:nR,typescript:wR,v8intrinsic:RR,placeholders:kR},AR=Object.keys(ih),fc=class extends pc{checkProto(n,e,r,i){if(n.type==="SpreadElement"||this.isObjectMethod(n)||n.computed||n.shorthand)return r;let s=n.key;return(s.type==="Identifier"?s.name:s.value)==="__proto__"?e?(this.raise(b.RecordNoProto,s),!0):(r&&(i?i.doubleProtoLoc===null&&(i.doubleProtoLoc=s.loc.start):this.raise(b.DuplicateProto,s)),!0):r}shouldExitDescending(n,e){return n.type==="ArrowFunctionExpression"&&this.offsetToSourcePos(n.start)===e}getExpression(){if(this.enterInitialScopes(),this.nextToken(),this.match(140))throw this.raise(b.ParseExpressionEmptyInput,this.state.startLoc);let n=this.parseExpression();if(!this.match(140))throw this.raise(b.ParseExpressionExpectsEOF,this.state.startLoc,{unexpected:this.input.codePointAt(this.state.start)});return this.finalizeRemainingComments(),n.comments=this.comments,n.errors=this.state.errors,this.optionFlags&256&&(n.tokens=this.tokens),n}parseExpression(n,e){return n?this.disallowInAnd(()=>this.parseExpressionBase(e)):this.allowInAnd(()=>this.parseExpressionBase(e))}parseExpressionBase(n){let e=this.state.startLoc,r=this.parseMaybeAssign(n);if(this.match(12)){let i=this.startNodeAt(e);for(i.expressions=[r];this.eat(12);)i.expressions.push(this.parseMaybeAssign(n));return this.toReferencedList(i.expressions),this.finishNode(i,"SequenceExpression")}return r}parseMaybeAssignDisallowIn(n,e){return this.disallowInAnd(()=>this.parseMaybeAssign(n,e))}parseMaybeAssignAllowIn(n,e){return this.allowInAnd(()=>this.parseMaybeAssign(n,e))}setOptionalParametersError(n){n.optionalParametersLoc=this.state.startLoc}parseMaybeAssign(n,e){let r=this.state.startLoc,i=this.isContextual(108);if(i&&this.prodParam.hasYield){this.next();let d=this.parseYield(r);return e&&(d=e.call(this,d,r)),d}let s;n?s=!1:(n=new dr,s=!0);let{type:a}=this.state;(a===10||se(a))&&(this.state.potentialArrowAt=this.state.start);let o=this.parseMaybeConditional(n);if(e&&(o=e.call(this,o,r)),$k(this.state.type)){let d=this.startNodeAt(r),c=this.state.value;if(d.operator=c,this.match(29)){this.toAssignable(o,!0),d.left=o;let l=r.index;n.doubleProtoLoc!=null&&n.doubleProtoLoc.index>=l&&(n.doubleProtoLoc=null),n.shorthandAssignLoc!=null&&n.shorthandAssignLoc.index>=l&&(n.shorthandAssignLoc=null),n.privateKeyLoc!=null&&n.privateKeyLoc.index>=l&&(this.checkDestructuringPrivate(n),n.privateKeyLoc=null),n.voidPatternLoc!=null&&n.voidPatternLoc.index>=l&&(n.voidPatternLoc=null)}else d.left=o;return this.next(),d.right=this.parseMaybeAssign(),this.checkLVal(o,this.finishNode(d,"AssignmentExpression"),void 0,void 0,void 0,void 0,c==="||="||c==="&&="||c==="??="),d}else s&&this.checkExpressionErrors(n,!0);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?hi(d):hi(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.YieldNotInGeneratorFunction,r),this.parseYield(r)}return o}parseMaybeConditional(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,i=this.parseExprOps(n);return this.shouldExitDescending(i,r)?i:this.parseConditional(i,e,n)}parseConditional(n,e,r){if(this.eat(17)){let i=this.startNodeAt(e);return i.test=n,i.consequent=this.parseMaybeAssignAllowIn(),this.expect(14),i.alternate=this.parseMaybeAssign(),this.finishNode(i,"ConditionalExpression")}return n}parseMaybeUnaryOrPrivate(n){return this.match(139)?this.parsePrivateName():this.parseMaybeUnary(n)}parseExprOps(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,i=this.parseMaybeUnaryOrPrivate(n);return this.shouldExitDescending(i,r)?i:this.parseExprOp(i,e,-1)}parseExprOp(n,e,r){if(this.isPrivateName(n)){let s=this.getPrivateNameSV(n);(r>=Qs(58)||!this.prodParam.hasIn||!this.match(58))&&this.raise(b.PrivateInExpectedIn,n,{identifierName:s}),this.classScope.usePrivateName(s,n.loc.start)}let i=this.state.type;if(Lk(i)&&(this.prodParam.hasIn||!this.match(58))){let s=Qs(i);if(s>r){if(i===39){if(this.expectPlugin("pipelineOperator"),this.state.inFSharpPipelineDirectBody)return n;this.checkPipelineAtInfixOperator(n,e)}let a=this.startNodeAt(e);a.left=n,a.operator=this.state.value;let o=i===41||i===42,d=i===40;if(d&&(s=Qs(42)),this.next(),i===39&&this.hasPlugin(["pipelineOperator",{proposal:"minimal"}])&&this.state.type===96&&this.prodParam.hasAwait)throw this.raise(b.UnexpectedAwaitAfterPipelineBody,this.state.startLoc);a.right=this.parseExprOpRightExpr(i,s);let c=this.finishNode(a,o||d?"LogicalExpression":"BinaryExpression"),l=this.state.type;if(d&&(l===41||l===42)||o&&l===40)throw this.raise(b.MixingCoalesceWithLogical,this.state.startLoc);return this.parseExprOp(c,e,r)}}return n}parseExprOpRightExpr(n,e){let r=this.state.startLoc;switch(n){case 39:switch(this.getPluginOption("pipelineOperator","proposal")){case"hack":return this.withTopicBindingContext(()=>this.parseHackPipeBody());case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e))}if(this.getPluginOption("pipelineOperator","proposal")==="smart")return this.withTopicBindingContext(()=>{if(this.prodParam.hasYield&&this.isContextual(108))throw this.raise(b.PipeBodyIsTighter,this.state.startLoc);return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(n,e),r)});default:return this.parseExprOpBaseRightExpr(n,e)}}parseExprOpBaseRightExpr(n,e){let r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnaryOrPrivate(),r,Bk(n)?e-1:e)}parseHackPipeBody(){var n;let{startLoc:e}=this.state,r=this.parseMaybeAssign();return xk.has(r.type)&&!((n=r.extra)!=null&&n.parenthesized)&&this.raise(b.PipeUnparenthesizedBody,e,{type:r.type}),this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipeTopicUnused,e),r}checkExponentialAfterUnary(n){this.match(57)&&this.raise(b.UnexpectedTokenUnaryExponentiation,n.argument)}parseMaybeUnary(n,e){let r=this.state.startLoc,i=this.isContextual(96);if(i&&this.recordAwaitIfAllowed()){this.next();let d=this.parseAwait(r);return e||this.checkExponentialAfterUnary(d),d}let s=this.match(34),a=this.startNode();if(_k(this.state.type)){a.operator=this.state.value,a.prefix=!0,this.match(72)&&this.expectPlugin("throwExpressions");let d=this.match(89);if(this.next(),a.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(n,!0),this.state.strict&&d){let c=a.argument;c.type==="Identifier"?this.raise(b.StrictDelete,a):this.hasPropertyAsPrivateName(c)&&this.raise(b.DeletePrivateField,a)}if(!s)return e||this.checkExponentialAfterUnary(a),this.finishNode(a,"UnaryExpression")}let o=this.parseUpdate(a,s,n);if(i){let{type:d}=this.state;if((this.hasPlugin("v8intrinsic")?hi(d):hi(d)&&!this.match(54))&&!this.isAmbiguousPrefixOrIdentifier())return this.raiseOverwrite(b.AwaitNotInAsyncContext,r),this.parseAwait(r)}return o}parseUpdate(n,e,r){if(e){let a=n;return this.checkLVal(a.argument,this.finishNode(a,"UpdateExpression")),n}let i=this.state.startLoc,s=this.parseExprSubscripts(r);if(this.checkExpressionErrors(r,!1))return s;for(;Mk(this.state.type)&&!this.canInsertSemicolon();){let a=this.startNodeAt(i);a.operator=this.state.value,a.prefix=!1,a.argument=s,this.next(),this.checkLVal(s,s=this.finishNode(a,"UpdateExpression"))}return s}parseExprSubscripts(n){let e=this.state.startLoc,r=this.state.potentialArrowAt,i=this.parseExprAtom(n);return this.shouldExitDescending(i,r)?i:this.parseSubscripts(i,e)}parseSubscripts(n,e,r){let i={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(n),stop:!1};do n=this.parseSubscript(n,e,r,i),i.maybeAsyncArrow=!1;while(!i.stop);return n}parseSubscript(n,e,r,i){let{type:s}=this.state;if(!r&&s===15)return this.parseBind(n,e,i);if(ta(s))return this.parseTaggedTemplateExpression(n,e,i);let a=!1;if(s===18){if(r&&(this.raise(b.OptionalChainingNoNew,this.state.startLoc),this.lookaheadCharCode()===40))return this.stopParseSubscript(n,i);i.optionalChainMember=a=!0,this.next()}if(!r&&this.match(10))return this.parseCoverCallAndAsyncArrowHead(n,e,i,a);{let o=this.eat(0);return o||a||this.eat(16)?this.parseMember(n,e,i,o,a):this.stopParseSubscript(n,i)}}stopParseSubscript(n,e){return e.stop=!0,n}parseMember(n,e,r,i,s){let a=this.startNodeAt(e);return a.object=n,a.computed=i,i?(a.property=this.parseExpression(),this.expect(3)):this.match(139)?(n.type==="Super"&&this.raise(b.SuperPrivateField,e),this.classScope.usePrivateName(this.state.value,this.state.startLoc),a.property=this.parsePrivateName()):a.property=this.parseIdentifier(!0),r.optionalChainMember?(a.optional=s,this.finishNode(a,"OptionalMemberExpression")):this.finishNode(a,"MemberExpression")}parseBind(n,e,r){let i=this.startNodeAt(e);i.object=n,this.next();let s=this.match(83),a=this.parseNoCallExpr();if(a.type==="Super"||s&&a.type==="ImportExpression"||a.type==="Import")throw this.raise(b.UnsupportedBindRHS,a);return i.callee=a,r.stop=!0,this.parseSubscripts(this.finishNode(i,"BindExpression"),e,!1)}parseCoverCallAndAsyncArrowHead(n,e,r,i){let s=this.state.maybeInArrowParameters,a=null;this.state.maybeInArrowParameters=!0,this.next();let o=this.startNodeAt(e);o.callee=n;let{maybeAsyncArrow:d,optionalChainMember:c}=r;d&&(this.expressionScope.enter(hR()),a=new dr),c&&(o.optional=i),i?o.arguments=this.parseCallExpressionArguments():o.arguments=this.parseCallExpressionArguments(n.type!=="Super",o,a);let l=this.finishCallExpression(o,c);return d&&this.shouldParseAsyncArrow()&&!i?(r.stop=!0,this.checkDestructuringPrivate(a),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),l=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e),l)):(d&&(this.checkExpressionErrors(a,!0),this.expressionScope.exit()),this.toReferencedArguments(l)),this.state.maybeInArrowParameters=s,l}toReferencedArguments(n,e){this.toReferencedListDeep(n.arguments,e)}parseTaggedTemplateExpression(n,e,r){let i=this.startNodeAt(e);return i.tag=n,i.quasi=this.parseTemplate(!0),r.optionalChainMember&&this.raise(b.OptionalChainingNoTemplate,e),this.finishNode(i,"TaggedTemplateExpression")}atPossibleAsyncArrow(n){return n.type==="Identifier"&&n.name==="async"&&this.state.lastTokEndLoc.index===n.end&&!this.canInsertSemicolon()&&n.end-n.start===5&&this.offsetToSourcePos(n.start)===this.state.potentialArrowAt}finishCallExpression(n,e){if(n.callee.type==="Import")if(n.arguments.length===0||n.arguments.length>2)this.raise(b.ImportCallArity,n);else for(let r of n.arguments)r.type==="SpreadElement"&&this.raise(b.ImportCallSpreadArgument,r);return this.finishNode(n,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(n,e,r){let i=[],s=!0,a=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(11);){if(s)s=!1;else if(this.expect(12),this.match(11)){e&&this.addTrailingCommaExtraToNode(e),this.next();break}i.push(this.parseExprListItem(11,!1,r,n))}return this.state.inFSharpPipelineDirectBody=a,i}shouldParseAsyncArrow(){return this.match(19)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(n,e){var r;return this.resetPreviousNodeTrailingComments(e),this.expect(19),this.parseArrowExpression(n,e.arguments,!0,(r=e.extra)==null?void 0:r.trailingCommaLoc),e.innerComments&&bi(n,e.innerComments),e.callee.trailingComments&&bi(n,e.callee.trailingComments),n}parseNoCallExpr(){let n=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),n,!0)}parseExprAtom(n){let e,r=null,{type:i}=this.state;switch(i){case 79:return this.parseSuper();case 83:return e=this.startNode(),this.next(),this.match(16)?this.parseImportMetaPropertyOrPhaseCall(e):this.match(10)?this.optionFlags&512?this.parseImportCall(e):this.finishNode(e,"Import"):(this.raise(b.UnsupportedImport,this.state.lastTokStartLoc),this.finishNode(e,"Import"));case 78:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case 90:return this.parseDo(this.startNode(),!1);case 56:case 31:return this.readRegexp(),this.parseRegExpLiteral(this.state.value);case 135:return this.parseNumericLiteral(this.state.value);case 136:return this.parseBigIntLiteral(this.state.value);case 134:return this.parseStringLiteral(this.state.value);case 84:return this.parseNullLiteral();case 85:return this.parseBooleanLiteral(!0);case 86:return this.parseBooleanLiteral(!1);case 10:{let s=this.state.potentialArrowAt===this.state.start;return this.parseParenAndDistinguishExpression(s)}case 0:return this.parseArrayLike(3,!1,n);case 5:return this.parseObjectLike(8,!1,!1,n);case 68:return this.parseFunctionOrFunctionSent();case 26:r=this.parseDecorators();case 80:return this.parseClass(this.maybeTakeDecorators(r,this.startNode()),!1);case 77:return this.parseNewOrNewTarget();case 25:case 24:return this.parseTemplate(!1);case 15:{e=this.startNode(),this.next(),e.object=null;let s=e.callee=this.parseNoCallExpr();if(s.type==="MemberExpression")return this.finishNode(e,"BindExpression");throw this.raise(b.UnsupportedBind,s)}case 139:return this.raise(b.PrivateInExpectedIn,this.state.startLoc,{identifierName:this.state.value}),this.parsePrivateName();case 33:return this.parseTopicReferenceThenEqualsSign(54,"%");case 32:return this.parseTopicReferenceThenEqualsSign(44,"^");case 37:case 38:return this.parseTopicReference("hack");case 44:case 54:case 27:{let s=this.getPluginOption("pipelineOperator","proposal");if(s)return this.parseTopicReference(s);throw this.unexpected()}case 47:{let s=this.input.codePointAt(this.nextTokenStart());throw bt(s)||s===62?this.expectOnePlugin(["jsx","flow","typescript"]):this.unexpected()}default:if(i===137)return this.parseDecimalLiteral(this.state.value);if(i===2||i===1)return this.parseArrayLike(this.state.type===2?4:3,!0);if(i===6||i===7)return this.parseObjectLike(this.state.type===6?9:8,!1,!0);if(se(i)){if(this.isContextual(127)&&this.lookaheadInLineCharCode()===123)return this.parseModuleExpression();let s=this.state.potentialArrowAt===this.state.start,a=this.state.containsEsc,o=this.parseIdentifier();if(!a&&o.name==="async"&&!this.canInsertSemicolon()){let{type:d}=this.state;if(d===68)return this.resetPreviousNodeTrailingComments(o),this.next(),this.parseAsyncFunctionExpression(this.startNodeAtNode(o));if(se(d))return s&&this.lookaheadCharCode()===61?this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(o)):o;if(d===90)return this.resetPreviousNodeTrailingComments(o),this.parseDo(this.startNodeAtNode(o),!0)}return s&&this.match(19)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(this.startNodeAtNode(o),[o],!1)):o}else throw this.unexpected()}}parseTopicReferenceThenEqualsSign(n,e){let r=this.getPluginOption("pipelineOperator","proposal");if(r)return this.state.type=n,this.state.value=e,this.state.pos--,this.state.end--,this.state.endLoc=_e(this.state.endLoc,-1),this.parseTopicReference(r);throw this.unexpected()}parseTopicReference(n){let e=this.startNode(),r=this.state.startLoc,i=this.state.type;return this.next(),this.finishTopicReference(e,r,n,i)}finishTopicReference(n,e,r,i){if(this.testTopicReferenceConfiguration(r,e,i))return r==="hack"?(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PipeTopicUnbound,e),this.registerTopicReference(),this.finishNode(n,"TopicReference")):(this.topicReferenceIsAllowedInCurrentContext()||this.raise(b.PrimaryTopicNotAllowed,e),this.registerTopicReference(),this.finishNode(n,"PipelinePrimaryTopicReference"));throw this.raise(b.PipeTopicUnconfiguredToken,e,{token:Yt(i)})}testTopicReferenceConfiguration(n,e,r){switch(n){case"hack":return this.hasPlugin(["pipelineOperator",{topicToken:Yt(r)}]);case"smart":return r===27;default:throw this.raise(b.PipeTopicRequiresHackPipes,e)}}parseAsyncArrowUnaryFunction(n){this.prodParam.enter(Zs(!0,this.prodParam.hasYield));let e=[this.parseIdentifier()];return this.prodParam.exit(),this.hasPrecedingLineBreak()&&this.raise(b.LineTerminatorBeforeArrow,this.state.curPosition()),this.expect(19),this.parseArrowExpression(n,e,!0)}parseDo(n,e){this.expectPlugin("doExpressions"),e&&this.expectPlugin("asyncDoExpressions"),n.async=e,this.next();let r=this.state.labels;return this.state.labels=[],e?(this.prodParam.enter(2),n.body=this.parseBlock(),this.prodParam.exit()):n.body=this.parseBlock(),this.state.labels=r,this.finishNode(n,"DoExpression")}parseSuper(){let n=this.startNode();return this.next(),this.match(10)&&!this.scope.allowDirectSuper?this.optionFlags&16||this.raise(b.SuperNotAllowed,n):this.scope.allowSuper||this.optionFlags&16||this.raise(b.UnexpectedSuper,n),!this.match(10)&&!this.match(0)&&!this.match(16)&&this.raise(b.UnsupportedSuper,n),this.finishNode(n,"Super")}parsePrivateName(){let n=this.startNode(),e=this.startNodeAt(_e(this.state.startLoc,1)),r=this.state.value;return this.next(),n.id=this.createIdentifier(e,r),this.finishNode(n,"PrivateName")}parseFunctionOrFunctionSent(){let n=this.startNode();if(this.next(),this.prodParam.hasYield&&this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(n),"function");return this.next(),this.match(103)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected(),this.parseMetaProperty(n,e,"sent")}return this.parseFunction(n)}parseMetaProperty(n,e,r){n.meta=e;let i=this.state.containsEsc;return n.property=this.parseIdentifier(!0),(n.property.name!==r||i)&&this.raise(b.UnsupportedMetaProperty,n.property,{target:e.name,onlyValidPropertyName:r}),this.finishNode(n,"MetaProperty")}parseImportMetaPropertyOrPhaseCall(n){if(this.next(),this.isContextual(105)||this.isContextual(97)){let e=this.isContextual(105);return this.expectPlugin(e?"sourcePhaseImports":"deferredImportEvaluation"),this.next(),n.phase=e?"source":"defer",this.parseImportCall(n)}else{let e=this.createIdentifierAt(this.startNodeAtNode(n),"import",this.state.lastTokStartLoc);return this.isContextual(101)&&(this.inModule||this.raise(b.ImportMetaOutsideModule,e),this.sawUnambiguousESM=!0),this.parseMetaProperty(n,e,"meta")}}parseLiteralAtNode(n,e,r){return this.addExtra(r,"rawValue",n),this.addExtra(r,"raw",this.input.slice(this.offsetToSourcePos(r.start),this.state.end)),r.value=n,this.next(),this.finishNode(r,e)}parseLiteral(n,e){let r=this.startNode();return this.parseLiteralAtNode(n,e,r)}parseStringLiteral(n){return this.parseLiteral(n,"StringLiteral")}parseNumericLiteral(n){return this.parseLiteral(n,"NumericLiteral")}parseBigIntLiteral(n){return this.parseLiteral(n,"BigIntLiteral")}parseDecimalLiteral(n){return this.parseLiteral(n,"DecimalLiteral")}parseRegExpLiteral(n){let e=this.startNode();return this.addExtra(e,"raw",this.input.slice(this.offsetToSourcePos(e.start),this.state.end)),e.pattern=n.pattern,e.flags=n.flags,this.next(),this.finishNode(e,"RegExpLiteral")}parseBooleanLiteral(n){let e=this.startNode();return e.value=n,this.next(),this.finishNode(e,"BooleanLiteral")}parseNullLiteral(){let n=this.startNode();return this.next(),this.finishNode(n,"NullLiteral")}parseParenAndDistinguishExpression(n){let e=this.state.startLoc,r;this.next(),this.expressionScope.enter(fR());let i=this.state.maybeInArrowParameters,s=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.inFSharpPipelineDirectBody=!1;let a=this.state.startLoc,o=[],d=new dr,c=!0,l,u;for(;!this.match(11);){if(c)c=!1;else if(this.expect(12,d.optionalParametersLoc===null?null:d.optionalParametersLoc),this.match(11)){u=this.state.startLoc;break}if(this.match(21)){let h=this.state.startLoc;if(l=this.state.startLoc,o.push(this.parseParenItem(this.parseRestBinding(),h)),!this.checkCommaAfterRest(41))break}else o.push(this.parseMaybeAssignAllowInOrVoidPattern(11,d,this.parseParenItem))}let p=this.state.lastTokEndLoc;this.expect(11),this.state.maybeInArrowParameters=i,this.state.inFSharpPipelineDirectBody=s;let f=this.startNodeAt(e);return n&&this.shouldParseArrow(o)&&(f=this.parseArrow(f))?(this.checkDestructuringPrivate(d),this.expressionScope.validateAsPattern(),this.expressionScope.exit(),this.parseArrowExpression(f,o,!1),f):(this.expressionScope.exit(),o.length||this.unexpected(this.state.lastTokStartLoc),u&&this.unexpected(u),l&&this.unexpected(l),this.checkExpressionErrors(d,!0),this.toReferencedListDeep(o,!0),o.length>1?(r=this.startNodeAt(a),r.expressions=o,this.finishNode(r,"SequenceExpression"),this.resetEndLocation(r,p)):r=o[0],this.wrapParenthesis(e,r))}wrapParenthesis(n,e){if(!(this.optionFlags&1024))return this.addExtra(e,"parenthesized",!0),this.addExtra(e,"parenStart",n.index),this.takeSurroundingComments(e,n.index,this.state.lastTokEndLoc.index),e;let r=this.startNodeAt(n);return r.expression=e,this.finishNode(r,"ParenthesizedExpression")}shouldParseArrow(n){return!this.canInsertSemicolon()}parseArrow(n){if(this.eat(19))return n}parseParenItem(n,e){return n}parseNewOrNewTarget(){let n=this.startNode();if(this.next(),this.match(16)){let e=this.createIdentifier(this.startNodeAtNode(n),"new");this.next();let r=this.parseMetaProperty(n,e,"target");return this.scope.allowNewTarget||this.raise(b.UnexpectedNewTarget,r),r}return this.parseNew(n)}parseNew(n){if(this.parseNewCallee(n),this.eat(10)){let e=this.parseExprList(11);this.toReferencedList(e),n.arguments=e}else n.arguments=[];return this.finishNode(n,"NewExpression")}parseNewCallee(n){let e=this.match(83),r=this.parseNoCallExpr();n.callee=r,(e&&r.type==="ImportExpression"||r.type==="Import")&&this.raise(b.ImportCallNotNewExpression,r),r.type==="Super"&&this.raise(b.SuperCallNotNewExpression,r)}parseTemplateElement(n){let{start:e,startLoc:r,end:i,value:s}=this.state,a=e+1,o=this.startNodeAt(_e(r,1));s===null&&(n||this.raise(b.InvalidEscapeSequenceTemplate,_e(this.state.firstInvalidTemplateEscapePos,1)));let d=this.match(24),c=d?-1:-2,l=i+c;o.value={raw:this.input.slice(a,l).replace(/\r\n?/g,`
10
+ `),cooked:s===null?null:s.slice(1,c)},o.tail=d,this.next();let u=this.finishNode(o,"TemplateElement");return this.resetEndLocation(u,_e(this.state.lastTokEndLoc,c)),u}parseTemplate(n){let e=this.startNode(),r=this.parseTemplateElement(n),i=[r],s=[];for(;!r.tail;)s.push(this.parseTemplateSubstitution()),this.readTemplateContinuation(),i.push(r=this.parseTemplateElement(n));return e.expressions=s,e.quasis=i,this.finishNode(e,"TemplateLiteral")}parseTemplateSubstitution(){return this.parseExpression()}parseObjectLike(n,e,r,i){r&&this.expectPlugin("recordAndTuple");let s=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let a=!1,o=!0,d=this.startNode();for(d.properties=[],this.next();!this.match(n);){if(o)o=!1;else if(this.expect(12),this.match(n)){this.addTrailingCommaExtraToNode(d);break}let l;e?l=this.parseBindingProperty():(l=this.parsePropertyDefinition(i),a=this.checkProto(l,r,a,i)),r&&!this.isObjectProperty(l)&&l.type!=="SpreadElement"&&this.raise(b.InvalidRecordProperty,l),l.shorthand&&this.addExtra(l,"shorthand",!0),d.properties.push(l)}this.next(),this.state.inFSharpPipelineDirectBody=s;let c="ObjectExpression";return e?c="ObjectPattern":r&&(c="RecordExpression"),this.finishNode(d,c)}addTrailingCommaExtraToNode(n){this.addExtra(n,"trailingComma",this.state.lastTokStartLoc.index),this.addExtra(n,"trailingCommaLoc",this.state.lastTokStartLoc,!1)}maybeAsyncOrAccessorProp(n){return!n.computed&&n.key.type==="Identifier"&&(this.isLiteralPropertyName()||this.match(0)||this.match(55))}parsePropertyDefinition(n){let e=[];if(this.match(26))for(this.hasPlugin("decorators")&&this.raise(b.UnsupportedPropertyDecorator,this.state.startLoc);this.match(26);)e.push(this.parseDecorator());let r=this.startNode(),i=!1,s=!1,a;if(this.match(21))return e.length&&this.unexpected(),this.parseSpread();e.length&&(r.decorators=e,e=[]),r.method=!1,n&&(a=this.state.startLoc);let o=this.eat(55);this.parsePropertyNamePrefixOperator(r);let d=this.state.containsEsc;if(this.parsePropertyName(r,n),!o&&!d&&this.maybeAsyncOrAccessorProp(r)){let{key:c}=r,l=c.name;l==="async"&&!this.hasPrecedingLineBreak()&&(i=!0,this.resetPreviousNodeTrailingComments(c),o=this.eat(55),this.parsePropertyName(r)),(l==="get"||l==="set")&&(s=!0,this.resetPreviousNodeTrailingComments(c),r.kind=l,this.match(55)&&(o=!0,this.raise(b.AccessorIsGenerator,this.state.curPosition(),{kind:l}),this.next()),this.parsePropertyName(r))}return this.parseObjPropValue(r,a,o,i,!1,s,n)}getGetterSetterExpectedParamCount(n){return n.kind==="get"?0:1}getObjectOrClassMethodParams(n){return n.params}checkGetterSetterParams(n){var e;let r=this.getGetterSetterExpectedParamCount(n),i=this.getObjectOrClassMethodParams(n);i.length!==r&&this.raise(n.kind==="get"?b.BadGetterArity:b.BadSetterArity,n),n.kind==="set"&&((e=i[i.length-1])==null?void 0:e.type)==="RestElement"&&this.raise(b.BadSetterRestParameter,n)}parseObjectMethod(n,e,r,i,s){if(s){let a=this.parseMethod(n,e,!1,!1,!1,"ObjectMethod");return this.checkGetterSetterParams(a),a}if(r||e||this.match(10))return i&&this.unexpected(),n.kind="method",n.method=!0,this.parseMethod(n,e,r,!1,!1,"ObjectMethod")}parseObjectProperty(n,e,r,i){if(n.shorthand=!1,this.eat(14))return n.value=r?this.parseMaybeDefault(this.state.startLoc):this.parseMaybeAssignAllowInOrVoidPattern(8,i),this.finishObjectProperty(n);if(!n.computed&&n.key.type==="Identifier"){if(this.checkReservedWord(n.key.name,n.key.loc.start,!0,!1),r)n.value=this.parseMaybeDefault(e,this.cloneIdentifier(n.key));else if(this.match(29)){let s=this.state.startLoc;i!=null?i.shorthandAssignLoc===null&&(i.shorthandAssignLoc=s):this.raise(b.InvalidCoverInitializedName,s),n.value=this.parseMaybeDefault(e,this.cloneIdentifier(n.key))}else n.value=this.cloneIdentifier(n.key);return n.shorthand=!0,this.finishObjectProperty(n)}}finishObjectProperty(n){return this.finishNode(n,"ObjectProperty")}parseObjPropValue(n,e,r,i,s,a,o){let d=this.parseObjectMethod(n,r,i,s,a)||this.parseObjectProperty(n,e,s,o);return d||this.unexpected(),d}parsePropertyName(n,e){if(this.eat(0))n.computed=!0,n.key=this.parseMaybeAssignAllowIn(),this.expect(3);else{let{type:r,value:i}=this.state,s;if(dt(r))s=this.parseIdentifier(!0);else switch(r){case 135:s=this.parseNumericLiteral(i);break;case 134:s=this.parseStringLiteral(i);break;case 136:s=this.parseBigIntLiteral(i);break;case 139:{let a=this.state.startLoc;e!=null?e.privateKeyLoc===null&&(e.privateKeyLoc=a):this.raise(b.UnexpectedPrivateField,a),s=this.parsePrivateName();break}default:if(r===137){s=this.parseDecimalLiteral(i);break}this.unexpected()}n.key=s,r!==139&&(n.computed=!1)}}initFunction(n,e){n.id=null,n.generator=!1,n.async=e}parseMethod(n,e,r,i,s,a,o=!1){this.initFunction(n,r),n.generator=e,this.scope.enter(530|(o?576:0)|(s?32:0)),this.prodParam.enter(Zs(r,n.generator)),this.parseFunctionParams(n,i);let d=this.parseFunctionBodyAndFinish(n,a,!0);return this.prodParam.exit(),this.scope.exit(),d}parseArrayLike(n,e,r){e&&this.expectPlugin("recordAndTuple");let i=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;let s=this.startNode();return this.next(),s.elements=this.parseExprList(n,!e,r,s),this.state.inFSharpPipelineDirectBody=i,this.finishNode(s,e?"TupleExpression":"ArrayExpression")}parseArrowExpression(n,e,r,i){this.scope.enter(518);let s=Zs(r,!1);!this.match(5)&&this.prodParam.hasIn&&(s|=8),this.prodParam.enter(s),this.initFunction(n,r);let a=this.state.maybeInArrowParameters;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(n,e,i)),this.state.maybeInArrowParameters=!1,this.parseFunctionBody(n,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=a,this.finishNode(n,"ArrowFunctionExpression")}setArrowFunctionParameters(n,e,r){this.toAssignableList(e,r,!1),n.params=e}parseFunctionBodyAndFinish(n,e,r=!1){return this.parseFunctionBody(n,!1,r),this.finishNode(n,e)}parseFunctionBody(n,e,r=!1){let i=e&&!this.match(5);if(this.expressionScope.enter(th()),i)n.body=this.parseMaybeAssign(),this.checkParams(n,!1,e,!1);else{let s=this.state.strict,a=this.state.labels;this.state.labels=[],this.prodParam.enter(this.prodParam.currentFlags()|4),n.body=this.parseBlock(!0,!1,o=>{let d=!this.isSimpleParamList(n.params);o&&d&&this.raise(b.IllegalLanguageModeDirective,(n.kind==="method"||n.kind==="constructor")&&n.key?n.key.loc.end:n);let c=!s&&this.state.strict;this.checkParams(n,!this.state.strict&&!e&&!r&&!d,e,c),this.state.strict&&n.id&&this.checkIdentifier(n.id,65,c)}),this.prodParam.exit(),this.state.labels=a}this.expressionScope.exit()}isSimpleParameter(n){return n.type==="Identifier"}isSimpleParamList(n){for(let e=0,r=n.length;e<r;e++)if(!this.isSimpleParameter(n[e]))return!1;return!0}checkParams(n,e,r,i=!0){let s=!e&&new Set,a={type:"FormalParameters"};for(let o of n.params)this.checkLVal(o,a,5,s,i)}parseExprList(n,e,r,i){let s=[],a=!0;for(;!this.eat(n);){if(a)a=!1;else if(this.expect(12),this.match(n)){i&&this.addTrailingCommaExtraToNode(i),this.next();break}s.push(this.parseExprListItem(n,e,r))}return s}parseExprListItem(n,e,r,i){let s;if(this.match(12))e||this.raise(b.UnexpectedToken,this.state.curPosition(),{unexpected:","}),s=null;else if(this.match(21)){let a=this.state.startLoc;s=this.parseParenItem(this.parseSpread(r),a)}else if(this.match(17)){this.expectPlugin("partialApplication"),i||this.raise(b.UnexpectedArgumentPlaceholder,this.state.startLoc);let a=this.startNode();this.next(),s=this.finishNode(a,"ArgumentPlaceholder")}else s=this.parseMaybeAssignAllowInOrVoidPattern(n,r,this.parseParenItem);return s}parseIdentifier(n){let e=this.startNode(),r=this.parseIdentifierName(n);return this.createIdentifier(e,r)}createIdentifier(n,e){return n.name=e,n.loc.identifierName=e,this.finishNode(n,"Identifier")}createIdentifierAt(n,e,r){return n.name=e,n.loc.identifierName=e,this.finishNodeAt(n,"Identifier",r)}parseIdentifierName(n){let e,{startLoc:r,type:i}=this.state;dt(i)?e=this.state.value:this.unexpected();let s=Nk(i);return n?s&&this.replaceToken(132):this.checkReservedWord(e,r,s,!1),this.next(),e}checkReservedWord(n,e,r,i){if(n.length>10||!Yk(n))return;if(r&&Kk(n)){this.raise(b.UnexpectedKeyword,e,{keyword:n});return}if((this.state.strict?i?Xf:Jf:Wf)(n,this.inModule)){this.raise(b.UnexpectedReservedWord,e,{reservedWord:n});return}else if(n==="yield"){if(this.prodParam.hasYield){this.raise(b.YieldBindingIdentifier,e);return}}else if(n==="await"){if(this.prodParam.hasAwait){this.raise(b.AwaitBindingIdentifier,e);return}if(this.scope.inStaticBlock){this.raise(b.AwaitBindingIdentifierInStaticBlock,e);return}this.expressionScope.recordAsyncArrowParametersError(e)}else if(n==="arguments"&&this.scope.inClassAndNotInNonArrowFunction){this.raise(b.ArgumentsInClass,e);return}}recordAwaitIfAllowed(){let n=this.prodParam.hasAwait;return n&&!this.scope.inFunction&&(this.state.hasTopLevelAwait=!0),n}parseAwait(n){let e=this.startNodeAt(n);return this.expressionScope.recordParameterInitializerError(b.AwaitExpressionFormalParameter,e),this.eat(55)&&this.raise(b.ObsoleteAwaitStar,e),!this.scope.inFunction&&!(this.optionFlags&1)&&(this.isAmbiguousPrefixOrIdentifier()?this.ambiguousScriptDifferentAst=!0:this.sawUnambiguousESM=!0),this.state.soloAwait||(e.argument=this.parseMaybeUnary(null,!0)),this.finishNode(e,"AwaitExpression")}isAmbiguousPrefixOrIdentifier(){if(this.hasPrecedingLineBreak())return!0;let{type:n}=this.state;return n===53||n===10||n===0||ta(n)||n===102&&!this.state.containsEsc||n===138||n===56||this.hasPlugin("v8intrinsic")&&n===54}parseYield(n){let e=this.startNodeAt(n);this.expressionScope.recordParameterInitializerError(b.YieldInParameter,e);let r=!1,i=null;if(!this.hasPrecedingLineBreak())switch(r=this.eat(55),this.state.type){case 13:case 140:case 8:case 11:case 3:case 9:case 14:case 12:if(!r)break;default:i=this.parseMaybeAssign()}return e.delegate=r,e.argument=i,this.finishNode(e,"YieldExpression")}parseImportCall(n){if(this.next(),n.source=this.parseMaybeAssignAllowIn(),n.options=null,this.eat(12)){if(this.match(11))this.addTrailingCommaExtraToNode(n.source);else if(n.options=this.parseMaybeAssignAllowIn(),this.eat(12)&&(this.addTrailingCommaExtraToNode(n.options),!this.match(11))){do this.parseMaybeAssignAllowIn();while(this.eat(12)&&!this.match(11));this.raise(b.ImportCallArity,n)}}return this.expect(11),this.finishNode(n,"ImportExpression")}checkPipelineAtInfixOperator(n,e){this.hasPlugin(["pipelineOperator",{proposal:"smart"}])&&n.type==="SequenceExpression"&&this.raise(b.PipelineHeadSequenceExpression,e)}parseSmartPipelineBodyInStyle(n,e){if(this.isSimpleReference(n)){let r=this.startNodeAt(e);return r.callee=n,this.finishNode(r,"PipelineBareFunction")}else{let r=this.startNodeAt(e);return this.checkSmartPipeTopicBodyEarlyErrors(e),r.expression=n,this.finishNode(r,"PipelineTopicExpression")}}isSimpleReference(n){switch(n.type){case"MemberExpression":return!n.computed&&this.isSimpleReference(n.object);case"Identifier":return!0;default:return!1}}checkSmartPipeTopicBodyEarlyErrors(n){if(this.match(19))throw this.raise(b.PipelineBodyNoArrow,this.state.startLoc);this.topicReferenceWasUsedInCurrentContext()||this.raise(b.PipelineTopicUnused,n)}withTopicBindingContext(n){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:1,maxTopicIndex:null};try{return n()}finally{this.state.topicContext=e}}withSmartMixTopicForbiddingContext(n){if(this.hasPlugin(["pipelineOperator",{proposal:"smart"}])){let e=this.state.topicContext;this.state.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null};try{return n()}finally{this.state.topicContext=e}}else return n()}withSoloAwaitPermittingContext(n){let e=this.state.soloAwait;this.state.soloAwait=!0;try{return n()}finally{this.state.soloAwait=e}}allowInAnd(n){let e=this.prodParam.currentFlags();if(8&~e){this.prodParam.enter(e|8);try{return n()}finally{this.prodParam.exit()}}return n()}disallowInAnd(n){let e=this.prodParam.currentFlags();if(8&e){this.prodParam.enter(e&-9);try{return n()}finally{this.prodParam.exit()}}return n()}registerTopicReference(){this.state.topicContext.maxTopicIndex=0}topicReferenceIsAllowedInCurrentContext(){return this.state.topicContext.maxNumOfResolvableTopics>=1}topicReferenceWasUsedInCurrentContext(){return this.state.topicContext.maxTopicIndex!=null&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(n){let e=this.state.startLoc;this.state.potentialArrowAt=this.state.start;let r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;let i=this.parseExprOp(this.parseMaybeUnaryOrPrivate(),e,n);return this.state.inFSharpPipelineDirectBody=r,i}parseModuleExpression(){this.expectPlugin("moduleBlocks");let n=this.startNode();this.next(),this.match(5)||this.unexpected(null,5);let e=this.startNodeAt(this.state.endLoc);this.next();let r=this.initializeScopes(!0);this.enterInitialScopes();try{n.body=this.parseProgram(e,8,"module")}finally{r()}return this.finishNode(n,"ModuleExpression")}parseVoidPattern(n){this.expectPlugin("discardBinding");let e=this.startNode();return n!=null&&(n.voidPatternLoc=this.state.startLoc),this.next(),this.finishNode(e,"VoidPattern")}parseMaybeAssignAllowInOrVoidPattern(n,e,r){if(e!=null&&this.match(88)){let i=this.lookaheadCharCode();if(i===44||i===(n===3?93:n===8?125:41)||i===61)return this.parseMaybeDefault(this.state.startLoc,this.parseVoidPattern(e))}return this.parseMaybeAssignAllowIn(e,r)}parsePropertyNamePrefixOperator(n){}},Gd={kind:1},TR={kind:2},PR=/[\uD800-\uDFFF]/u,Kd=/in(?:stanceof)?/y;function SR(t,n,e){for(let r=0;r<t.length;r++){let i=t[r],{type:s}=i;if(typeof s=="number"){if(s===139){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=_e(a.start,1);t.splice(r,1,new wt({type:Et(27),value:"#",start:o,end:l,startLoc:a.start,endLoc:u}),new wt({type:Et(132),value:d,start:l,end:c,startLoc:u,endLoc:a.end})),r++;continue}if(ta(s)){let{loc:a,start:o,value:d,end:c}=i,l=o+1,u=_e(a.start,1),p;n.charCodeAt(o-e)===96?p=new wt({type:Et(22),value:"`",start:o,end:l,startLoc:a.start,endLoc:u}):p=new wt({type:Et(8),value:"}",start:o,end:l,startLoc:a.start,endLoc:u});let f,h,m,g;s===24?(h=c-1,m=_e(a.end,-1),f=d===null?null:d.slice(1,-1),g=new wt({type:Et(22),value:"`",start:h,end:c,startLoc:m,endLoc:a.end})):(h=c-2,m=_e(a.end,-2),f=d===null?null:d.slice(1,-2),g=new wt({type:Et(23),value:"${",start:h,end:c,startLoc:m,endLoc:a.end})),t.splice(r,1,p,new wt({type:Et(20),value:f,start:l,end:h,startLoc:u,endLoc:m}),g),r+=2;continue}i.type=Et(s)}}return t}var hc=class extends fc{parseTopLevel(n,e){return n.program=this.parseProgram(e,140,this.options.sourceType==="module"?"module":"script"),n.comments=this.comments,this.optionFlags&256&&(n.tokens=SR(this.tokens,this.input,this.startIndex)),this.finishNode(n,"File")}parseProgram(n,e,r){if(n.sourceType=r,n.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(n,!0,!0,e),this.inModule){if(!(this.optionFlags&64)&&this.scope.undefinedExports.size>0)for(let[s,a]of Array.from(this.scope.undefinedExports))this.raise(b.ModuleExportUndefined,a,{localName:s});this.addExtra(n,"topLevelAwait",this.state.hasTopLevelAwait)}let i;return e===140?i=this.finishNode(n,"Program"):i=this.finishNodeAt(n,"Program",_e(this.state.startLoc,-1)),i}stmtToDirective(n){let e=this.castNodeTo(n,"Directive"),r=this.castNodeTo(n.expression,"DirectiveLiteral"),i=r.value,s=this.input.slice(this.offsetToSourcePos(r.start),this.offsetToSourcePos(r.end)),a=r.value=s.slice(1,-1);return this.addExtra(r,"raw",s),this.addExtra(r,"rawValue",a),this.addExtra(r,"expressionValue",i),e.value=r,delete n.expression,e}parseInterpreterDirective(){if(!this.match(28))return null;let n=this.startNode();return n.value=this.state.value,this.next(),this.finishNode(n,"InterpreterDirective")}isLet(){return this.isContextual(100)?this.hasFollowingBindingAtom():!1}isUsing(){return this.isContextual(107)?this.nextTokenIsIdentifierOnSameLine():!1}isForUsing(){if(!this.isContextual(107))return!1;let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);if(this.isUnparsedContextual(n,"of")){let r=this.lookaheadCharCodeSince(n+2);if(r!==61&&r!==58&&r!==59)return!1}return!!(this.chStartsBindingIdentifier(e,n)||this.isUnparsedContextual(n,"void"))}nextTokenIsIdentifierOnSameLine(){let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);return this.chStartsBindingIdentifier(e,n)}isAwaitUsing(){if(!this.isContextual(96))return!1;let n=this.nextTokenInLineStart();if(this.isUnparsedContextual(n,"using")){n=this.nextTokenInLineStartSince(n+5);let e=this.codePointAtPos(n);if(this.chStartsBindingIdentifier(e,n))return!0}return!1}chStartsBindingIdentifier(n,e){if(bt(n)){if(Kd.lastIndex=e,Kd.test(this.input)){let r=this.codePointAtPos(Kd.lastIndex);if(!wn(r)&&r!==92)return!1}return!0}else return n===92}chStartsBindingPattern(n){return n===91||n===123}hasFollowingBindingAtom(){let n=this.nextTokenStart(),e=this.codePointAtPos(n);return this.chStartsBindingPattern(e)||this.chStartsBindingIdentifier(e,n)}hasInLineFollowingBindingIdentifierOrBrace(){let n=this.nextTokenInLineStart(),e=this.codePointAtPos(n);return e===123||this.chStartsBindingIdentifier(e,n)}allowsUsing(){return(this.scope.inModule||!this.scope.inTopLevel)&&!this.scope.inBareCaseStatement}parseModuleItem(){return this.parseStatementLike(15)}parseStatementListItem(){return this.parseStatementLike(6|(!this.options.annexB||this.state.strict?0:8))}parseStatementOrSloppyAnnexBFunctionDeclaration(n=!1){let e=0;return this.options.annexB&&!this.state.strict&&(e|=4,n&&(e|=8)),this.parseStatementLike(e)}parseStatement(){return this.parseStatementLike(0)}parseStatementLike(n){let e=null;return this.match(26)&&(e=this.parseDecorators(!0)),this.parseStatementContent(n,e)}parseStatementContent(n,e){let r=this.state.type,i=this.startNode(),s=!!(n&2),a=!!(n&4),o=n&1;switch(r){case 60:return this.parseBreakContinueStatement(i,!0);case 63:return this.parseBreakContinueStatement(i,!1);case 64:return this.parseDebuggerStatement(i);case 90:return this.parseDoWhileStatement(i);case 91:return this.parseForStatement(i);case 68:if(this.lookaheadCharCode()===46)break;return a||this.raise(this.state.strict?b.StrictFunction:this.options.annexB?b.SloppyFunctionAnnexB:b.SloppyFunction,this.state.startLoc),this.parseFunctionStatement(i,!1,!s&&a);case 80:return s||this.unexpected(),this.parseClass(this.maybeTakeDecorators(e,i),!0);case 69:return this.parseIfStatement(i);case 70:return this.parseReturnStatement(i);case 71:return this.parseSwitchStatement(i);case 72:return this.parseThrowStatement(i);case 73:return this.parseTryStatement(i);case 96:if(this.isAwaitUsing())return this.allowsUsing()?s?this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,i):this.raise(b.UnexpectedLexicalDeclaration,i):this.raise(b.UnexpectedUsingDeclaration,i),this.next(),this.parseVarStatement(i,"await using");break;case 107:if(this.state.containsEsc||!this.hasInLineFollowingBindingIdentifierOrBrace())break;return this.allowsUsing()?s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc):this.raise(b.UnexpectedUsingDeclaration,this.state.startLoc),this.parseVarStatement(i,"using");case 100:{if(this.state.containsEsc)break;let l=this.nextTokenStart(),u=this.codePointAtPos(l);if(u!==91&&(!s&&this.hasFollowingLineBreak()||!this.chStartsBindingIdentifier(u,l)&&u!==123))break}case 75:s||this.raise(b.UnexpectedLexicalDeclaration,this.state.startLoc);case 74:{let l=this.state.value;return this.parseVarStatement(i,l)}case 92:return this.parseWhileStatement(i);case 76:return this.parseWithStatement(i);case 5:return this.parseBlock();case 13:return this.parseEmptyStatement(i);case 83:{let l=this.lookaheadCharCode();if(l===40||l===46)break}case 82:{!(this.optionFlags&8)&&!o&&this.raise(b.UnexpectedImportExport,this.state.startLoc),this.next();let l;return r===83?l=this.parseImport(i):l=this.parseExport(i,e),this.assertModuleNodeAllowed(l),l}default:if(this.isAsyncFunction())return s||this.raise(b.AsyncFunctionInSingleStatementContext,this.state.startLoc),this.next(),this.parseFunctionStatement(i,!0,!s&&a)}let d=this.state.value,c=this.parseExpression();return se(r)&&c.type==="Identifier"&&this.eat(14)?this.parseLabeledStatement(i,d,c,n):this.parseExpressionStatement(i,c,e)}assertModuleNodeAllowed(n){!(this.optionFlags&8)&&!this.inModule&&this.raise(b.ImportOutsideModule,n)}decoratorsEnabledBeforeExport(){return this.hasPlugin("decorators-legacy")?!0:this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")!==!1}maybeTakeDecorators(n,e,r){if(n){var i;(i=e.decorators)!=null&&i.length?(typeof this.getPluginOption("decorators","decoratorsBeforeExport")!="boolean"&&this.raise(b.DecoratorsBeforeAfterExport,e.decorators[0]),e.decorators.unshift(...n)):e.decorators=n,this.resetStartLocationFromNode(e,n[0]),r&&this.resetStartLocationFromNode(r,e)}return e}canHaveLeadingDecorator(){return this.match(80)}parseDecorators(n){let e=[];do e.push(this.parseDecorator());while(this.match(26));if(this.match(82))n||this.unexpected(),this.decoratorsEnabledBeforeExport()||this.raise(b.DecoratorExportClass,this.state.startLoc);else if(!this.canHaveLeadingDecorator())throw this.raise(b.UnexpectedLeadingDecorator,this.state.startLoc);return e}parseDecorator(){this.expectOnePlugin(["decorators","decorators-legacy"]);let n=this.startNode();if(this.next(),this.hasPlugin("decorators")){let e=this.state.startLoc,r;if(this.match(10)){let i=this.state.startLoc;this.next(),r=this.parseExpression(),this.expect(11),r=this.wrapParenthesis(i,r);let s=this.state.startLoc;n.expression=this.parseMaybeDecoratorArguments(r,i),this.getPluginOption("decorators","allowCallParenthesized")===!1&&n.expression!==r&&this.raise(b.DecoratorArgumentsOutsideParentheses,s)}else{for(r=this.parseIdentifier(!1);this.eat(16);){let i=this.startNodeAt(e);i.object=r,this.match(139)?(this.classScope.usePrivateName(this.state.value,this.state.startLoc),i.property=this.parsePrivateName()):i.property=this.parseIdentifier(!0),i.computed=!1,r=this.finishNode(i,"MemberExpression")}n.expression=this.parseMaybeDecoratorArguments(r,e)}}else n.expression=this.parseExprSubscripts();return this.finishNode(n,"Decorator")}parseMaybeDecoratorArguments(n,e){if(this.eat(10)){let r=this.startNodeAt(e);return r.callee=n,r.arguments=this.parseCallExpressionArguments(),this.toReferencedList(r.arguments),this.finishNode(r,"CallExpression")}return n}parseBreakContinueStatement(n,e){return this.next(),this.isLineTerminator()?n.label=null:(n.label=this.parseIdentifier(),this.semicolon()),this.verifyBreakContinue(n,e),this.finishNode(n,e?"BreakStatement":"ContinueStatement")}verifyBreakContinue(n,e){let r;for(r=0;r<this.state.labels.length;++r){let i=this.state.labels[r];if((n.label==null||i.name===n.label.name)&&(i.kind!=null&&(e||i.kind===1)||n.label&&e))break}if(r===this.state.labels.length){let i=e?"BreakStatement":"ContinueStatement";this.raise(b.IllegalBreakContinue,n,{type:i})}}parseDebuggerStatement(n){return this.next(),this.semicolon(),this.finishNode(n,"DebuggerStatement")}parseHeaderExpression(){this.expect(10);let n=this.parseExpression();return this.expect(11),n}parseDoWhileStatement(n){return this.next(),this.state.labels.push(Gd),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.expect(92),n.test=this.parseHeaderExpression(),this.eat(13),this.finishNode(n,"DoWhileStatement")}parseForStatement(n){this.next(),this.state.labels.push(Gd);let e=null;if(this.isContextual(96)&&this.recordAwaitIfAllowed()&&(e=this.state.startLoc,this.next()),this.scope.enter(0),this.expect(10),this.match(13))return e!==null&&this.unexpected(e),this.parseFor(n,null);let r=this.isContextual(100);{let d=this.isAwaitUsing(),c=d||this.isForUsing(),l=r&&this.hasFollowingBindingAtom()||c;if(this.match(74)||this.match(75)||l){let u=this.startNode(),p;d?(p="await using",this.recordAwaitIfAllowed()||this.raise(b.AwaitUsingNotInAsyncContext,this.state.startLoc),this.next()):p=this.state.value,this.next(),this.parseVar(u,!0,p);let f=this.finishNode(u,"VariableDeclaration"),h=this.match(58);return h&&c&&this.raise(b.ForInUsing,f),(h||this.isContextual(102))&&f.declarations.length===1?this.parseForIn(n,f,e):(e!==null&&this.unexpected(e),this.parseFor(n,f))}}let i=this.isContextual(95),s=new dr,a=this.parseExpression(!0,s),o=this.isContextual(102);if(o&&(r&&this.raise(b.ForOfLet,a),e===null&&i&&a.type==="Identifier"&&this.raise(b.ForOfAsync,a)),o||this.match(58)){this.checkDestructuringPrivate(s),this.toAssignable(a,!0);let d=o?"ForOfStatement":"ForInStatement";return this.checkLVal(a,{type:d}),this.parseForIn(n,a,e)}else this.checkExpressionErrors(s,!0);return e!==null&&this.unexpected(e),this.parseFor(n,a)}parseFunctionStatement(n,e,r){return this.next(),this.parseFunction(n,1|(r?2:0)|(e?8:0))}parseIfStatement(n){return this.next(),n.test=this.parseHeaderExpression(),n.consequent=this.parseStatementOrSloppyAnnexBFunctionDeclaration(),n.alternate=this.eat(66)?this.parseStatementOrSloppyAnnexBFunctionDeclaration():null,this.finishNode(n,"IfStatement")}parseReturnStatement(n){return this.prodParam.hasReturn||this.raise(b.IllegalReturn,this.state.startLoc),this.next(),this.isLineTerminator()?n.argument=null:(n.argument=this.parseExpression(),this.semicolon()),this.finishNode(n,"ReturnStatement")}parseSwitchStatement(n){this.next(),n.discriminant=this.parseHeaderExpression();let e=n.cases=[];this.expect(5),this.state.labels.push(TR),this.scope.enter(256);let r;for(let i;!this.match(8);)if(this.match(61)||this.match(65)){let s=this.match(61);r&&this.finishNode(r,"SwitchCase"),e.push(r=this.startNode()),r.consequent=[],this.next(),s?r.test=this.parseExpression():(i&&this.raise(b.MultipleDefaultsInSwitch,this.state.lastTokStartLoc),i=!0,r.test=null),this.expect(14)}else r?r.consequent.push(this.parseStatementListItem()):this.unexpected();return this.scope.exit(),r&&this.finishNode(r,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(n,"SwitchStatement")}parseThrowStatement(n){return this.next(),this.hasPrecedingLineBreak()&&this.raise(b.NewlineAfterThrow,this.state.lastTokEndLoc),n.argument=this.parseExpression(),this.semicolon(),this.finishNode(n,"ThrowStatement")}parseCatchClauseParam(){let n=this.parseBindingAtom();return this.scope.enter(this.options.annexB&&n.type==="Identifier"?8:0),this.checkLVal(n,{type:"CatchClause"},9),n}parseTryStatement(n){if(this.next(),n.block=this.parseBlock(),n.handler=null,this.match(62)){let e=this.startNode();this.next(),this.match(10)?(this.expect(10),e.param=this.parseCatchClauseParam(),this.expect(11)):(e.param=null,this.scope.enter(0)),e.body=this.withSmartMixTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),n.handler=this.finishNode(e,"CatchClause")}return n.finalizer=this.eat(67)?this.parseBlock():null,!n.handler&&!n.finalizer&&this.raise(b.NoCatchOrFinally,n),this.finishNode(n,"TryStatement")}parseVarStatement(n,e,r=!1){return this.next(),this.parseVar(n,!1,e,r),this.semicolon(),this.finishNode(n,"VariableDeclaration")}parseWhileStatement(n){return this.next(),n.test=this.parseHeaderExpression(),this.state.labels.push(Gd),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.state.labels.pop(),this.finishNode(n,"WhileStatement")}parseWithStatement(n){return this.state.strict&&this.raise(b.StrictWith,this.state.startLoc),this.next(),n.object=this.parseHeaderExpression(),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.finishNode(n,"WithStatement")}parseEmptyStatement(n){return this.next(),this.finishNode(n,"EmptyStatement")}parseLabeledStatement(n,e,r,i){for(let a of this.state.labels)a.name===e&&this.raise(b.LabelRedeclaration,r,{labelName:e});let s=Dk(this.state.type)?1:this.match(71)?2:null;for(let a=this.state.labels.length-1;a>=0;a--){let o=this.state.labels[a];if(o.statementStart===n.start)o.statementStart=this.sourceToOffsetPos(this.state.start),o.kind=s;else break}return this.state.labels.push({name:e,kind:s,statementStart:this.sourceToOffsetPos(this.state.start)}),n.body=i&8?this.parseStatementOrSloppyAnnexBFunctionDeclaration(!0):this.parseStatement(),this.state.labels.pop(),n.label=r,this.finishNode(n,"LabeledStatement")}parseExpressionStatement(n,e,r){return n.expression=e,this.semicolon(),this.finishNode(n,"ExpressionStatement")}parseBlock(n=!1,e=!0,r){let i=this.startNode();return n&&this.state.strictErrors.clear(),this.expect(5),e&&this.scope.enter(0),this.parseBlockBody(i,n,!1,8,r),e&&this.scope.exit(),this.finishNode(i,"BlockStatement")}isValidDirective(n){return n.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&!n.expression.extra.parenthesized}parseBlockBody(n,e,r,i,s){let a=n.body=[],o=n.directives=[];this.parseBlockOrModuleBlockBody(a,e?o:void 0,r,i,s)}parseBlockOrModuleBlockBody(n,e,r,i,s){let a=this.state.strict,o=!1,d=!1;for(;!this.match(i);){let c=r?this.parseModuleItem():this.parseStatementListItem();if(e&&!d){if(this.isValidDirective(c)){let l=this.stmtToDirective(c);e.push(l),!o&&l.value.value==="use strict"&&(o=!0,this.setStrict(!0));continue}d=!0,this.state.strictErrors.clear()}n.push(c)}s?.call(this,o),a||this.setStrict(!1),this.next()}parseFor(n,e){return n.init=e,this.semicolon(!1),n.test=this.match(13)?null:this.parseExpression(),this.semicolon(!1),n.update=this.match(11)?null:this.parseExpression(),this.expect(11),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(n,"ForStatement")}parseForIn(n,e,r){let i=this.match(58);return this.next(),i?r!==null&&this.unexpected(r):n.await=r!==null,e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!i||!this.options.annexB||this.state.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(b.ForInOfLoopInitializer,e,{type:i?"ForInStatement":"ForOfStatement"}),e.type==="AssignmentPattern"&&this.raise(b.InvalidLhs,e,{ancestor:{type:"ForStatement"}}),n.left=e,n.right=i?this.parseExpression():this.parseMaybeAssignAllowIn(),this.expect(11),n.body=this.withSmartMixTopicForbiddingContext(()=>this.parseStatement()),this.scope.exit(),this.state.labels.pop(),this.finishNode(n,i?"ForInStatement":"ForOfStatement")}parseVar(n,e,r,i=!1){let s=n.declarations=[];for(n.kind=r;;){let a=this.startNode();if(this.parseVarId(a,r),a.init=this.eat(29)?e?this.parseMaybeAssignDisallowIn():this.parseMaybeAssignAllowIn():null,a.init===null&&!i&&(a.id.type!=="Identifier"&&!(e&&(this.match(58)||this.isContextual(102)))?this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:"destructuring"}):(r==="const"||r==="using"||r==="await using")&&!(this.match(58)||this.isContextual(102))&&this.raise(b.DeclarationMissingInitializer,this.state.lastTokEndLoc,{kind:r})),s.push(this.finishNode(a,"VariableDeclarator")),!this.eat(12))break}return n}parseVarId(n,e){let r=this.parseBindingAtom();e==="using"||e==="await using"?(r.type==="ArrayPattern"||r.type==="ObjectPattern")&&this.raise(b.UsingDeclarationHasBindingPattern,r.loc.start):r.type==="VoidPattern"&&this.raise(b.UnexpectedVoidPattern,r.loc.start),this.checkLVal(r,{type:"VariableDeclarator"},e==="var"?5:8201),n.id=r}parseAsyncFunctionExpression(n){return this.parseFunction(n,8)}parseFunction(n,e=0){let r=e&2,i=!!(e&1),s=i&&!(e&4),a=!!(e&8);this.initFunction(n,a),this.match(55)&&(r&&this.raise(b.GeneratorInSingleStatementContext,this.state.startLoc),this.next(),n.generator=!0),i&&(n.id=this.parseFunctionId(s));let o=this.state.maybeInArrowParameters;return this.state.maybeInArrowParameters=!1,this.scope.enter(514),this.prodParam.enter(Zs(a,n.generator)),i||(n.id=this.parseFunctionId()),this.parseFunctionParams(n,!1),this.withSmartMixTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(n,i?"FunctionDeclaration":"FunctionExpression")}),this.prodParam.exit(),this.scope.exit(),i&&!r&&this.registerFunctionStatementId(n),this.state.maybeInArrowParameters=o,n}parseFunctionId(n){return n||se(this.state.type)?this.parseIdentifier():null}parseFunctionParams(n,e){this.expect(10),this.expressionScope.enter(pR()),n.params=this.parseBindingList(11,41,2|(e?4:0)),this.expressionScope.exit()}registerFunctionStatementId(n){n.id&&this.scope.declareName(n.id.name,!this.options.annexB||this.state.strict||n.generator||n.async?this.scope.treatFunctionsAsVar?5:8201:17,n.id.loc.start)}parseClass(n,e,r){this.next();let i=this.state.strict;return this.state.strict=!0,this.parseClassId(n,e,r),this.parseClassSuper(n),n.body=this.parseClassBody(!!n.superClass,i),this.finishNode(n,e?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(29)||this.match(13)||this.match(8)}isClassMethod(){return this.match(10)}nameIsConstructor(n){return n.type==="Identifier"&&n.name==="constructor"||n.type==="StringLiteral"&&n.value==="constructor"}isNonstaticConstructor(n){return!n.computed&&!n.static&&this.nameIsConstructor(n.key)}parseClassBody(n,e){this.classScope.enter();let r={hadConstructor:!1,hadSuperClass:n},i=[],s=this.startNode();if(s.body=[],this.expect(5),this.withSmartMixTopicForbiddingContext(()=>{for(;!this.match(8);){if(this.eat(13)){if(i.length>0)throw this.raise(b.DecoratorSemicolon,this.state.lastTokEndLoc);continue}if(this.match(26)){i.push(this.parseDecorator());continue}let a=this.startNode();i.length&&(a.decorators=i,this.resetStartLocationFromNode(a,i[0]),i=[]),this.parseClassMember(s,a,r),a.kind==="constructor"&&a.decorators&&a.decorators.length>0&&this.raise(b.DecoratorConstructor,a)}}),this.state.strict=e,this.next(),i.length)throw this.raise(b.TrailingDecorator,this.state.startLoc);return this.classScope.exit(),this.finishNode(s,"ClassBody")}parseClassMemberFromModifier(n,e){let r=this.parseIdentifier(!0);if(this.isClassMethod()){let i=e;return i.kind="method",i.computed=!1,i.key=r,i.static=!1,this.pushClassMethod(n,i,!1,!1,!1,!1),!0}else if(this.isClassProperty()){let i=e;return i.computed=!1,i.key=r,i.static=!1,n.body.push(this.parseClassProperty(i)),!0}return this.resetPreviousNodeTrailingComments(r),!1}parseClassMember(n,e,r){let i=this.isContextual(106);if(i){if(this.parseClassMemberFromModifier(n,e))return;if(this.eat(5)){this.parseClassStaticBlock(n,e);return}}this.parseClassMemberWithIsStatic(n,e,r,i)}parseClassMemberWithIsStatic(n,e,r,i){let s=e,a=e,o=e,d=e,c=e,l=s,u=s;if(e.static=i,this.parsePropertyNamePrefixOperator(e),this.eat(55)){l.kind="method";let y=this.match(139);if(this.parseClassElementName(l),this.parsePostMemberNameModifiers(l),y){this.pushClassPrivateMethod(n,a,!0,!1);return}this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsGenerator,s.key),this.pushClassMethod(n,s,!0,!1,!1,!1);return}let p=!this.state.containsEsc&&se(this.state.type),f=this.parseClassElementName(e),h=p?f.name:null,m=this.isPrivateName(f),g=this.state.startLoc;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(l.kind="method",m){this.pushClassPrivateMethod(n,a,!1,!1);return}let y=this.isNonstaticConstructor(s),w=!1;y&&(s.kind="constructor",r.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(b.DuplicateConstructor,f),y&&this.hasPlugin("typescript")&&e.override&&this.raise(b.OverrideOnConstructor,f),r.hadConstructor=!0,w=r.hadSuperClass),this.pushClassMethod(n,s,!1,!1,y,w)}else if(this.isClassProperty())m?this.pushClassPrivateProperty(n,d):this.pushClassProperty(n,o);else if(h==="async"&&!this.isLineTerminator()){this.resetPreviousNodeTrailingComments(f);let y=this.eat(55);u.optional&&this.unexpected(g),l.kind="method";let w=this.match(139);this.parseClassElementName(l),this.parsePostMemberNameModifiers(u),w?this.pushClassPrivateMethod(n,a,y,!0):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAsync,s.key),this.pushClassMethod(n,s,y,!0,!1,!1))}else if((h==="get"||h==="set")&&!(this.match(55)&&this.isLineTerminator())){this.resetPreviousNodeTrailingComments(f),l.kind=h;let y=this.match(139);this.parseClassElementName(s),y?this.pushClassPrivateMethod(n,a,!1,!1):(this.isNonstaticConstructor(s)&&this.raise(b.ConstructorIsAccessor,s.key),this.pushClassMethod(n,s,!1,!1,!1,!1)),this.checkGetterSetterParams(s)}else if(h==="accessor"&&!this.isLineTerminator()){this.expectPlugin("decoratorAutoAccessors"),this.resetPreviousNodeTrailingComments(f);let y=this.match(139);this.parseClassElementName(o),this.pushClassAccessorProperty(n,c,y)}else this.isLineTerminator()?m?this.pushClassPrivateProperty(n,d):this.pushClassProperty(n,o):this.unexpected()}parseClassElementName(n){let{type:e,value:r}=this.state;if((e===132||e===134)&&n.static&&r==="prototype"&&this.raise(b.StaticPrototype,this.state.startLoc),e===139){r==="constructor"&&this.raise(b.ConstructorClassPrivateField,this.state.startLoc);let i=this.parsePrivateName();return n.key=i,i}return this.parsePropertyName(n),n.key}parseClassStaticBlock(n,e){var r;this.scope.enter(720);let i=this.state.labels;this.state.labels=[],this.prodParam.enter(0);let s=e.body=[];this.parseBlockOrModuleBlockBody(s,void 0,!1,8),this.prodParam.exit(),this.scope.exit(),this.state.labels=i,n.body.push(this.finishNode(e,"StaticBlock")),(r=e.decorators)!=null&&r.length&&this.raise(b.DecoratorStaticBlock,e)}pushClassProperty(n,e){!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key),n.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(n,e){let r=this.parseClassPrivateProperty(e);n.body.push(r),this.classScope.declarePrivateName(this.getPrivateNameSV(r.key),0,r.key.loc.start)}pushClassAccessorProperty(n,e,r){!r&&!e.computed&&this.nameIsConstructor(e.key)&&this.raise(b.ConstructorClassField,e.key);let i=this.parseClassAccessorProperty(e);n.body.push(i),r&&this.classScope.declarePrivateName(this.getPrivateNameSV(i.key),0,i.key.loc.start)}pushClassMethod(n,e,r,i,s,a){n.body.push(this.parseMethod(e,r,i,s,a,"ClassMethod",!0))}pushClassPrivateMethod(n,e,r,i){let s=this.parseMethod(e,r,i,!1,!1,"ClassPrivateMethod",!0);n.body.push(s);let a=s.kind==="get"?s.static?6:2:s.kind==="set"?s.static?5:1:0;this.declareClassPrivateMethodInScope(s,a)}declareClassPrivateMethodInScope(n,e){this.classScope.declarePrivateName(this.getPrivateNameSV(n.key),e,n.key.loc.start)}parsePostMemberNameModifiers(n){}parseClassPrivateProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassPrivateProperty")}parseClassProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassProperty")}parseClassAccessorProperty(n){return this.parseInitializer(n),this.semicolon(),this.finishNode(n,"ClassAccessorProperty")}parseInitializer(n){this.scope.enter(592),this.expressionScope.enter(th()),this.prodParam.enter(0),n.value=this.eat(29)?this.parseMaybeAssignAllowIn():null,this.expressionScope.exit(),this.prodParam.exit(),this.scope.exit()}parseClassId(n,e,r,i=8331){if(se(this.state.type))n.id=this.parseIdentifier(),e&&this.declareNameFromIdentifier(n.id,i);else if(r||!e)n.id=null;else throw this.raise(b.MissingClassName,this.state.startLoc)}parseClassSuper(n){n.superClass=this.eat(81)?this.parseExprSubscripts():null}parseExport(n,e){let r=this.parseMaybeImportPhase(n,!0),i=this.maybeParseExportDefaultSpecifier(n,r),s=!i||this.eat(12),a=s&&this.eatExportStar(n),o=a&&this.maybeParseExportNamespaceSpecifier(n),d=s&&(!o||this.eat(12)),c=i||a;if(a&&!o){if(i&&this.unexpected(),e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.parseExportFrom(n,!0),this.sawUnambiguousESM=!0,this.finishNode(n,"ExportAllDeclaration")}let l=this.maybeParseExportNamedSpecifiers(n);i&&s&&!a&&!l&&this.unexpected(null,5),o&&d&&this.unexpected(null,98);let u;if(c||l){if(u=!1,e)throw this.raise(b.UnsupportedDecoratorExport,n);this.parseExportFrom(n,c)}else u=this.maybeParseExportDeclaration(n);if(c||l||u){var p;let f=n;if(this.checkExport(f,!0,!1,!!f.source),((p=f.declaration)==null?void 0:p.type)==="ClassDeclaration")this.maybeTakeDecorators(e,f.declaration,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.sawUnambiguousESM=!0,this.finishNode(f,"ExportNamedDeclaration")}if(this.eat(65)){let f=n,h=this.parseExportDefaultExpression();if(f.declaration=h,h.type==="ClassDeclaration")this.maybeTakeDecorators(e,h,f);else if(e)throw this.raise(b.UnsupportedDecoratorExport,n);return this.checkExport(f,!0,!0),this.sawUnambiguousESM=!0,this.finishNode(f,"ExportDefaultDeclaration")}throw this.unexpected(null,5)}eatExportStar(n){return this.eat(55)}maybeParseExportDefaultSpecifier(n,e){if(e||this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom",e?.loc.start);let r=e||this.parseIdentifier(!0),i=this.startNodeAtNode(r);return i.exported=r,n.specifiers=[this.finishNode(i,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(n){if(this.isContextual(93)){var e,r;(r=(e=n).specifiers)!=null||(e.specifiers=[]);let i=this.startNodeAt(this.state.lastTokStartLoc);return this.next(),i.exported=this.parseModuleExportName(),n.specifiers.push(this.finishNode(i,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(n){if(this.match(5)){let e=n;e.specifiers||(e.specifiers=[]);let r=e.exportKind==="type";return e.specifiers.push(...this.parseExportSpecifiers(r)),e.source=null,this.hasPlugin("importAssertions")?e.assertions=[]:e.attributes=[],e.declaration=null,!0}return!1}maybeParseExportDeclaration(n){return this.shouldParseExportDeclaration()?(n.specifiers=[],n.source=null,this.hasPlugin("importAssertions")?n.assertions=[]:n.attributes=[],n.declaration=this.parseExportDeclaration(n),!0):!1}isAsyncFunction(){if(!this.isContextual(95))return!1;let n=this.nextTokenInLineStart();return this.isUnparsedContextual(n,"function")}parseExportDefaultExpression(){let n=this.startNode();if(this.match(68))return this.next(),this.parseFunction(n,5);if(this.isAsyncFunction())return this.next(),this.next(),this.parseFunction(n,13);if(this.match(80))return this.parseClass(n,!0,!0);if(this.match(26))return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")===!0&&this.raise(b.DecoratorBeforeExport,this.state.startLoc),this.parseClass(this.maybeTakeDecorators(this.parseDecorators(!1),this.startNode()),!0,!0);if(this.match(75)||this.match(74)||this.isLet()||this.isUsing()||this.isAwaitUsing())throw this.raise(b.UnsupportedDefaultExport,this.state.startLoc);let e=this.parseMaybeAssignAllowIn();return this.semicolon(),e}parseExportDeclaration(n){return this.match(80)?this.parseClass(this.startNode(),!0,!1):this.parseStatementListItem()}isExportDefaultSpecifier(){let{type:n}=this.state;if(se(n)){if(n===95&&!this.state.containsEsc||n===100)return!1;if((n===130||n===129)&&!this.state.containsEsc){let i=this.nextTokenStart(),s=this.input.charCodeAt(i);if(s===123||this.chStartsBindingIdentifier(s,i)&&!this.input.startsWith("from",i))return this.expectOnePlugin(["flow","typescript"]),!1}}else if(!this.match(65))return!1;let e=this.nextTokenStart(),r=this.isUnparsedContextual(e,"from");if(this.input.charCodeAt(e)===44||se(this.state.type)&&r)return!0;if(this.match(65)&&r){let i=this.input.charCodeAt(this.nextTokenStartSince(e+4));return i===34||i===39}return!1}parseExportFrom(n,e){this.eatContextual(98)?(n.source=this.parseImportSource(),this.checkExport(n),this.maybeParseImportAttributes(n),this.checkJSONModuleImport(n)):e&&this.unexpected(),this.semicolon()}shouldParseExportDeclaration(){let{type:n}=this.state;return n===26&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))?(this.getPluginOption("decorators","decoratorsBeforeExport")===!0&&this.raise(b.DecoratorBeforeExport,this.state.startLoc),!0):this.isUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):this.isAwaitUsing()?(this.raise(b.UsingDeclarationExport,this.state.startLoc),!0):n===74||n===75||n===68||n===80||this.isLet()||this.isAsyncFunction()}checkExport(n,e,r,i){if(e){var s;if(r){if(this.checkDuplicateExports(n,"default"),this.hasPlugin("exportDefaultFrom")){var a;let o=n.declaration;o.type==="Identifier"&&o.name==="from"&&o.end-o.start===4&&!((a=o.extra)!=null&&a.parenthesized)&&this.raise(b.ExportDefaultFromAsIdentifier,o)}}else if((s=n.specifiers)!=null&&s.length)for(let o of n.specifiers){let{exported:d}=o,c=d.type==="Identifier"?d.name:d.value;if(this.checkDuplicateExports(o,c),!i&&o.local){let{local:l}=o;l.type!=="Identifier"?this.raise(b.ExportBindingIsString,o,{localName:l.value,exportName:c}):(this.checkReservedWord(l.name,l.loc.start,!0,!1),this.scope.checkLocalExport(l))}}else if(n.declaration){let o=n.declaration;if(o.type==="FunctionDeclaration"||o.type==="ClassDeclaration"){let{id:d}=o;if(!d)throw new Error("Assertion failure");this.checkDuplicateExports(n,d.name)}else if(o.type==="VariableDeclaration")for(let d of o.declarations)this.checkDeclaration(d.id)}}}checkDeclaration(n){if(n.type==="Identifier")this.checkDuplicateExports(n,n.name);else if(n.type==="ObjectPattern")for(let e of n.properties)this.checkDeclaration(e);else if(n.type==="ArrayPattern")for(let e of n.elements)e&&this.checkDeclaration(e);else n.type==="ObjectProperty"?this.checkDeclaration(n.value):n.type==="RestElement"?this.checkDeclaration(n.argument):n.type==="AssignmentPattern"&&this.checkDeclaration(n.left)}checkDuplicateExports(n,e){this.exportedIdentifiers.has(e)&&(e==="default"?this.raise(b.DuplicateDefaultExport,n):this.raise(b.DuplicateExport,n,{exportName:e})),this.exportedIdentifiers.add(e)}parseExportSpecifiers(n){let e=[],r=!0;for(this.expect(5);!this.eat(8);){if(r)r=!1;else if(this.expect(12),this.eat(8))break;let i=this.isContextual(130),s=this.match(134),a=this.startNode();a.local=this.parseModuleExportName(),e.push(this.parseExportSpecifier(a,s,n,i))}return e}parseExportSpecifier(n,e,r,i){return this.eatContextual(93)?n.exported=this.parseModuleExportName():e?n.exported=this.cloneStringLiteral(n.local):n.exported||(n.exported=this.cloneIdentifier(n.local)),this.finishNode(n,"ExportSpecifier")}parseModuleExportName(){if(this.match(134)){let n=this.parseStringLiteral(this.state.value),e=PR.exec(n.value);return e&&this.raise(b.ModuleExportNameHasLoneSurrogate,n,{surrogateCharCode:e[0].charCodeAt(0)}),n}return this.parseIdentifier(!0)}isJSONModuleImport(n){return n.assertions!=null?n.assertions.some(({key:e,value:r})=>r.value==="json"&&(e.type==="Identifier"?e.name==="type":e.value==="type")):!1}checkImportReflection(n){let{specifiers:e}=n,r=e.length===1?e[0].type:null;if(n.phase==="source")r!=="ImportDefaultSpecifier"&&this.raise(b.SourcePhaseImportRequiresDefault,e[0].loc.start);else if(n.phase==="defer")r!=="ImportNamespaceSpecifier"&&this.raise(b.DeferImportRequiresNamespace,e[0].loc.start);else if(n.module){var i;r!=="ImportDefaultSpecifier"&&this.raise(b.ImportReflectionNotBinding,e[0].loc.start),((i=n.assertions)==null?void 0:i.length)>0&&this.raise(b.ImportReflectionHasAssertion,e[0].loc.start)}}checkJSONModuleImport(n){if(this.isJSONModuleImport(n)&&n.type!=="ExportAllDeclaration"){let{specifiers:e}=n;if(e!=null){let r=e.find(i=>{let s;if(i.type==="ExportSpecifier"?s=i.local:i.type==="ImportSpecifier"&&(s=i.imported),s!==void 0)return s.type==="Identifier"?s.name!=="default":s.value!=="default"});r!==void 0&&this.raise(b.ImportJSONBindingNotDefault,r.loc.start)}}}isPotentialImportPhase(n){return n?!1:this.isContextual(105)||this.isContextual(97)||this.isContextual(127)}applyImportPhase(n,e,r,i){e||(r==="module"?(this.expectPlugin("importReflection",i),n.module=!0):this.hasPlugin("importReflection")&&(n.module=!1),r==="source"?(this.expectPlugin("sourcePhaseImports",i),n.phase="source"):r==="defer"?(this.expectPlugin("deferredImportEvaluation",i),n.phase="defer"):this.hasPlugin("sourcePhaseImports")&&(n.phase=null))}parseMaybeImportPhase(n,e){if(!this.isPotentialImportPhase(e))return this.applyImportPhase(n,e,null),null;let r=this.startNode(),i=this.parseIdentifierName(!0),{type:s}=this.state;return(dt(s)?s!==98||this.lookaheadCharCode()===102:s!==12)?(this.applyImportPhase(n,e,i,r.loc.start),null):(this.applyImportPhase(n,e,null),this.createIdentifier(r,i))}isPrecedingIdImportPhase(n){let{type:e}=this.state;return se(e)?e!==98||this.lookaheadCharCode()===102:e!==12}parseImport(n){return this.match(134)?this.parseImportSourceAndAttributes(n):this.parseImportSpecifiersAndAfter(n,this.parseMaybeImportPhase(n,!1))}parseImportSpecifiersAndAfter(n,e){n.specifiers=[];let i=!this.maybeParseDefaultImportSpecifier(n,e)||this.eat(12),s=i&&this.maybeParseStarImportSpecifier(n);return i&&!s&&this.parseNamedImportSpecifiers(n),this.expectContextual(98),this.parseImportSourceAndAttributes(n)}parseImportSourceAndAttributes(n){var e;return(e=n.specifiers)!=null||(n.specifiers=[]),n.source=this.parseImportSource(),this.maybeParseImportAttributes(n),this.checkImportReflection(n),this.checkJSONModuleImport(n),this.semicolon(),this.sawUnambiguousESM=!0,this.finishNode(n,"ImportDeclaration")}parseImportSource(){return this.match(134)||this.unexpected(),this.parseExprAtom()}parseImportSpecifierLocal(n,e,r){e.local=this.parseIdentifier(),n.specifiers.push(this.finishImportSpecifier(e,r))}finishImportSpecifier(n,e,r=8201){return this.checkLVal(n.local,{type:e},r),this.finishNode(n,e)}parseImportAttributes(){this.expect(5);let n=[],e=new Set;do{if(this.match(8))break;let r=this.startNode(),i=this.state.value;if(e.has(i)&&this.raise(b.ModuleAttributesWithDuplicateKeys,this.state.startLoc,{key:i}),e.add(i),this.match(134)?r.key=this.parseStringLiteral(i):r.key=this.parseIdentifier(!0),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),n.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return this.expect(8),n}parseModuleAttributes(){let n=[],e=new Set;do{let r=this.startNode();if(r.key=this.parseIdentifier(!0),r.key.name!=="type"&&this.raise(b.ModuleAttributeDifferentFromType,r.key),e.has(r.key.name)&&this.raise(b.ModuleAttributesWithDuplicateKeys,r.key,{key:r.key.name}),e.add(r.key.name),this.expect(14),!this.match(134))throw this.raise(b.ModuleAttributeInvalidValue,this.state.startLoc);r.value=this.parseStringLiteral(this.state.value),n.push(this.finishNode(r,"ImportAttribute"))}while(this.eat(12));return n}maybeParseImportAttributes(n){let e;var r=!1;if(this.match(76)){if(this.hasPrecedingLineBreak()&&this.lookaheadCharCode()===40)return;this.next(),this.hasPlugin("moduleAttributes")?(e=this.parseModuleAttributes(),this.addExtra(n,"deprecatedWithLegacySyntax",!0)):e=this.parseImportAttributes(),r=!0}else this.isContextual(94)&&!this.hasPrecedingLineBreak()?(!this.hasPlugin("deprecatedImportAssert")&&!this.hasPlugin("importAssertions")&&this.raise(b.ImportAttributesUseAssert,this.state.startLoc),this.hasPlugin("importAssertions")||this.addExtra(n,"deprecatedAssertSyntax",!0),this.next(),e=this.parseImportAttributes()):e=[];!r&&this.hasPlugin("importAssertions")?n.assertions=e:n.attributes=e}maybeParseDefaultImportSpecifier(n,e){if(e){let r=this.startNodeAtNode(e);return r.local=e,n.specifiers.push(this.finishImportSpecifier(r,"ImportDefaultSpecifier")),!0}else if(dt(this.state.type))return this.parseImportSpecifierLocal(n,this.startNode(),"ImportDefaultSpecifier"),!0;return!1}maybeParseStarImportSpecifier(n){if(this.match(55)){let e=this.startNode();return this.next(),this.expectContextual(93),this.parseImportSpecifierLocal(n,e,"ImportNamespaceSpecifier"),!0}return!1}parseNamedImportSpecifiers(n){let e=!0;for(this.expect(5);!this.eat(8);){if(e)e=!1;else{if(this.eat(14))throw this.raise(b.DestructureNamedImport,this.state.startLoc);if(this.expect(12),this.eat(8))break}let r=this.startNode(),i=this.match(134),s=this.isContextual(130);r.imported=this.parseModuleExportName();let a=this.parseImportSpecifier(r,i,n.importKind==="type"||n.importKind==="typeof",s,void 0);n.specifiers.push(a)}}parseImportSpecifier(n,e,r,i,s){if(this.eatContextual(93))n.local=this.parseIdentifier();else{let{imported:a}=n;if(e)throw this.raise(b.ImportBindingIsString,n,{importName:a.value});this.checkReservedWord(a.name,n.loc.start,!0,!0),n.local||(n.local=this.cloneIdentifier(a))}return this.finishImportSpecifier(n,"ImportSpecifier",s)}isThisParam(n){return n.type==="Identifier"&&n.name==="this"}},ra=class extends hc{constructor(n,e,r){let i=Tk(n);super(i,e),this.options=i,this.initializeScopes(),this.plugins=r,this.filename=i.sourceFilename,this.startIndex=i.startIndex;let s=0;i.allowAwaitOutsideFunction&&(s|=1),i.allowReturnOutsideFunction&&(s|=2),i.allowImportExportEverywhere&&(s|=8),i.allowSuperOutsideMethod&&(s|=16),i.allowUndeclaredExports&&(s|=64),i.allowNewTargetOutsideFunction&&(s|=4),i.allowYieldOutsideFunction&&(s|=32),i.ranges&&(s|=128),i.tokens&&(s|=256),i.createImportExpressions&&(s|=512),i.createParenthesizedExpressions&&(s|=1024),i.errorRecovery&&(s|=2048),i.attachComment&&(s|=4096),i.annexB&&(s|=8192),this.optionFlags=s}getScopeHandler(){return wi}parse(){this.enterInitialScopes();let n=this.startNode(),e=this.startNode();this.nextToken(),n.errors=null;let r=this.parseTopLevel(n,e);return r.errors=this.state.errors,r.comments.length=this.state.commentsLen,r}};function ER(t,n){var e;if(((e=n)==null?void 0:e.sourceType)==="unambiguous"){n=Object.assign({},n);try{n.sourceType="module";let r=mi(n,t),i=r.parse();if(r.sawUnambiguousESM)return i;if(r.ambiguousScriptDifferentAst)try{return n.sourceType="script",mi(n,t).parse()}catch{}else i.program.sourceType="script";return i}catch(r){try{return n.sourceType="script",mi(n,t).parse()}catch{}throw r}}else return mi(n,t).parse()}function CR(t,n){let e=mi(n,t);return e.options.strictMode&&(e.state.strict=!0),e.getExpression()}function NR(t){let n={};for(let e of Object.keys(t))n[e]=Et(t[e]);return n}var OR=NR(Ck);function mi(t,n){let e=ra,r=new Map;if(t!=null&&t.plugins){for(let i of t.plugins){let s,a;typeof i=="string"?s=i:[s,a]=i,r.has(s)||r.set(s,a||{})}IR(r),e=$R(r)}return new e(t,n,r)}var Uf=new Map;function $R(t){let n=[];for(let i of AR)t.has(i)&&n.push(i);let e=n.join("|"),r=Uf.get(e);if(!r){r=ra;for(let i of n)r=ih[i](r);Uf.set(e,r)}return r}xi.parse=ER;xi.parseExpression=CR;xi.tokTypes=OR});import{parseArgs as _D}from"node:util";import{writeFile as Jv}from"node:fs/promises";import{join as Yv}from"node:path";function wf(t,n){try{let e=new URL(t);return n.includes(e.protocol)&&e.username===""&&e.password===""&&e.search===""&&e.hash===""?e.href.replace(/\/+$/,""):void 0}catch{return}}function st(t,n=""){return wf(t===void 0||t===""?n:t,["https:"])}function Ed(t){return wf(t??"",["https:","http:"])}var Xv=3e4,Qv="7.1",bf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vf="KwikQA.Ci",Zv=4,kf=/^\$\([\w.-]+\)$/;function $d(t){return Object.fromEntries(Object.entries(t).filter(([,n])=>n===void 0||!kf.test(n.trim())))}function ek(t){if(!(t===void 0||t===""))try{let n=new URL(t);return n.username="",n.password="",st(n.href)}catch{return}}function Cd(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function xf(t){if(!(t===void 0||t===""||t.startsWith("refs/pull/")))return t.replace(/^refs\/(?:heads|tags)\//,"")}function zs(t){if(t.TF_BUILD!=="True")return;let n=st(t.SYSTEM_COLLECTIONURI),e=t.SYSTEM_TEAMPROJECT??"",r=Cd(t.BUILD_BUILDID),i=t.BUILD_REPOSITORY_PROVIDER??"",s=i==="GitHub"||i==="GitHubEnterprise",a=i==="TfsGit"?"pullrequest":s?"pull":void 0,o=a===void 0?void 0:ek(t.BUILD_REPOSITORY_URI),d=Cd((s?t.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER:void 0)||t.SYSTEM_PULLREQUEST_PULLREQUESTID),c=/^[0-9a-f]{40}$/i.test(t.BUILD_SOURCEVERSION??"")?t.BUILD_SOURCEVERSION:void 0,l=xf(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)??xf(t.BUILD_SOURCEBRANCH),u=(t.SYSTEM_ACCESSTOKEN??"").trim(),p=Cd(t.SYSTEM_JOBATTEMPT),f=/^refs\/[^\s\0]+$/.test(t.BUILD_SOURCEBRANCH??"")?t.BUILD_SOURCEBRANCH:void 0,h=t.SYSTEM_PULLREQUEST_SOURCEBRANCH?.startsWith("refs/heads/")?t.SYSTEM_PULLREQUEST_SOURCEBRANCH.slice(11):void 0,m=/^[0-9a-f]{40}$/i.test(t.SYSTEM_PULLREQUEST_SOURCECOMMITID??"")?t.SYSTEM_PULLREQUEST_SOURCECOMMITID?.toLowerCase():void 0,g=bf.test(t.SYSTEM_TEAMPROJECTID??"")?t.SYSTEM_TEAMPROJECTID:void 0,y=bf.test(t.BUILD_REPOSITORY_ID??"")?t.BUILD_REPOSITORY_ID:void 0;return{...n===void 0?{}:{collectionUrl:n},...g===void 0?{}:{projectId:g},...y===void 0?{}:{repositoryId:y},provider:i,...t.BUILD_REPOSITORY_NAME?{repository:t.BUILD_REPOSITORY_NAME}:{},...n===void 0||e===""||r===void 0?{}:{runUrl:`${n}/${encodeURIComponent(e)}/_build/results?buildId=${r}`},pipeline:t.SYSTEM_DEFINITIONID||t.BUILD_DEFINITIONNAME||"",job:[t.SYSTEM_STAGENAME,t.SYSTEM_JOBNAME].filter(Boolean).join("."),...l===void 0?{}:{branch:l},...c===void 0?{}:{commit:{sha:c,...o===void 0?{}:{url:`${o}/commit/${c}`}}},...t.AGENT_TEMPDIRECTORY?{tempDirectory:t.AGENT_TEMPDIRECTORY}:{},...u===""||kf.test(u)?{}:{token:u},...r===void 0?{}:{buildId:String(r)},...p===void 0?{}:{jobAttempt:p},...f===void 0?{}:{ref:f},...d!==void 0&&h!==void 0&&m!==void 0?{pullRequestHead:{ref:h,sha:m}}:{},...d===void 0?{}:{pullRequest:{number:d,...o===void 0?{}:{url:`${o}/${a}/${d}`},fork:t.SYSTEM_PULLREQUEST_ISFORK==="True"}}}}function tk(t){return`kwikqa-ci pipeline=${encodeURIComponent(t.pipeline)} job=${encodeURIComponent(t.job)}`}function nk(t){return t.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function gt(t){return t.ok&&t.status!==203}async function Hs(t){let n=await t.json().catch(()=>{});return typeof n?.message=="string"?n.message.replace(/\s+/g," ").trim().slice(0,200):void 0}async function Nd(t){if(t.status===429)return"Azure DevOps's rate limit was reached";if(t.status===401||t.status===203)return"Azure DevOps refused the token";if(t.status===403){let e=await Hs(t);return`the build service can't comment on this pull request; give it "Contribute to pull requests" on the repository${e===void 0?"":` (${e})`}`}if(t.status===404)return"Azure DevOps found no such pull request with this token";let n=await Hs(t);return`Azure DevOps answered ${t.status}${n===void 0?"":`: ${n}`}`}var Od=class{constructor(n,e,r){this.send=n;this.base=e;this.token=r}send;base;token;call(n,e,r){return this.send(`${this.base}${e}?api-version=${Qv}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.token}`,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(Xv)})}},rr=class extends Error{};function rk(t){if(typeof t=="string")return t;let n=typeof t=="object"&&t!==null?t:{};return typeof n.$value=="string"?n.$value:void 0}async function ik(t,n){let e=await t.call("GET","/threads");if(!gt(e))throw new rr(await Nd(e));let r=(await e.json()).value??[];for(let i of r){if(i.isDeleted===!0||rk(i.properties?.[vf])!==n)continue;let s=i.comments?.find(a=>a.parentCommentId===0&&a.isDeleted!==!0);if(typeof i.id=="number"&&typeof s?.id=="number")return{thread:i.id,comment:s.id}}}async function Dd(t,n,e,r,i){let s=e.noun??"pull-request comment",a=`${s.charAt(0).toUpperCase()}${s.slice(1)}`,o=new Od(n,`${e.collectionUrl}/${e.projectId}/_apis/git/repositories/${e.repositoryId}/pullRequests/${e.pullRequest}`,e.token);try{let d=await ik(o,e.marker);if(d!==void 0){let l=await o.call("PATCH",`/threads/${d.thread}/comments/${d.comment}`,{content:r});if(gt(l))return t.print(`${a}: updated.`);if(l.status!==403&&l.status!==404)throw new rr(await Nd(l))}if(d===void 0&&!i)return t.print(`No ${s}: nothing failed, and there is no earlier comment to update.`);let c=await o.call("POST","/threads",{comments:[{parentCommentId:0,content:r,commentType:1}],status:Zv,properties:{[vf]:{$type:"System.String",$value:e.marker}}});if(!gt(c))throw new rr(await Nd(c));t.print(`${a}: posted.`)}catch(d){let c=d instanceof rr?d.message:`Azure DevOps couldn't be reached (${d instanceof Error?d.message:String(d)})`;t.error(`No ${s}: ${c}.`)}}async function sk(t,n,e,r,i){let s=o=>t.print(`No pull-request comment: ${o}.`),a=e.pullRequest;if(a===void 0)return s("this run isn't for a pull request");if(e.provider!=="TfsGit")return s(`the repository is on ${e.provider||"another host"}, and KwikQA comments from Azure Pipelines only on Azure Repos pull requests`);if(a.fork)return s("the pull request comes from a fork, and its build gets no secrets by default");if(e.token===void 0)return s("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env");if(e.collectionUrl===void 0||e.projectId===void 0||e.repositoryId===void 0)return s("System.CollectionUri, System.TeamProjectId, or Build.Repository.ID isn't what Azure Pipelines sets");await Dd(t,n,{collectionUrl:e.collectionUrl,projectId:e.projectId,repositoryId:e.repositoryId,pullRequest:a.number,token:e.token,marker:tk(e)},r,i)}async function Ld(t,n,e,r,i){if(e.tempDirectory===void 0)t.print("No build summary: AGENT_TEMPDIRECTORY isn't set.");else{let s=Yv(e.tempDirectory,"kwikqa-summary.md");try{await Jv(s,r);let a=`##vso[task.addattachment type=Distributedtask.Core.Summary;name=KwikQA;]${nk(s)}`;t.command===void 0?t.print(a):t.command(a),t.print("Build summary: written.")}catch(a){t.error(`No build summary: ${a.message}`)}}await sk(t,n,e,r,i.failures)}import{createHash as Dw}from"node:crypto";import{readFile as z1,stat as V1}from"node:fs/promises";import{join as U1,relative as q1,sep as G1}from"node:path";import{createHash as ak}from"node:crypto";function Md(t,n){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("canonical JSON cannot contain non-finite numbers");return t}if(Array.isArray(t))return t.map(e=>Md(e,n));if(typeof t!="object")throw new TypeError(`canonical JSON cannot contain ${typeof t}`);if(n.has(t))throw new TypeError("canonical JSON cannot contain cycles");n.add(t);try{let e=t,r={};for(let i of Object.keys(e).sort()){let s=e[i];if(s===void 0)throw new TypeError(`canonical JSON cannot contain undefined at ${JSON.stringify(i)}`);r[i]=Md(s,n)}return r}finally{n.delete(t)}}function ue(t){return JSON.stringify(Md(t,new Set))}function L(t){return ak("sha256").update(ue(t),"utf8").digest("hex")}function Rf(t){let n=new Map;for(let e of t){if(n.has(e.logicalTestId))throw new Error("Logical test observation is duplicated.");n.set(e.logicalTestId,e.status)}return n}function If(t){return t!==void 0&&t!=="passed"}function _d(t){let n=new Set(t.targetLogicalTestIds);if(n.size===0||n.size!==t.targetLogicalTestIds.length)throw new Error("Target logical test identities must be unique and nonempty.");let e=Rf(t.baseline),r=[],i=new Set;for(let l of t.blockingReasons??[]){if(l.length===0)throw new Error("Blocking validation reasons must be nonempty.");r.push({classification:"incomplete-check",message:l})}for(let l of[...t.commands].sort((u,p)=>u.commandId.localeCompare(p.commandId))){if(!l.required)continue;if(l.timing==="post-patch")for(let p of l.expectedLogicalTestIds)i.add(p);if(!l.fresh){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command evidence is not fresh."});continue}if(l.status==="unavailable"){r.push({classification:"unavailable-check",commandId:l.commandId,message:"Required command was unavailable."});continue}if(l.status==="incomplete"){r.push({classification:"incomplete-check",commandId:l.commandId,message:"Required command did not produce authoritative evidence."});continue}if(l.timing==="baseline")continue;let u=Rf(l.observations);for(let p of l.expectedLogicalTestIds){let f=u.get(p);if(f===void 0){r.push({classification:"incomplete-check",logicalTestId:p,commandId:l.commandId,message:"An expected logical test is missing from post-patch evidence."});continue}if(n.has(p)){r.push({classification:f==="passed"?"fixed-target-failure":"still-failing-target",logicalTestId:p,commandId:l.commandId,message:f==="passed"?"The original target failure is fixed.":"The original target remains non-passing."});continue}let h=e.get(p);f!=="passed"&&r.push({classification:If(h)?"unchanged-pre-existing-failure":"newly-introduced-failure",logicalTestId:p,commandId:l.commandId,message:If(h)?"An affected test remains non-passing from its baseline.":"An affected test newly became non-passing."})}}for(let l of[...n].sort())i.has(l)||r.push({classification:"incomplete-check",logicalTestId:l,message:"No fresh focused evidence covers the target logical test."});let s=r.sort((l,u)=>`${l.classification}\0${l.logicalTestId??""}\0${l.commandId??""}`.localeCompare(`${u.classification}\0${u.logicalTestId??""}\0${u.commandId??""}`)),a=new Set(s.map(l=>l.classification)),o=[...n].every(l=>s.some(u=>u.classification==="fixed-target-failure"&&u.logicalTestId===l)),c={schemaVersion:"1.0",status:a.has("incomplete-check")?"incomplete":a.has("unavailable-check")?"unavailable":!o||a.has("still-failing-target")||a.has("unchanged-pre-existing-failure")||a.has("newly-introduced-failure")||t.commands.some(l=>l.required&&l.status==="failed")?"failed":"passed",classifications:s};return{...c,summaryHash:L(c)}}var Us="1.1",jd="1.0",qs="1.1";var Gs="1.0",Gt=/^[a-z][a-z0-9_-]{0,63}$/,ir=32*1024*1024,hn=16*1024*1024,di="report.json",Tf=["playwright-focused","playwright-affected","playwright-project","playwright-suite","cypress-focused","cypress-affected","cypress-project","cypress-suite","webdriverio-focused","webdriverio-affected","webdriverio-project","webdriverio-suite"];function sr(t){return Tf.includes(t)}var ke=/^[a-f0-9]{64}$/,ci=Gt;function Oe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Pf(t){return Array.isArray(t)&&t.every(n=>typeof n=="string")}function oi(t,n=!0){return Pf(t)&&(n||t.length>0)&&t.every(e=>e.length>0&&!e.includes("\0"))&&new Set(t).size===t.length}function Ce(t,n){let e=Object.keys(t).sort(),r=[...n].sort();return e.length===r.length&&e.every((i,s)=>i===r[s])}function ok(t){if(!Oe(t))return!1;let n=["outputDirectory","maxArtifacts","maxArtifactBytes"];return t.reportFile!==void 0&&n.push("reportFile"),Ce(t,n)&&typeof t.outputDirectory=="string"&&t.outputDirectory.length>0&&!t.outputDirectory.includes("\0")&&(t.reportFile===void 0||typeof t.reportFile=="string"&&t.reportFile.length>0&&!t.reportFile.includes("\0"))&&Number.isInteger(t.maxArtifacts)&&t.maxArtifacts>0&&Number.isInteger(t.maxArtifactBytes)&&t.maxArtifactBytes>0&&t.maxArtifactBytes<=ir}function dk(t){if(!Oe(t))return!1;let n=["kind","path","detail"];return t.sha256!==void 0&&n.push("sha256"),Ce(t,n)&&["package-root","package-manifest","package-entry","configuration","pnp-loader","source-graph","scope-escalation"].includes(String(t.kind))&&typeof t.path=="string"&&t.path.length>0&&!t.path.includes("\0")&&typeof t.detail=="string"&&t.detail.length>0&&(t.sha256===void 0||typeof t.sha256=="string"&&ke.test(t.sha256))}function Sf(t){return!Oe(t)||!ci.test(String(t.commandId))||!Ce(t,["commandId","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","artifactPolicy","resolutionEvidence"])||!(sr(String(t.kind))||["parse","format","typecheck","lint"].includes(String(t.kind)))||t.timing!=="baseline"&&t.timing!=="post-patch"||typeof t.executable!="string"||t.executable.length===0||!Pf(t.args)||t.args.some(n=>n.includes("\0"))||typeof t.workingDirectory!="string"||t.workingDirectory.length===0||t.workingDirectory.includes("\0")||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||t.required!==!0||typeof t.purpose!="string"||t.purpose.length===0||!oi(t.logicalTestIds)||!oi(t.projectIds)||!Oe(t.environmentDelta)||!ok(t.artifactPolicy)||!Array.isArray(t.resolutionEvidence)||!t.resolutionEvidence.every(dk)?!1:Object.entries(t.environmentDelta).every(([n,e])=>/^[A-Z][A-Z0-9_]*$/.test(n)&&typeof e=="string"&&!e.includes("\0"))}function Fd(t){return Oe(t)&&Ce(t,["path","sourceSha256","resultSha256"])&&typeof t.path=="string"&&t.path.length>0&&!t.path.includes("\0")&&typeof t.sourceSha256=="string"&&ke.test(t.sourceSha256)&&typeof t.resultSha256=="string"&&ke.test(t.resultSha256)}function ck(t){return Oe(t)&&Ce(t,["baselineId","commandId","logicalTestIds","reason"])&&/^baseline_[a-f0-9]{24}$/.test(String(t.baselineId))&&ci.test(String(t.commandId))&&oi(t.logicalTestIds,!1)&&typeof t.reason=="string"&&t.reason.length>0}function lk(t){if(!Oe(t))return!1;let n=["code","message"];return t.path!==void 0&&n.push("path"),Ce(t,n)&&["ambiguous-package-root","ambiguous-configuration","budget-exceeded","cancelled","entry-outside-workspace","invalid-artifact","invalid-command","malformed-manifest","missing-browser","missing-configuration","missing-dependency","missing-test-identity","package-mismatch","parse-failed","report-incomplete","resolution-failed","spawn-failed","symlink-escape","timeout","unsupported-layout"].includes(String(t.code))&&typeof t.message=="string"&&t.message.length>0&&(t.path===void 0||typeof t.path=="string"&&!t.path.includes("\0"))}function Ef(t){return L({purpose:"kwikqa-validation-baseline",...t})}function Ks(t){return L({purpose:"kwikqa-validation-run",...t})}function Vs(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function uk(t){if(!Oe(t)||typeof t.kind!="string")return!1;if(t.kind==="exit")return Ce(t,["kind","exitCode"])&&Number.isInteger(t.exitCode);if(t.kind==="signal")return Ce(t,["kind","signal"])&&typeof t.signal=="string";if(t.kind==="spawn-error"){let n=["kind",...t.code===void 0?[]:["code"]];return Ce(t,n)&&(t.code===void 0||typeof t.code=="string")}return(t.kind==="timeout"||t.kind==="cancelled")&&Ce(t,["kind"])}function Af(t){return Oe(t)&&Ce(t,["path","sha256","storedSha256","observedBytes","storedBytes","truncated","redacted"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&ke.test(t.sha256)&&typeof t.storedSha256=="string"&&ke.test(t.storedSha256)&&Number.isInteger(t.observedBytes)&&t.observedBytes>=0&&Number.isInteger(t.storedBytes)&&t.storedBytes>=0&&typeof t.truncated=="boolean"&&typeof t.redacted=="boolean"}function pk(t){return Oe(t)&&Ce(t,["path","sha256","bytes"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&ke.test(t.sha256)&&Number.isInteger(t.bytes)&&t.bytes>=0}function Bd(t){if(!Hd(t))throw new Error("Validation command record is malformed or failed integrity validation.");return t}function fk(t){if(!Oe(t))return!1;let n=["classification",...t.logicalTestId===void 0?[]:["logicalTestId"],...t.commandId===void 0?[]:["commandId"],"message"];return Ce(t,n)&&["fixed-target-failure","still-failing-target","unchanged-pre-existing-failure","newly-introduced-failure","unavailable-check","incomplete-check"].includes(String(t.classification))&&(t.logicalTestId===void 0||typeof t.logicalTestId=="string"&&t.logicalTestId.length>0)&&(t.commandId===void 0||typeof t.commandId=="string"&&ci.test(t.commandId))&&typeof t.message=="string"&&t.message.length>0}function Hd(t){if(!Oe(t))return!1;let n=t,{recordHash:e,...r}=n;return Ce(t,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])&&n.schemaVersion===jd&&/^vld_[a-f0-9]{24}$/.test(n.validationRunId)&&ci.test(n.commandId)&&ke.test(n.commandHash)&&ke.test(n.planHash)&&n.required===!0&&Sf({commandId:n.commandId,kind:n.kind,timing:n.timing,required:n.required,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:n.environmentDelta,timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,artifactPolicy:{outputDirectory:"artifacts",maxArtifacts:1,maxArtifactBytes:1},resolutionEvidence:[]})&&Vs(n.startedAt)&&Number.isInteger(n.durationMs)&&n.durationMs>=0&&uk(n.termination)&&Af(n.stdout)&&Af(n.stderr)&&Array.isArray(n.artifacts)&&n.artifacts.every(pk)&&["blocked","passed","failed","unavailable","incomplete"].includes(n.status)&&ke.test(e)&&L(r)===e}function li(t){if(!Oe(t))throw new Error("Baseline manifest is not an object.");let n=t,{baselineHash:e,...r}=n;if(!Ce(t,["schemaVersion","planHash","repositoryFingerprint","targetHashes","commandRecords","logicalTestOutcomes","capturedAt","baselineHash"])||n.schemaVersion!==jd||!ke.test(n.planHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(Fd)||!Array.isArray(n.commandRecords)||!n.commandRecords.every(Hd)||!Oe(n.logicalTestOutcomes)||!Object.entries(n.logicalTestOutcomes).every(([i,s])=>i.length>0&&typeof s=="string"&&["passed","failed","skipped","interrupted"].includes(s))||!Vs(n.capturedAt)||!ke.test(e)||Ef(r)!==e)throw new Error("Baseline manifest is malformed or failed integrity validation.");return n}function Kt(t){if(!Oe(t))throw new Error("Validation run manifest is not an object.");let n=t,{manifestHash:e,...r}=n;if(!Ce(t,["schemaVersion","validationRunId","transactionId","planHash","repositoryFingerprint","targetHashes","requiredCommandIds","status","commandRecords","classifications","startedAt","completedAt","manifestHash"])||n.schemaVersion!==qs||!/^vld_[a-f0-9]{24}$/.test(n.validationRunId)||!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||!ke.test(n.planHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(Fd)||!oi(n.requiredCommandIds,!1)||!n.requiredCommandIds.every(i=>ci.test(i))||!Array.isArray(n.commandRecords)||!n.commandRecords.every(Hd)||!Array.isArray(n.classifications)||!n.classifications.every(fk)||!["blocked","passed","failed","unavailable","incomplete"].includes(n.status)||!Vs(n.startedAt)||!Vs(n.completedAt)||Date.parse(n.completedAt)<Date.parse(n.startedAt)||!ke.test(e)||Ks(r)!==e)throw new Error("Validation run manifest is malformed or failed integrity validation.");if(new Set(n.targetHashes.map(i=>i.path)).size!==n.targetHashes.length||new Set(n.commandRecords.map(i=>i.commandId)).size!==n.commandRecords.length||n.commandRecords.some(i=>i.validationRunId!==n.validationRunId||i.planHash!==n.planHash))throw new Error("Validation run manifest contains inconsistent evidence.");if(!hk(n))throw new Error("Validation run manifest status is inconsistent with its evidence.");return n}function hk(t){let n=new Set(t.requiredCommandIds),e=new Set(t.commandRecords.map(i=>i.commandId)),r=new Set(t.classifications.map(i=>i.classification));if(t.commandRecords.some(i=>!n.has(i.commandId)||i.timing!=="post-patch")||t.requiredCommandIds.some(i=>!e.has(i)&&!t.classifications.some(s=>s.classification==="incomplete-check"&&s.commandId===i)))return!1;switch(t.status){case"passed":return t.classifications.length>0&&[...r].every(i=>i==="fixed-target-failure")&&e.size===n.size&&t.commandRecords.every(i=>i.status==="passed");case"incomplete":return r.has("incomplete-check");case"unavailable":return!r.has("incomplete-check")&&r.has("unavailable-check");case"failed":return!r.has("incomplete-check")&&!r.has("unavailable-check");default:return!0}}function Ws(t){return L({purpose:"kwikqa-resolved-validation-plan",...t})}function mn(t){if(!Oe(t))throw new Error("Resolved validation plan is not an object.");if(!Ce(t,["schemaVersion","policyVersion","status",...t.transactionId===void 0?[]:["transactionId"],"proposalHash","targetLogicalTestIds","targetHashes","advisoryPlanHash","repositoryFingerprint","commands","baselineRequirements","unresolvedReasons","planHash"]))throw new Error("Resolved validation plan contains unknown or missing fields.");let n=t,{planHash:e,...r}=n;if(n.schemaVersion!==Us||n.policyVersion!==Gs||n.status!=="resolved"&&n.status!=="unavailable"||!ke.test(n.proposalHash)||!oi(n.targetLogicalTestIds,!1)||!ke.test(n.advisoryPlanHash)||!ke.test(n.repositoryFingerprint)||!Array.isArray(n.commands)||!n.commands.every(Sf)||n.transactionId!==void 0&&!/^txn_[a-f0-9]{24}$/.test(n.transactionId)||!Array.isArray(n.targetHashes)||!n.targetHashes.every(Fd)||!Array.isArray(n.baselineRequirements)||!n.baselineRequirements.every(ck)||!Array.isArray(n.unresolvedReasons)||!n.unresolvedReasons.every(lk)||!ke.test(e)||Ws(r)!==e)throw new Error("Resolved validation plan is malformed or failed integrity validation.");if(new Set(n.commands.map(s=>s.commandId)).size!==n.commands.length)throw new Error("Resolved validation plan contains duplicate command ids.");if(new Set(n.targetHashes.map(s=>s.path)).size!==n.targetHashes.length)throw new Error("Resolved validation plan contains duplicate targets.");if(new Set(n.baselineRequirements.map(s=>s.baselineId)).size!==n.baselineRequirements.length)throw new Error("Resolved validation plan contains duplicate baseline ids.");let i=new Map(n.commands.map(s=>[s.commandId,s]));if(n.baselineRequirements.some(s=>{let a=i.get(s.commandId);return a===void 0||a.timing!=="baseline"}))throw new Error("Resolved validation plan baseline references are invalid.");if(n.status==="resolved"&&n.unresolvedReasons.length>0||n.status==="unavailable"&&n.unresolvedReasons.length===0)throw new Error("Resolved validation plan status is inconsistent.");return n}var hh=Bs(vi(),1);import{readdir as FR,realpath as ph}from"node:fs/promises";import{extname as BR,isAbsolute as fh,join as HR,relative as zR,resolve as VR,sep as lh}from"node:path";import{dirname as UR,extname as Sc,join as uh}from"node:path/posix";import{open as jR}from"node:fs/promises";import{createHash as sh}from"node:crypto";function DR(t){return`${Buffer.byteLength(t,"utf8")}:${t}`}function Ne(t){return sh("sha256").update(t).digest("hex")}function B(t,n){let e=n.map(DR).join("|"),r=sh("sha256").update(e,"utf8").digest("hex");return`${t}_${r.slice(0,24)}`}import{realpath as ah,stat as LR}from"node:fs/promises";import{isAbsolute as ch,relative as MR,resolve as _R,sep as oh}from"node:path";function dh(t,n){let e=MR(t,n);if(e==="")return"";if(!(e===".."||e.startsWith(`..${oh}`)||ch(e)))return e.split(oh).join("/")}async function ki(t,n){if(n.includes("\0"))return{kind:"unauthorized",message:"Path contains a NUL byte."};let e;try{e=await ah(t)}catch{return{kind:"unreadable",message:"Authorized root could not be resolved."}}let r=ch(n)?n:_R(e,n);if(dh(e,r)===void 0)return{kind:"unauthorized",message:"Path escapes the authorized root."};let i;try{i=await ah(r)}catch(a){return a.code==="ENOENT"?{kind:"unavailable",message:"Authorized artifact does not exist."}:{kind:"unreadable",message:"Authorized artifact could not be resolved."}}let s=dh(e,i);if(s===void 0)return{kind:"unauthorized",message:"Resolved path escapes the authorized root."};try{if(!(await LR(i)).isFile())return{kind:"unreadable",message:"Authorized artifact is not a regular file."}}catch{return{kind:"unreadable",message:"Authorized artifact could not be inspected."}}return{kind:"authorized",absolutePath:i,relativePath:s}}function Ic(t){return t.length===0||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[A-Za-z]:/.test(t)?!1:t.split("/").every(e=>e!==".."&&e!==".")}async function X(t,n,e){let r=await ki(t,n);if(r.kind!=="authorized")return r;let i;try{i=await jR(r.absolutePath,"r");let s=await i.stat();if(s.size>e)return{kind:"over-budget",message:`Artifact exceeds the ${e}-byte limit.`,relativePath:r.relativePath};let a=new Uint8Array(s.size),o=0;for(;o<a.byteLength;){let d=await i.read(a,o,a.byteLength-o,o);if(d.bytesRead===0)break;o+=d.bytesRead}return o!==a.byteLength?{kind:"unreadable",message:"Artifact changed or ended while it was being read.",relativePath:r.relativePath}:{kind:"read",bytes:a,sha256:Ne(a),relativePath:r.relativePath}}catch{return{kind:"unreadable",message:"Authorized artifact could not be read.",relativePath:r.relativePath}}finally{await i?.close()}}var Ac=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],mh=new Set(Ac),qR=new Set([".js",".mjs",".cjs"]),GR=[".ts",".tsx",".mts",".cts"],KR=/(?:^|\/)(?:[^/]+\.)?(?:spec|test|cy|e2e)\.(?:[cm]?[jt]sx?)$/i,WR=new Set([".git",".kwikqa","node_modules",".yarn",".pnpm-store","coverage","dist","build","out","test-results","playwright-report"]);function Ri(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function Tc(t,n,e=new Set){if(!e.has(t)){e.add(t),n(t);for(let[r,i]of Object.entries(t))if(r!=="loc")if(Array.isArray(i))for(let s of i)Ri(s)&&Tc(s,n,e);else Ri(i)&&Tc(i,n,e)}}function JR(t){let n=Sc(t).toLowerCase();return n===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(n)?["typescript"]:["jsx"]}function ia(t){return Ri(t)&&t.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function YR(t,n){try{let e=(0,hh.parse)(t,{sourceType:"unambiguous",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:JR(n)}),r=new Set,i=!1;return Tc(e,s=>{if(s.type==="ImportDeclaration"||s.type==="ExportNamedDeclaration"||s.type==="ExportAllDeclaration"){let c=ia(s.source);c!==void 0&&r.add(c),s.type==="ExportAllDeclaration"&&(i=!0);return}if(s.type==="ImportExpression"){let c=ia(s.source);c===void 0?i=!0:r.add(c);return}if(s.type!=="CallExpression")return;let a=s.callee,o=Array.isArray(s.arguments)?s.arguments:[];if(Ri(a)&&a.type==="Import"){let c=ia(o[0]);c===void 0?i=!0:r.add(c);return}if(!Ri(a)||a.type!=="Identifier"||a.name!=="require")return;let d=ia(o[0]);d===void 0?i=!0:r.add(d)}),{imports:[...r].sort(),ambiguous:i}}catch{return{code:"parse-failed",message:"Source could not be parsed for validation discovery.",path:n}}}function Pc(t){return t.length===0||t.includes("\0")||t.includes("\\")||fh(t)?!1:t.split("/").every(n=>n.length>0&&n!=="."&&n!=="..")}function XR(t,n){return t.split("/").some(r=>WR.has(r))?!0:n.some(r=>t===r||t.startsWith(`${r}/`))}function QR(t,n){let e=zR(t,n);if(!(e===""||e===".."||e.startsWith(`..${lh}`)||fh(e)))return e.split(lh).join("/")}async function ZR(t,n,e){let r=await ph(t),i=[],s=!1;async function a(o){if(s)return;let d=(await FR(o,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name,"en"));for(let c of d){if(c.isSymbolicLink())continue;let l=HR(o,c.name),u=QR(r,l);if(!(u===void 0||XR(u,n))){if(c.isDirectory())await a(l);else if(c.isFile()&&mh.has(BR(c.name).toLowerCase())){if(i.length>=e){s=!0;return}i.push(u)}}}}return await a(r),{files:i.sort(),exhausted:s}}function eI(t,n){if(!t.startsWith("./")&&!t.startsWith("../"))return[];let e=uh(n,t),r=[e],i=Sc(e).toLowerCase();if(qR.has(i)){let s=e.slice(0,e.length-i.length);for(let a of GR)r.push(`${s}${a}`)}if(i===""){for(let s of Ac)r.push(`${e}${s}`);for(let s of Ac)r.push(uh(e,`index${s}`))}return r.filter(Pc)}function tI(t,n,e){return eI(t,UR(n)).find(r=>e.has(r))}async function nI(t){let n=[],e=await ZR(t.workspaceRoot,t.ignoredPaths??[],t.limits.maxFiles);e.exhausted&&n.push({code:"budget-exceeded",message:"Source file discovery exceeded its file limit."});let r=new Set(e.files),i=new Map,s=0,a=0,o=!e.exhausted,d=e.exhausted;for(let u of e.files){let p=await X(t.workspaceRoot,u,t.limits.maxFileBytes);if(p.kind!=="read"||p.relativePath!==u){o=!1,n.push({code:"unsafe-path",message:"Source could not be safely read.",path:u});continue}if(s+=p.bytes.byteLength,s>t.limits.maxTotalBytes){o=!1,d=!0,n.push({code:"budget-exceeded",message:"Source discovery exceeded its total byte limit."});break}let f=YR(new TextDecoder("utf-8",{fatal:!0}).decode(p.bytes),u);if("code"in f){o=!1,n.push(f),i.set(u,{path:u,imports:[],ambiguous:!0});continue}let h=[],m=f.ambiguous;for(let g of f.imports){if(!g.startsWith("./")&&!g.startsWith("../"))continue;let y=tI(g,u,r);if(y===void 0){m=!0,o=!1,n.push({code:"unresolved-local-import",message:`Local import ${JSON.stringify(g)} could not be resolved safely.`,path:u});continue}if(a+=1,a>t.limits.maxImportEdges){o=!1,d=!0,n.push({code:"budget-exceeded",message:"Import graph exceeded its edge limit."});break}h.push(y)}if(i.set(u,{path:u,imports:[...new Set(h)].sort(),ambiguous:m}),m&&(o=!1,n.push({code:"dynamic-import",message:"Module contains an import flow that cannot be bounded.",path:u})),d)break}let c=new Map;for(let u of i.values())for(let p of u.imports){let f=c.get(p)??[];f.push(u.path),c.set(p,f)}let l=new Map([...c].map(([u,p])=>[u,[...new Set(p)].sort()]));return{modules:i,reverse:l,edges:Math.min(a,t.limits.maxImportEdges),complete:o,exhausted:d,reasons:n}}function yh(t,n){return n.filter(e=>t===e.testDirectory||t.startsWith(`${e.testDirectory}/`)).sort((e,r)=>r.testDirectory.length-e.testDirectory.length||e.id.localeCompare(r.id))}function rI(t,n,e){let r=new Set,i=[];for(let s of[...t.map(a=>a.path),...n]){let o=yh(s,e)[0];o!==void 0&&!r.has(o.id)&&(r.add(o.id),i.push(o))}return i.sort((s,a)=>s.id.localeCompare(a.id))}function iI(t,n,e){let r=new Set,i=new Set(t),s=[...t].sort(),a=!0;for(let o=0;s.length>0;o+=1){if(o>=e){a=!1;break}let d=[];for(let c of s){n.modules.get(c)?.ambiguous===!0&&(a=!1);for(let u of n.reverse.get(c)??[])KR.test(u)&&r.add(u),i.has(u)||(i.add(u),d.push(u))}s=[...new Set(d)].sort()}return{tests:[...r].sort(),complete:a}}async function sa(t,n){for(let e of n){let r=await X(t,e,1e6);if(r.kind==="read"&&r.relativePath===e)return e}}async function gh(t,n){let e=[];n.some(o=>mh.has(Sc(o).toLowerCase()))&&e.push({kind:"parse",tool:"kwikqa-babel",required:!0});let r=await sa(t,["biome.json","biome.jsonc"]),i=await sa(t,[".prettierrc",".prettierrc.json","prettier.config.js","prettier.config.cjs","prettier.config.mjs"]);r!==void 0?(e.push({kind:"format",tool:"biome",configPath:r,required:!0}),e.push({kind:"lint",tool:"biome",configPath:r,required:!0})):i!==void 0&&e.push({kind:"format",tool:"prettier",configPath:i,required:!0});let s=await sa(t,["tsconfig.json"]);s!==void 0&&e.push({kind:"typecheck",tool:"typescript",configPath:s,required:!0});let a=await sa(t,["eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json"]);return r===void 0&&a!==void 0&&e.push({kind:"lint",tool:"eslint",configPath:a,required:!0}),e}function sI(t,n,e){return t.some(r=>r.class==="playwright-config"||r.class==="framework-config")?n.length===1?"project":"suite":e?"affected":n.length===1?"project":"suite"}async function Ec(t){let n=await gh(t.workspaceRoot,t.targets.map(u=>u.path));if(t.targets.length===0||!Pc(t.originalTestPath)||t.targets.some(u=>!Pc(u.path))||t.limits.maxFiles<=0||t.limits.maxFileBytes<=0||t.limits.maxTotalBytes<=0||t.limits.maxImportEdges<=0||t.limits.maxImportDepth<=0)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:n,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Discovery input is unsafe or unbounded."}]};let e=await ph(t.workspaceRoot).catch(()=>{});if(e===void 0||VR(e,t.originalTestPath)===e)return{status:"unavailable",scope:"unavailable",testPaths:[],projectIds:[],staticChecks:n,indexedFiles:0,importEdges:0,completeGraph:!1,reasons:[{code:"unsafe-path",message:"Workspace could not be resolved safely."}]};let r=await nI(t),i=t.targets.filter(u=>u.class!=="spec");if(i.length===0)return{status:"resolved",scope:"focused",testPaths:[t.originalTestPath],projectIds:yh(t.originalTestPath,t.projects).slice(0,1).map(u=>u.id),staticChecks:n,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:r.complete,reasons:[]};let s=iI(i.map(u=>u.path),r,t.limits.maxImportDepth),a=r.complete&&s.complete&&!r.exhausted,o=rI(t.targets,s.tests,t.projects),d=sI(t.targets,o,a),c=d==="affected"?[...new Set([t.originalTestPath,...s.tests])].sort():d==="project"?[...new Set([t.originalTestPath,...s.tests])].sort():[t.originalTestPath],l=[...r.reasons];return d==="suite"&&t.projects.length>0&&o.length!==1&&l.push({code:"ambiguous-project",message:"Shared impact could not be partitioned to exactly one project; full-suite validation is required."}),{status:"resolved",scope:d,testPaths:c,projectIds:o.map(u=>u.id),staticChecks:n,indexedFiles:r.modules.size,importEdges:r.edges,completeGraph:a,reasons:l}}import{spawn as fI}from"node:child_process";import{createHash as ua,randomUUID as hI}from"node:crypto";import{lstat as Ti,mkdir as Ai,readdir as mI,readFile as yI,realpath as pa}from"node:fs/promises";import{isAbsolute as Eh,join as Ye,relative as fa,resolve as Ch,sep as ha}from"node:path";var aI=/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001B]*(?:\u0007|\u001B\\))/g;function vt(t){return t.replace(aI,"")}function ce(t,n,e,r){let i=vt(t),s=[];for(let a of[...new Set(r.map(o=>o.toLowerCase()))].sort()){let o=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(`(["']?${o}["']?\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^,;&}\\r\\n]*?(?=\\s+(?:and\\s+)?[A-Za-z_$][\\w$.-]*\\s*[:=]|\\s*$|[,;&}]))`,"gim"),c=0;if(i=i.replace(d,(l,u)=>(c+=1,`${u}[REDACTED]`)),c===0){let l=new RegExp(`(${o}\\s*[:=]\\s*)\\S+`,"gi");i=i.replace(l,(u,p)=>(c+=1,`${p}[REDACTED]`))}c>0&&s.push({redactionId:B("red",[n,e,a]),ruleId:`sensitive-name:${a}`,channel:n,locator:e,action:"mask",count:c})}return{value:i,records:s}}function Ii(t,n){let e=t.toLowerCase();return n.map(r=>r.toLowerCase()).sort().find(r=>e===r||e.includes(r))}function aa(t,n,e,r){let i=[],s=new Map;for(let o of t){let d=Ii(o.name,r);if(d===void 0){i.push(o);continue}s.set(d,(s.get(d)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",[n,e,`header:${o}`]),ruleId:`sensitive-header:${o}`,channel:n,locator:e,action:"remove",count:d}));return{value:i,records:a}}function Xt(t,n,e,r){let i;try{i=new URL(t)}catch{return ce(t,n,e,r)}let s=[];(i.username!==""||i.password!=="")&&(i.username="",i.password="",s.push({redactionId:B("red",[n,e,"url-userinfo"]),ruleId:"url-userinfo",channel:n,locator:e,action:"remove",count:1}));let a=new Map;for(let o of[...i.searchParams.keys()]){let d=Ii(o,r);d!==void 0&&(i.searchParams.set(o,"[REDACTED]"),a.set(d,(a.get(d)??0)+1))}for(let[o,d]of[...a.entries()].sort(([c],[l])=>c.localeCompare(l)))s.push({redactionId:B("red",[n,e,`query:${o}`]),ruleId:`sensitive-query:${o}`,channel:n,locator:e,action:"mask",count:d});return{value:i.toString(),records:s}}var oI=new Set(["value","data-value","content","__playwright_value_","__playwright_checked_","__playwright_selected_"]),wh=["type","name","id","autocomplete","placeholder","aria-label"];function Cc(t,n,e,r){if(t==="")return{value:t,records:[]};let i=n.filter(s=>wh.includes(s.name.toLowerCase())).map(s=>Ii(s.value,r)).find(s=>s!==void 0);return i===void 0?{value:t,records:[]}:{value:"[REDACTED]",records:[{redactionId:B("red",["dom",e,`text:${i}`]),ruleId:`sensitive-element-text:${i}`,channel:"dom",locator:e,action:"mask",count:1}]}}function Nc(t,n,e){let r=t.filter(o=>wh.includes(o.name.toLowerCase())).map(o=>Ii(o.value,e)).find(o=>o!==void 0),i=[],s=new Map;for(let o of t){let d=Ii(o.name,e),c=r!==void 0&&oI.has(o.name.toLowerCase())?r:void 0,l=d??c;if(l===void 0||o.value===""){i.push(o);continue}i.push({name:o.name,value:"[REDACTED]"});let u=d===void 0?`sensitive-element:${l}`:`sensitive-field:${l}`;s.set(u,(s.get(u)??0)+1)}let a=[...s.entries()].sort(([o],[d])=>o.localeCompare(d)).map(([o,d])=>({redactionId:B("red",["dom",n,o]),ruleId:o,channel:"dom",locator:n,action:"mask",count:d}));return{value:i,records:a}}import{createHash as dI,randomUUID as da}from"node:crypto";import{constants as pr}from"node:fs";import{chmod as cI,link as lI,lstat as Ot,mkdir as vh,open as oa,readFile as kh,realpath as Nt,rename as Dc,rm as bh,unlink as Oc}from"node:fs/promises";import{dirname as $c,isAbsolute as uI,join as Qt,relative as Rh,resolve as Lc,sep as Ih}from"node:path";var pI=/^txn_[a-f0-9]{24}$/;function bn(t,n){let e=Rh(t,n);return e===""||!uI(e)&&e!==".."&&!e.startsWith(`..${Ih}`)}async function fr(t){if(process.platform==="win32")return;let n=await oa(t,"r");try{await n.sync()}finally{await n.close()}}function xh(t){return dI("sha256").update(t).digest("hex")}function Ah(){return`txn_${da().replaceAll("-","").slice(0,24)}`}function xn(t){return pI.test(t)}async function ca(t){let n=await Nt(t),e=Lc(n,".kwikqa","transactions");if(!bn(n,e))throw new Error("Transaction path escapes workspace.");return{root:n,transactionsDirectory:e}}async function ze(t,n){let e=await Nt(t),r=e;for(let i of n){if(!/^[A-Za-z0-9_.-]+$/.test(i)||i==="."||i==="..")throw new Error("Unsafe transaction directory segment.");let s=Qt(r,i),a=await Ot(s).catch(d=>{if(d.code!=="ENOENT")throw d});if(a===void 0)await vh(s,{mode:448}),await fr(r);else if(!a.isDirectory()||a.isSymbolicLink())throw new Error("Transaction directory contains an unsafe path.");let o=await Nt(s);if(!bn(e,o))throw new Error("Transaction directory escapes workspace.");r=o}return r}async function Th(t,n,e){if(!/^\.staging-[a-f0-9]{24}$/.test(n)||!xn(e))throw new Error("Transaction publication name is invalid.");let r=await ca(t),i=await Nt(r.transactionsDirectory),s=Qt(i,n),a=Qt(i,e),o=await Ot(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Transaction staging directory is unsafe.");if(await Ot(a).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Transaction already exists.");await Dc(s,a),await fr(i)}async function ye(t,n,e){let r=await Nt($c(t)),i=Lc(r,t.slice($c(t).length+1));if(!bn(r,i))throw new Error("Write target escapes its directory.");if(!e.replace&&await Ot(i).catch(c=>{if(c.code!=="ENOENT")throw c})!==void 0)throw new Error("Durable record already exists.");let s=Qt(r,`.kwikqa-${da()}.tmp`),a=await oa(s,"wx",e.mode),o=!1;try{await a.writeFile(n),await a.sync(),await a.close(),e.replace?await Dc(s,i):(await lI(s,i),await Oc(s)),o=!0,await fr(r)}finally{await a.close().catch(()=>{}),o||await Oc(s).catch(()=>{})}}async function la(t,n,e,r){let i=await Nt(t),s=Lc(i,n);if(!bn(i,s))throw new Error("Target escapes workspace.");let a=await Ot(s);if(!a.isFile()||a.isSymbolicLink())throw new Error("Target is not a regular file.");let o=await Nt($c(s)),d=await Nt(s);if(!bn(i,o)||!bn(i,d))throw new Error("Target escapes workspace.");if(Rh(i,d).split(Ih).join("/")!==n)throw new Error("Target canonical path changed during final authorization.");let l=await oa(d,pr.O_RDONLY|pr.O_NOFOLLOW);try{let m=await l.stat();if(!m.isFile()||m.dev!==a.dev||m.ino!==a.ino)throw new Error("Target changed during final authorization.");let g=await l.readFile();if(xh(g)!==e)throw new Error("Target content changed during final authorization.")}finally{await l.close()}let u=Qt(o,`.kwikqa-target-${da()}.tmp`),p=a.mode&511,f=await oa(u,pr.O_CREAT|pr.O_EXCL|pr.O_WRONLY|pr.O_NOFOLLOW,p),h=!1;try{await f.writeFile(r),await f.sync(),await f.close(),await cI(u,p);let m=await Nt(s);if(m!==d||!bn(i,m))throw new Error("Target path changed before replacement.");let g=await kh(m),y=await Ot(m);if(!y.isFile()||y.isSymbolicLink()||y.dev!==a.dev||y.ino!==a.ino||xh(g)!==e)throw new Error("Target changed before replacement.");await Dc(u,m),h=!0,await fr(o)}finally{await f.close().catch(()=>{}),h||await Oc(u).catch(()=>{})}}async function Je(t,n){let e=await ze(t,[".kwikqa","transactions"]),r=Qt(e,".lock"),i=da();await vh(r,{mode:448});let s=await Ot(r);try{await ye(Qt(r,"owner.json"),`${JSON.stringify({...n,nonce:i})}
11
+ `,{mode:384,replace:!1})}catch(a){let o=await Ot(r).catch(()=>{});throw o?.dev===s.dev&&o.ino===s.ino&&await bh(r,{recursive:!0,force:!0}).catch(()=>{}),a}return await fr(e),{release:async()=>{let a=await Ot(r).catch(()=>{});if(a===void 0||a.dev!==s.dev||a.ino!==s.ino||a.isSymbolicLink())throw new Error("Workspace lock ownership changed before release.");if(JSON.parse(await kh(Qt(r,"owner.json"),"utf8")).nonce!==i)throw new Error("Workspace lock ownership changed before release.");await bh(r,{recursive:!0,force:!1}),await fr(e)}}}var gI=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,wI=["authorization","cookie","password","passwd","secret","token","api_key","private_key"];function Mc(t,n){let e=fa(t,n);return e===""||!Eh(e)&&e!==".."&&!e.startsWith(`..${ha}`)}function bI(t){return/^[a-f0-9]{64}$/.test(t)}function xI(t){let n=mn(t.plan),e=n.commands.find(r=>r.commandId===t.commandId);if(!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||n.status!=="resolved"||!bI(n.planHash)||!Gt.test(t.commandId)||e===void 0||e.executable!==process.execPath||!Eh(e.workingDirectory)||e.args.some(r=>r.includes("\0"))||!Number.isInteger(e.timeoutMs)||e.timeoutMs<=0||!Number.isInteger(t.limits.maxStreamBytes)||t.limits.maxStreamBytes<=0||t.limits.maxStreamBytes>hn||!Number.isInteger(t.limits.maxTotalStreamBytes)||t.limits.maxTotalStreamBytes<t.limits.maxStreamBytes||!Number.isInteger(t.limits.terminationGraceMs)||t.limits.terminationGraceMs<0)throw new Error("Validation command or execution limits are invalid.");for(let[r,i]of Object.entries(e.environmentDelta))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r)||i.includes("\0"))throw new Error("Validation environment delta is invalid.");return e}async function vI(t,n){let e=await pa(t.workspaceRoot),r=Ch(e,".kwikqa","transactions",t.transactionId);if(!Mc(e,r))throw new Error("Validation transaction escapes workspace.");let i=await Ti(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Validation transaction is unsafe.");let s=t.validationRunId??`vld_${hI().replaceAll("-","").slice(0,24)}`;if(!/^vld_[a-f0-9]{24}$/.test(s))throw new Error("Validation run id is invalid.");let a=Ye(r,"validation");await Ai(a,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let o=await Ti(a);if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Validation directory is unsafe.");let d=Ye(a,s);await Ai(d,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let c=await Ti(d);if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Validation run directory is unsafe.");let l=Ye(d,"commands");await Ai(l,{mode:448}).catch(f=>{if(f.code!=="EEXIST")throw f});let u=await Ti(l);if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Validation commands directory is unsafe.");let p=Ye(l,n.commandId);return await Ai(p,{mode:448}),await Ai(Ye(p,"artifacts"),{mode:448}),{root:d,commandDirectory:p,runId:s}}var ma=class{constructor(n,e){this.cap=n;this.consumeGlobal=e}cap;consumeGlobal;#e=ua("sha256");#n=[];#t=0;#r=0;add(n){this.#e.update(n),this.#t+=n.byteLength;let e=Math.max(0,this.cap-this.#r),r=this.consumeGlobal(Math.min(e,n.byteLength));r>0&&(this.#n.push(n.subarray(0,r)),this.#r+=r)}finish(){return{text:Buffer.concat(this.#n).toString("utf8"),observed:this.#t,hash:this.#e.digest("hex"),truncated:this.#r<this.#t}}};function Ph(t,n){let e=Buffer.from(t,"utf8");if(e.byteLength<=n)return{text:t,truncated:!1};let r=n;for(;r>0&&(e[r]??0)>=128&&(e[r]??0)<192;)r-=1;return{text:e.subarray(0,r).toString("utf8"),truncated:!0}}function Sh(t){return Object.fromEntries(Object.entries(t).sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>[n,gI.test(n)?"[REDACTED]":e]))}function kI(t){return t.kind==="timeout"||t.kind==="cancelled"?"incomplete":t.kind==="spawn-error"?"unavailable":t.kind==="signal"?"incomplete":t.exitCode===0?"passed":"failed"}function RI(t){return new Promise(n=>setTimeout(n,t))}async function II(t,n,e,r){let i=await mI(n,{withFileTypes:!0}),s=[],a=0;for(let o of i.sort((d,c)=>d.name.localeCompare(c.name))){if(!o.isFile()||o.isSymbolicLink())throw new Error("Validation artifact output contains an unsafe entry.");let d=Ye(n,o.name),c=await Ti(d),l=await pa(d);if(!c.isFile()||c.isSymbolicLink()||!Mc(n,l)||c.mtimeMs+1<r)throw new Error("Validation artifact is stale or unsafe.");let u=await yI(l);if(a+=u.byteLength,s.push({path:fa(t,l).split(ha).join("/"),sha256:ua("sha256").update(u).digest("hex"),bytes:u.byteLength}),s.length>e.artifactPolicy.maxArtifacts||a>e.artifactPolicy.maxArtifactBytes)throw new Error("Validation artifact policy limit was exceeded.")}if(e.artifactPolicy.reportFile!==void 0&&!s.some(o=>o.path.split("/").at(-1)===e.artifactPolicy.reportFile))throw new Error("Required validation report artifact is missing.");return s}async function _c(t){let n=xI(t),e=await pa(t.workspaceRoot),r=await pa(n.workingDirectory);if(!Mc(e,r))throw new Error("Validation working directory escapes workspace.");let i=t.repositoryRoot??e;for(let K of n.resolutionEvidence){if(K.sha256===void 0)continue;let te=await X(i,Ch(e,K.path),16*1024*1024);if(te.kind!=="read"||te.sha256!==K.sha256)throw new Error("Validation resolution evidence changed after approval.")}let s=await vI(t,n),a=t.now??(()=>new Date),o=a(),d=t.limits.maxTotalStreamBytes,c=K=>{let te=Math.min(K,d);return d-=te,te},l=new ma(t.limits.maxStreamBytes,c),u=new ma(t.limits.maxStreamBytes,c),p=Ye(s.commandDirectory,"artifacts"),f={...t.inheritedEnvironment??process.env,...n.environmentDelta,...n.kind.startsWith("playwright-")?{PLAYWRIGHT_JSON_OUTPUT_NAME:Ye(p,n.artifactPolicy.reportFile??di)}:{},...sr(n.kind)&&!n.kind.startsWith("playwright-")?{KWIKQA_REPORT_DIR:p}:{}},h=fI(n.executable,[...n.args],{cwd:n.workingDirectory,env:f,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"]});h.stdout.on("data",K=>l.add(K)),h.stderr.on("data",K=>u.add(K));let m,g,y=K=>{m===void 0&&(m=K,h.kill(),g=setTimeout(()=>h.kill("SIGKILL"),t.limits.terminationGraceMs))},w=()=>y("cancelled");t.signal?.addEventListener("abort",w,{once:!0}),t.signal?.aborted&&y("cancelled");let x=setTimeout(()=>y("timeout"),n.timeoutMs),v=await new Promise(K=>{let te=!1;h.once("error",le=>{te||(te=!0,K({kind:"spawn-error",...le.code===void 0?{}:{code:le.code}}))}),h.once("close",(le,Y)=>{te||(te=!0,K(m!==void 0?{kind:m}:Y!==null?{kind:"signal",signal:Y}:{kind:"exit",exitCode:le??1}))})});x!==void 0&&clearTimeout(x),g!==void 0&&clearTimeout(g),t.signal?.removeEventListener("abort",w),await RI(0);let R=t.sensitiveNames??wI,P=l.finish(),C=u.finish(),E=ce(P.text,"report","validation:stdout",R).value,M=Ph(E,t.limits.maxStreamBytes),A=ce(C.text,"report","validation:stderr",R).value,N=Ph(A,t.limits.maxStreamBytes),T=M.text,I=N.text,$=Ye(s.commandDirectory,"stdout.log"),D=Ye(s.commandDirectory,"stderr.log");await ye($,T,{mode:384,replace:!1}),await ye(D,I,{mode:384,replace:!1});let k=await II(s.root,p,n,o.getTime()),S=a(),_={schemaVersion:"1.0",validationRunId:s.runId,commandId:n.commandId,commandHash:L(n),planHash:t.plan.planHash,kind:n.kind,timing:n.timing,required:n.required,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:Sh(n.environmentDelta),timeoutMs:n.timeoutMs,purpose:n.purpose,logicalTestIds:n.logicalTestIds,projectIds:n.projectIds,startedAt:o.toISOString(),durationMs:Math.max(0,S.getTime()-o.getTime()),termination:v,stdout:{path:fa(s.root,$).split(ha).join("/"),observedBytes:P.observed,storedBytes:Buffer.byteLength(T),sha256:P.hash,storedSha256:ua("sha256").update(T).digest("hex"),truncated:P.truncated||M.truncated,redacted:E!==P.text},stderr:{path:fa(s.root,D).split(ha).join("/"),observedBytes:C.observed,storedBytes:Buffer.byteLength(I),sha256:C.hash,storedSha256:ua("sha256").update(I).digest("hex"),truncated:C.truncated||N.truncated,redacted:A!==C.text},artifacts:k,status:kI(v)},q={..._,recordHash:L(_)};return await ye(Ye(s.commandDirectory,"command.json"),`${ue({commandId:n.commandId,planHash:t.plan.planHash,executable:n.executable,args:n.args,workingDirectory:n.workingDirectory,environmentDelta:Sh(n.environmentDelta)})}
12
12
  `,{mode:384,replace:!1}),await ye(Ye(s.commandDirectory,"result.json"),`${ue(q)}
13
13
  `,{mode:384,replace:!1}),{directory:s.root,record:q}}import{realpath as wP}from"node:fs/promises";import{join as bP}from"node:path";import{createHash as AI}from"node:crypto";import{readdir as TI,readFile as ya}from"node:fs/promises";import{join as $t}from"node:path";var Pi="1.0";function Nh(t){let n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error("Journal record is not an object.");return n}function PI(t){if(t.schemaVersion!==Pi||typeof t.transactionId!="string"||!xn(t.transactionId)||typeof t.manifestHash!="string"||!Array.isArray(t.targets)||t.preview===null||typeof t.preview!="object"||t.authorization===null||typeof t.authorization!="object"||t.config===null||typeof t.config!="object"||typeof t.maxTargetBytes!="number"||typeof t.createdAt!="string")throw new Error("Transaction manifest is malformed.");let n=t,{manifestHash:e,...r}=n;if(L(r)!==e)throw new Error("Transaction manifest integrity check failed.");return n}function SI(t){let n=new Set(["prepared","applying","applied","validating","rolling-back","rolled-back","completed","conflicted"]);if(t.schemaVersion!==Pi||typeof t.transactionId!="string"||!xn(t.transactionId)||typeof t.manifestHash!="string"||typeof t.stateHash!="string"||typeof t.phase!="string"||!n.has(t.phase)||!Number.isInteger(t.revision)||t.revision<1||typeof t.updatedAt!="string"||!Array.isArray(t.history))throw new Error("Transaction state is malformed.");let e=t,{stateHash:r,...i}=e;if(L(i)!==r||e.history.length!==e.revision)throw new Error("Transaction state integrity check failed.");for(let[s,a]of e.history.entries())if(a===null||typeof a!="object"||a.sequence!==s+1||typeof a.type!="string"||a.type.length===0||typeof a.at!="string"||!n.has(a.phase)||a.path!==void 0&&typeof a.path!="string"||a.message!==void 0&&typeof a.message!="string"||a.planHash!==void 0&&typeof a.planHash!="string"||a.validationRunId!==void 0&&typeof a.validationRunId!="string"||a.validationManifestHash!==void 0&&typeof a.validationManifestHash!="string")throw new Error("Transaction history is malformed.");if(e.history.at(-1)?.phase!==e.phase)throw new Error("Transaction state phase does not match its history.");return e}function EI(t){return L({purpose:"kwikqa-transaction-target",path:t}).slice(0,32)}function Oh(t){return AI("sha256").update(t).digest("hex")}async function $h(t){if(!xn(t.transactionId))throw new Error("Transaction id is invalid.");let n=`.staging-${t.transactionId.slice(4)}`,e=await ze(t.workspaceRoot,[".kwikqa","transactions",n]);await ze(t.workspaceRoot,[".kwikqa","transactions",n,"preimages"]),await ze(t.workspaceRoot,[".kwikqa","transactions",n,"results"]);let r=[];for(let c of t.targets){let l=EI(c.path),u=`preimages/${l}.bin`,p=`results/${l}.bin`;await ye($t(e,u),c.sourceBytes,{mode:384,replace:!1}),await ye($t(e,p),c.resultBytes,{mode:384,replace:!1}),r.push({id:l,path:c.path,sourceSha256:c.sourceSha256,resultSha256:c.resultSha256,preimageFile:u,resultFile:p,preimageBytes:c.sourceBytes.byteLength,resultBytes:c.resultBytes.byteLength})}let i={schemaVersion:Pi,transactionId:t.transactionId,preview:t.preview,authorization:t.authorization,config:t.config,maxTargetBytes:t.maxTargetBytes,targets:r,createdAt:t.now},s={...i,manifestHash:L(i)};await ye($t(e,"manifest.json"),`${ue(s)}
14
14
  `,{mode:384,replace:!1});let a={sequence:1,type:"prepared",at:t.now,phase:"prepared"},o={schemaVersion:Pi,transactionId:t.transactionId,manifestHash:s.manifestHash,phase:"prepared",revision:1,updatedAt:t.now,history:[a]},d={...o,stateHash:L(o)};return await ye($t(e,"state.json"),`${ue(d)}
15
15
  `,{mode:384,replace:!1}),await Th(t.workspaceRoot,n,t.transactionId),Re(t.workspaceRoot,t.transactionId)}async function Re(t,n){if(!xn(n))throw new Error("Transaction id is invalid.");let e=await ca(t),r=await ze(e.root,[".kwikqa","transactions",n]),i=PI(Nh(await ya($t(r,"manifest.json"),"utf8"))),s=SI(Nh(await ya($t(r,"state.json"),"utf8")));if(i.transactionId!==n||s.transactionId!==n||s.manifestHash!==i.manifestHash)throw new Error("Transaction identity mismatch.");let a=new Map,o=new Map;for(let d of i.targets){if(!/^[a-f0-9]{32}$/.test(d.id)||d.preimageFile!==`preimages/${d.id}.bin`||d.resultFile!==`results/${d.id}.bin`)throw new Error("Transaction target record is malformed.");let c=await ya($t(r,d.preimageFile)),l=await ya($t(r,d.resultFile));if(c.byteLength!==d.preimageBytes||l.byteLength!==d.resultBytes||Oh(c)!==d.sourceSha256||Oh(l)!==d.resultSha256)throw new Error("Transaction target bytes are malformed.");a.set(d.path,c),o.set(d.path,l)}return{directory:r,manifest:i,state:s,preimages:a,results:o}}function CI(t,n){return n==="conflicted"?t!=="completed"&&t!=="rolled-back":{prepared:["applying","rolling-back"],applying:["applying","applied","rolling-back"],applied:["validating","rolling-back"],validating:["completed","rolling-back"],"rolling-back":["rolling-back","rolled-back","applying"],"rolled-back":[],completed:[],conflicted:[]}[t].includes(n)}async function Ge(t){let n=await Re(t.transaction.manifest.preview.workspace.workspaceRoot,t.transaction.manifest.transactionId);if(n.state.revision!==t.transaction.state.revision)throw new Error("Transaction state changed concurrently.");if(!CI(n.state.phase,t.phase))throw new Error("Transaction phase transition is not permitted.");let e={sequence:n.state.history.length+1,type:t.type,at:t.now,phase:t.phase,...t.path===void 0?{}:{path:t.path},...t.message===void 0?{}:{message:t.message},...t.planHash===void 0?{}:{planHash:t.planHash},...t.validationRunId===void 0?{}:{validationRunId:t.validationRunId},...t.validationManifestHash===void 0?{}:{validationManifestHash:t.validationManifestHash}},r={schemaVersion:Pi,transactionId:n.manifest.transactionId,manifestHash:n.manifest.manifestHash,phase:t.phase,revision:n.state.revision+1,updatedAt:t.now,history:[...n.state.history,e]},i={...r,stateHash:L(r)};return await ye($t(n.directory,"state.json"),`${ue(i)}
16
- `,{mode:384,replace:!0}),Re(n.manifest.preview.workspace.workspaceRoot,n.manifest.transactionId)}async function Si(t){let n=await ca(t);return(await TI(n.transactionsDirectory,{withFileTypes:!0}).catch(r=>{if(r.code==="ENOENT")return[];throw r})).filter(r=>r.isDirectory()&&!r.isSymbolicLink()&&xn(r.name)).map(r=>r.name).sort()}import{createHash as NI}from"node:crypto";import{lstat as Lh,readFile as Mh,realpath as ga}from"node:fs/promises";import{isAbsolute as OI,relative as $I,resolve as _h,sep as DI}from"node:path";var LI=2*1024*1024,ba=4*1024*1024;function wa(t,n){let e=$I(t,n);return e===""||!OI(e)&&e!==".."&&!e.startsWith(`..${DI}`)}async function vn(t,n,e){let r=await ga(t),i=_h(r,n);if(!wa(r,i))throw new Error("Validation evidence path escapes its run.");let s=await Lh(i),a=await ga(i);if(!s.isFile()||s.isSymbolicLink()||!wa(r,a)||s.size>e)throw new Error("Validation evidence file is unsafe or unbounded.");return JSON.parse(await Mh(a,"utf8"))}async function jc(t,n){if(!Gt.test(n))throw new Error("Validation command id is invalid.");return Bd(await vn(t,`commands/${n}/result.json`,LI))}async function Dh(t,n,e,r,i){let s=_h(t,n);if(!wa(t,s))return!1;let a=await Lh(s).catch(()=>{}),o=await ga(s).catch(()=>{});if(a===void 0||o===void 0||!a.isFile()||a.isSymbolicLink()||!wa(t,o)||a.size>i||a.size!==e)return!1;let d=await Mh(o).catch(()=>{});return d!==void 0&&d.byteLength===e&&NI("sha256").update(d).digest("hex")===r}async function Fc(t,n,e){let r=await ga(t);for(let i of[n.stdout,n.stderr])if(!await Dh(r,i.path,i.storedBytes,i.storedSha256,hn))return!1;for(let i of n.artifacts)if(!await Dh(r,i.path,i.bytes,i.sha256,e))return!1;return!0}async function jh(t,n,e){try{let r=await jc(t,n.commandId);return L(r)===L(n)&&await Fc(t,n,e)}catch{return!1}}import{createHash as fP}from"node:crypto";import{lstat as ny,readFile as ry,realpath as Ma}from"node:fs/promises";import{isAbsolute as hP,relative as mP,resolve as iy,sep as yP}from"node:path";import{isAbsolute as Fh,relative as MI,sep as Bh}from"node:path";var xa=["1.55.0","1.64.1"],kt=["playwright","cypress","webdriverio"],Bc=["vitest","jest","mocha","pytest","junit","testng","cucumber","unknown"];var Hc={playwright:xa,cypress:["16.2.0"],webdriverio:["10.1.0"],vitest:["4.1.11"],jest:["30.5.2"],mocha:["11.8.0"],pytest:["8.4.2"],junit:["6.1.3"],testng:["7.12.0"],cucumber:[],unknown:[]};function Vc(t){return{...t}}function va(t,n,e){return{errorId:B("err",[n,e]),source:e,...t.message===void 0?{}:{message:t.message},...t.name===void 0?{}:{name:t.name},...t.stack===void 0?{}:{stack:t.stack},...t.snippet===void 0?{}:{snippet:t.snippet},...t.value===void 0?{}:{value:t.value},...t.location===void 0?{}:{location:Vc(t.location)}}}function Vh(t){return{type:t.type,...t.description===void 0?{}:{description:t.description},...t.location===void 0?{}:{location:Vc(t.location)}}}function Hh(t){return"text"in t?{kind:"text",text:t.text}:{kind:"base64",base64:t.buffer}}function _I(t,n,e){return{attachmentId:B("att",[n,String(e)]),name:t.name,contentType:t.contentType,sourceIndex:e,...t.path===void 0?{}:{path:t.path},...t.body===void 0?{}:{bodyBase64:t.body}}}function Uh(t,n,e){return{title:t.title,duration:t.duration,...t.error===void 0?{}:{error:va(t.error,n,`${e}.error`)},steps:t.steps.map((r,i)=>Uh(r,n,`${e}.steps[${i}]`))}}function jI(t){let n=[],e=(r,i,s)=>{r.forEach((a,o)=>{let d=`${s}[${o}]`,c=a.title.length===0?i:[...i,a.title];a.specs.forEach((l,u)=>{l.tests.forEach((p,f)=>{n.push({titlePath:[...c,l.title],spec:l,test:p,sourcePath:`${d}.specs[${u}].tests[${f}]`})})}),e(a.suites,c,`${d}.suites`)})};return e(t.suites,[],"$report.suites"),n}function zc(t,n){if(!Fh(n))return;let e=MI(t,n);if(!(Fh(e)||e===".."||e.startsWith(`..${Bh}`)))return e.split(Bh).join("/")}function FI(t,n){return t.config.projects.map(e=>{let r=e.testDir===void 0?void 0:zc(n,e.testDir);return{projectId:B("prj",[e.id,e.name]),frameworkProjectId:e.id,name:e.name,repeatEach:e.repeatEach,retries:e.retries,...r===void 0?{}:{testDir:r}}}).sort((e,r)=>e.projectId.localeCompare(r.projectId))}function BI(t,n,e,r){let i=B("atm",[n,String(t.retry),"repeat:unknown",String(e)]),s=[];return t.error!==void 0&&s.push(va(t.error,i,`${r}.error`)),t.errors.forEach((a,o)=>{s.push(va(a,i,`${r}.errors[${o}]`))}),{attemptId:i,sourceIndex:e,retry:t.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:t.status,duration:t.duration,startTime:new Date(t.startTime).toISOString(),workerIndex:t.workerIndex,parallelIndex:t.parallelIndex,errors:s,stdout:t.stdout.map(Hh),stderr:t.stderr.map(Hh),steps:t.steps.map((a,o)=>Uh(a,i,`${r}.steps[${o}]`)),attachments:t.attachments.map((a,o)=>_I(a,i,o)),annotations:t.annotations.map(Vh),...t.errorLocation===void 0?{}:{errorLocation:Vc(t.errorLocation)}}}function HI(t,n){return t.length===0?"zero-tests":t.some(e=>e.attempts.some(r=>r.status==="interrupted"))?"interrupted":n.length>0?"report-errors":"analysis-ready"}function qh(t){let{report:n,reportHash:e,artifact:r,options:i}=t,s=i.workspaceRoot,a=FI(n,s),o=n.config.rootDir===void 0?void 0:zc(s,n.config.rootDir),d=y=>{let w=y.replaceAll("\\","/");return o===void 0||o===""?w:`${o}/${w}`},c=n.config.configFile===void 0?void 0:zc(s,n.config.configFile),l=new Map(a.map(y=>[y.frameworkProjectId,y.projectId])),p=jI(n).map(({spec:y,test:w,titlePath:x,sourcePath:v})=>{let R=l.get(w.projectId);if(R===void 0)throw new Error(`Validated test references unknown project ID: ${w.projectId}`);let P=d(y.file),C=B("tst",[s,R,P,...x]);return{logicalTestId:C,projectId:R,title:y.title,titlePath:x,tags:[...y.tags].sort(),location:{file:P,line:y.line,column:y.column},timeout:w.timeout,expectedStatus:w.expectedStatus,status:w.status,annotations:w.annotations.map(Vh),attempts:w.results.map((E,M)=>BI(E,C,M,`${v}.results[${M}]`))}});p.sort((y,w)=>y.logicalTestId.localeCompare(w.logicalTestId));let f=n.errors.map((y,w)=>va(y,r.artifactId,`$report.errors[${w}]`)),h=p.reduce((y,w)=>y+w.attempts.reduce((x,v)=>x+v.attachments.length,0),0),m=new Date(n.stats.startTime).toISOString(),g=B("run",[e,s,i.gitRoot??"","1.7","1"]);return{schemaVersion:"1.7",runId:g,framework:"playwright",createdAt:m,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:r,usability:HI(p,f),projects:a,...c===void 0?{}:{configFile:c},logicalTests:p,reportErrors:f,collections:{tests:p.length===0?"empty":"present",errors:f.length===0?"empty":"present",attachments:h===0?"empty":"present"},warnings:[...t.warnings].sort(),stats:{...n.stats,startTime:m}}}var hr=class extends Error{constructor(n){super(n),this.name="ReportValidationError"}};function $e(t,n){throw new hr(`${t} must be ${n}`)}function ne(t,n){return typeof t!="object"||t===null||Array.isArray(t)?$e(n,"an object"):t}function kn(t,n){return Array.isArray(t)?t:$e(n,"an array")}function G(t,n){return typeof t!="string"?$e(n,"a string"):t}function fe(t,n){return t===void 0?void 0:G(t,n)}function Xe(t,n){return typeof t!="number"||!Number.isFinite(t)?$e(n,"a finite number"):t}function ka(t,n){let e=Xe(t,n);return Number.isInteger(e)?e:$e(n,"an integer")}function be(t,n){let e=ka(t,n);return e<0?$e(n,"a non-negative integer"):e}function Uc(t,n){let e=G(t,n);return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)||new Date(e).toISOString()!==e?$e(n,"an ISO 8601 UTC timestamp with millisecond precision"):e}function Gh(t,n){return typeof t!="boolean"?$e(n,"a boolean"):t}function pe(t,n,e,r){let i=t[n];return i===void 0?void 0:e(i,`${r}.${n}`)}function ee(t,n,e){return kn(t,n).map((r,i)=>e(r,`${n}[${i}]`))}function zI(t){return t.length===0?!0:t.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}function qc(t,n){let e=G(t,n);return zI(e)?e:$e(n,"canonical base64")}function Rn(t,n,e){let r=G(t,n);return e.has(r)?r:$e(n,`one of ${[...e].join(", ")}`)}function Ra(t,n){return n===void 0?{}:{[t]:n}}function Gc(t,n){let e=ne(t,n),r=pe(e,"line",be,n),i=pe(e,"column",be,n);return{file:G(e.file,`${n}.file`),...r===void 0?{}:{line:r},...i===void 0?{}:{column:i}}}function Ia(t,n){let e=ne(t,n),r=pe(e,"message",G,n),i=pe(e,"name",G,n),s=pe(e,"stack",G,n),a=pe(e,"snippet",G,n),o=pe(e,"value",G,n),d=pe(e,"location",Gc,n);return{...r===void 0?{}:{message:r},...i===void 0?{}:{name:i},...s===void 0?{}:{stack:s},...a===void 0?{}:{snippet:a},...o===void 0?{}:{value:o},...d===void 0?{}:{location:d}}}function Wh(t,n){let e=ne(t,n),r=pe(e,"description",G,n),i=pe(e,"location",Gc,n);return{type:G(e.type,`${n}.type`),...r===void 0?{}:{description:r},...i===void 0?{}:{location:i}}}function Kh(t,n){let e=ne(t,n),r=typeof e.text=="string",i=typeof e.buffer=="string";return r===i?$e(n,"exactly one of text or buffer"):r?{text:G(e.text,`${n}.text`)}:{buffer:qc(e.buffer,`${n}.buffer`)}}function VI(t,n){let e=ne(t,n),r=pe(e,"path",G,n),i=pe(e,"body",qc,n);return{name:G(e.name,`${n}.name`),contentType:G(e.contentType,`${n}.contentType`),...r===void 0?{}:{path:r},...i===void 0?{}:{body:i}}}function Jh(t,n){let e=ne(t,n),r=pe(e,"error",Ia,n);return{title:G(e.title,`${n}.title`),duration:Xe(e.duration,`${n}.duration`),...r===void 0?{}:{error:r},steps:ee(e.steps??[],`${n}.steps`,Jh)}}var Yh=new Set(["passed","failed","timedOut","skipped","interrupted"]),UI=new Set(["expected","unexpected","flaky","skipped"]);function qI(t,n){let e=ne(t,n),r=pe(e,"error",Ia,n),i=pe(e,"errorLocation",Gc,n);return{workerIndex:ka(e.workerIndex,`${n}.workerIndex`),parallelIndex:ka(e.parallelIndex,`${n}.parallelIndex`),status:Rn(e.status,`${n}.status`,Yh),duration:Xe(e.duration,`${n}.duration`),startTime:Uc(e.startTime,`${n}.startTime`),retry:be(e.retry,`${n}.retry`),...r===void 0?{}:{error:r},errors:ee(e.errors??[],`${n}.errors`,Ia),stdout:ee(e.stdout??[],`${n}.stdout`,Kh),stderr:ee(e.stderr??[],`${n}.stderr`,Kh),steps:ee(e.steps??[],`${n}.steps`,Jh),attachments:ee(e.attachments??[],`${n}.attachments`,VI),annotations:ee(e.annotations??[],`${n}.annotations`,Wh),...i===void 0?{}:{errorLocation:i}}}function GI(t,n){let e=ne(t,n);return{timeout:Xe(e.timeout,`${n}.timeout`),annotations:ee(e.annotations??[],`${n}.annotations`,Wh),expectedStatus:Rn(e.expectedStatus,`${n}.expectedStatus`,Yh),projectName:G(e.projectName,`${n}.projectName`),projectId:G(e.projectId,`${n}.projectId`),results:ee(e.results,`${n}.results`,qI),status:Rn(e.status,`${n}.status`,UI)}}function KI(t,n){let e=ne(t,n);return{title:G(e.title,`${n}.title`),ok:Gh(e.ok,`${n}.ok`),tags:ee(e.tags??[],`${n}.tags`,G),tests:ee(e.tests,`${n}.tests`,GI),file:G(e.file,`${n}.file`),line:be(e.line,`${n}.line`),column:be(e.column,`${n}.column`)}}function Xh(t,n){let e=ne(t,n),r=pe(e,"file",G,n),i=pe(e,"line",be,n),s=pe(e,"column",be,n);return{title:G(e.title,`${n}.title`),...r===void 0?{}:{file:r},...i===void 0?{}:{line:i},...s===void 0?{}:{column:s},suites:ee(e.suites??[],`${n}.suites`,Xh),specs:ee(e.specs??[],`${n}.specs`,KI)}}function WI(t,n){let e=ne(t,n);return{id:G(e.id,`${n}.id`),name:G(e.name,`${n}.name`),repeatEach:be(e.repeatEach,`${n}.repeatEach`),retries:be(e.retries,`${n}.retries`),...Ra("testDir",fe(e.testDir,`${n}.testDir`))}}function Qh(t){let n=ne(t,"$report"),e=ne(n.config,"$report.config"),r=ne(n.stats,"$report.stats");return{config:{version:G(e.version,"$report.config.version"),projects:ee(e.projects,"$report.config.projects",WI),...Ra("rootDir",fe(e.rootDir,"$report.config.rootDir")),...Ra("configFile",fe(e.configFile,"$report.config.configFile"))},suites:ee(n.suites,"$report.suites",Xh),errors:ee(n.errors??[],"$report.errors",Ia),stats:{startTime:Uc(r.startTime,"$report.stats.startTime"),duration:Xe(r.duration,"$report.stats.duration"),expected:be(r.expected,"$report.stats.expected"),skipped:be(r.skipped,"$report.stats.skipped"),unexpected:be(r.unexpected,"$report.stats.unexpected"),flaky:be(r.flaky,"$report.stats.flaky")}}}var JI=new TextDecoder("utf-8",{fatal:!0});function In(t,n,e){return{kind:"unreadable",artifact:{artifactId:B("art",[t??"unavailable",n??"bytes"]),kind:"report",availability:"unreadable",...n===void 0?{}:{path:n},...t===void 0?{}:{sha256:t},warnings:[]},diagnostic:e}}function YI(t){return new Set(t??xa)}function mr(t,n){let e=Ne(t);if(t.byteLength===0)return In(e,n.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...n.reportPath===void 0?{}:{path:n.reportPath}});let r;try{r=JI.decode(t)}catch{return In(e,n.reportPath,{reasonCode:"invalid-utf8",message:"The Playwright JSON report is not valid UTF-8.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let i;try{i=JSON.parse(r)}catch(p){return In(e,n.reportPath,{reasonCode:"invalid-json",message:p instanceof Error?p.message:"The report is not valid JSON.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let s;try{s=Qh(i)}catch(p){return In(e,n.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof hr?p.message:"The JSON value is not a supported Playwright report.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let a=new Set;for(let p of s.config.projects){if(a.has(p.id))return In(e,n.reportPath,{reasonCode:"invalid-report-shape",message:`$report.config.projects contains duplicate project ID: ${p.id}`,...n.reportPath===void 0?{}:{path:n.reportPath}});a.add(p.id)}if(new Set(n.incompatiblePlaywrightVersions??[]).has(s.config.version))return In(e,n.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${s.config.version} is configured as incompatible.`,...n.reportPath===void 0?{}:{path:n.reportPath}});let c=YI(n.testedPlaywrightVersions).has(s.config.version),l=[];c||l.push(`unverified-producer-version:${s.config.version}`),s.config.projects.some(p=>p.repeatEach>1)&&l.push("repeat-index-unavailable");let u={artifactId:B("art",[e]),kind:"report",availability:"present",...n.reportPath===void 0?{}:{path:n.reportPath},sha256:e,format:"playwright-json",formatVersion:s.config.version,versionConfidence:c?"verified":"unverified",warnings:[...l].sort()};try{return{kind:"parsed",run:qh({report:s,reportHash:e,artifact:u,options:n,warnings:l})}}catch(p){return In(e,n.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Error?p.message:"The report could not be normalized.",...n.reportPath===void 0?{}:{path:n.reportPath}})}}import{createHash as QT}from"node:crypto";import{readdir as ZT,readFile as eP,stat as tP}from"node:fs/promises";import{basename as nP,dirname as rP,join as iP}from"node:path";import{resolve as oA}from"node:path";import{readdir as XI,stat as QI}from"node:fs/promises";import{join as Zh}from"node:path";var nm=/\.(?:java|kt|groovy|scala)$/,ZI=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,eA=/^(?:java|javax|jdk|sun|com\.sun|org\.junit|junit|org\.testng|org\.openqa\.selenium|org\.assertj|org\.hamcrest|org\.opentest4j|org\.apache\.maven|org\.gradle|worker\.org\.gradle|io\.cucumber|kotlin|kotlinx|scala|groovy|org\.codehaus\.groovy|org\.springframework\.test)\./,tA=["src/test/java","src/main/java","src/it/java","src/test/kotlin","src/main/kotlin","src/test/groovy","src/main/groovy","src/test/scala","src/main/scala"],nA=["src/test/resources","src/main/resources"];function Aa(t){return nm.test(t)}function em(t){return t.endsWith(".feature")}function An(t,n="java"){return`${(t.split("$")[0]??t).replaceAll(".","/")}.${n}`}function gr(t){let n=ZI.exec(t.trim());if(n===null)return;let[,e,r,i,s,a]=n;if(r===void 0||i===void 0||s===void 0||a===void 0||e!==void 0&&e!=="app"||eA.test(`${r}.`))return;let o=s.replace(nm,""),d=r.lastIndexOf(`.${o}`),c=d>=0?r.slice(0,d):r.split(".").slice(0,-1).join(".");return{file:`${c===""?"":`${c.replaceAll(".","/")}/`}${s}`,line:Number.parseInt(a,10),className:r,method:i}}async function tm(t){try{return(await QI(t)).isFile()}catch{return!1}}async function rA(t){return(await XI(t,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules"&&e.name!=="src"&&e.name!=="target"&&e.name!=="build").map(e=>e.name).sort()}var yr=class{constructor(n){this.workspaceRoot=n}workspaceRoot;modules;found=new Map;find(n){let e=this.found.get(n);return e===void 0&&(e=this.lookup(n),this.found.set(n,e)),e}async resolve(n){return Aa(n)||em(n)?await this.find(n)??n:n}async lookup(n){if(await tm(Zh(this.workspaceRoot,n)))return n;let e=em(n)?nA:tA;this.modules??=rA(this.workspaceRoot);let r=[...e,...(await this.modules).flatMap(i=>e.map(s=>`${i}/${s}`))];for(let i of r){let s=`${i}/${n}`;if(await tm(Zh(this.workspaceRoot,s)))return s}}};var iA=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,sA=/^File "([^"]+\.py)", line (\d+)/,aA=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/;function im(t){let n=t,e=/^webpack:\/\/[^/]*\/(.*)$/.exec(n);return e!==null&&(n=e[1]??""),n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1))),n.replace(/^(?:\.\/)+/,"")}function rm(t){return/^https?:\/\//.test(t)||t.includes("/__cypress/")||t.includes("node_modules/")||t.startsWith("node:")||t.startsWith("internal/")||t.includes("site-packages/")||/\/lib\/python\d/.test(t)||t.startsWith("<")}function sm(t){let n=[];for(let e of t.split(/\r?\n/)){let r=e.trim().replace(/^❯\s+/,""),i=gr(r);if(i!==void 0){n.push({file:i.file,line:i.line,column:1});continue}let s=sA.exec(r)??aA.exec(r),a=s===null?iA.exec(r):[s[0],s[1],s[2],"1"];if(a===null)continue;let[,o,d,c]=a;if(o===void 0||d===void 0||c===void 0||rm(o))continue;let l=im(o);l===""||rm(l)||n.push({file:l,line:Number.parseInt(d,10),column:Number.parseInt(c,10)})}return n}function ve(t,n){if(t===void 0)return;let e=sm(t);if(n!==void 0){let r=n.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),i=e.find(s=>{let a=s.file.replaceAll("\\","/");return a===r||a.endsWith(`/${r}`)||r.endsWith(`/${a}`)});if(i!==void 0)return i}return e[0]}var dA="1",cA="application/vnd.allure.playwright-trace";function Wc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jc(t){return Wc(t)&&typeof t.uuid=="string"&&typeof t.status=="string"&&Array.isArray(t.labels)&&(typeof t.historyId=="string"||typeof t.fullName=="string")}function Yc(t){return Wc(t)&&typeof t.uuid=="string"&&typeof t.status!="string"&&(Array.isArray(t.children)||Array.isArray(t.befores)||Array.isArray(t.afters))}function Xc(t){return Wc(t)&&t.uuid===void 0&&Array.isArray(t.errors)&&Array.isArray(t.attachments)}var lA={testng:"testng","junit-platform":"junit",junit5:"junit",junit4:"junit",junit:"junit",pytest:"pytest",playwright:"playwright",cypress:"cypress",webdriverio:"webdriverio",jest:"jest",vitest:"vitest",mocha:"mocha"};function Dt(t,n){return t.labels?.find(e=>e.name===n)?.value}var am={passed:"passed",failed:"failed",broken:"failed",skipped:"skipped"};function Ta(t){return t==="junit"||t==="testng"}function Ei(t,n){let e=t?.message?.trim()||void 0,r=t?.trace?.trim()||void 0;if(e===void 0&&r===void 0)return;let i=ve(r,n);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...i===void 0?{}:{location:i}}}function om(t){for(let n of(t??"").split(`
17
- `)){let e=gr(n);if(e!==void 0)return e}}function Qc(t){return typeof t.start=="number"&&typeof t.stop=="number"&&t.stop>=t.start?t.stop-t.start:0}function lm(t){let n=typeof t=="number"?new Date(t):void 0;return n===void 0||Number.isNaN(n.getTime())?{}:{startTime:n.toISOString()}}function Zc(t,n){let r=t.status==="failed"||t.status==="broken"?Ei(t.statusDetails,n):void 0;return{title:t.name??"",duration:Qc(t),...r===void 0?{}:{error:r},steps:(t.steps??[]).map(i=>Zc(i,n))}}function um(t,n){return[...(t.attachments??[]).flatMap(r=>r.source===void 0?[]:[{name:r.name??r.source,contentType:r.type===cA?"application/zip":r.type??"",path:n===void 0?r.source:oA(n,r.source)}]),...(t.steps??[]).flatMap(r=>um(r,n))]}function uA(t){return t.replace(/^\[/,"").replace(/\]$/,"").split("]/[").map(n=>{let e=n.indexOf(":");return{type:n.slice(0,e),value:n.slice(e+1)}})}function pA(t){let n=Dt(t,"junit.platform.uniqueid")??t.parameters?.find(a=>a.name==="UniqueId")?.value;if(n===void 0)return;let e=uA(n),r=e.findIndex(a=>a.type==="test-template"||a.type==="test-factory");if(r<0)return;let i=e.slice(r+1).map(a=>/^#(\d+)$/.exec(a.value)?.[1]);return i.length===0||i.includes(void 0)?void 0:`${(e[r]?.value??"").replace(/\(([^)]*)\)$/,(a,o)=>`(${o.split(",").map(c=>c.trim().split(/[.$]/).at(-1)??"").filter(c=>c!=="").join(", ")})`)}${i.map(a=>`[${a}]`).join("")}`}function fA(t){let n=t.split(".").filter(r=>r!==""),e=n.length;for(;e>1&&/^[A-Z]/.test(n[e-1]??"");)e-=1;return{file:`${n.slice(0,e).join("/")}.py`,classes:n.slice(e)}}function hA(t){let n=t.titlePath??[],e=n.findIndex(r=>r.endsWith(".py"));return e>=0?{file:n.slice(0,e+1).join("/"),classes:n.slice(e+1)}:fA((t.fullName??"").split("#")[0]??"")}function Kc(t,n){return{file:An(t),titlePath:[...t.split("$").filter(e=>e!==""),n],projectId:""}}function dm(t,n,e){let r=Dt(t,"testClass");if(r!==void 0&&Ta(n))return Kc(r,e);if(n==="pytest"){let{file:s,classes:a}=hA(t);return{file:s,titlePath:[...a,e],projectId:""}}if(n==="playwright"){let s=(t.fullName??e).split(" \u203A ");return{file:Dt(t,"suite")??s[0]??"",titlePath:s.length>1?s.slice(1):[e],projectId:Dt(t,"parentSuite")??""}}let i=Dt(t,"suite");return{file:i!==void 0&&/\.[cm]?[jt]sx?$/.test(i)?i:"",titlePath:[t.fullName??e],projectId:""}}function cm(t,n,e,r){return{status:"failed",retry:n,...lm(t.start),duration:Qc(t),errors:e===void 0?[]:[e],attachments:[],stdout:[],stderr:[],steps:(t.steps??[]).map(i=>Zc(i,r))}}function pm(t){let n=[],e=[],r=[];for(let A of t)Jc(A.json)?n.push({...A.json,...A.directory===void 0?{}:{directory:A.directory}}):Yc(A.json)?e.push(A.json):Xc(A.json)&&r.push(...A.json.errors);if(n.length===0)throw new Error("The Allure results hold no test result.");let i=new Set(n.map(A=>lA[Dt(A,"framework")??""]??"unknown")),s=i.size===1?[...i][0]??"unknown":"unknown",a=[];i.size>1&&a.push("allure-mixed-frameworks");let o=new Map;for(let A of n){let N=A.historyId??`uuid:${A.uuid}`,T=o.get(N)??{key:N,results:[]};o.set(N,T),T.results.push(A)}let d=new Map,c=A=>{let N=Dt(A,"testMethod");if(s==="junit")return pA(A)??N??A.name??"";if(s!=="testng")return A.name??"";let T=N??A.name??"",I=(A.parameters??[]).map(S=>S.value??"");if(I.length===0)return T;let $=`${Dt(A,"testClass")??""}\0${T}`,D=d.get($)??new Map;d.set($,D);let k=D.get(JSON.stringify(I))??D.size;return D.set(JSON.stringify(I),k),`${T}[${k}]`},l=0,u=0,p=new Map,f=[],h=[...o.values()].sort((A,N)=>{let T=I=>Math.min(...I.results.map($=>$.start??0));return T(A)-T(N)||A.key.localeCompare(N.key)});for(let A of h){let N=[...A.results].sort((D,k)=>(D.start??0)-(k.start??0)||D.uuid.localeCompare(k.uuid)),T=N.filter((D,k)=>{let S=D.status==="passed"&&k<N.length-1;return S&&(l+=1),!S}),I=T.at(-1);if(I===void 0)continue;p.set(A.key,I);let $=dm(I,s,c(I));f.push({file:$.file,titlePath:$.titlePath,projectId:$.projectId,attempts:T.map((D,k)=>{let S=k<T.length-1,_=am[D.status??""];!S&&_===void 0&&(u+=1);let q=S?"failed":_??"skipped",K=q==="passed"?void 0:Ei(D.statusDetails,$.file);return{status:q,retry:k,...lm(D.start),duration:Qc(D),errors:K===void 0?[]:[K],attachments:um(D,D.directory),stdout:[],stderr:[],steps:(D.steps??[]).map(te=>Zc(te,$.file))}})})}l>0&&a.push(`allure-passed-before-retry-ignored:${l}`),u>0&&a.push(`allure-unknown-status:${u}`);let m=new Map;for(let A of o.values()){let N=p.get(A.key);if(N!==void 0)for(let T of A.results)m.set(T.uuid,N)}let g=new Set;for(let A of e){let N=(A.children??[]).map(I=>m.get(I)).filter(I=>I!==void 0);if(N.some(I=>am[I.status??""]==="failed"))continue;let T=[...(A.befores??[]).map(I=>({fixture:I,phase:"setup"})),...(A.afters??[]).map(I=>({fixture:I,phase:"teardown"}))].filter(({fixture:I})=>I.status==="failed"||I.status==="broken");for(let{fixture:I,phase:$}of T){let D=Ta(s)?om(I.statusDetails?.trace):void 0,k=I.name??D?.method??"fixture",S=N[0],_=D?.className??(S===void 0?void 0:Dt(S,"testClass")),q=`${k} (${$})`,K=_!==void 0&&Ta(s)?Kc(_,q):S===void 0?void 0:dm(S,s,q);if(K===void 0)continue;let te=`${_??K.file}\0${k}`;g.has(te)||(g.add(te),f.push({...K,attempts:[cm(I,0,Ei(I.statusDetails,K.file),K.file)]}))}}let y=[],w=new Map,x=[...r].sort((A,N)=>(A.timestamp??0)-(N.timestamp??0));for(let A of x){let N=Ta(s)?om(A.trace):void 0;if(N===void 0){let S=Ei(A,"");S!==void 0&&y.push(S);continue}let T=`${N.className}\0${N.method}`;if(g.has(T))continue;let I=/\bdid not run\b/.test(A.message??"")?"setup":"teardown",$=Kc(N.className,`${N.method} (${I})`),D=w.get(T)??{...$,attempts:[]};w.set(T,D);let k=A.timestamp===void 0?{}:{start:A.timestamp};D.attempts.push(cm(k,D.attempts.length,Ei(A,$.file),$.file))}f.push(...w.values());let v=new Map;if(s==="playwright")for(let A of f)for(let N of A.attempts.flatMap(T=>T.errors)){let T=N.location?.file;T!==void 0&&!v.has(A.file)&&T.replaceAll("\\","/").endsWith(`/${A.file}`)&&v.set(A.file,T)}let R=f.map(A=>{let N=v.get(A.file);return N===void 0?A:{...A,file:N}}),P=n.flatMap(A=>typeof A.start=="number"?[A.start]:[]),C=n.flatMap(A=>typeof A.stop=="number"?[A.stop]:[]),E=P.length===0?void 0:new Date(Math.min(...P)).toISOString(),M=[...new Set(R.map(A=>A.projectId))].sort();return{framework:s,format:"allure-json",adapterVersion:dA,...E===void 0?{}:{startTime:E},duration:P.length===0||C.length===0?0:Math.max(...C)-Math.min(...P),projects:(M.length===0?[""]:M).map(A=>({id:A,name:A,retries:0})),tests:R,errors:y,interrupted:!1,warnings:a}}var mA="1",yA=["0.2.0","1.0.0"];function fm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function el(t){return fm(t)&&t.reportFormat==="CTRF"&&fm(t.results)&&Array.isArray(t.results.tests)}var gA=[...kt,...Bc];function wA(t){let n=t?.trim().toLowerCase()??"";return gA.includes(n)?n:"unknown"}var bA={passed:"passed",failed:"failed",skipped:"skipped",pending:"skipped"};function ym(t){if(typeof t!="number")return;let n=new Date(t);return Number.isNaN(n.getTime())?void 0:n.toISOString()}function xA(t,n){let e=t.message?.trim()||void 0,r=t.trace?.trim()||void 0,i=t.snippet?.trimEnd()||void 0;if(e===void 0&&r===void 0)return;let s=ve(r,n);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...i===void 0?{}:{snippet:i},...s===void 0?{}:{location:s}}}function vA(t){return(t.attachments??[]).flatMap(n=>n.path===void 0||n.path===""?[]:[{name:n.name??n.path,contentType:n.contentType??"",path:n.path}])}function hm(t,n,e,r,i){let s=ym(t.start),a=t.duration,o=typeof t.start=="number"&&typeof t.stop=="number"?t.stop-t.start:void 0,d=typeof a=="number"&&a>=0?a:o??0,c=n==="passed"?void 0:xA(t,r);return{status:n,retry:e,...s===void 0?{}:{startTime:s},duration:d>=0?d:0,errors:c===void 0?[]:[c],attachments:vA(t),stdout:t.stdout??[],stderr:t.stderr??[],steps:i}}function mm(t,n){if(n===void 0||t==="")return!1;let e=n.replaceAll("\\","/"),r=t.replaceAll("\\","/");return e===r||e.endsWith(`/${r}`)}function kA(t,n){let e=(t.suite??[]).filter(o=>o!==""),r=t.name??"",i=e.findIndex(o=>mm(o,t.filePath)),s=i<0?e:e.slice(i+1),a=i>0?e.slice(0,i).join(" \u203A "):"";if(n==="pytest"&&r.includes("::")){let o=r.split("::");return{titlePath:mm(o[0]??"",t.filePath)?o.slice(1):o,projectId:a}}if(n==="jest"){let o=`${s.join(" ")} `,d=s.length>0&&r.startsWith(o)?r.slice(o.length):r;return{titlePath:[...s,d],projectId:a}}return{titlePath:[...s,r],projectId:a}}function gm(t){if(!el(t))throw new Error("A CTRF report needs results with a tests array.");let n=t,e=wA(n.results.tool?.name),r=n.results.tool?.version?.trim()||void 0,i=[],s=n.specVersion??"";yA.includes(s)||i.push(`unverified-ctrf-spec-version:${s===""?"unrecorded":s}`);let a=0,o=0,d=!1,c=m=>{let g=bA[m.status??""];return g===void 0&&(a+=1),g??"skipped"},l=n.results.tests.map(m=>{let g=m.filePath??"",y=kA(m,e),w=m.retryAttempts??[];typeof m.retries=="number"&&m.retries>w.length&&(d=!0);let x=(m.steps??[]).map(P=>({title:P.name??"",duration:0,steps:[]})),v=[...w.map((P,C)=>hm(P,c(P),C,g,[])),hm(m,c(m),w.length,g,x)],R=v.at(-1)?.status==="passed"&&v.slice(0,-1).some(P=>P.status==="failed");return typeof m.flaky=="boolean"&&m.flaky!==R&&(o+=1),{file:g,titlePath:y.titlePath,...typeof m.line=="number"&&m.line>0?{line:m.line}:{},projectId:y.projectId,...m.tags===void 0?{}:{tags:m.tags},attempts:v}});a>0&&i.push(`ctrf-other-status:${a}`),o>0&&i.push(`ctrf-flaky-mismatch:${o}`),d&&i.push("final-attempt-only");let{start:u,stop:p}=n.results.summary??{},f=ym(u),h=[...new Set(l.map(m=>m.projectId))].sort();return{framework:e,format:"ctrf-json",adapterVersion:mA,...r===void 0?{}:{frameworkVersion:r},...f===void 0?{}:{startTime:f},duration:typeof u=="number"&&typeof p=="number"&&p>=u?p-u:0,projects:(h.length===0?[""]:h).map(m=>({id:m,name:m,retries:0})),tests:l,errors:[],interrupted:!1,warnings:i}}var RA="1";function IA(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function tl(t){return Array.isArray(t)&&t.length>0&&t.every(n=>IA(n)&&typeof n.uri=="string"&&typeof n.keyword=="string"&&Array.isArray(n.elements))}function AA(t){return t.startsWith("classpath:")?t.slice(10).replace(/^\/+/,""):t}var bm=new Set(["undefined","ambiguous","pending"]),TA=1e6;function wm(t){let n=t.result?.duration;return typeof n=="number"&&n>0?n/TA:0}function PA(t,n){return n!==void 0?`${n} hook`:`${(t.keyword??"").trim()} ${t.name??""}`.trim()}function SA(t,n){if(n!==void 0||t.hidden!==!0)return n;let e=(t.keyword??"").trim();return e==="Before"||e==="After"?e:void 0}function EA(t,n,e,r){let i=t.result?.status??"",s=t.result?.error_message?.trim()||void 0,a=typeof t.line=="number"?{file:r,line:t.line}:void 0;if(bm.has(i))return{message:`${i[0]?.toUpperCase()}${i.slice(1)} step: ${n}`,...s===void 0?{}:{stack:s},...a===void 0?{}:{location:a}};if(i!=="failed"||s===void 0)return;let o=s.split(/\r?\n/),d=o.findIndex(u=>/^\s*at\s/.test(u)),c=(d<0?o:o.slice(0,d)).join(`
16
+ `,{mode:384,replace:!0}),Re(n.manifest.preview.workspace.workspaceRoot,n.manifest.transactionId)}async function Si(t){let n=await ca(t);return(await TI(n.transactionsDirectory,{withFileTypes:!0}).catch(r=>{if(r.code==="ENOENT")return[];throw r})).filter(r=>r.isDirectory()&&!r.isSymbolicLink()&&xn(r.name)).map(r=>r.name).sort()}import{createHash as NI}from"node:crypto";import{lstat as Lh,readFile as Mh,realpath as ga}from"node:fs/promises";import{isAbsolute as OI,relative as $I,resolve as _h,sep as DI}from"node:path";var LI=2*1024*1024,ba=4*1024*1024;function wa(t,n){let e=$I(t,n);return e===""||!OI(e)&&e!==".."&&!e.startsWith(`..${DI}`)}async function vn(t,n,e){let r=await ga(t),i=_h(r,n);if(!wa(r,i))throw new Error("Validation evidence path escapes its run.");let s=await Lh(i),a=await ga(i);if(!s.isFile()||s.isSymbolicLink()||!wa(r,a)||s.size>e)throw new Error("Validation evidence file is unsafe or unbounded.");return JSON.parse(await Mh(a,"utf8"))}async function jc(t,n){if(!Gt.test(n))throw new Error("Validation command id is invalid.");return Bd(await vn(t,`commands/${n}/result.json`,LI))}async function Dh(t,n,e,r,i){let s=_h(t,n);if(!wa(t,s))return!1;let a=await Lh(s).catch(()=>{}),o=await ga(s).catch(()=>{});if(a===void 0||o===void 0||!a.isFile()||a.isSymbolicLink()||!wa(t,o)||a.size>i||a.size!==e)return!1;let d=await Mh(o).catch(()=>{});return d!==void 0&&d.byteLength===e&&NI("sha256").update(d).digest("hex")===r}async function Fc(t,n,e){let r=await ga(t);for(let i of[n.stdout,n.stderr])if(!await Dh(r,i.path,i.storedBytes,i.storedSha256,hn))return!1;for(let i of n.artifacts)if(!await Dh(r,i.path,i.bytes,i.sha256,e))return!1;return!0}async function jh(t,n,e){try{let r=await jc(t,n.commandId);return L(r)===L(n)&&await Fc(t,n,e)}catch{return!1}}import{createHash as fP}from"node:crypto";import{lstat as ny,readFile as ry,realpath as Ma}from"node:fs/promises";import{isAbsolute as hP,relative as mP,resolve as iy,sep as yP}from"node:path";import{isAbsolute as Fh,relative as MI,sep as Bh}from"node:path";var xa=["1.55.0","1.64.1"],kt=["playwright","cypress","webdriverio"],Bc=["vitest","jest","mocha","pytest","junit","testng","cucumber","unknown"];var Hc={playwright:xa,cypress:["16.2.0"],webdriverio:["10.1.0"],vitest:["4.1.11"],jest:["30.5.2"],mocha:["11.8.0"],pytest:["8.4.2"],junit:["6.1.3"],testng:["7.12.0"],cucumber:[],unknown:[]};function Vc(t){return{...t}}function va(t,n,e){return{errorId:B("err",[n,e]),source:e,...t.message===void 0?{}:{message:t.message},...t.name===void 0?{}:{name:t.name},...t.stack===void 0?{}:{stack:t.stack},...t.snippet===void 0?{}:{snippet:t.snippet},...t.value===void 0?{}:{value:t.value},...t.location===void 0?{}:{location:Vc(t.location)}}}function Vh(t){return{type:t.type,...t.description===void 0?{}:{description:t.description},...t.location===void 0?{}:{location:Vc(t.location)}}}function Hh(t){return"text"in t?{kind:"text",text:t.text}:{kind:"base64",base64:t.buffer}}function _I(t,n,e){return{attachmentId:B("att",[n,String(e)]),name:t.name,contentType:t.contentType,sourceIndex:e,...t.path===void 0?{}:{path:t.path},...t.body===void 0?{}:{bodyBase64:t.body}}}function Uh(t,n,e){return{title:t.title,duration:t.duration,...t.error===void 0?{}:{error:va(t.error,n,`${e}.error`)},steps:t.steps.map((r,i)=>Uh(r,n,`${e}.steps[${i}]`))}}function jI(t){let n=[],e=(r,i,s)=>{r.forEach((a,o)=>{let d=`${s}[${o}]`,c=a.title.length===0?i:[...i,a.title];a.specs.forEach((l,u)=>{l.tests.forEach((p,f)=>{n.push({titlePath:[...c,l.title],spec:l,test:p,sourcePath:`${d}.specs[${u}].tests[${f}]`})})}),e(a.suites,c,`${d}.suites`)})};return e(t.suites,[],"$report.suites"),n}function zc(t,n){if(!Fh(n))return;let e=MI(t,n);if(!(Fh(e)||e===".."||e.startsWith(`..${Bh}`)))return e.split(Bh).join("/")}function FI(t,n){return t.config.projects.map(e=>{let r=e.testDir===void 0?void 0:zc(n,e.testDir);return{projectId:B("prj",[e.id,e.name]),frameworkProjectId:e.id,name:e.name,repeatEach:e.repeatEach,retries:e.retries,...r===void 0?{}:{testDir:r}}}).sort((e,r)=>e.projectId.localeCompare(r.projectId))}function BI(t,n,e,r){let i=B("atm",[n,String(t.retry),"repeat:unknown",String(e)]),s=[];return t.error!==void 0&&s.push(va(t.error,i,`${r}.error`)),t.errors.forEach((a,o)=>{s.push(va(a,i,`${r}.errors[${o}]`))}),{attemptId:i,sourceIndex:e,retry:t.retry,repeat:{state:"unknown",reason:"not-serialized-by-playwright-json-reporter"},status:t.status,duration:t.duration,startTime:new Date(t.startTime).toISOString(),workerIndex:t.workerIndex,parallelIndex:t.parallelIndex,errors:s,stdout:t.stdout.map(Hh),stderr:t.stderr.map(Hh),steps:t.steps.map((a,o)=>Uh(a,i,`${r}.steps[${o}]`)),attachments:t.attachments.map((a,o)=>_I(a,i,o)),annotations:t.annotations.map(Vh),...t.errorLocation===void 0?{}:{errorLocation:Vc(t.errorLocation)}}}function HI(t,n){return t.length===0?"zero-tests":t.some(e=>e.attempts.some(r=>r.status==="interrupted"))?"interrupted":n.length>0?"report-errors":"analysis-ready"}function qh(t){let{report:n,reportHash:e,artifact:r,options:i}=t,s=i.workspaceRoot,a=FI(n,s),o=n.config.rootDir===void 0?void 0:zc(s,n.config.rootDir),d=y=>{let w=y.replaceAll("\\","/");return o===void 0||o===""?w:`${o}/${w}`},c=n.config.configFile===void 0?void 0:zc(s,n.config.configFile),l=new Map(a.map(y=>[y.frameworkProjectId,y.projectId])),p=jI(n).map(({spec:y,test:w,titlePath:x,sourcePath:v})=>{let R=l.get(w.projectId);if(R===void 0)throw new Error(`Validated test references unknown project ID: ${w.projectId}`);let P=d(y.file),C=B("tst",[s,R,P,...x]);return{logicalTestId:C,projectId:R,title:y.title,titlePath:x,tags:[...y.tags].sort(),location:{file:P,line:y.line,column:y.column},timeout:w.timeout,expectedStatus:w.expectedStatus,status:w.status,annotations:w.annotations.map(Vh),attempts:w.results.map((E,M)=>BI(E,C,M,`${v}.results[${M}]`))}});p.sort((y,w)=>y.logicalTestId.localeCompare(w.logicalTestId));let f=n.errors.map((y,w)=>va(y,r.artifactId,`$report.errors[${w}]`)),h=p.reduce((y,w)=>y+w.attempts.reduce((x,v)=>x+v.attachments.length,0),0),m=new Date(n.stats.startTime).toISOString(),g=B("run",[e,s,i.gitRoot??"","1.7","1"]);return{schemaVersion:"1.7",runId:g,framework:"playwright",createdAt:m,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:r,usability:HI(p,f),projects:a,...c===void 0?{}:{configFile:c},logicalTests:p,reportErrors:f,collections:{tests:p.length===0?"empty":"present",errors:f.length===0?"empty":"present",attachments:h===0?"empty":"present"},warnings:[...t.warnings].sort(),stats:{...n.stats,startTime:m}}}var mr=class extends Error{constructor(n){super(n),this.name="ReportValidationError"}};function $e(t,n){throw new mr(`${t} must be ${n}`)}function ne(t,n){return typeof t!="object"||t===null||Array.isArray(t)?$e(n,"an object"):t}function kn(t,n){return Array.isArray(t)?t:$e(n,"an array")}function G(t,n){return typeof t!="string"?$e(n,"a string"):t}function fe(t,n){return t===void 0?void 0:G(t,n)}function Xe(t,n){return typeof t!="number"||!Number.isFinite(t)?$e(n,"a finite number"):t}function ka(t,n){let e=Xe(t,n);return Number.isInteger(e)?e:$e(n,"an integer")}function be(t,n){let e=ka(t,n);return e<0?$e(n,"a non-negative integer"):e}function Uc(t,n){let e=G(t,n);return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)||new Date(e).toISOString()!==e?$e(n,"an ISO 8601 UTC timestamp with millisecond precision"):e}function Gh(t,n){return typeof t!="boolean"?$e(n,"a boolean"):t}function pe(t,n,e,r){let i=t[n];return i===void 0?void 0:e(i,`${r}.${n}`)}function ee(t,n,e){return kn(t,n).map((r,i)=>e(r,`${n}[${i}]`))}function zI(t){return t.length===0?!0:t.length%4!==0?!1:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}function qc(t,n){let e=G(t,n);return zI(e)?e:$e(n,"canonical base64")}function Rn(t,n,e){let r=G(t,n);return e.has(r)?r:$e(n,`one of ${[...e].join(", ")}`)}function Ra(t,n){return n===void 0?{}:{[t]:n}}function Gc(t,n){let e=ne(t,n),r=pe(e,"line",be,n),i=pe(e,"column",be,n);return{file:G(e.file,`${n}.file`),...r===void 0?{}:{line:r},...i===void 0?{}:{column:i}}}function Ia(t,n){let e=ne(t,n),r=pe(e,"message",G,n),i=pe(e,"name",G,n),s=pe(e,"stack",G,n),a=pe(e,"snippet",G,n),o=pe(e,"value",G,n),d=pe(e,"location",Gc,n);return{...r===void 0?{}:{message:r},...i===void 0?{}:{name:i},...s===void 0?{}:{stack:s},...a===void 0?{}:{snippet:a},...o===void 0?{}:{value:o},...d===void 0?{}:{location:d}}}function Wh(t,n){let e=ne(t,n),r=pe(e,"description",G,n),i=pe(e,"location",Gc,n);return{type:G(e.type,`${n}.type`),...r===void 0?{}:{description:r},...i===void 0?{}:{location:i}}}function Kh(t,n){let e=ne(t,n),r=typeof e.text=="string",i=typeof e.buffer=="string";return r===i?$e(n,"exactly one of text or buffer"):r?{text:G(e.text,`${n}.text`)}:{buffer:qc(e.buffer,`${n}.buffer`)}}function VI(t,n){let e=ne(t,n),r=pe(e,"path",G,n),i=pe(e,"body",qc,n);return{name:G(e.name,`${n}.name`),contentType:G(e.contentType,`${n}.contentType`),...r===void 0?{}:{path:r},...i===void 0?{}:{body:i}}}function Jh(t,n){let e=ne(t,n),r=pe(e,"error",Ia,n);return{title:G(e.title,`${n}.title`),duration:Xe(e.duration,`${n}.duration`),...r===void 0?{}:{error:r},steps:ee(e.steps??[],`${n}.steps`,Jh)}}var Yh=new Set(["passed","failed","timedOut","skipped","interrupted"]),UI=new Set(["expected","unexpected","flaky","skipped"]);function qI(t,n){let e=ne(t,n),r=pe(e,"error",Ia,n),i=pe(e,"errorLocation",Gc,n);return{workerIndex:ka(e.workerIndex,`${n}.workerIndex`),parallelIndex:ka(e.parallelIndex,`${n}.parallelIndex`),status:Rn(e.status,`${n}.status`,Yh),duration:Xe(e.duration,`${n}.duration`),startTime:Uc(e.startTime,`${n}.startTime`),retry:be(e.retry,`${n}.retry`),...r===void 0?{}:{error:r},errors:ee(e.errors??[],`${n}.errors`,Ia),stdout:ee(e.stdout??[],`${n}.stdout`,Kh),stderr:ee(e.stderr??[],`${n}.stderr`,Kh),steps:ee(e.steps??[],`${n}.steps`,Jh),attachments:ee(e.attachments??[],`${n}.attachments`,VI),annotations:ee(e.annotations??[],`${n}.annotations`,Wh),...i===void 0?{}:{errorLocation:i}}}function GI(t,n){let e=ne(t,n);return{timeout:Xe(e.timeout,`${n}.timeout`),annotations:ee(e.annotations??[],`${n}.annotations`,Wh),expectedStatus:Rn(e.expectedStatus,`${n}.expectedStatus`,Yh),projectName:G(e.projectName,`${n}.projectName`),projectId:G(e.projectId,`${n}.projectId`),results:ee(e.results,`${n}.results`,qI),status:Rn(e.status,`${n}.status`,UI)}}function KI(t,n){let e=ne(t,n);return{title:G(e.title,`${n}.title`),ok:Gh(e.ok,`${n}.ok`),tags:ee(e.tags??[],`${n}.tags`,G),tests:ee(e.tests,`${n}.tests`,GI),file:G(e.file,`${n}.file`),line:be(e.line,`${n}.line`),column:be(e.column,`${n}.column`)}}function Xh(t,n){let e=ne(t,n),r=pe(e,"file",G,n),i=pe(e,"line",be,n),s=pe(e,"column",be,n);return{title:G(e.title,`${n}.title`),...r===void 0?{}:{file:r},...i===void 0?{}:{line:i},...s===void 0?{}:{column:s},suites:ee(e.suites??[],`${n}.suites`,Xh),specs:ee(e.specs??[],`${n}.specs`,KI)}}function WI(t,n){let e=ne(t,n);return{id:G(e.id,`${n}.id`),name:G(e.name,`${n}.name`),repeatEach:be(e.repeatEach,`${n}.repeatEach`),retries:be(e.retries,`${n}.retries`),...Ra("testDir",fe(e.testDir,`${n}.testDir`))}}function Qh(t){let n=ne(t,"$report"),e=ne(n.config,"$report.config"),r=ne(n.stats,"$report.stats");return{config:{version:G(e.version,"$report.config.version"),projects:ee(e.projects,"$report.config.projects",WI),...Ra("rootDir",fe(e.rootDir,"$report.config.rootDir")),...Ra("configFile",fe(e.configFile,"$report.config.configFile"))},suites:ee(n.suites,"$report.suites",Xh),errors:ee(n.errors??[],"$report.errors",Ia),stats:{startTime:Uc(r.startTime,"$report.stats.startTime"),duration:Xe(r.duration,"$report.stats.duration"),expected:be(r.expected,"$report.stats.expected"),skipped:be(r.skipped,"$report.stats.skipped"),unexpected:be(r.unexpected,"$report.stats.unexpected"),flaky:be(r.flaky,"$report.stats.flaky")}}}var JI=new TextDecoder("utf-8",{fatal:!0});function In(t,n,e){return{kind:"unreadable",artifact:{artifactId:B("art",[t??"unavailable",n??"bytes"]),kind:"report",availability:"unreadable",...n===void 0?{}:{path:n},...t===void 0?{}:{sha256:t},warnings:[]},diagnostic:e}}function YI(t){return new Set(t??xa)}function yr(t,n){let e=Ne(t);if(t.byteLength===0)return In(e,n.reportPath,{reasonCode:"empty-input",message:"The Playwright JSON report is empty.",...n.reportPath===void 0?{}:{path:n.reportPath}});let r;try{r=JI.decode(t)}catch{return In(e,n.reportPath,{reasonCode:"invalid-utf8",message:"The Playwright JSON report is not valid UTF-8.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let i;try{i=JSON.parse(r)}catch(p){return In(e,n.reportPath,{reasonCode:"invalid-json",message:p instanceof Error?p.message:"The report is not valid JSON.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let s;try{s=Qh(i)}catch(p){return In(e,n.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof mr?p.message:"The JSON value is not a supported Playwright report.",...n.reportPath===void 0?{}:{path:n.reportPath}})}let a=new Set;for(let p of s.config.projects){if(a.has(p.id))return In(e,n.reportPath,{reasonCode:"invalid-report-shape",message:`$report.config.projects contains duplicate project ID: ${p.id}`,...n.reportPath===void 0?{}:{path:n.reportPath}});a.add(p.id)}if(new Set(n.incompatiblePlaywrightVersions??[]).has(s.config.version))return In(e,n.reportPath,{reasonCode:"incompatible-playwright-version",message:`Playwright ${s.config.version} is configured as incompatible.`,...n.reportPath===void 0?{}:{path:n.reportPath}});let c=YI(n.testedPlaywrightVersions).has(s.config.version),l=[];c||l.push(`unverified-producer-version:${s.config.version}`),s.config.projects.some(p=>p.repeatEach>1)&&l.push("repeat-index-unavailable");let u={artifactId:B("art",[e]),kind:"report",availability:"present",...n.reportPath===void 0?{}:{path:n.reportPath},sha256:e,format:"playwright-json",formatVersion:s.config.version,versionConfidence:c?"verified":"unverified",warnings:[...l].sort()};try{return{kind:"parsed",run:qh({report:s,reportHash:e,artifact:u,options:n,warnings:l})}}catch(p){return In(e,n.reportPath,{reasonCode:"invalid-report-shape",message:p instanceof Error?p.message:"The report could not be normalized.",...n.reportPath===void 0?{}:{path:n.reportPath}})}}import{createHash as QT}from"node:crypto";import{readdir as ZT,readFile as eP,stat as tP}from"node:fs/promises";import{basename as nP,dirname as rP,join as iP}from"node:path";import{resolve as oA}from"node:path";import{readdir as XI,stat as QI}from"node:fs/promises";import{join as Zh}from"node:path";var nm=/\.(?:java|kt|groovy|scala)$/,ZI=/^at (?:([\w.$-]+)\/\/?)?([\w$]+(?:\.[\w$]+)*)\.([\w$<>-]+)\(([\w$-]+\.(?:java|kt|groovy|scala)):(\d+)\)\s*$/,eA=/^(?:java|javax|jdk|sun|com\.sun|org\.junit|junit|org\.testng|org\.openqa\.selenium|org\.assertj|org\.hamcrest|org\.opentest4j|org\.apache\.maven|org\.gradle|worker\.org\.gradle|io\.cucumber|kotlin|kotlinx|scala|groovy|org\.codehaus\.groovy|org\.springframework\.test)\./,tA=["src/test/java","src/main/java","src/it/java","src/test/kotlin","src/main/kotlin","src/test/groovy","src/main/groovy","src/test/scala","src/main/scala"],nA=["src/test/resources","src/main/resources"];function Aa(t){return nm.test(t)}function em(t){return t.endsWith(".feature")}function An(t,n="java"){return`${(t.split("$")[0]??t).replaceAll(".","/")}.${n}`}function wr(t){let n=ZI.exec(t.trim());if(n===null)return;let[,e,r,i,s,a]=n;if(r===void 0||i===void 0||s===void 0||a===void 0||e!==void 0&&e!=="app"||eA.test(`${r}.`))return;let o=s.replace(nm,""),d=r.lastIndexOf(`.${o}`),c=d>=0?r.slice(0,d):r.split(".").slice(0,-1).join(".");return{file:`${c===""?"":`${c.replaceAll(".","/")}/`}${s}`,line:Number.parseInt(a,10),className:r,method:i}}async function tm(t){try{return(await QI(t)).isFile()}catch{return!1}}async function rA(t){return(await XI(t,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&e.name!=="node_modules"&&e.name!=="src"&&e.name!=="target"&&e.name!=="build").map(e=>e.name).sort()}var gr=class{constructor(n){this.workspaceRoot=n}workspaceRoot;modules;found=new Map;find(n){let e=this.found.get(n);return e===void 0&&(e=this.lookup(n),this.found.set(n,e)),e}async resolve(n){return Aa(n)||em(n)?await this.find(n)??n:n}async lookup(n){if(await tm(Zh(this.workspaceRoot,n)))return n;let e=em(n)?nA:tA;this.modules??=rA(this.workspaceRoot);let r=[...e,...(await this.modules).flatMap(i=>e.map(s=>`${i}/${s}`))];for(let i of r){let s=`${i}/${n}`;if(await tm(Zh(this.workspaceRoot,s)))return s}}};var iA=/(?:\(|\bat\s+|^)((?:webpack:\/\/[^\s()]*|file:\/\/[^\s()]*|(?:[A-Za-z]:)?[^():\s][^():]*?)):(\d+):(\d+)\)?\s*$/,sA=/^File "([^"]+\.py)", line (\d+)/,aA=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/;function im(t){let n=t,e=/^webpack:\/\/[^/]*\/(.*)$/.exec(n);return e!==null&&(n=e[1]??""),n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1))),n.replace(/^(?:\.\/)+/,"")}function rm(t){return/^https?:\/\//.test(t)||t.includes("/__cypress/")||t.includes("node_modules/")||t.startsWith("node:")||t.startsWith("internal/")||t.includes("site-packages/")||/\/lib\/python\d/.test(t)||t.startsWith("<")}function sm(t){let n=[];for(let e of t.split(/\r?\n/)){let r=e.trim().replace(/^❯\s+/,""),i=wr(r);if(i!==void 0){n.push({file:i.file,line:i.line,column:1});continue}let s=sA.exec(r)??aA.exec(r),a=s===null?iA.exec(r):[s[0],s[1],s[2],"1"];if(a===null)continue;let[,o,d,c]=a;if(o===void 0||d===void 0||c===void 0||rm(o))continue;let l=im(o);l===""||rm(l)||n.push({file:l,line:Number.parseInt(d,10),column:Number.parseInt(c,10)})}return n}function ve(t,n){if(t===void 0)return;let e=sm(t);if(n!==void 0){let r=n.replaceAll("\\","/").replace(/^(?:\.\/)+/,""),i=e.find(s=>{let a=s.file.replaceAll("\\","/");return a===r||a.endsWith(`/${r}`)||r.endsWith(`/${a}`)});if(i!==void 0)return i}return e[0]}var dA="1",cA="application/vnd.allure.playwright-trace";function Wc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jc(t){return Wc(t)&&typeof t.uuid=="string"&&typeof t.status=="string"&&Array.isArray(t.labels)&&(typeof t.historyId=="string"||typeof t.fullName=="string")}function Yc(t){return Wc(t)&&typeof t.uuid=="string"&&typeof t.status!="string"&&(Array.isArray(t.children)||Array.isArray(t.befores)||Array.isArray(t.afters))}function Xc(t){return Wc(t)&&t.uuid===void 0&&Array.isArray(t.errors)&&Array.isArray(t.attachments)}var lA={testng:"testng","junit-platform":"junit",junit5:"junit",junit4:"junit",junit:"junit",pytest:"pytest",playwright:"playwright",cypress:"cypress",webdriverio:"webdriverio",jest:"jest",vitest:"vitest",mocha:"mocha"};function Dt(t,n){return t.labels?.find(e=>e.name===n)?.value}var am={passed:"passed",failed:"failed",broken:"failed",skipped:"skipped"};function Ta(t){return t==="junit"||t==="testng"}function Ei(t,n){let e=t?.message?.trim()||void 0,r=t?.trace?.trim()||void 0;if(e===void 0&&r===void 0)return;let i=ve(r,n);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...i===void 0?{}:{location:i}}}function om(t){for(let n of(t??"").split(`
17
+ `)){let e=wr(n);if(e!==void 0)return e}}function Qc(t){return typeof t.start=="number"&&typeof t.stop=="number"&&t.stop>=t.start?t.stop-t.start:0}function lm(t){let n=typeof t=="number"?new Date(t):void 0;return n===void 0||Number.isNaN(n.getTime())?{}:{startTime:n.toISOString()}}function Zc(t,n){let r=t.status==="failed"||t.status==="broken"?Ei(t.statusDetails,n):void 0;return{title:t.name??"",duration:Qc(t),...r===void 0?{}:{error:r},steps:(t.steps??[]).map(i=>Zc(i,n))}}function um(t,n){return[...(t.attachments??[]).flatMap(r=>r.source===void 0?[]:[{name:r.name??r.source,contentType:r.type===cA?"application/zip":r.type??"",path:n===void 0?r.source:oA(n,r.source)}]),...(t.steps??[]).flatMap(r=>um(r,n))]}function uA(t){return t.replace(/^\[/,"").replace(/\]$/,"").split("]/[").map(n=>{let e=n.indexOf(":");return{type:n.slice(0,e),value:n.slice(e+1)}})}function pA(t){let n=Dt(t,"junit.platform.uniqueid")??t.parameters?.find(a=>a.name==="UniqueId")?.value;if(n===void 0)return;let e=uA(n),r=e.findIndex(a=>a.type==="test-template"||a.type==="test-factory");if(r<0)return;let i=e.slice(r+1).map(a=>/^#(\d+)$/.exec(a.value)?.[1]);return i.length===0||i.includes(void 0)?void 0:`${(e[r]?.value??"").replace(/\(([^)]*)\)$/,(a,o)=>`(${o.split(",").map(c=>c.trim().split(/[.$]/).at(-1)??"").filter(c=>c!=="").join(", ")})`)}${i.map(a=>`[${a}]`).join("")}`}function fA(t){let n=t.split(".").filter(r=>r!==""),e=n.length;for(;e>1&&/^[A-Z]/.test(n[e-1]??"");)e-=1;return{file:`${n.slice(0,e).join("/")}.py`,classes:n.slice(e)}}function hA(t){let n=t.titlePath??[],e=n.findIndex(r=>r.endsWith(".py"));return e>=0?{file:n.slice(0,e+1).join("/"),classes:n.slice(e+1)}:fA((t.fullName??"").split("#")[0]??"")}function Kc(t,n){return{file:An(t),titlePath:[...t.split("$").filter(e=>e!==""),n],projectId:""}}function dm(t,n,e){let r=Dt(t,"testClass");if(r!==void 0&&Ta(n))return Kc(r,e);if(n==="pytest"){let{file:s,classes:a}=hA(t);return{file:s,titlePath:[...a,e],projectId:""}}if(n==="playwright"){let s=(t.fullName??e).split(" \u203A ");return{file:Dt(t,"suite")??s[0]??"",titlePath:s.length>1?s.slice(1):[e],projectId:Dt(t,"parentSuite")??""}}let i=Dt(t,"suite");return{file:i!==void 0&&/\.[cm]?[jt]sx?$/.test(i)?i:"",titlePath:[t.fullName??e],projectId:""}}function cm(t,n,e,r){return{status:"failed",retry:n,...lm(t.start),duration:Qc(t),errors:e===void 0?[]:[e],attachments:[],stdout:[],stderr:[],steps:(t.steps??[]).map(i=>Zc(i,r))}}function pm(t){let n=[],e=[],r=[];for(let A of t)Jc(A.json)?n.push({...A.json,...A.directory===void 0?{}:{directory:A.directory}}):Yc(A.json)?e.push(A.json):Xc(A.json)&&r.push(...A.json.errors);if(n.length===0)throw new Error("The Allure results hold no test result.");let i=new Set(n.map(A=>lA[Dt(A,"framework")??""]??"unknown")),s=i.size===1?[...i][0]??"unknown":"unknown",a=[];i.size>1&&a.push("allure-mixed-frameworks");let o=new Map;for(let A of n){let N=A.historyId??`uuid:${A.uuid}`,T=o.get(N)??{key:N,results:[]};o.set(N,T),T.results.push(A)}let d=new Map,c=A=>{let N=Dt(A,"testMethod");if(s==="junit")return pA(A)??N??A.name??"";if(s!=="testng")return A.name??"";let T=N??A.name??"",I=(A.parameters??[]).map(S=>S.value??"");if(I.length===0)return T;let $=`${Dt(A,"testClass")??""}\0${T}`,D=d.get($)??new Map;d.set($,D);let k=D.get(JSON.stringify(I))??D.size;return D.set(JSON.stringify(I),k),`${T}[${k}]`},l=0,u=0,p=new Map,f=[],h=[...o.values()].sort((A,N)=>{let T=I=>Math.min(...I.results.map($=>$.start??0));return T(A)-T(N)||A.key.localeCompare(N.key)});for(let A of h){let N=[...A.results].sort((D,k)=>(D.start??0)-(k.start??0)||D.uuid.localeCompare(k.uuid)),T=N.filter((D,k)=>{let S=D.status==="passed"&&k<N.length-1;return S&&(l+=1),!S}),I=T.at(-1);if(I===void 0)continue;p.set(A.key,I);let $=dm(I,s,c(I));f.push({file:$.file,titlePath:$.titlePath,projectId:$.projectId,attempts:T.map((D,k)=>{let S=k<T.length-1,_=am[D.status??""];!S&&_===void 0&&(u+=1);let q=S?"failed":_??"skipped",K=q==="passed"?void 0:Ei(D.statusDetails,$.file);return{status:q,retry:k,...lm(D.start),duration:Qc(D),errors:K===void 0?[]:[K],attachments:um(D,D.directory),stdout:[],stderr:[],steps:(D.steps??[]).map(te=>Zc(te,$.file))}})})}l>0&&a.push(`allure-passed-before-retry-ignored:${l}`),u>0&&a.push(`allure-unknown-status:${u}`);let m=new Map;for(let A of o.values()){let N=p.get(A.key);if(N!==void 0)for(let T of A.results)m.set(T.uuid,N)}let g=new Set;for(let A of e){let N=(A.children??[]).map(I=>m.get(I)).filter(I=>I!==void 0);if(N.some(I=>am[I.status??""]==="failed"))continue;let T=[...(A.befores??[]).map(I=>({fixture:I,phase:"setup"})),...(A.afters??[]).map(I=>({fixture:I,phase:"teardown"}))].filter(({fixture:I})=>I.status==="failed"||I.status==="broken");for(let{fixture:I,phase:$}of T){let D=Ta(s)?om(I.statusDetails?.trace):void 0,k=I.name??D?.method??"fixture",S=N[0],_=D?.className??(S===void 0?void 0:Dt(S,"testClass")),q=`${k} (${$})`,K=_!==void 0&&Ta(s)?Kc(_,q):S===void 0?void 0:dm(S,s,q);if(K===void 0)continue;let te=`${_??K.file}\0${k}`;g.has(te)||(g.add(te),f.push({...K,attempts:[cm(I,0,Ei(I.statusDetails,K.file),K.file)]}))}}let y=[],w=new Map,x=[...r].sort((A,N)=>(A.timestamp??0)-(N.timestamp??0));for(let A of x){let N=Ta(s)?om(A.trace):void 0;if(N===void 0){let S=Ei(A,"");S!==void 0&&y.push(S);continue}let T=`${N.className}\0${N.method}`;if(g.has(T))continue;let I=/\bdid not run\b/.test(A.message??"")?"setup":"teardown",$=Kc(N.className,`${N.method} (${I})`),D=w.get(T)??{...$,attempts:[]};w.set(T,D);let k=A.timestamp===void 0?{}:{start:A.timestamp};D.attempts.push(cm(k,D.attempts.length,Ei(A,$.file),$.file))}f.push(...w.values());let v=new Map;if(s==="playwright")for(let A of f)for(let N of A.attempts.flatMap(T=>T.errors)){let T=N.location?.file;T!==void 0&&!v.has(A.file)&&T.replaceAll("\\","/").endsWith(`/${A.file}`)&&v.set(A.file,T)}let R=f.map(A=>{let N=v.get(A.file);return N===void 0?A:{...A,file:N}}),P=n.flatMap(A=>typeof A.start=="number"?[A.start]:[]),C=n.flatMap(A=>typeof A.stop=="number"?[A.stop]:[]),E=P.length===0?void 0:new Date(Math.min(...P)).toISOString(),M=[...new Set(R.map(A=>A.projectId))].sort();return{framework:s,format:"allure-json",adapterVersion:dA,...E===void 0?{}:{startTime:E},duration:P.length===0||C.length===0?0:Math.max(...C)-Math.min(...P),projects:(M.length===0?[""]:M).map(A=>({id:A,name:A,retries:0})),tests:R,errors:y,interrupted:!1,warnings:a}}var mA="1",yA=["0.2.0","1.0.0"];function fm(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function el(t){return fm(t)&&t.reportFormat==="CTRF"&&fm(t.results)&&Array.isArray(t.results.tests)}var gA=[...kt,...Bc];function wA(t){let n=t?.trim().toLowerCase()??"";return gA.includes(n)?n:"unknown"}var bA={passed:"passed",failed:"failed",skipped:"skipped",pending:"skipped"};function ym(t){if(typeof t!="number")return;let n=new Date(t);return Number.isNaN(n.getTime())?void 0:n.toISOString()}function xA(t,n){let e=t.message?.trim()||void 0,r=t.trace?.trim()||void 0,i=t.snippet?.trimEnd()||void 0;if(e===void 0&&r===void 0)return;let s=ve(r,n);return{...e===void 0?{}:{message:e},...r===void 0?{}:{stack:r},...i===void 0?{}:{snippet:i},...s===void 0?{}:{location:s}}}function vA(t){return(t.attachments??[]).flatMap(n=>n.path===void 0||n.path===""?[]:[{name:n.name??n.path,contentType:n.contentType??"",path:n.path}])}function hm(t,n,e,r,i){let s=ym(t.start),a=t.duration,o=typeof t.start=="number"&&typeof t.stop=="number"?t.stop-t.start:void 0,d=typeof a=="number"&&a>=0?a:o??0,c=n==="passed"?void 0:xA(t,r);return{status:n,retry:e,...s===void 0?{}:{startTime:s},duration:d>=0?d:0,errors:c===void 0?[]:[c],attachments:vA(t),stdout:t.stdout??[],stderr:t.stderr??[],steps:i}}function mm(t,n){if(n===void 0||t==="")return!1;let e=n.replaceAll("\\","/"),r=t.replaceAll("\\","/");return e===r||e.endsWith(`/${r}`)}function kA(t,n){let e=(t.suite??[]).filter(o=>o!==""),r=t.name??"",i=e.findIndex(o=>mm(o,t.filePath)),s=i<0?e:e.slice(i+1),a=i>0?e.slice(0,i).join(" \u203A "):"";if(n==="pytest"&&r.includes("::")){let o=r.split("::");return{titlePath:mm(o[0]??"",t.filePath)?o.slice(1):o,projectId:a}}if(n==="jest"){let o=`${s.join(" ")} `,d=s.length>0&&r.startsWith(o)?r.slice(o.length):r;return{titlePath:[...s,d],projectId:a}}return{titlePath:[...s,r],projectId:a}}function gm(t){if(!el(t))throw new Error("A CTRF report needs results with a tests array.");let n=t,e=wA(n.results.tool?.name),r=n.results.tool?.version?.trim()||void 0,i=[],s=n.specVersion??"";yA.includes(s)||i.push(`unverified-ctrf-spec-version:${s===""?"unrecorded":s}`);let a=0,o=0,d=!1,c=m=>{let g=bA[m.status??""];return g===void 0&&(a+=1),g??"skipped"},l=n.results.tests.map(m=>{let g=m.filePath??"",y=kA(m,e),w=m.retryAttempts??[];typeof m.retries=="number"&&m.retries>w.length&&(d=!0);let x=(m.steps??[]).map(P=>({title:P.name??"",duration:0,steps:[]})),v=[...w.map((P,C)=>hm(P,c(P),C,g,[])),hm(m,c(m),w.length,g,x)],R=v.at(-1)?.status==="passed"&&v.slice(0,-1).some(P=>P.status==="failed");return typeof m.flaky=="boolean"&&m.flaky!==R&&(o+=1),{file:g,titlePath:y.titlePath,...typeof m.line=="number"&&m.line>0?{line:m.line}:{},projectId:y.projectId,...m.tags===void 0?{}:{tags:m.tags},attempts:v}});a>0&&i.push(`ctrf-other-status:${a}`),o>0&&i.push(`ctrf-flaky-mismatch:${o}`),d&&i.push("final-attempt-only");let{start:u,stop:p}=n.results.summary??{},f=ym(u),h=[...new Set(l.map(m=>m.projectId))].sort();return{framework:e,format:"ctrf-json",adapterVersion:mA,...r===void 0?{}:{frameworkVersion:r},...f===void 0?{}:{startTime:f},duration:typeof u=="number"&&typeof p=="number"&&p>=u?p-u:0,projects:(h.length===0?[""]:h).map(m=>({id:m,name:m,retries:0})),tests:l,errors:[],interrupted:!1,warnings:i}}var RA="1";function IA(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function tl(t){return Array.isArray(t)&&t.length>0&&t.every(n=>IA(n)&&typeof n.uri=="string"&&typeof n.keyword=="string"&&Array.isArray(n.elements))}function AA(t){return t.startsWith("classpath:")?t.slice(10).replace(/^\/+/,""):t}var bm=new Set(["undefined","ambiguous","pending"]),TA=1e6;function wm(t){let n=t.result?.duration;return typeof n=="number"&&n>0?n/TA:0}function PA(t,n){return n!==void 0?`${n} hook`:`${(t.keyword??"").trim()} ${t.name??""}`.trim()}function SA(t,n){if(n!==void 0||t.hidden!==!0)return n;let e=(t.keyword??"").trim();return e==="Before"||e==="After"?e:void 0}function EA(t,n,e,r){let i=t.result?.status??"",s=t.result?.error_message?.trim()||void 0,a=typeof t.line=="number"?{file:r,line:t.line}:void 0;if(bm.has(i))return{message:`${i[0]?.toUpperCase()}${i.slice(1)} step: ${n}`,...s===void 0?{}:{stack:s},...a===void 0?{}:{location:a}};if(i!=="failed"||s===void 0)return;let o=s.split(/\r?\n/),d=o.findIndex(u=>/^\s*at\s/.test(u)),c=(d<0?o:o.slice(0,d)).join(`
18
18
  `).trim()||s,l=ve(s,r)??a;return{message:e===void 0?c:`${e} hook failed: ${c}`,stack:s,...l===void 0?{}:{location:l}}}function CA(t){return(t.embeddings??[]).flatMap(n=>n.data===void 0||n.data===""?[]:[{name:n.name??"attachment",contentType:n.mime_type??n.media?.type??"",body:n.data}])}function NA(t,n,e){let r=t.map(({step:c})=>c.result?.status??""),i=r.some(c=>c==="failed"||bm.has(c))?"failed":r.some(c=>c==="passed")?"passed":"skipped",s=[],a=[],o=[];for(let c of t){let{step:l}=c,u=SA(l,c.hook),p=PA(l,u),f=EA(l,p,u,n);f!==void 0&&a.length===0&&a.push(f),s.push({title:p,duration:wm(l),...f===void 0?{}:{error:f},steps:[]}),o.push(...CA(l))}let d=e===void 0||Number.isNaN(new Date(e).getTime())?void 0:new Date(e).toISOString();return{status:i,retry:0,...d===void 0?{}:{startTime:d},duration:t.reduce((c,{step:l})=>c+wm(l),0),errors:a,attachments:o,stdout:[],stderr:[],steps:s}}function OA(...t){return[...new Set(t.flatMap(n=>(n??[]).flatMap(e=>e.name??[])))].sort()}function xm(t){if(!tl(t))throw new Error("A Cucumber report is an array of features.");let n=[],e=[];for(let i of t){let s=AA(i.uri),a=[],o=[];for(let l of i.elements){if(l.type==="background"){o.push(l);continue}a.push({element:l,background:o}),o=[]}let d=new Map;for(let{element:l}of a){let u=l.name??"";d.set(u,(d.get(u)??0)+1)}let c=new Map;for(let{element:l,background:u}of a){let p=l.name??"",f=(c.get(p)??0)+1;c.set(p,f);let h=[...u.flatMap(m=>(m.before??[]).map(g=>({step:g,hook:"Before"}))),...(l.before??[]).map(m=>({step:m,hook:"Before"})),...u.flatMap(m=>(m.steps??[]).map(g=>({step:g}))),...(l.steps??[]).map(m=>({step:m})),...(l.after??[]).map(m=>({step:m,hook:"After"})),...u.flatMap(m=>(m.after??[]).map(g=>({step:g,hook:"After"})))];l.start_timestamp!==void 0&&e.push(l.start_timestamp),n.push({file:s,titlePath:[i.name??"",p,...(d.get(p)??0)>1?[`Example #${f}`]:[]],...typeof l.line=="number"?{line:l.line}:{},projectId:"",tags:OA(i.tags,l.tags),attempts:[NA(h,s,l.start_timestamp)]})}}let r=e.map(i=>new Date(i)).filter(i=>!Number.isNaN(i.getTime())).map(i=>i.toISOString()).sort()[0];return{framework:"cucumber",format:"cucumber-json",adapterVersion:RA,...r===void 0?{}:{startTime:r},duration:n.reduce((i,s)=>i+(s.attempts[0]?.duration??0),0),projects:[{id:"",name:"",retries:0}],tests:n,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}import{join as $A}from"node:path";var Pa="kwikqa-test-report",nl="1.0",DA="1",LA=new Set(["cypress","webdriverio"]),MA=new Set(["passed","failed","timedOut","skipped","interrupted"]);function vm(t,n){let e=n.replaceAll("\\","/");return/^(?:[A-Za-z]:\/|\/|file:\/\/)/.test(e)?n:$A(t,e.replace(/^(?:\.\/)+/,""))}function _A(t){let n=t.rootDir;return n===void 0?t:{...t,tests:t.tests.map(e=>({...e,file:vm(n,e.file),attempts:e.attempts.map(r=>({...r,attachments:r.attachments.map(i=>i.path===void 0?i:{...i,path:vm(n,i.path)})}))}))}}function km(t){return typeof t=="object"&&t!==null&&t.schema===Pa}function jA(t,n){let e=ne(t,n),r=pe(e,"line",be,n),i=pe(e,"column",be,n);return{file:G(e.file,`${n}.file`),...r===void 0?{}:{line:r},...i===void 0?{}:{column:i}}}function Rm(t,n,e){let r=ne(t,n),i=fe(r.message,`${n}.message`),s=fe(r.name,`${n}.name`),a=fe(r.stack,`${n}.stack`),o=fe(r.snippet,`${n}.snippet`),d=fe(r.expected,`${n}.expected`),c=fe(r.actual,`${n}.actual`),u=pe(r,"location",jA,n)??ve(a,e);return{...i===void 0?{}:{message:i},...s===void 0?{}:{name:s},...a===void 0?{}:{stack:a},...o===void 0?{}:{snippet:o},...d===void 0&&c===void 0?{}:{value:`Expected: ${d??"(not recorded)"}
19
19
  Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function FA(t,n,e){let r=ne(t,n),i=fe(r.startTime,`${n}.startTime`);return{status:Rn(r.status,`${n}.status`,MA),retry:be(r.retry,`${n}.retry`),...i===void 0?{}:{startTime:i},duration:Xe(r.duration??0,`${n}.duration`),errors:ee(r.errors??[],`${n}.errors`,(s,a)=>Rm(s,a,e)),attachments:ee(r.attachments??[],`${n}.attachments`,(s,a)=>{let o=ne(s,a),d=fe(o.path,`${a}.path`);return{name:G(o.name,`${a}.name`),contentType:G(o.contentType,`${a}.contentType`),...d===void 0?{}:{path:d}}}),stdout:ee(r.stdout??[],`${n}.stdout`,G),stderr:ee(r.stderr??[],`${n}.stderr`,G),steps:[]}}function BA(t,n){let e=ne(t,n),r=G(e.file,`${n}.file`),i=ee(e.titlePath,`${n}.titlePath`,G);i.length===0&&$e(`${n}.titlePath`,"a non-empty array");let s=pe(e,"line",be,n),a=pe(e,"column",be,n),o=pe(e,"timeout",Xe,n);return{file:r,titlePath:i,...s===void 0?{}:{line:s},...a===void 0?{}:{column:a},projectId:G(e.project,`${n}.project`),...o===void 0?{}:{timeout:o},tags:ee(e.tags??[],`${n}.tags`,G),attempts:ee(e.attempts,`${n}.attempts`,(d,c)=>FA(d,c,r))}}function Im(t){let n=ne(t,"$report");n.schema!==Pa&&$e("$report.schema",Pa),String(n.schemaVersion??"").split(".")[0]!==nl.split(".")[0]&&$e("$report.schemaVersion",`a ${nl.split(".")[0]}.x version`);let r=Rn(n.framework,"$report.framework",LA),i=fe(n.frameworkVersion,"$report.frameworkVersion"),s=fe(n.rootDir,"$report.rootDir"),a=fe(n.configFile,"$report.configFile"),o=fe(n.startTime,"$report.startTime"),d=pe(n,"duration",Xe,"$report"),c=ee(n.projects,"$report.projects",(l,u)=>{let p=ne(l,u);return{id:G(p.id,`${u}.id`),name:G(p.name,`${u}.name`),retries:be(p.retries??0,`${u}.retries`)}});return kn(n.tests,"$report.tests"),{framework:r,format:"kwikqa-json",adapterVersion:DA,...i===void 0?{}:{frameworkVersion:i},...s===void 0?{}:{rootDir:s},...a===void 0?{}:{configFile:a},...o===void 0?{}:{startTime:o},...d===void 0?{}:{duration:d},projects:c,tests:ee(n.tests,"$report.tests",BA),errors:ee(n.errors??[],"$report.errors",(l,u)=>Rm(l,u,void 0)),interrupted:n.interrupted===!0,warnings:[]}}function Am(t){let n=t.map(_A),e=n[0];if(e===void 0)throw new Error("No report parts to merge.");let r=e.framework;if(n.some(l=>l.framework!==r))throw new Error("Report parts come from different frameworks.");let i=[...new Set(n.map(l=>l.frameworkVersion).filter(Boolean))],s=new Map;for(let l of n)for(let u of l.projects){let p=s.get(u.id);(p===void 0||u.retries>p.retries)&&s.set(u.id,u)}let a=n.map(l=>l.startTime).filter(l=>l!==void 0).sort(),o=[...new Set(n.map(l=>l.rootDir).filter(Boolean))],d=[...new Set(n.map(l=>l.configFile).filter(Boolean))],c=n.flatMap(l=>l.warnings);return i.length>1&&c.push(`mixed-framework-versions:${i.join(",")}`),o.length>1&&c.push("mixed-report-roots"),{framework:r,format:e.format,adapterVersion:e.adapterVersion,...i.length===1&&i[0]!==void 0?{frameworkVersion:i[0]}:{},...o.length===1&&o[0]!==void 0?{rootDir:o[0]}:{},...d.length===1&&d[0]!==void 0?{configFile:d[0]}:{},...a[0]===void 0?{}:{startTime:a[0]},duration:n.reduce((l,u)=>Math.max(l,u.duration??0),0),projects:[...s.values()],tests:n.flatMap(l=>l.tests),errors:n.flatMap(l=>l.errors),interrupted:n.some(l=>l.interrupted),warnings:c}}import{basename as qA,dirname as GA,isAbsolute as KA,resolve as WA}from"node:path";var Sa=class extends Error{constructor(n){super(n),this.name="XmlError"}},HA=64,zA=5e5,VA=/^[A-Za-z_:][\w.:-]*/,UA={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function Tm(t){return t.replace(/&(#x[0-9A-Fa-f]+|#\d+|[A-Za-z]+);/g,(n,e)=>{if(e.startsWith("#x")){let i=Number.parseInt(e.slice(2),16);return i<=1114111?String.fromCodePoint(i):n}if(e.startsWith("#")){let i=Number.parseInt(e.slice(1),10);return i<=1114111?String.fromCodePoint(i):n}let r=UA[e];if(r===void 0)throw new Sa(`Unknown XML entity: &${e};`);return r})}function Ea(t){let n=0,e=0,r=t.charCodeAt(0)===65279?t.slice(1):t,i=c=>{throw new Sa(`${c} at offset ${n}`)},s=()=>{for(;;){for(;n<r.length&&/\s/.test(r[n]??"");)n+=1;if(r.startsWith("<?",n)){let c=r.indexOf("?>",n);c<0&&i("Unterminated processing instruction"),n=c+2}else if(r.startsWith("<!--",n)){let c=r.indexOf("-->",n);c<0&&i("Unterminated comment"),n=c+3}else if(r.startsWith("<!DOCTYPE",n)||r.startsWith("<!doctype",n))i("Document type declarations are not accepted");else return}},a=()=>{let c=VA.exec(r.slice(n,n+256));return c===null?i("Expected a name"):(n+=c[0].length,c[0])},o=c=>{c>HA&&i("XML nests too deeply"),e+=1,e>zA&&i("XML has too many nodes"),r[n]!=="<"&&i("Expected an element"),n+=1;let l=a(),u={};for(;;){for(;/\s/.test(r[n]??"");)n+=1;if(r.startsWith("/>",n))return n+=2,{name:l,attributes:u,children:[]};if(r[n]===">"){n+=1;break}let m=a();for(;/\s/.test(r[n]??"");)n+=1;for(r[n]!=="="&&i(`Expected = after attribute ${m}`),n+=1;/\s/.test(r[n]??"");)n+=1;let g=r[n];if(g!=='"'&&g!=="'")return i("Expected a quoted attribute value");let y=r.indexOf(g,n+1);y<0&&i("Unterminated attribute value");let w=r.slice(n+1,y);w.includes("<")&&i("Attribute values must not contain <"),u[m]=Tm(w),n=y+1}let p=[],f="",h=()=>{f.length>0&&(p.push(f),e+=1,f="")};for(;;){if(n>=r.length&&i(`Unterminated element <${l}>`),r.startsWith("</",n)){n+=2;let y=a();for(y!==l&&i(`Expected </${l}> but found </${y}>`);/\s/.test(r[n]??"");)n+=1;return r[n]!==">"&&i("Expected >"),n+=1,h(),{name:l,attributes:u,children:p}}if(r.startsWith("<![CDATA[",n)){let y=r.indexOf("]]>",n);y<0&&i("Unterminated CDATA section"),f+=r.slice(n+9,y),n=y+3;continue}if(r.startsWith("<!--",n)){let y=r.indexOf("-->",n);y<0&&i("Unterminated comment"),n=y+3;continue}if(r.startsWith("<?",n)){let y=r.indexOf("?>",n);y<0&&i("Unterminated processing instruction"),n=y+2;continue}if(r[n]==="<"){h(),p.push(o(c+1));continue}let m=r.indexOf("<",n),g=m<0?r.length:m;f+=Tm(r.slice(n,g)),n=g}};s();let d=o(0);return s(),n<r.length&&i("Unexpected content after the root element"),d}function Q(t,n){return t.children.filter(e=>typeof e!="string"&&(n===void 0||e.name===n))}function Ve(t){return t.children.map(n=>typeof n=="string"?n:Ve(n)).join("")}var Ni="3",JA=/(?:^|[\\/])cypress[\\/]|\.cy\.[cm]?[jt]sx?$/,YA=/webpack:\/\/|__cypress|CypressError/;function Cm(t){let n=t.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testsuites?\b/.test(n)}function Pn(t){if(t.name==="testsuite")return[t];if(t.name!=="testsuites")throw new Error("A JUnit report's root must be testsuites.");let n=[],e=r=>{for(let i of Q(r,"testsuite"))n.push(i),e(i)};return e(t),n}function rl(t){let n=new Map;for(let e of Q(t,"properties"))for(let r of Q(e,"property")){let i=r.attributes.name;i!==void 0&&n.set(i,r.attributes.value??Ve(r))}return n}function XA(t,n){if(t.name!=="testsuites"||t.attributes.id===void 0)return!1;let e=n.flatMap(r=>Q(r,"testcase").map(i=>({suite:r,testcase:i})));return e.length>0&&e.every(({suite:r,testcase:i})=>i.attributes.classname===r.attributes.name)}function QA(t){let n=Object.entries(t.attributes).find(([i])=>i.endsWith("noNamespaceSchemaLocation"))?.[1];if(t.name!=="testsuite"||n===void 0||!n.includes("surefire"))return;let e=rl(t),r=`${e.get("surefire.test.class.path")??""}:${e.get("java.class.path")??""}`;return/[\\/]testng-[\d.]+\.jar/.test(r)?"surefire-testng":"surefire-junit"}var ZA=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;function eT(t){let n=t.attributes.name??"",e=Q(t,"properties");return t.name==="testsuite"&&t.attributes.timestamp!==void 0&&t.attributes.hostname!==void 0&&e.length===1&&e.every(r=>Q(r,"property").length===0)&&ZA.test(n)&&Q(t,"testcase").every(r=>r.attributes.classname===n)}function il(t){if(t.some(e=>/\bat org\.testng\./.test(e)))return"testng";let n=e=>/\bat org\.junit\./.test(e)||/<testcase\b[^>]*\bname="[^"]*\(\)"/.test(e);return t.some(n)?"junit":void 0}function tT(t,n){let e=QA(t);if(e!==void 0)return e;if(eT(t))return"gradle";let r=Pn(t),i=t.name==="testsuites"?t.attributes.name:void 0;if(r.some(o=>rl(o).has("capabilities")))return"webdriverio";if(i==="vitest tests")return"vitest";if(i==="jest tests")return"jest";if(i==="pytest tests"||r.some(o=>o.attributes.name==="pytest"))return"pytest";let s=r.some(o=>o.attributes.name==="Root Suite"),a=r.some(o=>JA.test(o.attributes.file??""));return s&&a||YA.test(n)?"cypress":s?"mocha":XA(t,r)?"playwright":"unknown"}function Sn(t){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>=0?Math.round(n*1e3):0}function nT(t){if(t===void 0)return;let n=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?$/.test(t)?`${t}Z`:t,e=new Date(n);return Number.isNaN(e.getTime())?void 0:e.toISOString()}function sl(t){return t.map(n=>nT(n.attributes.timestamp)).filter(n=>n!==void 0).sort()[0]}function Ca(t,n){return t.name==="testsuites"&&t.attributes.time!==void 0?Sn(t.attributes.time):n.reduce((e,r)=>e+Sn(r.attributes.time),0)}function Na(t,n,e={retriedAsSkipped:!0}){let r=Q(t,"failure")[0]??Q(t,"error")[0]??void 0,i=Q(t,"system-err").map(s=>Ve(s).trim()).filter(s=>s!=="").join(`
20
20
  `);if(r!==void 0){let s=Ve(r).trim(),a=s!==""?s:i!==""?i:void 0,o=e.messageFromBody===!0?s.split(`
@@ -23,10 +23,10 @@ Received: ${c??"(not recorded)"}`},...u===void 0?{}:{location:u}}}function FA(t,
23
23
  `).trim();o!==""&&r.push(o)}let i=Q(t,"system-err").map(s=>Ve(s).trim()).filter(s=>s!=="");return{attachments:e,stdout:r,stderr:i}}function Pm(t,n){let e=[],r=Pn(t),i="";for(let a of r){a.attributes.file!==void 0&&a.attributes.file!==""&&(i=a.attributes.file);let o=a.attributes.name??"";for(let d of Q(a,"testcase")){let c=d.attributes.name??"",l=d.attributes.classname??c,u=Na(d,i);e.push({file:i,titlePath:rT(c,o,l),projectId:"",attempts:[En(u.status,u.errors,0,Sn(d.attributes.time))]})}}let s=sl(r);return{framework:n,format:"junit-xml",adapterVersion:Ni,...s===void 0?{}:{startTime:s},duration:Ca(t,r),projects:[{id:"",name:"",retries:0}],tests:e,errors:[],interrupted:!1,warnings:["final-attempt-only"]}}function oT(t){let n=[],e=new Set;for(let r of Pn(t)){let i=rl(r),s=i.get("file")??r.attributes.file??"",a=(i.get("capabilities")??"").split(".")[0]??"";e.add(a);let o=i.get("suiteName")??r.attributes.name??"",d=new Map,c=[];for(let l of Q(r,"testcase")){let u=l.attributes.name??"",p=Na(l,s),f=d.get(u);f===void 0&&(f=[],d.set(u,f),c.push(u)),f.push(En(p.status,p.errors,f.length,Sn(l.attributes.time)))}for(let l of c)n.push({file:s,titlePath:o===""?[l]:[o,l],projectId:a,attempts:d.get(l)??[]})}return{framework:"webdriverio",format:"junit-xml",adapterVersion:Ni,projects:[...e].map(r=>({id:r,name:r,retries:0})),tests:n,errors:[],interrupted:!1,warnings:[]}}function Ci(t,n,e,r,i={}){let s=Pn(t),a=[],o=new Set;for(let c of s)for(let l of Q(c,"testcase")){let{file:u,titlePath:p,projectId:f="",line:h}=r(c,l);o.add(f);let m=Na(l,u,i);a.push({file:u,titlePath:p,...h===void 0?{}:{line:h},projectId:f,attempts:[En(m.status,m.errors,0,Sn(l.attributes.time),aT(l,e))]})}let d=sl(s);return{framework:n,format:"junit-xml",adapterVersion:Ni,...d===void 0?{}:{startTime:d},duration:Ca(t,s),projects:[...o.size===0?new Set([""]):o].map(c=>({id:c,name:c,retries:0})),tests:a,errors:[],interrupted:!1,warnings:[...i.warnings??[]]}}function dT(t){let n=t.attributes.name??"";for(let e of Q(t,"testcase")){let r=Q(e,"failure")[0]??Q(e,"error")[0],i=r===void 0?void 0:ve(Ve(r),n)?.file;if(i?.replaceAll("\\","/").endsWith(`/${n}`))return i}return n}function cT(t,n){let e=new Map(Pn(t).map(r=>[r,dT(r)]));return Ci(t,"playwright",n,(r,i)=>({file:e.get(r)??r.attributes.name??"",titlePath:(i.attributes.name??"").split(" \u203A "),projectId:r.attributes.hostname??""}),{warnings:["final-attempt-only"]})}function lT(t){let n=(t.attributes.classname??"").split(".").filter(a=>a!==""),e=n.length;for(;e>1&&/^[A-Z]/.test(n[e-1]??"");)e-=1;let r=n.slice(e),i=t.attributes.file,s=Number.parseInt(t.attributes.line??"",10);return{file:i??`${n.slice(0,e).join("/")}.py`,titlePath:[...r,t.attributes.name??""],...Number.isInteger(s)&&s>=0?{line:s+1}:{}}}var Nm=new Set(["failure","error"]),uT=new Set(["rerunFailure","rerunError"]),pT=new Set(["flakyFailure","flakyError"]);function Tn(t,n){return Q(t,n).map(e=>Ve(e).trim()).filter(e=>e!=="").join(`
24
24
  `)}function Sm(t,n,e,r,i){let s=!Nm.has(t.name),a=(s?Tn(t,"stackTrace"):Ve(t).trim())||void 0,o=t.attributes.message,d=ve(a,r);return En(n,[{...o===void 0?{}:{message:o},...t.attributes.type===void 0?{}:{name:t.attributes.type},...a===void 0?{}:{stack:a},...d===void 0?{}:{location:d}}],e,i,s?{stdout:[Tn(t,"system-out")].filter(c=>c!==""),stderr:[Tn(t,"system-err")].filter(c=>c!=="")}:{})}function Om(t,n){let e=Q(t),r=Sn(t.attributes.time),i={stdout:[Tn(t,"system-out")].filter(o=>o!==""),stderr:[Tn(t,"system-err")].filter(o=>o!=="")},s=e.find(o=>Nm.has(o.name));if(s!==void 0){let o=e.filter(d=>uT.has(d.name));return[s,...o].map((d,c)=>Sm(d,"failed",c,n,r))}let a=e.filter(o=>pT.has(o.name));return e.some(o=>o.name==="skipped")?[En("skipped",[],0,r,i)]:[...a.map((o,d)=>Sm(o,"failed",d,n,r)),En("passed",[],a.length,r,i)]}function Em(t,n){let e=[];for(let r of Pn(t))for(let i of Q(r,"testcase")){let s=i.attributes.classname??r.attributes.name??"",a=An(s),d=[...s.split("$").filter(l=>l!==""),i.attributes.name??""];if(n==="junit"){e.push({file:a,titlePath:d,projectId:"",attempts:Om(i,a)});continue}let c=Na(i,a,{});e.push({file:a,titlePath:d,projectId:"",attempts:[En(c.status,c.errors,0,Sn(i.attributes.time),{stdout:[Tn(i,"system-out")].filter(l=>l!==""),stderr:[Tn(i,"system-err")].filter(l=>l!=="")})]})}return{framework:n,format:"junit-xml",adapterVersion:Ni,duration:Ca(t,Pn(t)),projects:[{id:"",name:"",retries:0}],tests:e,errors:[],interrupted:!1,warnings:n==="testng"?["testng-retries-uncorrelated"]:[]}}var fT=/^([\w$]+\[\d+\])\(.*\)$/s;function hT(t,n){return n==="testng"?fT.exec(t)?.[1]??t:t.endsWith("()")?t.slice(0,-2):t}function mT(t,n){let e=new Map;for(let s of Q(t,"testcase")){let a=s.attributes.classname??t.attributes.name??"",o=s.attributes.name??"",d=`${a}\0${o}`,c=e.get(d)??{className:a,name:o,cases:[]};e.set(d,c),c.cases.push(s)}let r=[...e.values()].map(({className:s,name:a,cases:o})=>{let d=An(s),c=s.split("$").filter(l=>l!=="");return{file:d,titlePath:[...c,hT(a,n)],projectId:"",attempts:o.flatMap(l=>Om(l,d)).map((l,u)=>({...l,retry:u}))}}),i=sl([t]);return{framework:n,format:"junit-xml",adapterVersion:Ni,...i===void 0?{}:{startTime:i},duration:Ca(t,[t]),projects:[{id:"",name:"",retries:0}],tests:r,errors:[],interrupted:!1,warnings:[]}}function $m(t,n){let e=Ea(t),r=tT(e,t),i=(r==="unknown"||r==="mocha")&&n.framework!==void 0?n.framework:r,s=n.reportPath;switch(i){case"surefire-junit":return Em(e,"junit");case"surefire-testng":return Em(e,"testng");case"gradle":return mT(e,n.jvmFramework??il([t])??"unknown");case"cypress":return Pm(e,"cypress");case"mocha":return Pm(e,"mocha");case"webdriverio":return oT(e);case"playwright":return cT(e,s);case"vitest":return Ci(e,"vitest",s,(a,o)=>({file:o.attributes.file??o.attributes.classname??a.attributes.name??"",titlePath:(o.attributes.name??"").split(" > ")}),{warnings:["final-attempt-only"]});case"jest":{let a=Ci(e,"jest",s,(o,d)=>({file:d.attributes.file??"",titlePath:[(d.attributes.name??"").trim()]}),{messageFromBody:!0,warnings:["final-attempt-only"]});return a.tests.some(o=>o.file==="")?{...a,warnings:[...a.warnings,"test-file-unrecorded"]}:a}case"pytest":return Ci(e,"pytest",s,(a,o)=>lT(o));case"unknown":return Ci(e,"unknown",s,(a,o)=>{let d=o.attributes.classname??"",c=o.attributes.name??"";return{file:o.attributes.file??a.attributes.file??"",titlePath:d===""||d===c?[c]:[d,c]}},{warnings:["final-attempt-only","junit-producer-unknown"]})}}var yT="1";function Lm(t){let n=t.slice(0,4096).replace(/^\uFEFF/,"");return/^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<testng-results\b/.test(n)}function Mm(t){if(t===void 0)return;let n=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?) ?(UTC|GMT|Z|[+-]\d\d:?\d\d)?$/.exec(t.trim());if(n?.[1]===void 0||n[2]===void 0)return;let e=n[2],r=e==="UTC"||e==="GMT"||e==="Z"?"Z":e.includes(":")?e:`${e.slice(0,3)}:${e.slice(3)}`,i=new Date(`${n[1]}${r}`);return Number.isNaN(i.getTime())?void 0:i.toISOString()}function Dm(t){if(t===void 0)return;let n=Ve(t).trim();return n===""?void 0:n}function gT(t,n){let e=Q(t,"exception")[0];if(e===void 0)return[];let r=Dm(Q(e,"message")[0]),i=Dm(Q(e,"full-stacktrace")[0]),s=ve(i,n);return[{...r===void 0?{}:{message:r},...e.attributes.class===void 0?{}:{name:e.attributes.class},...i===void 0?{}:{stack:i},...s===void 0?{}:{location:s}}]}function wT(t){return Q(t,"params").flatMap(n=>Q(n,"param").map(e=>Ve(Q(e,"value")[0]??e).trim()))}function bT(t){let e=Q(t,"reporter-output").flatMap(r=>Q(r,"line").map(i=>Ve(i).trim())).filter(r=>r!=="").join(`
25
25
  `);return e===""?[]:[e]}var xT={PASS:"passed",FAIL:"failed",SKIP:"skipped"};function vT(t,n,e){let{method:r}=t,i=Mm(r.attributes["started-at"]),s=Number.parseInt(r.attributes["duration-ms"]??"",10);return{status:t.retried?"failed":xT[r.attributes.status??""]??"skipped",retry:n,...i===void 0?{}:{startTime:i},duration:Number.isFinite(s)&&s>=0?s:0,errors:gT(r,e),attachments:[],stdout:bT(r),stderr:[],steps:[]}}function kT(t,n){let e=t.attributes.name??"",r=An(e),i=new Map,s=new Map;for(let a of Q(t,"test-method")){let o=a.attributes.name??"",d=a.attributes["is-config"]==="true";if(d&&a.attributes.status!=="FAIL")continue;let c=wT(a),l=d?`${o} (configuration)`:o;if(!d&&c.length>0){let p=s.get(o)??new Map;s.set(o,p);let f=JSON.stringify(c),h=p.get(f)??p.size;p.set(f,h),l=`${o}[${h}]`}let u=i.get(l)??[];i.set(l,u),u.push({method:a,retried:a.attributes.retried==="true"})}return[...i].map(([a,o])=>{let d=[...o.filter(c=>c.retried),...o.filter(c=>!c.retried)];return{file:r,titlePath:[e,a],projectId:n,attempts:d.map((c,l)=>vT(c,l,r))}})}function _m(t){let n=Ea(t);if(n.name!=="testng-results")throw new Error("A TestNG report's root must be testng-results.");let e=Q(n,"suite"),r=e.flatMap(c=>Q(c,"test")),i=r.length>1,s=r.flatMap(c=>Q(c,"class").flatMap(l=>kT(l,i?c.attributes.name??"":""))),a=e.map(c=>Mm(c.attributes["started-at"])).filter(c=>c!==void 0).sort()[0],o=e.reduce((c,l)=>{let u=Number.parseInt(l.attributes["duration-ms"]??"",10);return c+(Number.isFinite(u)&&u>=0?u:0)},0),d=i?r.map(c=>c.attributes.name??""):[""];return{framework:"testng",format:"testng-xml",adapterVersion:yT,...a===void 0?{}:{startTime:a},duration:o,projects:[...new Set(d)].map(c=>({id:c,name:c,retries:0})),tests:s,errors:[],interrupted:!1,warnings:[]}}import{dirname as PT,isAbsolute as ST,join as ET}from"node:path";import{isAbsolute as $a,relative as RT,sep as Oi}from"node:path";var Oa="1970-01-01T00:00:00.000Z";function $i(t,n){switch(t){case"playwright":case"vitest":case"jest":case"mocha":case"pytest":case"junit":case"testng":case"cucumber":case"unknown":return n;case"cypress":return[n.filter(e=>e!=="").join(" ")];case"webdriverio":return n.filter(e=>e!=="").slice(-2)}}function jm(t,n,e,r,i){return B("tst",[n,e,r,...t==="playwright"?[]:[`framework:${t}`],...$i(t,i)])}function Da(t,n){if(!$a(n))return;let e=RT(t,n);if(!($a(e)||e===".."||e.startsWith(`..${Oi}`)))return e.split(Oi).join("/")}function Di(t){let n=t.trim();return n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)).replaceAll("\\","/"),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1))),n.replaceAll("\\","/")}function Fm(t,n,e){let r=Di(e),i=Oi==="\\"?r.replaceAll("/","\\"):r;if($a(i)||/^[A-Za-z]:\//.test(r))return Da(t,i)??r;let s=r.replace(/^(?:\.\/)+/,"");if(n===void 0)return s;let a=Da(t,n);return a===void 0||a===""?s:`${a}/${s}`}function ol(t,n,e,r,i){let s=t.location===void 0?void 0:{...t.location,file:Fm(r,i,t.location.file)};return{errorId:B("err",[n,e]),source:e,...t.message===void 0?{}:{message:t.message},...t.name===void 0?{}:{name:t.name},...t.stack===void 0?{}:{stack:t.stack},...t.snippet===void 0?{}:{snippet:t.snippet},...t.value===void 0?{}:{value:t.value},...s===void 0?{}:{location:s}}}function Bm(t,n,e,r,i){return{title:t.title,duration:t.duration,...t.error===void 0?{}:{error:ol(t.error,n,`${e}.error`,r,i)},steps:t.steps.map((s,a)=>Bm(s,n,`${e}.steps[${a}]`,r,i))}}function IT(t,n){let e=Di(n),r=Oi==="\\"?e.replaceAll("/","\\"):e;return $a(r)||t===void 0?r:`${t}${Oi}${r.replace(/^(?:\.[/\\])+/,"")}`}function AT(t){let n=t.filter(r=>r.status!=="skipped");return n.length===0?"skipped":n.at(-1)?.status==="passed"?n.some(r=>r.status!=="passed")?"flaky":"expected":"unexpected"}function TT(t,n,e){return t.length===0?"zero-tests":e||t.some(r=>r.attempts.some(i=>i.status==="interrupted"))?"interrupted":n.length>0?"report-errors":"analysis-ready"}function al(t){if(t===void 0)return;let n=new Date(t);return Number.isNaN(n.getTime())?void 0:n.toISOString()}function Hm(t){let{report:n,reportHash:e,artifact:r,options:i}=t,s=i.workspaceRoot,a=new Set(t.warnings),o=n.projects.map(w=>{let x=w.testDir===void 0?void 0:Da(s,w.testDir);return{projectId:B("prj",[`framework:${n.framework}`,w.id,w.name]),frameworkProjectId:w.id,name:w.name,repeatEach:1,retries:w.retries,...x===void 0?{}:{testDir:x}}}).sort((w,x)=>w.projectId.localeCompare(x.projectId)),d=new Map(o.map(w=>[w.frameworkProjectId,w.projectId])),c=new Set,l=[];n.tests.forEach((w,x)=>{let v=d.get(w.projectId);if(v===void 0)throw new Error(`Test ${x} references unknown project: ${w.projectId}`);let R=Fm(s,n.rootDir,w.file),P=jm(n.framework,s,v,R,w.titlePath);if(c.has(P)){a.add(`duplicate-test-identity:${R}`);return}c.add(P);let C=`$tests[${x}]`,E=w.attempts.map((A,N)=>{let T=B("atm",[P,String(A.retry),"repeat:unknown",String(N)]),I=`${C}.attempts[${N}]`,$=A.errors.map((k,S)=>ol(k,T,`${I}.errors[${S}]`,s,n.rootDir)),D=$.find(k=>k.location!==void 0)?.location;return{attemptId:T,sourceIndex:N,retry:A.retry,repeat:{state:"unknown",reason:"not-serialized-by-report"},status:A.status,duration:A.duration,startTime:al(A.startTime)??al(n.startTime)??Oa,workerIndex:0,parallelIndex:0,errors:$,stdout:A.stdout.map(k=>({kind:"text",text:k})),stderr:A.stderr.map(k=>({kind:"text",text:k})),steps:A.steps.map((k,S)=>Bm(k,T,`${I}.steps[${S}]`,s,n.rootDir)),attachments:A.attachments.map((k,S)=>({attachmentId:B("att",[T,String(S)]),name:k.name,contentType:k.contentType,sourceIndex:S,...k.path===void 0?{}:{path:IT(n.rootDir,k.path)},...k.body===void 0?{}:{bodyBase64:k.body}})),annotations:[],...D===void 0?{}:{errorLocation:D}}}),M=AT(w.attempts);l.push({logicalTestId:P,projectId:v,title:w.titlePath.at(-1)??"",titlePath:w.titlePath,tags:[...w.tags??[]].sort(),location:{file:R,...w.line===void 0?{}:{line:w.line},...w.column===void 0?{}:{column:w.column}},timeout:w.timeout??0,expectedStatus:M==="skipped"?"skipped":"passed",status:M,annotations:[],attempts:E})}),l.sort((w,x)=>w.logicalTestId.localeCompare(x.logicalTestId));let u=n.errors.map((w,x)=>ol(w,r.artifactId,`$errors[${x}]`,s,n.rootDir)),p=l.reduce((w,x)=>w+x.attempts.reduce((v,R)=>v+R.attachments.length,0),0),f=l.flatMap(w=>w.attempts.map(x=>x.startTime)).filter(w=>w!==Oa).sort()[0],h=al(n.startTime)??f??Oa;h===Oa&&a.add("start-time-unavailable");let m={expected:0,unexpected:0,flaky:0,skipped:0};for(let w of l)m[w.status]+=1;let g=n.configFile===void 0?void 0:Da(s,Di(n.configFile)),y=B("run",[e,s,i.gitRoot??"","1.7",`${n.format}:${n.adapterVersion}`]);return{schemaVersion:"1.7",runId:y,framework:n.framework,createdAt:h,workspace:{root:s,...i.gitRoot===void 0?{}:{gitRoot:i.gitRoot}},sourceHashes:{report:e},artifact:r,usability:TT(l,u,n.interrupted),projects:o,...g===void 0?{}:{configFile:g},logicalTests:l,reportErrors:u,collections:{tests:l.length===0?"empty":"present",errors:u.length===0?"empty":"present",attachments:p===0?"empty":"present"},warnings:[...a].sort(),stats:{startTime:h,duration:n.duration??0,...m}}}var CT="1",NT=/\.(?:png|jpe?g|webp|gif|mp4|webm)$/i;function Vm(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t;if(!Array.isArray(n.results)||typeof n.stats!="object")return!1;let e=n.results[0];return e===void 0||typeof e=="object"&&e!==null&&"uuid"in e&&Array.isArray(e.suites)&&Array.isArray(e.tests)}function OT(t,n){let e=[],r=i=>{if(typeof i=="string"){let s;try{s=JSON.parse(i)}catch{s=void 0}if(s!==void 0&&typeof s!="string"){r(s);return}let a=typeof s=="string"?s:i;NT.test(a)&&!/^https?:/i.test(a)&&e.push(a);return}if(Array.isArray(i)){for(let s of i)r(s);return}typeof i=="object"&&i!==null&&r(i.value)};return r(t),e.map(i=>{let s=Di(i);return ST(s)||n===void 0?s:ET(n,s)})}function $T(t){let n=JSON.stringify(t.results??[]).slice(0,2e5);return/webpack:\/\/|__cypress|\bcy\.|Cypress/.test(n)?"cypress":/\bbrowser\.|\$\(|webdriverio|wdio/.test(n)?"webdriverio":"cypress"}function zm(t){return t.pending===!0||t.skipped===!0?"skipped":t.state==="passed"||t.pass===!0?"passed":t.timedOut===!0?"timedOut":t.state==="failed"||t.fail===!0?"failed":"skipped"}function DT(t,n,e){let r=t.err;if(typeof r!="object"||r===null)return[];let i=r,s=fe(i.message,`${n}.err.message`),a=fe(i.estack,`${n}.err.estack`),o=fe(i.diff??void 0,`${n}.err.diff`);if(s===void 0&&a===void 0)return[];let d=ve(a,e);return[{...s===void 0?{}:{message:s},...a===void 0?{}:{stack:a},...o===void 0||o===""?{}:{value:o},...d===void 0?{}:{location:d}}]}function Um(t,n){let e=ne(t,"$report"),r=kn(e.results,"$report.results"),i=ne(e.stats,"$report.stats"),s=n.reportPath===void 0?void 0:PT(n.reportPath),a=n.framework??$T(e),o=[],d=[],c=(u,p,f,h)=>{let m=ne(u,p),g=typeof m.title=="string"?m.title:"",y=(typeof m.file=="string"&&m.file!==""?m.file:void 0)??(typeof m.fullFile=="string"&&m.fullFile!==""?m.fullFile:void 0)??h,w=g===""?f:[...f,g];ee(m.tests??[],`${p}.tests`,(x,v)=>{let R=ne(x,v),P=G(R.title,`${v}.title`),C=DT(R,v,y);if(R.isHook===!0){zm(R)!=="passed"&&d.push(...C);return}let E=OT(R.context,s).map(M=>({name:/\.(?:mp4|webm)$/i.test(M)?"video":"screenshot",contentType:/\.(?:mp4|webm)$/i.test(M)?"video/mp4":/\.png$/i.test(M)?"image/png":"image/jpeg",path:M}));o.push({file:y,titlePath:[...w,P],projectId:"",attempts:[{status:zm(R),retry:0,duration:typeof R.duration=="number"?R.duration:0,errors:C,attachments:E,stdout:[],stderr:[],steps:[]}]})}),ee(m.suites??[],`${p}.suites`,(x,v)=>c(x,v,w,y))};r.forEach((u,p)=>{c(u,`$report.results[${p}]`,[],"")});let l=fe(i.start,"$report.stats.start");return{framework:a,format:"mochawesome-json",adapterVersion:CT,...l===void 0?{}:{startTime:l},...typeof i.duration=="number"?{duration:Xe(i.duration,"$report.stats.duration")}:{},projects:[{id:"",name:"",retries:0}],tests:o,errors:d,interrupted:!1,warnings:["final-attempt-only"]}}var LT="1";function Gm(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t;return Array.isArray(n.suites)&&Array.isArray(n.specs)&&typeof n.capabilities=="object"&&n.capabilities!==null}function Km(t){if(typeof t!="object"||t===null)return"";let n=t;if(typeof n.browserName=="string")return n.browserName;let e=Object.values(n);return e.length>0&&e.every(r=>typeof r=="object"&&r!==null)?"multiremote":""}function MT(t){switch(t){case"passed":return"passed";case"failed":return"failed";default:return"skipped"}}function qm(t,n,e){if(typeof t!="object"||t===null)return;let r=ne(t,n),i=fe(r.message,`${n}.message`),s=fe(r.name,`${n}.name`),a=fe(r.stack,`${n}.stack`),o=ve(a,e);return{...i===void 0?{}:{message:i},...s===void 0?{}:{name:s},...a===void 0?{}:{stack:a},...o===void 0?{}:{location:o}}}function Wm(t){let n=ne(t,"$report"),e=ee(n.specs,"$report.specs",G),r=[];e.length!==1&&r.push("ambiguous-spec-file");let i=e[0]??"",s=Km(n.capabilities),a=n.capabilities,o=typeof a.browserVersion=="string"?a.browserVersion:void 0,d=[];return kn(n.suites,"$report.suites").forEach((c,l)=>{let u=`$report.suites[${l}]`,p=ne(c,u),f=typeof p.name=="string"?p.name:"",h=new Map,m=[];ee(p.tests??[],`${u}.tests`,(g,y)=>{let w=ne(g,y),x=G(w.name,`${y}.name`),v=qm(w.error,`${y}.error`,i),R=h.get(x);R===void 0&&(R=[],h.set(x,R),m.push(x)),R.push({status:MT(w.state),retry:R.length,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:v===void 0?[]:[v],attachments:[],stdout:[],stderr:[],steps:[]})}),ee(p.hooks??[],`${u}.hooks`,(g,y)=>{let w=ne(g,y);if(w.state!=="failed")return;let x=qm(w.error,`${y}.error`,i),v=typeof w.title=="string"?w.title:"hook",R=typeof w.associatedTest=="string"&&w.associatedTest!==""?w.associatedTest:v,P={...x??{},message:`${v}: ${x?.message??"failed"}`},C=h.get(R),E=C?.at(-1);if(C!==void 0&&E!==void 0){E.status!=="failed"&&(C[C.length-1]={...E,status:"failed",errors:[P]});return}h.set(R,[{status:"failed",retry:0,...typeof w.start=="string"?{startTime:w.start}:{},duration:typeof w.duration=="number"?w.duration:0,errors:[P],attachments:[],stdout:[],stderr:[],steps:[]}]),m.push(R)});for(let g of m)d.push({file:i,titlePath:f===""?[g]:[f,g],projectId:s,attempts:h.get(g)??[]})}),{framework:"webdriverio",format:"wdio-json",adapterVersion:LT,...typeof n.start=="string"?{startTime:n.start}:{},...typeof n.start=="string"&&typeof n.end=="string"?{duration:Math.max(0,Date.parse(n.end)-Date.parse(n.start))||0}:{},projects:[{id:s,name:s,retries:0}],tests:d,errors:[],interrupted:!1,warnings:[...r,...o===void 0?[]:[`browser-version:${s}@${o}`]]}}var Xm=Bs(vi(),1);import{lstat as _T,readFile as jT,realpath as Jm}from"node:fs/promises";import{isAbsolute as Ym,relative as FT,resolve as BT,sep as HT}from"node:path";var zT=2*1024*1024,VT=new Set(["it","test","specify","xit","fit","xtest","xspecify"]),UT=new Set(["describe","context","suite","xdescribe","fdescribe","xcontext"]),qT=new Set(["only","skip","fixme","serial","parallel","fail","slow"]);function Li(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function GT(t){let n=[],e=t;for(;Li(e)&&e.type==="MemberExpression";){let s=e.property;Li(s)&&s.type==="Identifier"&&n.unshift(String(s.name)),e=e.object}if(!Li(e)||e.type!=="Identifier")return;n.unshift(String(e.name));let i=n.filter(s=>!qT.has(s)).at(-1);if(i!==void 0){if(UT.has(i))return"suite";if(VT.has(i))return"test"}}function KT(t){if(Li(t)){if(t.type==="StringLiteral")return String(t.value);if(t.type==="TemplateLiteral"){let n=t.expressions,e=t.quasis;if(n.length===0&&e.length===1)return e[0]?.value.cooked}}}function WT(t,n){if(!/\.[cm]?[jt]sx?$/i.test(n))return[];let e=[],r=/\.([cm]?[jt]sx?)$/i.exec(n)?.[1]?.toLowerCase()??"ts";r.includes("t")&&e.push("typescript"),(r.endsWith("x")||!r.includes("t"))&&e.push("jsx");let i;try{i=(0,Xm.parse)(t,{sourceType:"unambiguous",errorRecovery:!0,plugins:e})}catch{return[]}let s=[],a=(o,d)=>{if(Array.isArray(o)){for(let c of o)a(c,d);return}if(Li(o)){if(o.type==="CallExpression"){let c=GT(o.callee),l=o.arguments,u=KT(l[0]);if(c!==void 0&&u!==void 0){if(c==="test"){let p=o.loc;p!==void 0&&s.push({titlePath:[...d,u],line:p.start.line,column:p.start.column+1});return}for(let p of l.slice(1))a(p,[...d,u]);return}}for(let[c,l]of Object.entries(o))c==="loc"||c==="start"||c==="end"||c==="extra"||typeof l=="object"&&l!==null&&a(l,d)}};return a(i,[]),s}function JT(t,n){let e=FT(t,n);return e===""||!Ym(e)&&e!==".."&&!e.startsWith(`..${HT}`)}async function YT(t,n){if(!(Ym(n)||n.split("/").includes("..")))try{let e=await Jm(t),r=await Jm(BT(e,n));if(!JT(e,r))return;let i=await _T(r);return!i.isFile()||i.size>zT?void 0:await jT(r,"utf8")}catch{return}}function XT(t,n,e){let r=$i(t,n),i=$i(t,e);return r.length===i.length&&r.every((s,a)=>s===i[a])}async function dl(t){let n=t.logicalTests.filter(i=>i.location.line===void 0);if(n.length===0)return t;let e=new Map;for(let i of new Set(n.map(s=>s.location.file))){let s=await YT(t.workspace.root,i);e.set(i,s===void 0?[]:WT(s,i))}let r=t.logicalTests.map(i=>{if(i.location.line!==void 0)return i;let s=(e.get(i.location.file)??[]).filter(o=>XT(t.framework,o.titlePath,i.titlePath)),a=s.length===1?s[0]:void 0;return a===void 0?i:{...i,location:{...i.location,line:a.line,column:a.column}}});return{...t,logicalTests:r}}var Qm=5e4,Zm=256*1024*1024,sP=["kwikqa-json","playwright-json","mochawesome-json","wdio-json","allure-json","ctrf-json","testng-xml","cucumber-json","junit-xml"],aP=new TextDecoder("utf-8",{fatal:!0});function oP(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=t,e=n.config;return typeof e=="object"&&e!==null&&"version"in e&&Array.isArray(n.suites)}function dP(t){if(t.bytes.byteLength===0)return{kind:"unreadable",diagnostic:{reasonCode:"empty-input",message:"The report is empty."}};let n;try{n=aP.decode(t.bytes)}catch{return{kind:"unreadable",diagnostic:{reasonCode:"invalid-utf8",message:"The report is not valid UTF-8."}}}if(Lm(n))return{kind:"classified",value:{file:t,format:"testng-xml",text:n}};if(Cm(n))return{kind:"classified",value:{file:t,format:"junit-xml",text:n}};let e;try{e=JSON.parse(n)}catch(i){return{kind:"unreadable",diagnostic:{reasonCode:"invalid-json",message:i instanceof Error?i.message:"The report is not valid JSON."}}}let r=km(e)?"kwikqa-json":oP(e)?"playwright-json":Vm(e)?"mochawesome-json":Gm(e)?"wdio-json":Jc(e)||Yc(e)||Xc(e)?"allure-json":el(e)?"ctrf-json":tl(e)?"cucumber-json":void 0;return r===void 0?{kind:"unreadable",diagnostic:{reasonCode:"unsupported-report-format",message:"The JSON is not a report KwikQA reads: Playwright JSON, KwikQA's Cypress or WebdriverIO reporter, mochawesome, @wdio/json-reporter, Allure results, CTRF, or Cucumber JSON."}}:{kind:"classified",value:{file:t,format:r,text:n,json:e}}}function cP(t,n,e){switch(t.format){case"kwikqa-json":return Im(t.json);case"mochawesome-json":return Um(t.json,{...t.file.path===void 0?{}:{reportPath:t.file.path},...n.framework===void 0?{}:{framework:n.framework}});case"wdio-json":return Wm(t.json);case"ctrf-json":return gm(t.json);case"cucumber-json":return xm(t.json);case"testng-xml":return _m(t.text);case"junit-xml":return $m(t.text,{...n.framework===void 0?{}:{framework:n.framework},...t.file.path===void 0?{}:{reportPath:t.file.path},...e===void 0?{}:{jvmFramework:e}});case"playwright-json":throw new Error("Playwright JSON is read by its own parser.");case"allure-json":throw new Error("Allure results are read as one set.")}}function Qe(t,n,e){let r=e.reasonCode==="missing-report"?"unavailable":"unreadable";return{kind:"unreadable",artifact:{artifactId:B("art",[t??r,n??"bytes"]),kind:"report",availability:r,...n===void 0?{}:{path:n},...t===void 0?{}:{sha256:t},warnings:[]},diagnostic:{...e,...n===void 0?{}:{path:n}}}}function lP(t){if(t.length===1&&t[0]!==void 0)return Ne(t[0].bytes);let n=t.map(e=>`${nP(e.path??"")}\0${Ne(e.bytes)}`).sort();return QT("sha256").update(n.join(`
26
- `),"utf8").digest("hex")}function La(t,n){let e=n.reportPath;if(t.length===0)return Qe(void 0,e,{reasonCode:"missing-report",message:"No report files were found."});let r=lP(t),i=[],s;for(let y of t){let w=dP(y);w.kind==="classified"?i.push(w.value):s??=w.diagnostic}if(i.length===0)return Qe(r,e,s??{reasonCode:"unsupported-report-format",message:"No report was found."});let a=sP.find(y=>i.some(w=>w.format===y)),o=i.filter(y=>y.format===a),d=i.length-o.length+(t.length-i.length),c=d>0?[`ignored-report-files:${d}`]:[];if(a==="playwright-json"){let y=o[0];return o.length!==1||y===void 0?Qe(r,e,{reasonCode:"invalid-report-shape",message:"Found several Playwright JSON reports; point --report at one, or merge them with `npx playwright merge-reports`."}):mr(y.file.bytes,{...n,...y.file.path===void 0?{}:{reportPath:y.file.path}})}let l=a==="junit-xml"?il(o.map(y=>y.text)):void 0,u;try{u=a==="allure-json"?pm(o.map(y=>({json:y.json,...y.file.path===void 0?{}:{directory:rP(y.file.path)}}))):Am(o.map(y=>cP(y,n,l)))}catch(y){return Qe(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be read."})}let p=new Set(Hc[u.framework]),f=u.frameworkVersion,h=f!==void 0&&p.has(f),m=[...u.warnings,...c,f===void 0?"producer-version-unrecorded":h?void 0:`unverified-producer-version:${f}`].filter(y=>y!==void 0),g={artifactId:B("art",[r]),kind:"report",availability:"present",...e===void 0?{}:{path:e},sha256:r,format:u.format,...f===void 0?{}:{formatVersion:f},versionConfidence:h?"verified":"unverified",warnings:[...new Set(m)].sort()};try{return{kind:"parsed",run:Hm({report:u,reportHash:r,artifact:g,options:n,warnings:m})}}catch(y){return Qe(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be normalized."})}}async function uP(t){return(await ZT(t,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>iP(t,e.name)).sort()}async function ct(t,n){let e;try{e=await tP(t)}catch(o){let d=o.code==="ENOENT";return Qe(void 0,t,{reasonCode:d?"missing-report":"read-failed",message:d?`Test report does not exist: ${t}`:`Could not inspect: ${t}`})}let r;if(e.isDirectory()){try{r=await uP(t)}catch{return Qe(void 0,t,{reasonCode:"read-failed",message:`Could not list report directory: ${t}`})}if(r.length===0)return Qe(void 0,t,{reasonCode:"missing-report",message:`No .json or .xml report files in ${t}`});if(r.length>Qm)return Qe(void 0,t,{reasonCode:"read-failed",message:`${t} holds ${r.length} report files; KwikQA reads at most ${Qm} from one directory.`})}else if(e.isFile())r=[t];else return Qe(void 0,t,{reasonCode:"not-a-file",message:`Test report path is not a regular file or directory: ${t}`});let i=[],s=0;for(let o of r)try{let d=await eP(o);if(s+=d.byteLength,s>Zm)return Qe(void 0,t,{reasonCode:"read-failed",message:`Report files under ${t} exceed ${Zm} bytes.`});i.push({path:o,bytes:d})}catch{return Qe(void 0,t,{reasonCode:"read-failed",message:`Could not read test report: ${o}`})}let a=La(i,{...n,reportPath:t});return a.kind!=="parsed"||a.run.artifact.format==="playwright-json"?a:{kind:"parsed",run:await dl(await pP(a.run))}}async function pP(t){if(t.framework!=="junit"&&t.framework!=="testng"&&t.framework!=="cucumber")return t;let n=new yr(t.workspace.root),e=async a=>{let o=await n.resolve(a.file);return o===a.file?a:{...a,file:o}},r=async a=>a.location===void 0?a:{...a,location:await e(a.location)},i=async a=>({...a,...a.error===void 0?{}:{error:await r(a.error)},steps:await Promise.all(a.steps.map(i))}),s=await Promise.all(t.logicalTests.map(async a=>({...a,location:await e(a.location),attempts:await Promise.all(a.attempts.map(async o=>({...o,errors:await Promise.all(o.errors.map(r)),steps:await Promise.all(o.steps.map(i)),...o.errorLocation===void 0?{}:{errorLocation:await e(o.errorLocation)}})))})));return{...t,logicalTests:s}}var Rt={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO",vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"pytest",junit:"JUnit",testng:"TestNG",cucumber:"Cucumber",unknown:"Unidentified framework"},Zt={"playwright-json":"JSON report","kwikqa-json":"KwikQA reporter","mochawesome-json":"mochawesome report","wdio-json":"@wdio/json-reporter report","allure-json":"Allure results","ctrf-json":"CTRF report","testng-xml":"TestNG results","cucumber-json":"Cucumber JSON report","junit-xml":"JUnit report"};var ey={playwright:["playwright-json"],cypress:["kwikqa-json","mochawesome-json","junit-xml"],webdriverio:["kwikqa-json","wdio-json","junit-xml"]};function cl(t){return kt.includes(t)}function Ze(t){let{framework:n}=t;if(!cl(n))return;let e=t.artifact.format;return e!==void 0&&ey[n].includes(e)?n:void 0}function lt(t){let{framework:n}=t;if(n==="unknown")return"KwikQA can't tell which test framework wrote this report, so it diagnoses the run but doesn't capture, repair, or validate it.";if(cl(n)){let e=ey[n].map(s=>Zt[s]).join(", "),r=t.artifact.format===void 0?void 0:Zt[t.artifact.format],i=r===void 0?"this format":r.endsWith(" results")?r:`a ${r}`;return`KwikQA repairs ${Rt[n]} tests from a ${e}, whose test identities its validation can match; it only diagnoses a run read from ${i}.`}return`KwikQA diagnoses ${Rt[n]} runs but doesn't capture, repair, or validate them.`}function _a(t,n){let e=mP(t,n);return e===""||!hP(e)&&e!==".."&&!e.startsWith(`..${yP}`)}function gP(t){return t.status==="expected"?"passed":t.status==="skipped"?"skipped":t.attempts.some(n=>n.status==="interrupted")?"interrupted":"failed"}var ty={passed:0,skipped:1,interrupted:2,failed:3};function sy(t){let n=new Map;for(let e of t){let r=gP(e),i=n.get(e.logicalTestId);(i===void 0||ty[r]>ty[i])&&n.set(e.logicalTestId,r)}return[...n].map(([e,r])=>({logicalTestId:e,status:r})).sort((e,r)=>e.logicalTestId.localeCompare(r.logicalTestId))}async function ll(t){if(!Number.isInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let n=await Ma(t.runDirectory).catch(()=>{});if(n===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=iy(n,t.artifact.path);if(!_a(n,e))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let r=await ny(e).catch(()=>{}),i=await Ma(e).catch(()=>{});if(r===void 0||i===void 0||!r.isFile()||r.isSymbolicLink()||!_a(n,i)||r.size>t.maxBytes||r.size!==t.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};let s=await ry(i).catch(()=>{});if(s===void 0||s.byteLength>t.maxBytes||s.byteLength!==t.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};let a=mr(s,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},reportPath:t.artifact.path});if(a.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${a.diagnostic.reasonCode}.`};if(a.run.usability!=="analysis-ready")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${a.run.usability}.`};if(a.run.sourceHashes.report!==t.artifact.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};let o=sy(a.run.logicalTests),d=new Set(o.map(c=>c.logicalTestId));return t.expectedLogicalTestIds.some(c=>!d.has(c))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:a.run.sourceHashes.report,observations:o}}var ja=/^(?:cypress|wdio)-[^/]*\.json$/;async function ul(t){if(!Number.isInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let n=await Ma(t.runDirectory).catch(()=>{});if(n===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=t.artifacts.filter(d=>ja.test(d.path.split("/").at(-1)??""));if(e.length===0)return{kind:"incomplete",reason:"The test run wrote no KwikQA report."};let r=[],i=0;for(let d of e){let c=iy(n,d.path);if(!_a(n,c))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let l=await ny(c).catch(()=>{}),u=await Ma(c).catch(()=>{});if(l===void 0||u===void 0||!l.isFile()||l.isSymbolicLink()||!_a(n,u)||l.size!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};if(i+=l.size,i>t.maxBytes)return{kind:"incomplete",reason:"Validation reports exceed their byte limit."};let p=await ry(u).catch(()=>{});if(p===void 0||p.byteLength!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};if(fP("sha256").update(p).digest("hex")!==d.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};r.push({path:u,bytes:p})}let s=La(r,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot}});if(s.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${s.diagnostic.reasonCode}.`};if(s.run.artifact.format!=="kwikqa-json")return{kind:"incomplete",reason:"Validation report was not written by KwikQA's reporter."};if(s.run.usability==="interrupted"||s.run.usability==="zero-tests")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${s.run.usability}.`};let a=sy(s.run.logicalTests),o=new Set(a.map(d=>d.logicalTestId));return t.expectedLogicalTestIds.some(d=>!o.has(d))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:s.run.sourceHashes.report,observations:a}}var xP=/^txn_[a-f0-9]{24}$/,vP=/^vld_[a-f0-9]{24}$/,kP=new Set(["rolling-back","rolled-back","conflicted"]);function RP(t){return t.length>0&&Number.isFinite(Date.parse(t))}function IP(t){return t.commands.filter(n=>n.required&&n.timing==="post-patch").sort((n,e)=>n.commandId.localeCompare(e.commandId))}function AP(t,n){let e=new Set(t);return e.size===t.length&&t.length===n.length&&n.every(r=>e.has(r))}function TP(t,n,e){let r=t.manifest.preview.authoritativeValidation,i=new Map(r.requiredCommands.map(s=>[s.commandId,s.commandHash]));return r.planHash===n.planHash&&r.repositoryFingerprint===n.repositoryFingerprint&&L(r.targetHashes)===L(n.targetHashes)&&AP(r.requiredCommandIds,e.map(s=>s.commandId))&&e.every(s=>i.get(s.commandId)===L(s))}async function PP(t,n){for(let e of n.manifest.targets){let r=await X(t,e.path,Math.max(1,e.resultBytes)).catch(()=>{});if(r?.kind!=="read"||r.relativePath!==e.path||r.sha256!==e.resultSha256)return!1}return!0}function SP(t){return t===void 0?[]:Object.entries(t.logicalTestOutcomes).map(([n,e])=>({logicalTestId:n,status:e})).sort((n,e)=>n.logicalTestId.localeCompare(e.logicalTestId))}async function EP(t,n,e,r,i,s){let a={classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:"incomplete",fresh:!0,expectedLogicalTestIds:i.logicalTestIds,observations:[]}},o=await jc(e,i.commandId).catch(()=>{});if(o===void 0||o.validationRunId!==t.validationRunId||o.planHash!==r.planHash||o.commandId!==i.commandId||o.commandHash!==L(i)||o.timing!=="post-patch"||!await Fc(e,o,i.artifactPolicy.maxArtifactBytes))return a;let d=[],c=o.status==="blocked"?"incomplete":o.status;if(ir(i.kind)&&!i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=await ul({workspaceRoot:n,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},runDirectory:e,artifacts:o.artifacts,expectedLogicalTestIds:i.logicalTestIds,maxBytes:t.reportMaxBytes});l.kind==="observed"?d=l.observations:c="incomplete"}else if(i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=i.artifactPolicy.reportFile??di,u=o.artifacts.find(p=>p.path.split("/").at(-1)===l);if(u===void 0)c="incomplete";else{let p=await ll({workspaceRoot:n,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},runDirectory:e,artifact:u,expectedLogicalTestIds:i.logicalTestIds,maxBytes:t.reportMaxBytes});p.kind==="observed"?d=p.observations:c="incomplete"}}return{record:o,classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:c,fresh:Date.parse(o.startedAt)>=s&&!o.stdout.truncated&&!o.stderr.truncated,expectedLogicalTestIds:i.logicalTestIds,observations:d}}}async function CP(t,n,e,r){let i=await Re(n,t.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history,o=a.findLastIndex(R=>R.type==="validation-started"),d=a[o],c=IP(e);if(d===void 0||d.validationRunId!==t.validationRunId||d.planHash!==e.planHash||!TP(i,e,c))throw new Error("Validation run does not match the durable transaction approval.");if(s.baselineManifestHash!==r?.baselineHash||r!==void 0&&(r.planHash!==e.planHash||r.repositoryFingerprint!==e.repositoryFingerprint||L(r.targetHashes)!==L(e.targetHashes)))throw new Error("Required validation baseline is missing or mismatched.");let l=await ze(n,[".kwikqa","transactions",t.transactionId,"validation",t.validationRunId]),u=await vn(l,"manifest.json",ba).catch(R=>{if(R.code!=="ENOENT")throw R});if(u!==void 0){let R=Kt(u);if(R.transactionId!==t.transactionId||R.validationRunId!==t.validationRunId||R.planHash!==e.planHash)throw new Error("Validation run was already finalized for different evidence.");return{directory:l,manifest:R}}let p=[],f=i.state.phase;if(f==="validating")await PP(n,i)||p.push("Applied validation targets changed before the run was finalized.");else if(kP.has(f)&&!a.slice(o+1).some(R=>R.type==="validation-passed"))p.push("The transaction left validation before M6 accepted this run.");else throw new Error("Validation run cannot be finalized from the current transaction phase.");let h=Date.parse(d.at),m=t.completedAt??new Date().toISOString();if(Date.parse(m)<h)throw new Error("Validation completion precedes command execution.");let g=[],y=[];for(let R of c){let P=await EP(t,n,l,e,R,h);P.record!==void 0&&g.push(P.record),y.push(P.classification)}let w=_d({targetLogicalTestIds:e.targetLogicalTestIds,baseline:SP(r),commands:y,blockingReasons:p}),x={schemaVersion:qs,validationRunId:t.validationRunId,transactionId:t.transactionId,planHash:e.planHash,repositoryFingerprint:e.repositoryFingerprint,targetHashes:e.targetHashes,requiredCommandIds:c.map(R=>R.commandId),status:w.status,commandRecords:g,classifications:w.classifications,startedAt:d.at,completedAt:m},v=Kt({...x,manifestHash:Ks(x)});return await ye(bP(l,"manifest.json"),`${ue(v)}
27
- `,{mode:384,replace:!1}),{directory:l,manifest:v}}async function pl(t){if(!xP.test(t.transactionId)||!vP.test(t.validationRunId)||!Number.isInteger(t.reportMaxBytes)||t.reportMaxBytes<=0||t.completedAt!==void 0&&!RP(t.completedAt))throw new Error("Validation finalization identity, timestamp, or limits are invalid.");let n=mn(t.plan);if(n.status!=="resolved")throw new Error("Unavailable validation plan cannot be finalized.");if(n.transactionId!==void 0&&n.transactionId!==t.transactionId)throw new Error("Validation plan is bound to another transaction.");let e=t.baseline===void 0?void 0:li(t.baseline),r=await wP(t.workspaceRoot),i=await Je(r,{operation:"finalize-validation",transactionId:t.transactionId,validationRunId:t.validationRunId});try{return await CP(t,r,n,e)}finally{await i.release().catch(()=>{})}}import{fileURLToPath as UP}from"node:url";import{execFile as NP}from"node:child_process";import{lstat as Fa,realpath as et}from"node:fs/promises";import{createRequire as OP}from"node:module";import{dirname as Lt,isAbsolute as dy,join as hl,relative as cy,resolve as ml,sep as ly}from"node:path";import{fileURLToPath as $P}from"node:url";import{promisify as DP}from"node:util";var LP=DP(NP),uy=128*1024,MP=64*1024,_P=/^[a-f0-9]{64}$/,ay={"@playwright/test":{entryRequests:["@playwright/test/cli"]},cypress:{entryRequests:["cypress/bin/cypress"],bin:"cypress"},"@wdio/cli":{entryRequests:["@wdio/cli/bin/wdio.js"],bin:"wdio"},"@biomejs/biome":{entryRequests:["@biomejs/biome/bin/biome"]},prettier:{entryRequests:["prettier/bin/prettier.cjs","prettier/bin/prettier.js"]},typescript:{entryRequests:["typescript/bin/tsc"],bin:"tsc"},eslint:{entryRequests:["eslint/bin/eslint.js"]}};function Cn(t,n){let e=cy(t,n);return e===""||!dy(e)&&e!==".."&&!e.startsWith(`..${ly}`)}function fl(t,n){return cy(t,n).split(ly).join("/")}function Mi(t,n,e){return{code:t,message:n,...e===void 0?{}:{path:e}}}function jP(t,n){let e=new TextDecoder("utf-8",{fatal:!0}).decode(t),r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("Package manifest is not an object.");let i=r;if(i.name!==n||typeof i.version!="string"||i.version.trim().length===0)throw new Error("Package identity does not match the requested tool.");return{name:i.name,version:i.version}}async function FP(t,n){let e=await et(t),r=dy(n)?n:ml(e,n),i=await et(r).catch(()=>r);if(!Cn(e,i))return;let s=i;for((await Fa(s).catch(()=>{}))?.isFile()&&(s=Lt(s));Cn(e,s);){let o=hl(s,"package.json"),d=await Fa(o).catch(()=>{});if(d?.isFile()&&!d.isSymbolicLink())return o;if(s===e)break;s=Lt(s)}}async function BP(t,n){let e=await et(t),r=Lt(n);for(;Cn(e,r);){let i=hl(r,".pnp.cjs"),s=await Fa(i).catch(()=>{});if(s?.isFile()&&!s.isSymbolicLink())return i;if(r===e)break;r=Lt(r)}}async function oy(t,n,e){let r=Lt(t);for(;;){let i=hl(r,"node_modules",...n.split("/"),"package.json");if(await Fa(i).catch(()=>{})!==void 0){let o=await et(i),d=await X(Lt(o),o,uy).catch(()=>{}),l=(d?.kind==="read"?JSON.parse(new TextDecoder().decode(d.bytes)):void 0)?.bin,u=typeof l=="string"?l:typeof l=="object"&&l!==null?l[e]:void 0;if(typeof u!="string")throw new Error("Package declares no CLI entry.");let p=await et(ml(Lt(o),u));return{manifestPath:o,entryPath:p}}let a=Lt(r);if(a===r)throw new Error("Package is not installed.");r=a}}async function HP(t,n){let e=OP(t),r=ay[n].bin,i;try{i=await et(e.resolve(`${n}/package.json`))}catch(a){if(r===void 0)throw a;return oy(t,n,r)}let s;for(let a of ay[n].entryRequests)try{s=await et(e.resolve(a));break}catch{}if(s===void 0){if(r!==void 0)return oy(t,n,r);throw new Error("Package CLI entry could not be resolved.")}return{manifestPath:i,entryPath:s}}async function yl(t,n){let e=await et(n),r=await X(t,e,16*1024*1024);if(r.kind!=="read")throw new Error("PnP loader is not an authorized repository-local regular file.");return{path:e,relativePath:r.relativePath,sha256:r.sha256}}async function zP(t,n,e,r){let i=$P(new URL("./pnp-resolver.mjs",import.meta.url)),{stdout:s}=await LP(process.execPath,[i,t,n.path,n.sha256,e,r],{encoding:"utf8",maxBuffer:MP,timeout:1e4,windowsHide:!0,env:{PATH:process.env.PATH??""}}),a=JSON.parse(s);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error("PnP resolver output is malformed.");let o=a;if(typeof o.manifestPath!="string"||typeof o.entryPath!="string"||o.loaderSha256!==n.sha256)throw new Error("PnP resolver output is incomplete or has the wrong loader identity.");let d=await yl(t,n.path);if(d.path!==n.path||d.relativePath!==n.relativePath||d.sha256!==n.sha256)throw new Error("PnP loader identity changed during resolution.");return{manifestPath:await et(o.manifestPath),entryPath:await et(o.entryPath)}}async function VP(t){let n=await X(t.root,t.paths.manifestPath,t.maxManifestBytes),e=await X(t.root,t.paths.entryPath,16*1024*1024);if(n.kind!=="read"||e.kind!=="read")throw new Error("Resolved package files are not authorized repository-local regular files.");let r=jP(n.bytes,t.packageName),i=Lt(t.paths.manifestPath);if(!Cn(i,t.paths.entryPath))throw new Error("Package CLI entry escapes its package root.");let s=[],a=[];if(t.loader!==void 0){let o=await yl(t.root,t.loader.path);if(o.path!==t.loader.path||o.relativePath!==t.loader.relativePath||o.sha256!==t.loader.sha256)throw new Error("PnP loader identity changed before tool authorization completed.");a.push("--require",t.loader.path),s.push({kind:"pnp-loader",path:fl(t.workspace,t.loader.path),sha256:t.loader.sha256,detail:"Repository-local Yarn Plug'n'Play loader."})}return a.push(t.paths.entryPath),{packageName:t.packageName,packageVersion:r.version,packageRoot:i,packageManifest:t.paths.manifestPath,packageManifestSha256:n.sha256,entryPath:t.paths.entryPath,entrySha256:e.sha256,executable:process.execPath,nodeArguments:a,packageManagerLayout:t.layout,resolutionEvidence:[{kind:"package-root",path:i,detail:`Canonical repository-local ${t.packageName} package root.`},{kind:"package-manifest",path:fl(t.workspace,t.paths.manifestPath),sha256:n.sha256,detail:`${r.name}@${r.version}`},{kind:"package-entry",path:fl(t.workspace,t.paths.entryPath),sha256:e.sha256,detail:"JavaScript CLI entry executed directly through the current Node runtime."},...s]}}async function _i(t){try{let n=await et(t.workspaceRoot),e=t.repositoryRoot===void 0?n:await et(t.repositoryRoot);if(!Cn(e,n))return{kind:"unavailable",reasons:[Mi("entry-outside-workspace","The workspace is outside its containing repository.")]};let r=await FP(e,ml(n,t.ownerPath));if(r===void 0)return{kind:"unavailable",reasons:[Mi("ambiguous-package-root","No owning repository package was found.")]};let i=t.maxManifestBytes??uy;if(!Number.isInteger(i)||i<=0)return{kind:"unavailable",reasons:[Mi("budget-exceeded","Package manifest byte limit is invalid.")]};let s,a="node-modules",o;try{s=await HP(r,t.packageName)}catch{let c=await BP(e,r);if(c===void 0)throw new Error("No repository-local dependency resolution succeeded.");o=await yl(e,c),a="pnp",s=await zP(e,o,r,t.packageName)}return!Cn(e,s.manifestPath)||!Cn(e,s.entryPath)?{kind:"unavailable",reasons:[Mi("entry-outside-workspace","Resolved package files are outside the repository.")]}:{kind:"resolved",tool:await VP({root:e,workspace:n,packageName:t.packageName,paths:s,maxManifestBytes:i,layout:a,...o===void 0?{}:{loader:o}})}}catch{return{kind:"unavailable",reasons:[Mi("missing-dependency",`Repository-local ${t.packageName} could not be resolved safely. No installation or global fallback was attempted.`)]}}}function ji(t){if(t.tool.executable!==process.execPath||t.args.some(i=>i.includes("\0"))||t.workingDirectory.includes("\0")||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0)throw new Error("Resolved validation command is invalid.");let n=[...t.tool.nodeArguments,...t.args],e=[...t.tool.resolutionEvidence,...t.extraEvidence??[]],r=L({packageManifestSha256:t.tool.packageManifestSha256,entrySha256:t.tool.entrySha256,resolutionEvidence:e,kind:t.kind,timing:t.timing,executable:t.tool.executable,args:n,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:t.artifactPolicy});if(!_P.test(r))throw new Error("Command identity could not be constructed.");return{commandId:`cmd_${r.slice(0,24)}`,kind:t.kind,timing:t.timing,required:!0,executable:t.tool.executable,args:n,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:t.artifactPolicy,resolutionEvidence:e}}function gl(t,n){return L({purpose:"kwikqa-validation-repository-fingerprint",evidence:t,targetHashes:n})}var qP=/^[a-f0-9]{64}$/,Fi=3,GP=/^rps_[a-f0-9]{24}$/,wl=UP(new URL("./parse-check.mjs",import.meta.url));function KP(t,n){switch(t.tool){case"biome":return n.biome;case"prettier":return n.prettier;case"typescript":return n.typescript;case"eslint":return n.eslint;case"kwikqa-babel":return}}function WP(t,n){return n==="unavailable"?void 0:`${t}-${n}`}var py={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function JP(t,n){let e=["test"];if(n==="focused"?e.push(`${t.originalTest.path}:${t.originalTest.line}`,`--repeat-each=${Fi}`):n==="affected"&&e.push(...t.discovery.testPaths),n!=="suite")for(let r of t.discovery.projectIds)r!==""&&e.push(`--project=${r}`);return t.originalTest.configPath!==void 0&&e.push(`--config=${t.originalTest.configPath}`),e.push("--reporter=json",`--output=${t.artifactRoot}`,"--trace=retain-on-failure","--retries=0"),e}function YP(t,n){let e=n.targets.map(r=>r.path);switch(t.tool){case"biome":return t.kind==="format"?["format",...e]:["lint",...e];case"prettier":return["--check",...e];case"typescript":return["--noEmit","--pretty","false",...t.configPath?["--project",t.configPath]:[]];case"eslint":return e;case"kwikqa-babel":return[]}}function Ba(t){return{code:"resolution-failed",message:t}}function bl(t){if(!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||t.originalTest.line<=0||t.originalTest.logicalTestId.trim().length===0||t.originalTest.projectId.trim().length===0)throw new Error("Validation preparation input is invalid.");let n=L(t.advisoryPlan),e=[...new Set(t.affectedLogicalTestIds??[])].sort(),r=[...t.discovery.reasons.map(y=>({code:y.code==="budget-exceeded"?"budget-exceeded":"resolution-failed",message:y.message,...y.path===void 0?{}:{path:y.path}}))],i=[],s=[],a=t.framework??"playwright",o=t.tools[a],d=WP(a,t.discovery.scope),c=a==="playwright"?void 0:t.frameworkRun,l=()=>c?.args??JP(t,t.discovery.scope),u=c?.evidence??[],p=c?.workingDirectory??t.workspaceRoot;if(t.discovery.status!=="resolved"||d===void 0||o===void 0||a!=="playwright"&&c===void 0)r.push(Ba(`Repository-local ${py[a]} validation could not be resolved.`));else{let y=[t.originalTest.logicalTestId,...(t.companionLogicalTestIds??[]).filter(x=>x!==t.originalTest.logicalTestId)],w=a!=="playwright"&&t.discovery.scope==="focused"?Fi:1;for(let x=1;x<=w;x+=1)i.push(ji({tool:o,kind:d,timing:"post-patch",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:`Run the approved risk-based ${py[a]} validation scope${w>1?` (run ${x} of ${w})`:""}.`,logicalTestIds:t.discovery.scope==="focused"?[...new Set(y)].sort():e,projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u}));if(t.discovery.scope!=="focused"){(e.length===0||!e.includes(t.originalTest.logicalTestId))&&r.push(Ba("Shared validation scope lacks complete canonical affected-test identities."));let x=ji({tool:o,kind:d,timing:"baseline",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:"Capture required affected-test outcomes before shared-source mutation.",logicalTestIds:e,projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:`${t.artifactRoot}-baseline`,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u});i.push(x);let v=`baseline_${L({commandId:x.commandId}).slice(0,24)}`;s.push({baselineId:v,commandId:x.commandId,logicalTestIds:e,reason:"Shared test support requires a pre-patch affected-test baseline."})}else t.originalTest.environmentEquivalent||r.push(Ba("Original failure evidence is not environment-equivalent to validation."))}for(let y of t.discovery.staticChecks){if(y.tool==="kwikqa-babel"){let x=L({purpose:"kwikqa-parse-check-command",executable:process.execPath,shim:wl,paths:t.proposal.targets.map(v=>v.path),workingDirectory:t.workspaceRoot});i.push({commandId:`cmd_${x.slice(0,24)}`,kind:"parse",timing:"post-patch",required:!0,executable:process.execPath,args:[wl,...t.proposal.targets.map(v=>v.path)],workingDirectory:t.workspaceRoot,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:"Parse every changed JavaScript or TypeScript source file.",logicalTestIds:[],projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,maxArtifacts:1,maxArtifactBytes:1e6},resolutionEvidence:[{kind:"configuration",path:wl,detail:"KwikQA-owned Babel parse-only validation shim."}]});continue}let w=KP(y,t.tools);if(w===void 0){r.push(Ba(`Required ${y.tool} check could not be resolved locally.`));continue}i.push(ji({tool:w,kind:y.kind,timing:"post-patch",args:YP(y,t.proposal),workingDirectory:t.workspaceRoot,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:`Run required ${y.kind} validation.`,logicalTestIds:[],projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,maxArtifacts:10,maxArtifactBytes:8*1024*1024}}))}let f=i.flatMap(y=>y.resolutionEvidence),h=t.proposal.targets.map(y=>({path:y.path,sourceSha256:y.sourceSha256,resultSha256:y.resultSha256})),m={schemaVersion:Us,policyVersion:Gs,status:r.length===0?"resolved":"unavailable",proposalHash:t.proposal.proposalHash,targetLogicalTestIds:[t.originalTest.logicalTestId],targetHashes:h,advisoryPlanHash:n,repositoryFingerprint:gl(f,h),commands:[...i].sort((y,w)=>y.commandId.localeCompare(w.commandId)),baselineRequirements:[...s].sort((y,w)=>y.baselineId.localeCompare(w.baselineId)),unresolvedReasons:r},g={...m,planHash:Ws(m)};return{plan:g,requiredBaselineCommands:g.commands.filter(y=>y.timing==="baseline")}}function xl(t){if(t.plan.status!=="resolved"||!qP.test(t.plan.planHash)||!GP.test(t.repairSessionId)||t.attemptOrdinal!==1&&t.attemptOrdinal!==2)throw new Error("Only a resolved plan can become application execution authority.");let n=t.plan.baselineRequirements.map(i=>i.baselineId),e;if(n.length>0){if(t.baseline===void 0)throw new Error("Required pre-application baseline is missing.");e=li(t.baseline);let i=new Map(t.plan.baselineRequirements.map(s=>[s.commandId,s]));if(e.planHash!==t.plan.planHash||e.repositoryFingerprint!==t.plan.repositoryFingerprint||L(e.targetHashes)!==L(t.plan.targetHashes)||e.commandRecords.length!==i.size||e.commandRecords.some(s=>{let a=i.get(s.commandId);return a===void 0||s.planHash!==t.plan.planHash||s.timing!=="baseline"||s.status!=="passed"||s.termination.kind!=="exit"||s.termination.exitCode!==0||s.stdout.truncated||s.stderr.truncated||a.logicalTestIds.some(o=>e?.logicalTestOutcomes[o]===void 0)}))throw new Error("Required pre-application baseline does not match the resolved plan.")}let r=t.plan.commands.filter(i=>i.timing==="post-patch"&&i.required).sort((i,s)=>i.commandId.localeCompare(s.commandId));return{schemaVersion:"1.0",policyVersion:"1.0",planHash:t.plan.planHash,repositoryFingerprint:t.plan.repositoryFingerprint,targetHashes:t.plan.targetHashes,advisoryPlanHash:L(t.advisoryPlan),...e===void 0?{}:{baselineManifestHash:e.baselineHash},requiredBaselineIds:n,requiredCommandIds:r.map(i=>i.commandId),requiredCommands:r.map(i=>({commandId:i.commandId,commandHash:L(i)})),repairSessionId:t.repairSessionId,attemptOrdinal:t.attemptOrdinal}}import{randomUUID as xS}from"node:crypto";import{lstat as Vi,mkdir as Cl,readFile as vS,realpath as kS,rm as RS}from"node:fs/promises";import{isAbsolute as IS,join as vr,relative as AS,resolve as TS,sep as PS}from"node:path";import{realpath as br}from"node:fs/promises";import{realpath as wr}from"node:fs/promises";var Ke=/^[a-f0-9]{64}$/,XP=/^rps_[a-f0-9]{24}$/,QP=/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+$/,ZP=new Set(["github-actions","azure-pipelines","gitlab-ci"]),eS=/^[a-f0-9]{40}$/;function fy(t){let n=t.map(e=>e.trim());return n.every(e=>e.length>0)&&new Set(n).size===t.length}function tS(t){return{kind:"rejected",reasons:t}}function yy(t){return t.length>0&&Number.isFinite(Date.parse(t))}function Ha(t){return Number.isFinite(t)&&t>0}function nS(t){return t.kind==="interactive"?t.sessionId.trim().length>0:t.kind==="ci-policy"&&ZP.has(t.system)&&QP.test(t.repository)&&/^\d+$/.test(t.runId)&&Number.isSafeInteger(t.runAttempt)&&t.runAttempt>0&&eS.test(t.commit)&&Ke.test(t.policyHash)}function rS(t){let{proposalHash:n,...e}=t;return Ke.test(n)&&L(e)===n}function iS(t){let n=[];(!rS(t)||L(t.diff)!==t.diffHash)&&n.push({code:"invalid-proposal",message:"Proposal and diff integrity hashes must match their canonical contents."}),(t.targets.length===0||t.changedFiles!==t.targets.length||t.targets.some(i=>!Ke.test(i.sourceSha256)||!Ke.test(i.resultSha256)||i.sourceSha256===i.resultSha256))&&n.push({code:"invalid-proposal",message:"Proposal targets and their source/result hashes must be complete and consistent."});let e=new Set,r=new Map;for(let i of t.targets){let s=i.path.toLocaleLowerCase("en-US"),a=r.get(s);(e.has(i.path)||a!==void 0&&a!==i.path)&&n.push({code:"invalid-proposal",message:"Proposal targets may not duplicate or case-collide.",path:i.path}),e.add(i.path),r.set(s,i.path)}return(t.replacements.length===0||t.replacements.some(i=>!e.has(i.path)))&&n.push({code:"invalid-proposal",message:"Every approved replacement must resolve to an approved proposal target."}),n}function sS(t){let n=iS(t.proposal);(t.context.workspace.workspaceRoot.length===0||t.context.workspace.gitRoot.length===0||t.context.snapshot.workspaceRoot!==t.context.workspace.workspaceRoot||t.context.snapshot.gitRoot!==t.context.workspace.gitRoot)&&n.push({code:"invalid-workspace",message:"Confirmed workspace and git roots must match the repository snapshot identity."}),(!Number.isInteger(t.context.maxTargetBytes)||t.context.maxTargetBytes<=0||t.context.config.schemaVersion.length===0)&&n.push({code:"invalid-configuration",message:"Application configuration and target byte limit must be explicit and bounded."}),(!nS(t.approver)||!yy(t.previewedAt))&&n.push({code:"invalid-preview",message:"An approver, an interactive session or a CI run under a committed policy, and a valid preview timestamp are required."});let e=t.costBounds;(!Number.isInteger(e.maxRequestTokens)||!Number.isInteger(e.maxRunTokens)||!Ha(e.maxRequestTokens)||!Ha(e.maxRunTokens)||!Ha(e.maxRequestDollars)||!Ha(e.maxRunDollars)||e.maxRequestTokens>e.maxRunTokens||e.maxRequestDollars>e.maxRunDollars)&&n.push({code:"invalid-preview",message:"Approved request and run token/dollar bounds must be positive and internally consistent."});let r=new Set;for(let s of t.payloadManifests){if(!Ke.test(s.manifestHash)||!Ke.test(s.payloadHash)||!Ke.test(s.packetHash)||s.model.trim().length===0||s.provider.trim().length===0||s.promptVersion.trim().length===0||s.outputSchemaVersion.trim().length===0||r.has(s.manifestHash)){n.push({code:"invalid-preview",message:"Model payload manifest references must be sanitized, complete, and unique."});break}r.add(s.manifestHash)}(t.scopes.baseline.some(s=>s.trim().length===0)||t.scopes.validation.some(s=>s.trim().length===0))&&n.push({code:"invalid-preview",message:"Baseline and validation scopes may not contain empty entries."});let i=t.authoritativeValidation;return(i.schemaVersion!=="1.0"||i.policyVersion!=="1.0"||!Ke.test(i.planHash)||!Ke.test(i.repositoryFingerprint)||!Ke.test(i.advisoryPlanHash)||i.targetHashes.length!==t.proposal.targets.length||i.targetHashes.some((s,a)=>{let o=t.proposal.targets[a];return o===void 0||s.path!==o.path||s.sourceSha256!==o.sourceSha256||s.resultSha256!==o.resultSha256})||i.baselineManifestHash!==void 0&&!Ke.test(i.baselineManifestHash)||!XP.test(i.repairSessionId)||i.attemptOrdinal!==1&&i.attemptOrdinal!==2||!fy(i.requiredBaselineIds)||!fy(i.requiredCommandIds)||i.requiredCommandIds.length===0||i.requiredCommands.length!==i.requiredCommandIds.length||i.requiredCommands.some((s,a)=>s.commandId!==i.requiredCommandIds[a]||!Ke.test(s.commandHash))||i.requiredBaselineIds.length>0&&i.baselineManifestHash===void 0)&&n.push({code:"invalid-preview",message:"Authoritative validation approval metadata is incomplete or inconsistent."}),n}function vl(t){return L({purpose:"kwikqa-approved-application",...t})}function kl(t){let n=sS(t);if(n.length>0)return tS(n);let e={schemaVersion:"3.0",bindingVersion:"3.0",proposal:t.proposal,workspace:t.context.workspace,checkoutPristine:t.context.snapshot.dirtyPaths.length===0,validationPlan:t.proposal.validationPlan,scopes:t.scopes,authoritativeValidation:t.authoritativeValidation,payloadManifests:t.payloadManifests,costBounds:t.costBounds,previewedAt:t.previewedAt,approver:t.approver};return{kind:"preview-ready",preview:{...e,bindingHash:vl(e)}}}function za(t,n,e,r){return L({purpose:"kwikqa-application-authorization",previewBindingHash:t.bindingHash,authorizationId:n,authorizedAt:e,approver:r})}function Rl(t,n){let{bindingHash:e,...r}=t;return Ke.test(e)&&vl(r)===e&&n.authorizationId.trim().length>0&&yy(n.authorizedAt)&&n.bindingHash===za(t,n.authorizationId,n.authorizedAt,n.approver)&&L(n.approver)===L(t.approver)}import{realpath as Va}from"node:fs/promises";import{isAbsolute as uS,relative as pS,sep as fS}from"node:path";import{createHash as aS}from"node:crypto";function oS(t){return aS("sha256").update(t,"utf8").digest("hex")}function Il(t,n,e){let r=[],i=[];for(let o of e){if(o.oldText.length===0||o.newText===o.oldText||o.rationale.trim().length===0||o.expectedEffect.trim().length===0||o.evidenceIds.length===0){r.push({code:"invalid-replacement",message:"Replacement fields must be meaningful, cited, and non-no-op.",path:t});continue}if(o.oldText===n){r.push({code:"invalid-replacement",message:"A replacement may not rewrite the complete file.",path:t});continue}let d=n.indexOf(o.oldText);if(d<0||n.indexOf(o.oldText,d+1)>=0){r.push({code:"non-unique-match",message:"Replacement preimage must occur exactly once.",path:t});continue}i.push({start:d,end:d+o.oldText.length,newText:o.newText})}let s=[...i].sort((o,d)=>o.start-d.start);for(let o=1;o<s.length;o+=1){let d=s[o-1],c=s[o];d!==void 0&&c!==void 0&&c.start<d.end&&r.push({code:"overlapping-replacement",message:"Exact replacements overlap in the original source.",path:t})}if(r.length>0)return{kind:"rejected",reasons:r};let a=n;for(let o of[...s].sort((d,c)=>c.start-d.start))a=`${a.slice(0,o.start)}${o.newText}${a.slice(o.end)}`;return{kind:"applied",result:a,resultSha256:oS(a)}}function gy(t){let n=[],e=[];for(let r of t){let i=Il(r.path,r.source,r.replacements);if(i.kind==="rejected"){n.push(...i.reasons);continue}e.push({...r,result:i.result,resultSha256:i.resultSha256})}return n.length>0?{kind:"rejected",reasons:n}:{kind:"applied",targets:e}}import{isAbsolute as dS}from"node:path";function cS(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function wy(t,n){let e=cS(t).replaceAll("**/","\0").replaceAll("**","").replaceAll("*","[^/]*").replaceAll("\0","(?:.*/)?").replaceAll("",".*");return new RegExp(`^${e}$`).test(n)}function Bi(t){return t.length===0||t.includes("\0")||t.includes("\\")||dS(t)||/^[A-Za-z]:/.test(t)?!0:t.split("/").some(n=>n===""||n==="."||n==="..")}function Hi(t,n){let e=t.toLowerCase(),r=e.split("/").at(-1)??e;return e.includes("/node_modules/")||e.startsWith("node_modules/")||e.includes("/src/")||e.startsWith("src/")||new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]).has(r)?!0:n.generatedPaths.some(i=>wy(i,t))}function zi(t,n){return n.find(e=>wy(e.pattern,t))}function lS(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}async function by(t,n,e,r){let i=[],s=new Map;for(let l of e){if(Bi(l.path)){i.push({code:"unauthorized-target",message:"Target path is not a safe repository-relative path.",path:l.path});continue}let u=s.get(l.path)??[];u.push(l),s.set(l.path,u)}if(i.length>0)return{kind:"rejected",reasons:i};let a=new Set(n.dirtyPaths.map(l=>l.replaceAll("\\","/").toLocaleLowerCase("en-US"))),o=new Set,d=new Map,c=[];for(let[l,u]of[...s].sort(([p],[f])=>p.localeCompare(f))){let p=zi(l,t.editablePaths);if(p===void 0||Hi(l,t)){i.push({code:"unauthorized-target",message:"Target is outside the configured test-support repair boundary.",path:l});continue}if(a.has(l.toLocaleLowerCase("en-US"))){i.push({code:"dirty-target-file",message:"Already-dirty target files are read-only.",path:l});continue}let f=await X(n.workspaceRoot,l,r);if(f.kind!=="read"){i.push({code:f.kind==="unauthorized"?"unauthorized-target":"unreadable-target",message:f.message,...f.relativePath===void 0?{path:l}:{path:f.relativePath}});continue}if(f.relativePath!==l){i.push({code:"unauthorized-target",message:"Target path does not match its canonical repository-relative path.",path:l});continue}let h=f.relativePath.toLocaleLowerCase("en-US"),m=d.get(h);if(o.has(f.relativePath)||m!==void 0&&m!==f.relativePath){i.push({code:"unauthorized-target",message:"Target aliases or case-collides with another target.",path:l});continue}o.add(f.relativePath),d.set(h,f.relativePath);let g=lS(f.bytes);if(g===void 0){i.push({code:"unreadable-target",message:"Target is not valid UTF-8.",path:l});continue}if(u.some(y=>y.sourceSha256!==void 0&&y.sourceSha256!==f.sha256)){i.push({code:"source-hash-mismatch",message:"Target source hash differs from the proposed preimage.",path:l});continue}c.push({path:f.relativePath,class:p.class,source:g,sourceSha256:f.sha256,replacements:u})}return i.length>0?{kind:"rejected",reasons:i}:{kind:"authorized",targets:c}}function hS(t,n){let e=pS(t,n);return e===""||!uS(e)&&e!==".."&&!e.startsWith(`..${fS}`)}function mS(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}async function xy(t){if(!Number.isInteger(t.maxTargetBytes)||t.maxTargetBytes<=0||t.maxTargetBytes>1e6)return{kind:"rejected",code:"invalid-limit",message:"Target limit is invalid."};let n,e,r,i;try{[n,e,r,i]=await Promise.all([Va(t.workspaceRoot),Va(t.gitRoot),Va(t.approvedWorkspaceRoot),Va(t.approvedGitRoot)])}catch{return{kind:"rejected",code:"workspace-mismatch",message:"Workspace roots are unreadable."}}if(n!==r||e!==i||!hS(e,n))return{kind:"rejected",code:"workspace-mismatch",message:"Current and approved canonical workspace identities differ."};let s=new Set(t.dirtyPaths.map(c=>c.replaceAll("\\","/").toLocaleLowerCase("en-US"))),a=new Map;for(let c of t.proposal.replacements){let l=a.get(c.path)??[];l.push(c),a.set(c.path,l)}let o=new Set,d=[];for(let c of t.proposal.targets){let l=c.path.toLocaleLowerCase("en-US");if(o.has(l)||Bi(c.path))return{kind:"rejected",code:"unsafe-target",message:"Target aliases, case-collides, or has an unsafe path.",path:c.path};o.add(l);let u=zi(c.path,t.config.editablePaths);if(u===void 0||u.class!==c.class||Hi(c.path,t.config))return{kind:"rejected",code:"unauthorized-target",message:"Target is outside the approved repair boundary.",path:c.path};if(s.has(l))return{kind:"rejected",code:"dirty-target-file",message:"An approved target is currently dirty.",path:c.path};let p=await X(n,c.path,t.maxTargetBytes);if(p.kind!=="read"||p.relativePath!==c.path)return{kind:"rejected",code:"unreadable-target",message:"Target could not be read through its canonical authorized path.",path:c.path};if(p.sha256!==c.sourceSha256)return{kind:"rejected",code:"source-hash-mismatch",message:"Target no longer matches the approved preimage.",path:c.path};let f=mS(p.bytes);if(f===void 0)return{kind:"rejected",code:"unreadable-target",message:"Target is not valid UTF-8.",path:c.path};let h=a.get(c.path)??[],m=Il(c.path,f,h);if(m.kind!=="applied"||m.resultSha256!==c.resultSha256)return{kind:"rejected",code:"result-hash-mismatch",message:"Approved replacements no longer derive the approved result.",path:c.path};d.push({path:c.path,source:f,sourceBytes:p.bytes,sourceSha256:p.sha256,result:m.result,resultBytes:new TextEncoder().encode(m.result),resultSha256:m.resultSha256,replacements:h})}return{kind:"verified",workspaceRoot:n,gitRoot:e,targets:d,nonPristine:t.dirtyPaths.length>0}}var yS=new Set(["completed","rolled-back","conflicted"]);function Nn(t,n,e){return{code:t,message:n,...e===void 0?{}:{path:e}}}function Te(t){return{schemaVersion:"2.0",transactionId:t.manifest.transactionId,authorizationId:t.manifest.authorization.authorizationId,approvalBindingHash:t.manifest.preview.bindingHash,proposalHash:t.manifest.preview.proposal.proposalHash,diffHash:t.manifest.preview.proposal.diffHash,workspace:t.manifest.preview.workspace,phase:t.state.phase,revision:t.state.revision,targets:t.manifest.targets.map(n=>({path:n.path,sourceSha256:n.sourceSha256,resultSha256:n.resultSha256,preimageBytes:n.preimageBytes,resultBytes:n.resultBytes})),validationPlan:t.manifest.preview.validationPlan,authoritativeValidation:t.manifest.preview.authoritativeValidation,createdAt:t.manifest.createdAt,updatedAt:t.state.updatedAt}}async function gS(t){return(await Promise.all((await Si(t)).map(e=>Re(t,e)))).filter(e=>!yS.has(e.state.phase))}async function vy(t,n,e,r){let i=await X(t,n,e);return i.kind==="read"&&i.relativePath===n&&i.sha256===r}async function Al(t){return wS(t,{})}async function wS(t,n){if(!Rl(t.preview,t.authorization))return{kind:"rejected",reasons:[Nn("authorization-mismatch","Authorization does not match this exact preview.")]};let e=t.now??new Date().toISOString(),r;try{let[i,s,a,o,d,c]=await Promise.all([wr(t.context.workspace.workspaceRoot),wr(t.context.snapshot.workspaceRoot),wr(t.preview.workspace.workspaceRoot),wr(t.context.workspace.gitRoot),wr(t.context.snapshot.gitRoot),wr(t.preview.workspace.gitRoot)]);if(i!==s||i!==a||o!==d||o!==c)return{kind:"rejected",reasons:[Nn("invalid-workspace","Application workspace identity changed.")]};let l=a;r=await Je(l,{operation:"apply",authorizationId:t.authorization.authorizationId,at:e});let u=await gS(l);if(u.length>0)return{kind:"recovery-required",reasons:[Nn("transaction-blocked","A nonterminal transaction must be recovered before another application.")],transaction:Te(u[0])};if((await Promise.all((await Si(l)).map(g=>Re(l,g)))).some(g=>g.manifest.authorization.authorizationId===t.authorization.authorizationId))return{kind:"rejected",reasons:[Nn("authorization-replayed","Authorization has already been consumed.")]};let f=await xy({workspaceRoot:t.context.snapshot.workspaceRoot,gitRoot:t.context.snapshot.gitRoot,approvedWorkspaceRoot:t.preview.workspace.workspaceRoot,approvedGitRoot:t.preview.workspace.gitRoot,config:t.context.config,dirtyPaths:t.context.snapshot.dirtyPaths,proposal:t.preview.proposal,maxTargetBytes:t.context.maxTargetBytes});if(f.kind!=="verified")return{kind:"rejected",reasons:[Nn(f.code==="dirty-target-file"?"dirty-target-file":f.code==="source-hash-mismatch"?"source-hash-mismatch":f.code==="result-hash-mismatch"?"result-hash-mismatch":"unsafe-target",f.message,f.path)]};let h=Ah(),m=await $h({workspaceRoot:f.workspaceRoot,transactionId:h,preview:t.preview,authorization:t.authorization,config:t.context.config,maxTargetBytes:t.context.maxTargetBytes,targets:f.targets,now:e});await n.failpoint?.("journal-prepared"),m=await Ge({transaction:m,phase:"applying",type:"application-started",now:e}),await n.failpoint?.("phase-applying");for(let g of m.manifest.targets){if(!await vy(f.workspaceRoot,g.path,t.context.maxTargetBytes,g.sourceSha256))return{kind:"recovery-required",reasons:[Nn("source-hash-mismatch","Target changed immediately before mutation.",g.path)],transaction:Te(m)};m=await Ge({transaction:m,phase:"applying",type:"target-write-intent",path:g.path,now:e}),await n.failpoint?.(`before-target:${g.path}`);let w=m.results.get(g.path);if(w===void 0)throw new Error("Journal result bytes are unavailable.");if(await la(f.workspaceRoot,g.path,g.sourceSha256,w),await n.failpoint?.(`after-target:${g.path}`),!await vy(f.workspaceRoot,g.path,t.context.maxTargetBytes,g.resultSha256))throw new Error("Applied target hash could not be verified.");m=await Ge({transaction:m,phase:"applying",type:"target-write-complete",path:g.path,now:e})}return m=await Ge({transaction:m,phase:"applied",type:"application-complete",now:e}),await n.failpoint?.("phase-applied"),{kind:"applied",transaction:Te(m)}}catch{return{kind:"failed",reasons:[Nn("application-failed","Application stopped safely; inspect transaction discovery before continuing.")]}}finally{await r?.release().catch(()=>{})}}var Ry=new Set(["completed","rolled-back","conflicted"]);function en(t,n){return{code:"transaction-conflict",message:t,...n===void 0?{}:{path:n}}}async function Pl(t,n){let e=t.manifest.targets.find(i=>i.path===n);if(e===void 0)return"conflict";let r=await X(t.manifest.preview.workspace.workspaceRoot,n,t.manifest.maxTargetBytes);return r.kind!=="read"||r.relativePath!==n?"conflict":r.sha256===e.sourceSha256?"preimage":r.sha256===e.resultSha256?"applied":"conflict"}async function Ua(t,n){let e=await Re(t,n),r=await Promise.all(e.manifest.targets.map(async i=>({path:i.path,classification:await Pl(e,i.path)})));return{transactionId:n,phase:e.state.phase,targets:r}}async function Sl(t){try{let n=await Promise.all((await Si(t)).map(r=>Ua(t,r))),e=n.filter(r=>!Ry.has(r.phase));return e.some(r=>r.targets.some(i=>i.classification==="conflict"))?{kind:"conflicted",transactions:e}:e.length===0?{kind:"clear",transactions:n}:{kind:"recovery-required",transactions:e}}catch{return{kind:"failed",reasons:[en("Transaction discovery failed closed because a journal is unreadable.")]}}}async function Tl(t,n,e){return t.state.phase==="conflicted"?t:Ge({transaction:t,phase:"conflicted",type:"conflict-detected",message:e,now:n})}async function ky(t){let n=await Promise.all(t.manifest.targets.map(async e=>[e.path,await Pl(t,e.path)]));return new Map(n)}async function bS(t,n,e,r,i){let s;try{let[a,o,d,c]=await Promise.all([br(t.workspace.workspaceRoot),br(t.snapshot.workspaceRoot),br(t.workspace.gitRoot),br(t.snapshot.gitRoot)]);if(a!==o||d!==c)return{kind:"rejected",reasons:[en("Recovery workspace identity differs.")]};s=await Je(a,{operation:e,transactionId:n,at:r});let l=await Re(a,n);if(await br(l.manifest.preview.workspace.workspaceRoot)!==a||await br(l.manifest.preview.workspace.gitRoot)!==d)return{kind:"rejected",reasons:[en("Recovery workspace identity differs.")]};if(Ry.has(l.state.phase))return e==="rollback"&&l.state.phase==="rolled-back"?{kind:"rolled-back",transaction:Te(l)}:{kind:"rejected",reasons:[en("Terminal transaction cannot perform this recovery operation.")],transaction:Te(l)};let u=await ky(l),p=[...u].find(([,m])=>m==="conflict");if(p!==void 0)return l=await Tl(l,r,"Current target bytes match neither recorded preimage nor applied image."),{kind:"conflicted",reasons:[en("Developer or unknown target bytes prohibit automatic recovery.",p[0])],transaction:Te(l)};e==="rollback"&&(l=await Ge({transaction:l,phase:"rolling-back",type:"rollback-started",now:r}),await i?.("phase-rolling-back"));for(let m of l.manifest.targets){let g=u.get(m.path);if(!(e==="resume"&&g==="preimage"||e==="rollback"&&g==="applied"))continue;let w=e==="resume"?"resume":"rollback";if(await i?.(`before-${w}-target:${m.path}`),await Pl(l,m.path)!==g)return l=await Tl(l,r,"Target changed after recovery classification."),{kind:"conflicted",reasons:[en("Target changed immediately before recovery mutation.",m.path)],transaction:Te(l)};let v=e==="resume"?l.results.get(m.path):l.preimages.get(m.path);if(v===void 0)throw new Error("Recovery bytes are unavailable.");await la(a,m.path,e==="resume"?m.sourceSha256:m.resultSha256,v),await i?.(`after-${w}-target:${m.path}`),l=await Ge({transaction:l,phase:e==="resume"?"applying":"rolling-back",type:`${e}-target-complete`,path:m.path,now:r})}let f=await ky(l),h=e==="resume"?"applied":"preimage";return[...f.values()].some(m=>m!==h)?(l=await Tl(l,r,"Recovery result hashes did not verify."),{kind:"conflicted",reasons:[en("Recovery completed with an unknown target state.")],transaction:Te(l)}):(l=await Ge({transaction:l,phase:e==="resume"?"applied":"rolled-back",type:e==="resume"?"resume-complete":"rollback-complete",now:r}),{kind:e==="resume"?"resumed":"rolled-back",transaction:Te(l)})}catch{return{kind:"failed",reasons:[en("Recovery stopped safely; rediscover transaction state.")]}}finally{await s?.release().catch(()=>{})}}async function El(t,n,e=new Date().toISOString()){return bS(t,n,"rollback",e)}var Iy=/^rps_[a-f0-9]{24}$/,qa=/^[a-f0-9]{64}$/,SS=new Set(["rolling-back","rolled-back","conflicted"]);function ES(t,n){let e=AS(t,n);return e===""||!IS(e)&&e!==".."&&!e.startsWith(`..${PS}`)}function xr(t){return t.length>0&&Number.isFinite(Date.parse(t))}function Ay(t){if(t.ordinal!==1&&t.ordinal!==2||!qa.test(t.proposalHash)||!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||t.validationManifestHash!==void 0&&!qa.test(t.validationManifestHash)||!xr(t.recordedAt))throw new Error("Repair attempt record is malformed.")}function CS(t){let{sessionHash:n,...e}=t;if(t.schemaVersion!=="1.0"||!Iy.test(t.repairSessionId)||t.originalRunId.trim().length===0||!qa.test(t.originalPacketHash)||t.maxAttempts!==2||!xr(t.createdAt)||!xr(t.updatedAt)||!Number.isInteger(t.revision)||t.revision<1||t.attempts.length>2||L(e)!==n)throw new Error("Repair session integrity check failed.");t.attempts.forEach(Ay);for(let[r,i]of t.attempts.entries())if(i.ordinal!==r+1)throw new Error("Repair attempt order is malformed.");return t}async function Ga(t){let n=await kS(t),e=TS(n,".kwikqa");if(!ES(n,e))throw new Error("Repair session directory escapes workspace.");await Cl(e,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let r=await Vi(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Repair session path is unsafe.");let i=vr(e,"repair-sessions");await Cl(i,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let s=await Vi(i);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Repair session path is unsafe.");return i}function Ka(t){return{...t,sessionHash:L(t)}}function Nl(t){return{schemaVersion:t.schemaVersion,repairSessionId:t.repairSessionId,originalRunId:t.originalRunId,originalPacketHash:t.originalPacketHash,maxAttempts:t.maxAttempts,attempts:t.attempts,state:t.state,createdAt:t.createdAt,updatedAt:t.updatedAt,revision:t.revision}}async function Ol(t){if(t.originalRunId.trim().length===0||!qa.test(t.originalPacketHash))throw new Error("Original repair evidence identity is invalid.");let n=t.now??new Date().toISOString();if(!xr(n))throw new Error("Repair session timestamp is invalid.");let e=`rps_${xS().replaceAll("-","").slice(0,24)}`,r=Ka({schemaVersion:"1.0",repairSessionId:e,originalRunId:t.originalRunId,originalPacketHash:t.originalPacketHash,maxAttempts:2,attempts:[],state:"first-attempt",createdAt:n,updatedAt:n,revision:1}),i=await Ga(t.workspaceRoot);return await ye(vr(i,`${e}.json`),`${ue(r)}
28
- `,{mode:384,replace:!1}),r}async function tn(t,n){if(!Iy.test(n))throw new Error("Repair session id is invalid.");let e=await Ga(t),r=vr(e,`${n}.json`),i=await Vi(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Repair session record is unsafe.");let s=JSON.parse(await vS(r,"utf8"));if(s===null||typeof s!="object"||Array.isArray(s))throw new Error("Repair session record is malformed.");return CS(s)}async function $l(t,n){let e=await Ga(t),r=vr(e,`${n}.lock`);await Cl(r,{mode:448});let i=await Vi(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Repair session lock is unsafe.");return{release:async()=>{let s=await Vi(r);if(s.dev!==i.dev||s.ino!==i.ino||s.isSymbolicLink())throw new Error("Repair session lock ownership changed.");await RS(r,{recursive:!0,force:!1})}}}async function Dl(t,n,e){let r=await tn(t,n.repairSessionId);if(r.revision!==n.revision||r.sessionHash!==n.sessionHash)throw new Error("Repair session changed concurrently.");let i=await Ga(t);return await ye(vr(i,`${n.repairSessionId}.json`),`${ue(e)}
29
- `,{mode:384,replace:!0}),tn(t,n.repairSessionId)}async function Ll(t,n,e){Ay(e);let r=await $l(t,n);try{let i=await tn(t,n);if(i.state==="repaired"||i.state==="stopped")throw new Error("Terminal repair session cannot accept another attempt.");if(e.ordinal!==i.attempts.length+1||e.ordinal>i.maxAttempts)throw new Error("Repair session attempt limit or ordering was violated.");if(e.ordinal===1&&i.state!=="first-attempt"||e.ordinal===2&&i.state!=="retry-approval-required")throw new Error("Repair session is not ready for this attempt.");let s=e.recordedAt,a=Ka({...Nl(i),attempts:[...i.attempts,e],state:e.ordinal===1?"first-attempt":"second-attempt",updatedAt:s,revision:i.revision+1});return await Dl(t,i,a)}finally{await r.release()}}function NS(t,n){let e=t.status;if(e==="blocked")throw new Error("A blocked validation run has no attempt outcome.");let r=n.state.history,i=r.findLastIndex(d=>d.type==="validation-started"),s=r[i];if(s===void 0||s.validationRunId!==t.validationRunId||s.planHash!==t.planHash)throw new Error("Validation run was not started for this transaction approval.");let a=r.slice(i+1).find(d=>d.type==="validation-passed"),o=n.state.phase;if(a!==void 0){if(o!=="completed"||e!=="passed"||a.validationRunId!==t.validationRunId||a.planHash!==t.planHash||a.validationManifestHash!==t.manifestHash)throw new Error("Validation outcome does not match the durable transaction state.");return"passed"}if(o==="validating"){if(e==="passed")throw new Error("A passing validation run must be completed by M6, or rolled back, before it is recorded.");return e}if(SS.has(o))return e==="passed"?"incomplete":e;throw new Error("Validation outcome does not match the durable transaction state.")}async function Wa(t){if(!/^vld_[a-f0-9]{24}$/.test(t.validationRunId))throw new Error("Validation run id is invalid.");let n=t.now??new Date().toISOString();if(!xr(n))throw new Error("Repair session timestamp is invalid.");let e=await $l(t.workspaceRoot,t.repairSessionId),r;try{r=await Je(t.workspaceRoot,{operation:"record-repair-validation",repairSessionId:t.repairSessionId,validationRunId:t.validationRunId});let i=await tn(t.workspaceRoot,t.repairSessionId),s=i.attempts.at(-1);if(s===void 0||s.ordinal!==t.ordinal)throw new Error("Repair attempt cannot be finalized from its current state.");let a=await Re(t.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation,d=vr(a.directory,"validation",t.validationRunId),c=Kt(await vn(d,"manifest.json",ba)),l=new Map(o.requiredCommands.map(m=>[m.commandId,m.commandHash]));if(c.transactionId!==s.transactionId||c.validationRunId!==t.validationRunId||c.planHash!==o.planHash||c.repositoryFingerprint!==o.repositoryFingerprint||L(c.targetHashes)!==L(o.targetHashes)||c.requiredCommandIds.length!==l.size||c.requiredCommandIds.some(m=>!l.has(m))||c.commandRecords.some(m=>l.get(m.commandId)!==m.commandHash)||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Validation manifest does not match the repair attempt authority.");for(let m of c.commandRecords)if(!await jh(d,m,rr))throw new Error("Validation manifest command evidence failed verification.");let u=NS(c,a);if(s.outcome!=="applied"){if(s.validationManifestHash===c.manifestHash&&s.outcome===u)return{session:i};throw new Error("Repair attempt was already finalized with different evidence.")}let p={...s,validationManifestHash:c.manifestHash,outcome:u,recordedAt:n},f=u==="passed"?"repaired":"rollback-required",h=Ka({...Nl(i),attempts:[...i.attempts.slice(0,-1),p],state:f,updatedAt:n,revision:i.revision+1});return{session:await Dl(t.workspaceRoot,i,h)}}finally{await r?.release(),await e.release()}}async function Ml(t){if(!/^txn_[a-f0-9]{24}$/.test(t.proof.transactionId)||t.proof.phase!=="rolled-back"||!Number.isInteger(t.proof.transactionRevision)||t.proof.transactionRevision<1)throw new Error("Repair rollback proof is invalid.");let n=t.now??new Date().toISOString();if(!xr(n))throw new Error("Repair session timestamp is invalid.");let e=await $l(t.workspaceRoot,t.repairSessionId),r;try{r=await Je(t.workspaceRoot,{operation:"confirm-repair-rollback",repairSessionId:t.repairSessionId,transactionId:t.proof.transactionId});let i=await tn(t.workspaceRoot,t.repairSessionId),s=i.attempts.at(-1);if(i.state!=="rollback-required"||s===void 0||s.ordinal!==t.ordinal||s.transactionId!==t.proof.transactionId||s.validationManifestHash===void 0||s.outcome==="passed"||s.outcome==="applied")throw new Error("Repair session does not match the rolled-back attempt.");let a=await Re(t.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation;if(a.state.phase!=="rolled-back"||a.state.revision!==t.proof.transactionRevision||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Repair rollback proof does not match the durable transaction.");let d=await Ua(t.workspaceRoot,s.transactionId);if(d.phase!=="rolled-back"||d.targets.some(f=>f.classification!=="preimage"))throw new Error("Durable rollback could not be verified from recorded preimages.");let c=t.ordinal===1?"retry-approval-required":"stopped",l=Ka({...Nl(i),state:c,updatedAt:n,revision:i.revision+1}),u=await Dl(t.workspaceRoot,i,l);if(c!=="retry-approval-required")return{session:u};let p={repairSessionId:u.repairSessionId,failedTransactionId:s.transactionId,failedValidationManifestHash:s.validationManifestHash,nextAttemptOrdinal:2};return{session:u,retry:{...p,handoffHash:L(p)}}}finally{await r?.release(),await e.release()}}import{lstat as US,mkdir as qS,open as GS}from"node:fs/promises";import{dirname as $y,resolve as KS}from"node:path";import{createHash as OS}from"node:crypto";var Ja="kwikqa-report",Cy="1",Mt={"test-support":"Test code",application:"Application",environment:"Environment",undetermined:"Undetermined",inconclusive:"Inconclusive","not-diagnosed":"Not diagnosed"},$S=12,DS=800,Ty=`
26
+ `),"utf8").digest("hex")}function La(t,n){let e=n.reportPath;if(t.length===0)return Qe(void 0,e,{reasonCode:"missing-report",message:"No report files were found."});let r=lP(t),i=[],s;for(let y of t){let w=dP(y);w.kind==="classified"?i.push(w.value):s??=w.diagnostic}if(i.length===0)return Qe(r,e,s??{reasonCode:"unsupported-report-format",message:"No report was found."});let a=sP.find(y=>i.some(w=>w.format===y)),o=i.filter(y=>y.format===a),d=i.length-o.length+(t.length-i.length),c=d>0?[`ignored-report-files:${d}`]:[];if(a==="playwright-json"){let y=o[0];return o.length!==1||y===void 0?Qe(r,e,{reasonCode:"invalid-report-shape",message:"Found several Playwright JSON reports; point --report at one, or merge them with `npx playwright merge-reports`."}):yr(y.file.bytes,{...n,...y.file.path===void 0?{}:{reportPath:y.file.path}})}let l=a==="junit-xml"?il(o.map(y=>y.text)):void 0,u;try{u=a==="allure-json"?pm(o.map(y=>({json:y.json,...y.file.path===void 0?{}:{directory:rP(y.file.path)}}))):Am(o.map(y=>cP(y,n,l)))}catch(y){return Qe(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be read."})}let p=new Set(Hc[u.framework]),f=u.frameworkVersion,h=f!==void 0&&p.has(f),m=[...u.warnings,...c,f===void 0?"producer-version-unrecorded":h?void 0:`unverified-producer-version:${f}`].filter(y=>y!==void 0),g={artifactId:B("art",[r]),kind:"report",availability:"present",...e===void 0?{}:{path:e},sha256:r,format:u.format,...f===void 0?{}:{formatVersion:f},versionConfidence:h?"verified":"unverified",warnings:[...new Set(m)].sort()};try{return{kind:"parsed",run:Hm({report:u,reportHash:r,artifact:g,options:n,warnings:m})}}catch(y){return Qe(r,e,{reasonCode:"invalid-report-shape",message:y instanceof Error?y.message:"The report could not be normalized."})}}async function uP(t){return(await ZT(t,{withFileTypes:!0})).filter(e=>e.isFile()&&/\.(?:json|xml|log)$/i.test(e.name)).map(e=>iP(t,e.name)).sort()}async function ct(t,n){let e;try{e=await tP(t)}catch(o){let d=o.code==="ENOENT";return Qe(void 0,t,{reasonCode:d?"missing-report":"read-failed",message:d?`Test report does not exist: ${t}`:`Could not inspect: ${t}`})}let r;if(e.isDirectory()){try{r=await uP(t)}catch{return Qe(void 0,t,{reasonCode:"read-failed",message:`Could not list report directory: ${t}`})}if(r.length===0)return Qe(void 0,t,{reasonCode:"missing-report",message:`No .json or .xml report files in ${t}`});if(r.length>Qm)return Qe(void 0,t,{reasonCode:"read-failed",message:`${t} holds ${r.length} report files; KwikQA reads at most ${Qm} from one directory.`})}else if(e.isFile())r=[t];else return Qe(void 0,t,{reasonCode:"not-a-file",message:`Test report path is not a regular file or directory: ${t}`});let i=[],s=0;for(let o of r)try{let d=await eP(o);if(s+=d.byteLength,s>Zm)return Qe(void 0,t,{reasonCode:"read-failed",message:`Report files under ${t} exceed ${Zm} bytes.`});i.push({path:o,bytes:d})}catch{return Qe(void 0,t,{reasonCode:"read-failed",message:`Could not read test report: ${o}`})}let a=La(i,{...n,reportPath:t});return a.kind!=="parsed"||a.run.artifact.format==="playwright-json"?a:{kind:"parsed",run:await dl(await pP(a.run))}}async function pP(t){if(t.framework!=="junit"&&t.framework!=="testng"&&t.framework!=="cucumber")return t;let n=new gr(t.workspace.root),e=async a=>{let o=await n.resolve(a.file);return o===a.file?a:{...a,file:o}},r=async a=>a.location===void 0?a:{...a,location:await e(a.location)},i=async a=>({...a,...a.error===void 0?{}:{error:await r(a.error)},steps:await Promise.all(a.steps.map(i))}),s=await Promise.all(t.logicalTests.map(async a=>({...a,location:await e(a.location),attempts:await Promise.all(a.attempts.map(async o=>({...o,errors:await Promise.all(o.errors.map(r)),steps:await Promise.all(o.steps.map(i)),...o.errorLocation===void 0?{}:{errorLocation:await e(o.errorLocation)}})))})));return{...t,logicalTests:s}}var Rt={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO",vitest:"Vitest",jest:"Jest",mocha:"Mocha",pytest:"pytest",junit:"JUnit",testng:"TestNG",cucumber:"Cucumber",unknown:"Unidentified framework"},Zt={"playwright-json":"JSON report","kwikqa-json":"KwikQA reporter","mochawesome-json":"mochawesome report","wdio-json":"@wdio/json-reporter report","allure-json":"Allure results","ctrf-json":"CTRF report","testng-xml":"TestNG results","cucumber-json":"Cucumber JSON report","junit-xml":"JUnit report"};var ey={playwright:["playwright-json"],cypress:["kwikqa-json","mochawesome-json","junit-xml"],webdriverio:["kwikqa-json","wdio-json","junit-xml"]};function cl(t){return kt.includes(t)}function Ze(t){let{framework:n}=t;if(!cl(n))return;let e=t.artifact.format;return e!==void 0&&ey[n].includes(e)?n:void 0}function lt(t){let{framework:n}=t;if(n==="unknown")return"KwikQA can't tell which test framework wrote this report, so it diagnoses the run but doesn't capture, repair, or validate it.";if(cl(n)){let e=ey[n].map(s=>Zt[s]).join(", "),r=t.artifact.format===void 0?void 0:Zt[t.artifact.format],i=r===void 0?"this format":r.endsWith(" results")?r:`a ${r}`;return`KwikQA repairs ${Rt[n]} tests from a ${e}, whose test identities its validation can match; it only diagnoses a run read from ${i}.`}return`KwikQA diagnoses ${Rt[n]} runs but doesn't capture, repair, or validate them.`}function _a(t,n){let e=mP(t,n);return e===""||!hP(e)&&e!==".."&&!e.startsWith(`..${yP}`)}function gP(t){return t.status==="expected"?"passed":t.status==="skipped"?"skipped":t.attempts.some(n=>n.status==="interrupted")?"interrupted":"failed"}var ty={passed:0,skipped:1,interrupted:2,failed:3};function sy(t){let n=new Map;for(let e of t){let r=gP(e),i=n.get(e.logicalTestId);(i===void 0||ty[r]>ty[i])&&n.set(e.logicalTestId,r)}return[...n].map(([e,r])=>({logicalTestId:e,status:r})).sort((e,r)=>e.logicalTestId.localeCompare(r.logicalTestId))}async function ll(t){if(!Number.isInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let n=await Ma(t.runDirectory).catch(()=>{});if(n===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=iy(n,t.artifact.path);if(!_a(n,e))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let r=await ny(e).catch(()=>{}),i=await Ma(e).catch(()=>{});if(r===void 0||i===void 0||!r.isFile()||r.isSymbolicLink()||!_a(n,i)||r.size>t.maxBytes||r.size!==t.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};let s=await ry(i).catch(()=>{});if(s===void 0||s.byteLength>t.maxBytes||s.byteLength!==t.artifact.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};let a=yr(s,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},reportPath:t.artifact.path});if(a.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${a.diagnostic.reasonCode}.`};if(a.run.usability!=="analysis-ready")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${a.run.usability}.`};if(a.run.sourceHashes.report!==t.artifact.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};let o=sy(a.run.logicalTests),d=new Set(o.map(c=>c.logicalTestId));return t.expectedLogicalTestIds.some(c=>!d.has(c))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:a.run.sourceHashes.report,observations:o}}var ja=/^(?:cypress|wdio)-[^/]*\.json$/;async function ul(t){if(!Number.isInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("Validation report byte limit is invalid.");let n=await Ma(t.runDirectory).catch(()=>{});if(n===void 0)return{kind:"incomplete",reason:"Validation run directory is unavailable."};let e=t.artifacts.filter(d=>ja.test(d.path.split("/").at(-1)??""));if(e.length===0)return{kind:"incomplete",reason:"The test run wrote no KwikQA report."};let r=[],i=0;for(let d of e){let c=iy(n,d.path);if(!_a(n,c))return{kind:"incomplete",reason:"Validation report path escapes its run directory."};let l=await ny(c).catch(()=>{}),u=await Ma(c).catch(()=>{});if(l===void 0||u===void 0||!l.isFile()||l.isSymbolicLink()||!_a(n,u)||l.size!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unsafe."};if(i+=l.size,i>t.maxBytes)return{kind:"incomplete",reason:"Validation reports exceed their byte limit."};let p=await ry(u).catch(()=>{});if(p===void 0||p.byteLength!==d.bytes)return{kind:"incomplete",reason:"Validation report artifact is missing or unbounded."};if(fP("sha256").update(p).digest("hex")!==d.sha256)return{kind:"incomplete",reason:"Validation report content hash does not match its record."};r.push({path:u,bytes:p})}let s=La(r,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot}});if(s.kind!=="parsed")return{kind:"incomplete",reason:`Validation report could not be parsed: ${s.diagnostic.reasonCode}.`};if(s.run.artifact.format!=="kwikqa-json")return{kind:"incomplete",reason:"Validation report was not written by KwikQA's reporter."};if(s.run.usability==="interrupted"||s.run.usability==="zero-tests")return{kind:"incomplete",reason:`Validation report is not analysis-ready: ${s.run.usability}.`};let a=sy(s.run.logicalTests),o=new Set(a.map(d=>d.logicalTestId));return t.expectedLogicalTestIds.some(d=>!o.has(d))?{kind:"incomplete",reason:"Validation report omits an expected logical test."}:{kind:"observed",reportSha256:s.run.sourceHashes.report,observations:a}}var xP=/^txn_[a-f0-9]{24}$/,vP=/^vld_[a-f0-9]{24}$/,kP=new Set(["rolling-back","rolled-back","conflicted"]);function RP(t){return t.length>0&&Number.isFinite(Date.parse(t))}function IP(t){return t.commands.filter(n=>n.required&&n.timing==="post-patch").sort((n,e)=>n.commandId.localeCompare(e.commandId))}function AP(t,n){let e=new Set(t);return e.size===t.length&&t.length===n.length&&n.every(r=>e.has(r))}function TP(t,n,e){let r=t.manifest.preview.authoritativeValidation,i=new Map(r.requiredCommands.map(s=>[s.commandId,s.commandHash]));return r.planHash===n.planHash&&r.repositoryFingerprint===n.repositoryFingerprint&&L(r.targetHashes)===L(n.targetHashes)&&AP(r.requiredCommandIds,e.map(s=>s.commandId))&&e.every(s=>i.get(s.commandId)===L(s))}async function PP(t,n){for(let e of n.manifest.targets){let r=await X(t,e.path,Math.max(1,e.resultBytes)).catch(()=>{});if(r?.kind!=="read"||r.relativePath!==e.path||r.sha256!==e.resultSha256)return!1}return!0}function SP(t){return t===void 0?[]:Object.entries(t.logicalTestOutcomes).map(([n,e])=>({logicalTestId:n,status:e})).sort((n,e)=>n.logicalTestId.localeCompare(e.logicalTestId))}async function EP(t,n,e,r,i,s){let a={classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:"incomplete",fresh:!0,expectedLogicalTestIds:i.logicalTestIds,observations:[]}},o=await jc(e,i.commandId).catch(()=>{});if(o===void 0||o.validationRunId!==t.validationRunId||o.planHash!==r.planHash||o.commandId!==i.commandId||o.commandHash!==L(i)||o.timing!=="post-patch"||!await Fc(e,o,i.artifactPolicy.maxArtifactBytes))return a;let d=[],c=o.status==="blocked"?"incomplete":o.status;if(sr(i.kind)&&!i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=await ul({workspaceRoot:n,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},runDirectory:e,artifacts:o.artifacts,expectedLogicalTestIds:i.logicalTestIds,maxBytes:t.reportMaxBytes});l.kind==="observed"?d=l.observations:c="incomplete"}else if(i.kind.startsWith("playwright-")&&o.status!=="unavailable"){let l=i.artifactPolicy.reportFile??di,u=o.artifacts.find(p=>p.path.split("/").at(-1)===l);if(u===void 0)c="incomplete";else{let p=await ll({workspaceRoot:n,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},runDirectory:e,artifact:u,expectedLogicalTestIds:i.logicalTestIds,maxBytes:t.reportMaxBytes});p.kind==="observed"?d=p.observations:c="incomplete"}}return{record:o,classification:{commandId:i.commandId,required:!0,timing:"post-patch",status:c,fresh:Date.parse(o.startedAt)>=s&&!o.stdout.truncated&&!o.stderr.truncated,expectedLogicalTestIds:i.logicalTestIds,observations:d}}}async function CP(t,n,e,r){let i=await Re(n,t.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history,o=a.findLastIndex(R=>R.type==="validation-started"),d=a[o],c=IP(e);if(d===void 0||d.validationRunId!==t.validationRunId||d.planHash!==e.planHash||!TP(i,e,c))throw new Error("Validation run does not match the durable transaction approval.");if(s.baselineManifestHash!==r?.baselineHash||r!==void 0&&(r.planHash!==e.planHash||r.repositoryFingerprint!==e.repositoryFingerprint||L(r.targetHashes)!==L(e.targetHashes)))throw new Error("Required validation baseline is missing or mismatched.");let l=await ze(n,[".kwikqa","transactions",t.transactionId,"validation",t.validationRunId]),u=await vn(l,"manifest.json",ba).catch(R=>{if(R.code!=="ENOENT")throw R});if(u!==void 0){let R=Kt(u);if(R.transactionId!==t.transactionId||R.validationRunId!==t.validationRunId||R.planHash!==e.planHash)throw new Error("Validation run was already finalized for different evidence.");return{directory:l,manifest:R}}let p=[],f=i.state.phase;if(f==="validating")await PP(n,i)||p.push("Applied validation targets changed before the run was finalized.");else if(kP.has(f)&&!a.slice(o+1).some(R=>R.type==="validation-passed"))p.push("The transaction left validation before M6 accepted this run.");else throw new Error("Validation run cannot be finalized from the current transaction phase.");let h=Date.parse(d.at),m=t.completedAt??new Date().toISOString();if(Date.parse(m)<h)throw new Error("Validation completion precedes command execution.");let g=[],y=[];for(let R of c){let P=await EP(t,n,l,e,R,h);P.record!==void 0&&g.push(P.record),y.push(P.classification)}let w=_d({targetLogicalTestIds:e.targetLogicalTestIds,baseline:SP(r),commands:y,blockingReasons:p}),x={schemaVersion:qs,validationRunId:t.validationRunId,transactionId:t.transactionId,planHash:e.planHash,repositoryFingerprint:e.repositoryFingerprint,targetHashes:e.targetHashes,requiredCommandIds:c.map(R=>R.commandId),status:w.status,commandRecords:g,classifications:w.classifications,startedAt:d.at,completedAt:m},v=Kt({...x,manifestHash:Ks(x)});return await ye(bP(l,"manifest.json"),`${ue(v)}
27
+ `,{mode:384,replace:!1}),{directory:l,manifest:v}}async function pl(t){if(!xP.test(t.transactionId)||!vP.test(t.validationRunId)||!Number.isInteger(t.reportMaxBytes)||t.reportMaxBytes<=0||t.completedAt!==void 0&&!RP(t.completedAt))throw new Error("Validation finalization identity, timestamp, or limits are invalid.");let n=mn(t.plan);if(n.status!=="resolved")throw new Error("Unavailable validation plan cannot be finalized.");if(n.transactionId!==void 0&&n.transactionId!==t.transactionId)throw new Error("Validation plan is bound to another transaction.");let e=t.baseline===void 0?void 0:li(t.baseline),r=await wP(t.workspaceRoot),i=await Je(r,{operation:"finalize-validation",transactionId:t.transactionId,validationRunId:t.validationRunId});try{return await CP(t,r,n,e)}finally{await i.release().catch(()=>{})}}import{fileURLToPath as UP}from"node:url";import{execFile as NP}from"node:child_process";import{lstat as Fa,realpath as et}from"node:fs/promises";import{createRequire as OP}from"node:module";import{dirname as Lt,isAbsolute as dy,join as hl,relative as cy,resolve as ml,sep as ly}from"node:path";import{fileURLToPath as $P}from"node:url";import{promisify as DP}from"node:util";var LP=DP(NP),uy=128*1024,MP=64*1024,_P=/^[a-f0-9]{64}$/,ay={"@playwright/test":{entryRequests:["@playwright/test/cli"]},cypress:{entryRequests:["cypress/bin/cypress"],bin:"cypress"},"@wdio/cli":{entryRequests:["@wdio/cli/bin/wdio.js"],bin:"wdio"},"@biomejs/biome":{entryRequests:["@biomejs/biome/bin/biome"]},prettier:{entryRequests:["prettier/bin/prettier.cjs","prettier/bin/prettier.js"]},typescript:{entryRequests:["typescript/bin/tsc"],bin:"tsc"},eslint:{entryRequests:["eslint/bin/eslint.js"]}};function Cn(t,n){let e=cy(t,n);return e===""||!dy(e)&&e!==".."&&!e.startsWith(`..${ly}`)}function fl(t,n){return cy(t,n).split(ly).join("/")}function Mi(t,n,e){return{code:t,message:n,...e===void 0?{}:{path:e}}}function jP(t,n){let e=new TextDecoder("utf-8",{fatal:!0}).decode(t),r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("Package manifest is not an object.");let i=r;if(i.name!==n||typeof i.version!="string"||i.version.trim().length===0)throw new Error("Package identity does not match the requested tool.");return{name:i.name,version:i.version}}async function FP(t,n){let e=await et(t),r=dy(n)?n:ml(e,n),i=await et(r).catch(()=>r);if(!Cn(e,i))return;let s=i;for((await Fa(s).catch(()=>{}))?.isFile()&&(s=Lt(s));Cn(e,s);){let o=hl(s,"package.json"),d=await Fa(o).catch(()=>{});if(d?.isFile()&&!d.isSymbolicLink())return o;if(s===e)break;s=Lt(s)}}async function BP(t,n){let e=await et(t),r=Lt(n);for(;Cn(e,r);){let i=hl(r,".pnp.cjs"),s=await Fa(i).catch(()=>{});if(s?.isFile()&&!s.isSymbolicLink())return i;if(r===e)break;r=Lt(r)}}async function oy(t,n,e){let r=Lt(t);for(;;){let i=hl(r,"node_modules",...n.split("/"),"package.json");if(await Fa(i).catch(()=>{})!==void 0){let o=await et(i),d=await X(Lt(o),o,uy).catch(()=>{}),l=(d?.kind==="read"?JSON.parse(new TextDecoder().decode(d.bytes)):void 0)?.bin,u=typeof l=="string"?l:typeof l=="object"&&l!==null?l[e]:void 0;if(typeof u!="string")throw new Error("Package declares no CLI entry.");let p=await et(ml(Lt(o),u));return{manifestPath:o,entryPath:p}}let a=Lt(r);if(a===r)throw new Error("Package is not installed.");r=a}}async function HP(t,n){let e=OP(t),r=ay[n].bin,i;try{i=await et(e.resolve(`${n}/package.json`))}catch(a){if(r===void 0)throw a;return oy(t,n,r)}let s;for(let a of ay[n].entryRequests)try{s=await et(e.resolve(a));break}catch{}if(s===void 0){if(r!==void 0)return oy(t,n,r);throw new Error("Package CLI entry could not be resolved.")}return{manifestPath:i,entryPath:s}}async function yl(t,n){let e=await et(n),r=await X(t,e,16*1024*1024);if(r.kind!=="read")throw new Error("PnP loader is not an authorized repository-local regular file.");return{path:e,relativePath:r.relativePath,sha256:r.sha256}}async function zP(t,n,e,r){let i=$P(new URL("./pnp-resolver.mjs",import.meta.url)),{stdout:s}=await LP(process.execPath,[i,t,n.path,n.sha256,e,r],{encoding:"utf8",maxBuffer:MP,timeout:1e4,windowsHide:!0,env:{PATH:process.env.PATH??""}}),a=JSON.parse(s);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error("PnP resolver output is malformed.");let o=a;if(typeof o.manifestPath!="string"||typeof o.entryPath!="string"||o.loaderSha256!==n.sha256)throw new Error("PnP resolver output is incomplete or has the wrong loader identity.");let d=await yl(t,n.path);if(d.path!==n.path||d.relativePath!==n.relativePath||d.sha256!==n.sha256)throw new Error("PnP loader identity changed during resolution.");return{manifestPath:await et(o.manifestPath),entryPath:await et(o.entryPath)}}async function VP(t){let n=await X(t.root,t.paths.manifestPath,t.maxManifestBytes),e=await X(t.root,t.paths.entryPath,16*1024*1024);if(n.kind!=="read"||e.kind!=="read")throw new Error("Resolved package files are not authorized repository-local regular files.");let r=jP(n.bytes,t.packageName),i=Lt(t.paths.manifestPath);if(!Cn(i,t.paths.entryPath))throw new Error("Package CLI entry escapes its package root.");let s=[],a=[];if(t.loader!==void 0){let o=await yl(t.root,t.loader.path);if(o.path!==t.loader.path||o.relativePath!==t.loader.relativePath||o.sha256!==t.loader.sha256)throw new Error("PnP loader identity changed before tool authorization completed.");a.push("--require",t.loader.path),s.push({kind:"pnp-loader",path:fl(t.workspace,t.loader.path),sha256:t.loader.sha256,detail:"Repository-local Yarn Plug'n'Play loader."})}return a.push(t.paths.entryPath),{packageName:t.packageName,packageVersion:r.version,packageRoot:i,packageManifest:t.paths.manifestPath,packageManifestSha256:n.sha256,entryPath:t.paths.entryPath,entrySha256:e.sha256,executable:process.execPath,nodeArguments:a,packageManagerLayout:t.layout,resolutionEvidence:[{kind:"package-root",path:i,detail:`Canonical repository-local ${t.packageName} package root.`},{kind:"package-manifest",path:fl(t.workspace,t.paths.manifestPath),sha256:n.sha256,detail:`${r.name}@${r.version}`},{kind:"package-entry",path:fl(t.workspace,t.paths.entryPath),sha256:e.sha256,detail:"JavaScript CLI entry executed directly through the current Node runtime."},...s]}}async function _i(t){try{let n=await et(t.workspaceRoot),e=t.repositoryRoot===void 0?n:await et(t.repositoryRoot);if(!Cn(e,n))return{kind:"unavailable",reasons:[Mi("entry-outside-workspace","The workspace is outside its containing repository.")]};let r=await FP(e,ml(n,t.ownerPath));if(r===void 0)return{kind:"unavailable",reasons:[Mi("ambiguous-package-root","No owning repository package was found.")]};let i=t.maxManifestBytes??uy;if(!Number.isInteger(i)||i<=0)return{kind:"unavailable",reasons:[Mi("budget-exceeded","Package manifest byte limit is invalid.")]};let s,a="node-modules",o;try{s=await HP(r,t.packageName)}catch{let c=await BP(e,r);if(c===void 0)throw new Error("No repository-local dependency resolution succeeded.");o=await yl(e,c),a="pnp",s=await zP(e,o,r,t.packageName)}return!Cn(e,s.manifestPath)||!Cn(e,s.entryPath)?{kind:"unavailable",reasons:[Mi("entry-outside-workspace","Resolved package files are outside the repository.")]}:{kind:"resolved",tool:await VP({root:e,workspace:n,packageName:t.packageName,paths:s,maxManifestBytes:i,layout:a,...o===void 0?{}:{loader:o}})}}catch{return{kind:"unavailable",reasons:[Mi("missing-dependency",`Repository-local ${t.packageName} could not be resolved safely. No installation or global fallback was attempted.`)]}}}function ji(t){if(t.tool.executable!==process.execPath||t.args.some(i=>i.includes("\0"))||t.workingDirectory.includes("\0")||!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0)throw new Error("Resolved validation command is invalid.");let n=[...t.tool.nodeArguments,...t.args],e=[...t.tool.resolutionEvidence,...t.extraEvidence??[]],r=L({packageManifestSha256:t.tool.packageManifestSha256,entrySha256:t.tool.entrySha256,resolutionEvidence:e,kind:t.kind,timing:t.timing,executable:t.tool.executable,args:n,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:t.artifactPolicy});if(!_P.test(r))throw new Error("Command identity could not be constructed.");return{commandId:`cmd_${r.slice(0,24)}`,kind:t.kind,timing:t.timing,required:!0,executable:t.tool.executable,args:n,workingDirectory:t.workingDirectory,environmentDelta:t.environmentDelta,timeoutMs:t.timeoutMs,purpose:t.purpose,logicalTestIds:t.logicalTestIds,projectIds:t.projectIds,artifactPolicy:t.artifactPolicy,resolutionEvidence:e}}function gl(t,n){return L({purpose:"kwikqa-validation-repository-fingerprint",evidence:t,targetHashes:n})}var qP=/^[a-f0-9]{64}$/,Fi=3,GP=/^rps_[a-f0-9]{24}$/,wl=UP(new URL("./parse-check.mjs",import.meta.url));function KP(t,n){switch(t.tool){case"biome":return n.biome;case"prettier":return n.prettier;case"typescript":return n.typescript;case"eslint":return n.eslint;case"kwikqa-babel":return}}function WP(t,n){return n==="unavailable"?void 0:`${t}-${n}`}var py={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function JP(t,n){let e=["test"];if(n==="focused"?e.push(`${t.originalTest.path}:${t.originalTest.line}`,`--repeat-each=${Fi}`):n==="affected"&&e.push(...t.discovery.testPaths),n!=="suite")for(let r of t.discovery.projectIds)r!==""&&e.push(`--project=${r}`);return t.originalTest.configPath!==void 0&&e.push(`--config=${t.originalTest.configPath}`),e.push("--reporter=json",`--output=${t.artifactRoot}`,"--trace=retain-on-failure","--retries=0"),e}function YP(t,n){let e=n.targets.map(r=>r.path);switch(t.tool){case"biome":return t.kind==="format"?["format",...e]:["lint",...e];case"prettier":return["--check",...e];case"typescript":return["--noEmit","--pretty","false",...t.configPath?["--project",t.configPath]:[]];case"eslint":return e;case"kwikqa-babel":return[]}}function Ba(t){return{code:"resolution-failed",message:t}}function bl(t){if(!Number.isInteger(t.timeoutMs)||t.timeoutMs<=0||t.originalTest.line<=0||t.originalTest.logicalTestId.trim().length===0||t.originalTest.projectId.trim().length===0)throw new Error("Validation preparation input is invalid.");let n=L(t.advisoryPlan),e=[...new Set(t.affectedLogicalTestIds??[])].sort(),r=[...t.discovery.reasons.map(y=>({code:y.code==="budget-exceeded"?"budget-exceeded":"resolution-failed",message:y.message,...y.path===void 0?{}:{path:y.path}}))],i=[],s=[],a=t.framework??"playwright",o=t.tools[a],d=WP(a,t.discovery.scope),c=a==="playwright"?void 0:t.frameworkRun,l=()=>c?.args??JP(t,t.discovery.scope),u=c?.evidence??[],p=c?.workingDirectory??t.workspaceRoot;if(t.discovery.status!=="resolved"||d===void 0||o===void 0||a!=="playwright"&&c===void 0)r.push(Ba(`Repository-local ${py[a]} validation could not be resolved.`));else{let y=[t.originalTest.logicalTestId,...(t.companionLogicalTestIds??[]).filter(x=>x!==t.originalTest.logicalTestId)],w=a!=="playwright"&&t.discovery.scope==="focused"?Fi:1;for(let x=1;x<=w;x+=1)i.push(ji({tool:o,kind:d,timing:"post-patch",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:`Run the approved risk-based ${py[a]} validation scope${w>1?` (run ${x} of ${w})`:""}.`,logicalTestIds:t.discovery.scope==="focused"?[...new Set(y)].sort():e,projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u}));if(t.discovery.scope!=="focused"){(e.length===0||!e.includes(t.originalTest.logicalTestId))&&r.push(Ba("Shared validation scope lacks complete canonical affected-test identities."));let x=ji({tool:o,kind:d,timing:"baseline",args:l(),workingDirectory:p,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:"Capture required affected-test outcomes before shared-source mutation.",logicalTestIds:e,projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:`${t.artifactRoot}-baseline`,...a==="playwright"?{reportFile:"report.json"}:{},maxArtifacts:100,maxArtifactBytes:32*1024*1024},extraEvidence:u});i.push(x);let v=`baseline_${L({commandId:x.commandId}).slice(0,24)}`;s.push({baselineId:v,commandId:x.commandId,logicalTestIds:e,reason:"Shared test support requires a pre-patch affected-test baseline."})}else t.originalTest.environmentEquivalent||r.push(Ba("Original failure evidence is not environment-equivalent to validation."))}for(let y of t.discovery.staticChecks){if(y.tool==="kwikqa-babel"){let x=L({purpose:"kwikqa-parse-check-command",executable:process.execPath,shim:wl,paths:t.proposal.targets.map(v=>v.path),workingDirectory:t.workspaceRoot});i.push({commandId:`cmd_${x.slice(0,24)}`,kind:"parse",timing:"post-patch",required:!0,executable:process.execPath,args:[wl,...t.proposal.targets.map(v=>v.path)],workingDirectory:t.workspaceRoot,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:"Parse every changed JavaScript or TypeScript source file.",logicalTestIds:[],projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,maxArtifacts:1,maxArtifactBytes:1e6},resolutionEvidence:[{kind:"configuration",path:wl,detail:"KwikQA-owned Babel parse-only validation shim."}]});continue}let w=KP(y,t.tools);if(w===void 0){r.push(Ba(`Required ${y.tool} check could not be resolved locally.`));continue}i.push(ji({tool:w,kind:y.kind,timing:"post-patch",args:YP(y,t.proposal),workingDirectory:t.workspaceRoot,environmentDelta:{},timeoutMs:t.timeoutMs,purpose:`Run required ${y.kind} validation.`,logicalTestIds:[],projectIds:t.discovery.projectIds,artifactPolicy:{outputDirectory:t.artifactRoot,maxArtifacts:10,maxArtifactBytes:8*1024*1024}}))}let f=i.flatMap(y=>y.resolutionEvidence),h=t.proposal.targets.map(y=>({path:y.path,sourceSha256:y.sourceSha256,resultSha256:y.resultSha256})),m={schemaVersion:Us,policyVersion:Gs,status:r.length===0?"resolved":"unavailable",proposalHash:t.proposal.proposalHash,targetLogicalTestIds:[t.originalTest.logicalTestId],targetHashes:h,advisoryPlanHash:n,repositoryFingerprint:gl(f,h),commands:[...i].sort((y,w)=>y.commandId.localeCompare(w.commandId)),baselineRequirements:[...s].sort((y,w)=>y.baselineId.localeCompare(w.baselineId)),unresolvedReasons:r},g={...m,planHash:Ws(m)};return{plan:g,requiredBaselineCommands:g.commands.filter(y=>y.timing==="baseline")}}function xl(t){if(t.plan.status!=="resolved"||!qP.test(t.plan.planHash)||!GP.test(t.repairSessionId)||t.attemptOrdinal!==1&&t.attemptOrdinal!==2)throw new Error("Only a resolved plan can become application execution authority.");let n=t.plan.baselineRequirements.map(i=>i.baselineId),e;if(n.length>0){if(t.baseline===void 0)throw new Error("Required pre-application baseline is missing.");e=li(t.baseline);let i=new Map(t.plan.baselineRequirements.map(s=>[s.commandId,s]));if(e.planHash!==t.plan.planHash||e.repositoryFingerprint!==t.plan.repositoryFingerprint||L(e.targetHashes)!==L(t.plan.targetHashes)||e.commandRecords.length!==i.size||e.commandRecords.some(s=>{let a=i.get(s.commandId);return a===void 0||s.planHash!==t.plan.planHash||s.timing!=="baseline"||s.status!=="passed"||s.termination.kind!=="exit"||s.termination.exitCode!==0||s.stdout.truncated||s.stderr.truncated||a.logicalTestIds.some(o=>e?.logicalTestOutcomes[o]===void 0)}))throw new Error("Required pre-application baseline does not match the resolved plan.")}let r=t.plan.commands.filter(i=>i.timing==="post-patch"&&i.required).sort((i,s)=>i.commandId.localeCompare(s.commandId));return{schemaVersion:"1.0",policyVersion:"1.0",planHash:t.plan.planHash,repositoryFingerprint:t.plan.repositoryFingerprint,targetHashes:t.plan.targetHashes,advisoryPlanHash:L(t.advisoryPlan),...e===void 0?{}:{baselineManifestHash:e.baselineHash},requiredBaselineIds:n,requiredCommandIds:r.map(i=>i.commandId),requiredCommands:r.map(i=>({commandId:i.commandId,commandHash:L(i)})),repairSessionId:t.repairSessionId,attemptOrdinal:t.attemptOrdinal}}import{randomUUID as xS}from"node:crypto";import{lstat as Vi,mkdir as Cl,readFile as vS,realpath as kS,rm as RS}from"node:fs/promises";import{isAbsolute as IS,join as kr,relative as AS,resolve as TS,sep as PS}from"node:path";import{realpath as xr}from"node:fs/promises";import{realpath as br}from"node:fs/promises";var Ke=/^[a-f0-9]{64}$/,XP=/^rps_[a-f0-9]{24}$/,QP=/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+$/,ZP=new Set(["github-actions","azure-pipelines","gitlab-ci"]),eS=/^[a-f0-9]{40}$/;function fy(t){let n=t.map(e=>e.trim());return n.every(e=>e.length>0)&&new Set(n).size===t.length}function tS(t){return{kind:"rejected",reasons:t}}function yy(t){return t.length>0&&Number.isFinite(Date.parse(t))}function Ha(t){return Number.isFinite(t)&&t>0}function nS(t){return t.kind==="interactive"?t.sessionId.trim().length>0:t.kind==="ci-policy"&&ZP.has(t.system)&&QP.test(t.repository)&&/^\d+$/.test(t.runId)&&Number.isSafeInteger(t.runAttempt)&&t.runAttempt>0&&eS.test(t.commit)&&Ke.test(t.policyHash)}function rS(t){let{proposalHash:n,...e}=t;return Ke.test(n)&&L(e)===n}function iS(t){let n=[];(!rS(t)||L(t.diff)!==t.diffHash)&&n.push({code:"invalid-proposal",message:"Proposal and diff integrity hashes must match their canonical contents."}),(t.targets.length===0||t.changedFiles!==t.targets.length||t.targets.some(i=>!Ke.test(i.sourceSha256)||!Ke.test(i.resultSha256)||i.sourceSha256===i.resultSha256))&&n.push({code:"invalid-proposal",message:"Proposal targets and their source/result hashes must be complete and consistent."});let e=new Set,r=new Map;for(let i of t.targets){let s=i.path.toLocaleLowerCase("en-US"),a=r.get(s);(e.has(i.path)||a!==void 0&&a!==i.path)&&n.push({code:"invalid-proposal",message:"Proposal targets may not duplicate or case-collide.",path:i.path}),e.add(i.path),r.set(s,i.path)}return(t.replacements.length===0||t.replacements.some(i=>!e.has(i.path)))&&n.push({code:"invalid-proposal",message:"Every approved replacement must resolve to an approved proposal target."}),n}function sS(t){let n=iS(t.proposal);(t.context.workspace.workspaceRoot.length===0||t.context.workspace.gitRoot.length===0||t.context.snapshot.workspaceRoot!==t.context.workspace.workspaceRoot||t.context.snapshot.gitRoot!==t.context.workspace.gitRoot)&&n.push({code:"invalid-workspace",message:"Confirmed workspace and git roots must match the repository snapshot identity."}),(!Number.isInteger(t.context.maxTargetBytes)||t.context.maxTargetBytes<=0||t.context.config.schemaVersion.length===0)&&n.push({code:"invalid-configuration",message:"Application configuration and target byte limit must be explicit and bounded."}),(!nS(t.approver)||!yy(t.previewedAt))&&n.push({code:"invalid-preview",message:"An approver, an interactive session or a CI run under a committed policy, and a valid preview timestamp are required."});let e=t.costBounds;(!Number.isInteger(e.maxRequestTokens)||!Number.isInteger(e.maxRunTokens)||!Ha(e.maxRequestTokens)||!Ha(e.maxRunTokens)||!Ha(e.maxRequestDollars)||!Ha(e.maxRunDollars)||e.maxRequestTokens>e.maxRunTokens||e.maxRequestDollars>e.maxRunDollars)&&n.push({code:"invalid-preview",message:"Approved request and run token/dollar bounds must be positive and internally consistent."});let r=new Set;for(let s of t.payloadManifests){if(!Ke.test(s.manifestHash)||!Ke.test(s.payloadHash)||!Ke.test(s.packetHash)||s.model.trim().length===0||s.provider.trim().length===0||s.promptVersion.trim().length===0||s.outputSchemaVersion.trim().length===0||r.has(s.manifestHash)){n.push({code:"invalid-preview",message:"Model payload manifest references must be sanitized, complete, and unique."});break}r.add(s.manifestHash)}(t.scopes.baseline.some(s=>s.trim().length===0)||t.scopes.validation.some(s=>s.trim().length===0))&&n.push({code:"invalid-preview",message:"Baseline and validation scopes may not contain empty entries."});let i=t.authoritativeValidation;return(i.schemaVersion!=="1.0"||i.policyVersion!=="1.0"||!Ke.test(i.planHash)||!Ke.test(i.repositoryFingerprint)||!Ke.test(i.advisoryPlanHash)||i.targetHashes.length!==t.proposal.targets.length||i.targetHashes.some((s,a)=>{let o=t.proposal.targets[a];return o===void 0||s.path!==o.path||s.sourceSha256!==o.sourceSha256||s.resultSha256!==o.resultSha256})||i.baselineManifestHash!==void 0&&!Ke.test(i.baselineManifestHash)||!XP.test(i.repairSessionId)||i.attemptOrdinal!==1&&i.attemptOrdinal!==2||!fy(i.requiredBaselineIds)||!fy(i.requiredCommandIds)||i.requiredCommandIds.length===0||i.requiredCommands.length!==i.requiredCommandIds.length||i.requiredCommands.some((s,a)=>s.commandId!==i.requiredCommandIds[a]||!Ke.test(s.commandHash))||i.requiredBaselineIds.length>0&&i.baselineManifestHash===void 0)&&n.push({code:"invalid-preview",message:"Authoritative validation approval metadata is incomplete or inconsistent."}),n}function vl(t){return L({purpose:"kwikqa-approved-application",...t})}function kl(t){let n=sS(t);if(n.length>0)return tS(n);let e={schemaVersion:"3.0",bindingVersion:"3.0",proposal:t.proposal,workspace:t.context.workspace,checkoutPristine:t.context.snapshot.dirtyPaths.length===0,validationPlan:t.proposal.validationPlan,scopes:t.scopes,authoritativeValidation:t.authoritativeValidation,payloadManifests:t.payloadManifests,costBounds:t.costBounds,previewedAt:t.previewedAt,approver:t.approver};return{kind:"preview-ready",preview:{...e,bindingHash:vl(e)}}}function za(t,n,e,r){return L({purpose:"kwikqa-application-authorization",previewBindingHash:t.bindingHash,authorizationId:n,authorizedAt:e,approver:r})}function Rl(t,n){let{bindingHash:e,...r}=t;return Ke.test(e)&&vl(r)===e&&n.authorizationId.trim().length>0&&yy(n.authorizedAt)&&n.bindingHash===za(t,n.authorizationId,n.authorizedAt,n.approver)&&L(n.approver)===L(t.approver)}import{realpath as Va}from"node:fs/promises";import{isAbsolute as uS,relative as pS,sep as fS}from"node:path";import{createHash as aS}from"node:crypto";function oS(t){return aS("sha256").update(t,"utf8").digest("hex")}function Il(t,n,e){let r=[],i=[];for(let o of e){if(o.oldText.length===0||o.newText===o.oldText||o.rationale.trim().length===0||o.expectedEffect.trim().length===0||o.evidenceIds.length===0){r.push({code:"invalid-replacement",message:"Replacement fields must be meaningful, cited, and non-no-op.",path:t});continue}if(o.oldText===n){r.push({code:"invalid-replacement",message:"A replacement may not rewrite the complete file.",path:t});continue}let d=n.indexOf(o.oldText);if(d<0||n.indexOf(o.oldText,d+1)>=0){r.push({code:"non-unique-match",message:"Replacement preimage must occur exactly once.",path:t});continue}i.push({start:d,end:d+o.oldText.length,newText:o.newText})}let s=[...i].sort((o,d)=>o.start-d.start);for(let o=1;o<s.length;o+=1){let d=s[o-1],c=s[o];d!==void 0&&c!==void 0&&c.start<d.end&&r.push({code:"overlapping-replacement",message:"Exact replacements overlap in the original source.",path:t})}if(r.length>0)return{kind:"rejected",reasons:r};let a=n;for(let o of[...s].sort((d,c)=>c.start-d.start))a=`${a.slice(0,o.start)}${o.newText}${a.slice(o.end)}`;return{kind:"applied",result:a,resultSha256:oS(a)}}function gy(t){let n=[],e=[];for(let r of t){let i=Il(r.path,r.source,r.replacements);if(i.kind==="rejected"){n.push(...i.reasons);continue}e.push({...r,result:i.result,resultSha256:i.resultSha256})}return n.length>0?{kind:"rejected",reasons:n}:{kind:"applied",targets:e}}import{isAbsolute as dS}from"node:path";function cS(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function wy(t,n){let e=cS(t).replaceAll("**/","\0").replaceAll("**","").replaceAll("*","[^/]*").replaceAll("\0","(?:.*/)?").replaceAll("",".*");return new RegExp(`^${e}$`).test(n)}function Bi(t){return t.length===0||t.includes("\0")||t.includes("\\")||dS(t)||/^[A-Za-z]:/.test(t)?!0:t.split("/").some(n=>n===""||n==="."||n==="..")}function Hi(t,n){let e=t.toLowerCase(),r=e.split("/").at(-1)??e;return e.includes("/node_modules/")||e.startsWith("node_modules/")||e.includes("/src/")||e.startsWith("src/")||new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"]).has(r)?!0:n.generatedPaths.some(i=>wy(i,t))}function zi(t,n){return n.find(e=>wy(e.pattern,t))}function lS(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}async function by(t,n,e,r){let i=[],s=new Map;for(let l of e){if(Bi(l.path)){i.push({code:"unauthorized-target",message:"Target path is not a safe repository-relative path.",path:l.path});continue}let u=s.get(l.path)??[];u.push(l),s.set(l.path,u)}if(i.length>0)return{kind:"rejected",reasons:i};let a=new Set(n.dirtyPaths.map(l=>l.replaceAll("\\","/").toLocaleLowerCase("en-US"))),o=new Set,d=new Map,c=[];for(let[l,u]of[...s].sort(([p],[f])=>p.localeCompare(f))){let p=zi(l,t.editablePaths);if(p===void 0||Hi(l,t)){i.push({code:"unauthorized-target",message:"Target is outside the configured test-support repair boundary.",path:l});continue}if(a.has(l.toLocaleLowerCase("en-US"))){i.push({code:"dirty-target-file",message:"Already-dirty target files are read-only.",path:l});continue}let f=await X(n.workspaceRoot,l,r);if(f.kind!=="read"){i.push({code:f.kind==="unauthorized"?"unauthorized-target":"unreadable-target",message:f.message,...f.relativePath===void 0?{path:l}:{path:f.relativePath}});continue}if(f.relativePath!==l){i.push({code:"unauthorized-target",message:"Target path does not match its canonical repository-relative path.",path:l});continue}let h=f.relativePath.toLocaleLowerCase("en-US"),m=d.get(h);if(o.has(f.relativePath)||m!==void 0&&m!==f.relativePath){i.push({code:"unauthorized-target",message:"Target aliases or case-collides with another target.",path:l});continue}o.add(f.relativePath),d.set(h,f.relativePath);let g=lS(f.bytes);if(g===void 0){i.push({code:"unreadable-target",message:"Target is not valid UTF-8.",path:l});continue}if(u.some(y=>y.sourceSha256!==void 0&&y.sourceSha256!==f.sha256)){i.push({code:"source-hash-mismatch",message:"Target source hash differs from the proposed preimage.",path:l});continue}c.push({path:f.relativePath,class:p.class,source:g,sourceSha256:f.sha256,replacements:u})}return i.length>0?{kind:"rejected",reasons:i}:{kind:"authorized",targets:c}}function hS(t,n){let e=pS(t,n);return e===""||!uS(e)&&e!==".."&&!e.startsWith(`..${fS}`)}function mS(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}async function xy(t){if(!Number.isInteger(t.maxTargetBytes)||t.maxTargetBytes<=0||t.maxTargetBytes>1e6)return{kind:"rejected",code:"invalid-limit",message:"Target limit is invalid."};let n,e,r,i;try{[n,e,r,i]=await Promise.all([Va(t.workspaceRoot),Va(t.gitRoot),Va(t.approvedWorkspaceRoot),Va(t.approvedGitRoot)])}catch{return{kind:"rejected",code:"workspace-mismatch",message:"Workspace roots are unreadable."}}if(n!==r||e!==i||!hS(e,n))return{kind:"rejected",code:"workspace-mismatch",message:"Current and approved canonical workspace identities differ."};let s=new Set(t.dirtyPaths.map(c=>c.replaceAll("\\","/").toLocaleLowerCase("en-US"))),a=new Map;for(let c of t.proposal.replacements){let l=a.get(c.path)??[];l.push(c),a.set(c.path,l)}let o=new Set,d=[];for(let c of t.proposal.targets){let l=c.path.toLocaleLowerCase("en-US");if(o.has(l)||Bi(c.path))return{kind:"rejected",code:"unsafe-target",message:"Target aliases, case-collides, or has an unsafe path.",path:c.path};o.add(l);let u=zi(c.path,t.config.editablePaths);if(u===void 0||u.class!==c.class||Hi(c.path,t.config))return{kind:"rejected",code:"unauthorized-target",message:"Target is outside the approved repair boundary.",path:c.path};if(s.has(l))return{kind:"rejected",code:"dirty-target-file",message:"An approved target is currently dirty.",path:c.path};let p=await X(n,c.path,t.maxTargetBytes);if(p.kind!=="read"||p.relativePath!==c.path)return{kind:"rejected",code:"unreadable-target",message:"Target could not be read through its canonical authorized path.",path:c.path};if(p.sha256!==c.sourceSha256)return{kind:"rejected",code:"source-hash-mismatch",message:"Target no longer matches the approved preimage.",path:c.path};let f=mS(p.bytes);if(f===void 0)return{kind:"rejected",code:"unreadable-target",message:"Target is not valid UTF-8.",path:c.path};let h=a.get(c.path)??[],m=Il(c.path,f,h);if(m.kind!=="applied"||m.resultSha256!==c.resultSha256)return{kind:"rejected",code:"result-hash-mismatch",message:"Approved replacements no longer derive the approved result.",path:c.path};d.push({path:c.path,source:f,sourceBytes:p.bytes,sourceSha256:p.sha256,result:m.result,resultBytes:new TextEncoder().encode(m.result),resultSha256:m.resultSha256,replacements:h})}return{kind:"verified",workspaceRoot:n,gitRoot:e,targets:d,nonPristine:t.dirtyPaths.length>0}}var yS=new Set(["completed","rolled-back","conflicted"]);function Nn(t,n,e){return{code:t,message:n,...e===void 0?{}:{path:e}}}function Te(t){return{schemaVersion:"2.0",transactionId:t.manifest.transactionId,authorizationId:t.manifest.authorization.authorizationId,approvalBindingHash:t.manifest.preview.bindingHash,proposalHash:t.manifest.preview.proposal.proposalHash,diffHash:t.manifest.preview.proposal.diffHash,workspace:t.manifest.preview.workspace,phase:t.state.phase,revision:t.state.revision,targets:t.manifest.targets.map(n=>({path:n.path,sourceSha256:n.sourceSha256,resultSha256:n.resultSha256,preimageBytes:n.preimageBytes,resultBytes:n.resultBytes})),validationPlan:t.manifest.preview.validationPlan,authoritativeValidation:t.manifest.preview.authoritativeValidation,createdAt:t.manifest.createdAt,updatedAt:t.state.updatedAt}}async function gS(t){return(await Promise.all((await Si(t)).map(e=>Re(t,e)))).filter(e=>!yS.has(e.state.phase))}async function vy(t,n,e,r){let i=await X(t,n,e);return i.kind==="read"&&i.relativePath===n&&i.sha256===r}async function Al(t){return wS(t,{})}async function wS(t,n){if(!Rl(t.preview,t.authorization))return{kind:"rejected",reasons:[Nn("authorization-mismatch","Authorization does not match this exact preview.")]};let e=t.now??new Date().toISOString(),r;try{let[i,s,a,o,d,c]=await Promise.all([br(t.context.workspace.workspaceRoot),br(t.context.snapshot.workspaceRoot),br(t.preview.workspace.workspaceRoot),br(t.context.workspace.gitRoot),br(t.context.snapshot.gitRoot),br(t.preview.workspace.gitRoot)]);if(i!==s||i!==a||o!==d||o!==c)return{kind:"rejected",reasons:[Nn("invalid-workspace","Application workspace identity changed.")]};let l=a;r=await Je(l,{operation:"apply",authorizationId:t.authorization.authorizationId,at:e});let u=await gS(l);if(u.length>0)return{kind:"recovery-required",reasons:[Nn("transaction-blocked","A nonterminal transaction must be recovered before another application.")],transaction:Te(u[0])};if((await Promise.all((await Si(l)).map(g=>Re(l,g)))).some(g=>g.manifest.authorization.authorizationId===t.authorization.authorizationId))return{kind:"rejected",reasons:[Nn("authorization-replayed","Authorization has already been consumed.")]};let f=await xy({workspaceRoot:t.context.snapshot.workspaceRoot,gitRoot:t.context.snapshot.gitRoot,approvedWorkspaceRoot:t.preview.workspace.workspaceRoot,approvedGitRoot:t.preview.workspace.gitRoot,config:t.context.config,dirtyPaths:t.context.snapshot.dirtyPaths,proposal:t.preview.proposal,maxTargetBytes:t.context.maxTargetBytes});if(f.kind!=="verified")return{kind:"rejected",reasons:[Nn(f.code==="dirty-target-file"?"dirty-target-file":f.code==="source-hash-mismatch"?"source-hash-mismatch":f.code==="result-hash-mismatch"?"result-hash-mismatch":"unsafe-target",f.message,f.path)]};let h=Ah(),m=await $h({workspaceRoot:f.workspaceRoot,transactionId:h,preview:t.preview,authorization:t.authorization,config:t.context.config,maxTargetBytes:t.context.maxTargetBytes,targets:f.targets,now:e});await n.failpoint?.("journal-prepared"),m=await Ge({transaction:m,phase:"applying",type:"application-started",now:e}),await n.failpoint?.("phase-applying");for(let g of m.manifest.targets){if(!await vy(f.workspaceRoot,g.path,t.context.maxTargetBytes,g.sourceSha256))return{kind:"recovery-required",reasons:[Nn("source-hash-mismatch","Target changed immediately before mutation.",g.path)],transaction:Te(m)};m=await Ge({transaction:m,phase:"applying",type:"target-write-intent",path:g.path,now:e}),await n.failpoint?.(`before-target:${g.path}`);let w=m.results.get(g.path);if(w===void 0)throw new Error("Journal result bytes are unavailable.");if(await la(f.workspaceRoot,g.path,g.sourceSha256,w),await n.failpoint?.(`after-target:${g.path}`),!await vy(f.workspaceRoot,g.path,t.context.maxTargetBytes,g.resultSha256))throw new Error("Applied target hash could not be verified.");m=await Ge({transaction:m,phase:"applying",type:"target-write-complete",path:g.path,now:e})}return m=await Ge({transaction:m,phase:"applied",type:"application-complete",now:e}),await n.failpoint?.("phase-applied"),{kind:"applied",transaction:Te(m)}}catch{return{kind:"failed",reasons:[Nn("application-failed","Application stopped safely; inspect transaction discovery before continuing.")]}}finally{await r?.release().catch(()=>{})}}var Ry=new Set(["completed","rolled-back","conflicted"]);function en(t,n){return{code:"transaction-conflict",message:t,...n===void 0?{}:{path:n}}}async function Pl(t,n){let e=t.manifest.targets.find(i=>i.path===n);if(e===void 0)return"conflict";let r=await X(t.manifest.preview.workspace.workspaceRoot,n,t.manifest.maxTargetBytes);return r.kind!=="read"||r.relativePath!==n?"conflict":r.sha256===e.sourceSha256?"preimage":r.sha256===e.resultSha256?"applied":"conflict"}async function Ua(t,n){let e=await Re(t,n),r=await Promise.all(e.manifest.targets.map(async i=>({path:i.path,classification:await Pl(e,i.path)})));return{transactionId:n,phase:e.state.phase,targets:r}}async function Sl(t){try{let n=await Promise.all((await Si(t)).map(r=>Ua(t,r))),e=n.filter(r=>!Ry.has(r.phase));return e.some(r=>r.targets.some(i=>i.classification==="conflict"))?{kind:"conflicted",transactions:e}:e.length===0?{kind:"clear",transactions:n}:{kind:"recovery-required",transactions:e}}catch{return{kind:"failed",reasons:[en("Transaction discovery failed closed because a journal is unreadable.")]}}}async function Tl(t,n,e){return t.state.phase==="conflicted"?t:Ge({transaction:t,phase:"conflicted",type:"conflict-detected",message:e,now:n})}async function ky(t){let n=await Promise.all(t.manifest.targets.map(async e=>[e.path,await Pl(t,e.path)]));return new Map(n)}async function bS(t,n,e,r,i){let s;try{let[a,o,d,c]=await Promise.all([xr(t.workspace.workspaceRoot),xr(t.snapshot.workspaceRoot),xr(t.workspace.gitRoot),xr(t.snapshot.gitRoot)]);if(a!==o||d!==c)return{kind:"rejected",reasons:[en("Recovery workspace identity differs.")]};s=await Je(a,{operation:e,transactionId:n,at:r});let l=await Re(a,n);if(await xr(l.manifest.preview.workspace.workspaceRoot)!==a||await xr(l.manifest.preview.workspace.gitRoot)!==d)return{kind:"rejected",reasons:[en("Recovery workspace identity differs.")]};if(Ry.has(l.state.phase))return e==="rollback"&&l.state.phase==="rolled-back"?{kind:"rolled-back",transaction:Te(l)}:{kind:"rejected",reasons:[en("Terminal transaction cannot perform this recovery operation.")],transaction:Te(l)};let u=await ky(l),p=[...u].find(([,m])=>m==="conflict");if(p!==void 0)return l=await Tl(l,r,"Current target bytes match neither recorded preimage nor applied image."),{kind:"conflicted",reasons:[en("Developer or unknown target bytes prohibit automatic recovery.",p[0])],transaction:Te(l)};e==="rollback"&&(l=await Ge({transaction:l,phase:"rolling-back",type:"rollback-started",now:r}),await i?.("phase-rolling-back"));for(let m of l.manifest.targets){let g=u.get(m.path);if(!(e==="resume"&&g==="preimage"||e==="rollback"&&g==="applied"))continue;let w=e==="resume"?"resume":"rollback";if(await i?.(`before-${w}-target:${m.path}`),await Pl(l,m.path)!==g)return l=await Tl(l,r,"Target changed after recovery classification."),{kind:"conflicted",reasons:[en("Target changed immediately before recovery mutation.",m.path)],transaction:Te(l)};let v=e==="resume"?l.results.get(m.path):l.preimages.get(m.path);if(v===void 0)throw new Error("Recovery bytes are unavailable.");await la(a,m.path,e==="resume"?m.sourceSha256:m.resultSha256,v),await i?.(`after-${w}-target:${m.path}`),l=await Ge({transaction:l,phase:e==="resume"?"applying":"rolling-back",type:`${e}-target-complete`,path:m.path,now:r})}let f=await ky(l),h=e==="resume"?"applied":"preimage";return[...f.values()].some(m=>m!==h)?(l=await Tl(l,r,"Recovery result hashes did not verify."),{kind:"conflicted",reasons:[en("Recovery completed with an unknown target state.")],transaction:Te(l)}):(l=await Ge({transaction:l,phase:e==="resume"?"applied":"rolled-back",type:e==="resume"?"resume-complete":"rollback-complete",now:r}),{kind:e==="resume"?"resumed":"rolled-back",transaction:Te(l)})}catch{return{kind:"failed",reasons:[en("Recovery stopped safely; rediscover transaction state.")]}}finally{await s?.release().catch(()=>{})}}async function El(t,n,e=new Date().toISOString()){return bS(t,n,"rollback",e)}var Iy=/^rps_[a-f0-9]{24}$/,qa=/^[a-f0-9]{64}$/,SS=new Set(["rolling-back","rolled-back","conflicted"]);function ES(t,n){let e=AS(t,n);return e===""||!IS(e)&&e!==".."&&!e.startsWith(`..${PS}`)}function vr(t){return t.length>0&&Number.isFinite(Date.parse(t))}function Ay(t){if(t.ordinal!==1&&t.ordinal!==2||!qa.test(t.proposalHash)||!/^txn_[a-f0-9]{24}$/.test(t.transactionId)||t.validationManifestHash!==void 0&&!qa.test(t.validationManifestHash)||!vr(t.recordedAt))throw new Error("Repair attempt record is malformed.")}function CS(t){let{sessionHash:n,...e}=t;if(t.schemaVersion!=="1.0"||!Iy.test(t.repairSessionId)||t.originalRunId.trim().length===0||!qa.test(t.originalPacketHash)||t.maxAttempts!==2||!vr(t.createdAt)||!vr(t.updatedAt)||!Number.isInteger(t.revision)||t.revision<1||t.attempts.length>2||L(e)!==n)throw new Error("Repair session integrity check failed.");t.attempts.forEach(Ay);for(let[r,i]of t.attempts.entries())if(i.ordinal!==r+1)throw new Error("Repair attempt order is malformed.");return t}async function Ga(t){let n=await kS(t),e=TS(n,".kwikqa");if(!ES(n,e))throw new Error("Repair session directory escapes workspace.");await Cl(e,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let r=await Vi(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Repair session path is unsafe.");let i=kr(e,"repair-sessions");await Cl(i,{mode:448}).catch(a=>{if(a.code!=="EEXIST")throw a});let s=await Vi(i);if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Repair session path is unsafe.");return i}function Ka(t){return{...t,sessionHash:L(t)}}function Nl(t){return{schemaVersion:t.schemaVersion,repairSessionId:t.repairSessionId,originalRunId:t.originalRunId,originalPacketHash:t.originalPacketHash,maxAttempts:t.maxAttempts,attempts:t.attempts,state:t.state,createdAt:t.createdAt,updatedAt:t.updatedAt,revision:t.revision}}async function Ol(t){if(t.originalRunId.trim().length===0||!qa.test(t.originalPacketHash))throw new Error("Original repair evidence identity is invalid.");let n=t.now??new Date().toISOString();if(!vr(n))throw new Error("Repair session timestamp is invalid.");let e=`rps_${xS().replaceAll("-","").slice(0,24)}`,r=Ka({schemaVersion:"1.0",repairSessionId:e,originalRunId:t.originalRunId,originalPacketHash:t.originalPacketHash,maxAttempts:2,attempts:[],state:"first-attempt",createdAt:n,updatedAt:n,revision:1}),i=await Ga(t.workspaceRoot);return await ye(kr(i,`${e}.json`),`${ue(r)}
28
+ `,{mode:384,replace:!1}),r}async function tn(t,n){if(!Iy.test(n))throw new Error("Repair session id is invalid.");let e=await Ga(t),r=kr(e,`${n}.json`),i=await Vi(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Repair session record is unsafe.");let s=JSON.parse(await vS(r,"utf8"));if(s===null||typeof s!="object"||Array.isArray(s))throw new Error("Repair session record is malformed.");return CS(s)}async function $l(t,n){let e=await Ga(t),r=kr(e,`${n}.lock`);await Cl(r,{mode:448});let i=await Vi(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Repair session lock is unsafe.");return{release:async()=>{let s=await Vi(r);if(s.dev!==i.dev||s.ino!==i.ino||s.isSymbolicLink())throw new Error("Repair session lock ownership changed.");await RS(r,{recursive:!0,force:!1})}}}async function Dl(t,n,e){let r=await tn(t,n.repairSessionId);if(r.revision!==n.revision||r.sessionHash!==n.sessionHash)throw new Error("Repair session changed concurrently.");let i=await Ga(t);return await ye(kr(i,`${n.repairSessionId}.json`),`${ue(e)}
29
+ `,{mode:384,replace:!0}),tn(t,n.repairSessionId)}async function Ll(t,n,e){Ay(e);let r=await $l(t,n);try{let i=await tn(t,n);if(i.state==="repaired"||i.state==="stopped")throw new Error("Terminal repair session cannot accept another attempt.");if(e.ordinal!==i.attempts.length+1||e.ordinal>i.maxAttempts)throw new Error("Repair session attempt limit or ordering was violated.");if(e.ordinal===1&&i.state!=="first-attempt"||e.ordinal===2&&i.state!=="retry-approval-required")throw new Error("Repair session is not ready for this attempt.");let s=e.recordedAt,a=Ka({...Nl(i),attempts:[...i.attempts,e],state:e.ordinal===1?"first-attempt":"second-attempt",updatedAt:s,revision:i.revision+1});return await Dl(t,i,a)}finally{await r.release()}}function NS(t,n){let e=t.status;if(e==="blocked")throw new Error("A blocked validation run has no attempt outcome.");let r=n.state.history,i=r.findLastIndex(d=>d.type==="validation-started"),s=r[i];if(s===void 0||s.validationRunId!==t.validationRunId||s.planHash!==t.planHash)throw new Error("Validation run was not started for this transaction approval.");let a=r.slice(i+1).find(d=>d.type==="validation-passed"),o=n.state.phase;if(a!==void 0){if(o!=="completed"||e!=="passed"||a.validationRunId!==t.validationRunId||a.planHash!==t.planHash||a.validationManifestHash!==t.manifestHash)throw new Error("Validation outcome does not match the durable transaction state.");return"passed"}if(o==="validating"){if(e==="passed")throw new Error("A passing validation run must be completed by M6, or rolled back, before it is recorded.");return e}if(SS.has(o))return e==="passed"?"incomplete":e;throw new Error("Validation outcome does not match the durable transaction state.")}async function Wa(t){if(!/^vld_[a-f0-9]{24}$/.test(t.validationRunId))throw new Error("Validation run id is invalid.");let n=t.now??new Date().toISOString();if(!vr(n))throw new Error("Repair session timestamp is invalid.");let e=await $l(t.workspaceRoot,t.repairSessionId),r;try{r=await Je(t.workspaceRoot,{operation:"record-repair-validation",repairSessionId:t.repairSessionId,validationRunId:t.validationRunId});let i=await tn(t.workspaceRoot,t.repairSessionId),s=i.attempts.at(-1);if(s===void 0||s.ordinal!==t.ordinal)throw new Error("Repair attempt cannot be finalized from its current state.");let a=await Re(t.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation,d=kr(a.directory,"validation",t.validationRunId),c=Kt(await vn(d,"manifest.json",ba)),l=new Map(o.requiredCommands.map(m=>[m.commandId,m.commandHash]));if(c.transactionId!==s.transactionId||c.validationRunId!==t.validationRunId||c.planHash!==o.planHash||c.repositoryFingerprint!==o.repositoryFingerprint||L(c.targetHashes)!==L(o.targetHashes)||c.requiredCommandIds.length!==l.size||c.requiredCommandIds.some(m=>!l.has(m))||c.commandRecords.some(m=>l.get(m.commandId)!==m.commandHash)||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Validation manifest does not match the repair attempt authority.");for(let m of c.commandRecords)if(!await jh(d,m,ir))throw new Error("Validation manifest command evidence failed verification.");let u=NS(c,a);if(s.outcome!=="applied"){if(s.validationManifestHash===c.manifestHash&&s.outcome===u)return{session:i};throw new Error("Repair attempt was already finalized with different evidence.")}let p={...s,validationManifestHash:c.manifestHash,outcome:u,recordedAt:n},f=u==="passed"?"repaired":"rollback-required",h=Ka({...Nl(i),attempts:[...i.attempts.slice(0,-1),p],state:f,updatedAt:n,revision:i.revision+1});return{session:await Dl(t.workspaceRoot,i,h)}}finally{await r?.release(),await e.release()}}async function Ml(t){if(!/^txn_[a-f0-9]{24}$/.test(t.proof.transactionId)||t.proof.phase!=="rolled-back"||!Number.isInteger(t.proof.transactionRevision)||t.proof.transactionRevision<1)throw new Error("Repair rollback proof is invalid.");let n=t.now??new Date().toISOString();if(!vr(n))throw new Error("Repair session timestamp is invalid.");let e=await $l(t.workspaceRoot,t.repairSessionId),r;try{r=await Je(t.workspaceRoot,{operation:"confirm-repair-rollback",repairSessionId:t.repairSessionId,transactionId:t.proof.transactionId});let i=await tn(t.workspaceRoot,t.repairSessionId),s=i.attempts.at(-1);if(i.state!=="rollback-required"||s===void 0||s.ordinal!==t.ordinal||s.transactionId!==t.proof.transactionId||s.validationManifestHash===void 0||s.outcome==="passed"||s.outcome==="applied")throw new Error("Repair session does not match the rolled-back attempt.");let a=await Re(t.workspaceRoot,s.transactionId),o=a.manifest.preview.authoritativeValidation;if(a.state.phase!=="rolled-back"||a.state.revision!==t.proof.transactionRevision||o.repairSessionId!==i.repairSessionId||o.attemptOrdinal!==s.ordinal||a.manifest.preview.proposal.proposalHash!==s.proposalHash)throw new Error("Repair rollback proof does not match the durable transaction.");let d=await Ua(t.workspaceRoot,s.transactionId);if(d.phase!=="rolled-back"||d.targets.some(f=>f.classification!=="preimage"))throw new Error("Durable rollback could not be verified from recorded preimages.");let c=t.ordinal===1?"retry-approval-required":"stopped",l=Ka({...Nl(i),state:c,updatedAt:n,revision:i.revision+1}),u=await Dl(t.workspaceRoot,i,l);if(c!=="retry-approval-required")return{session:u};let p={repairSessionId:u.repairSessionId,failedTransactionId:s.transactionId,failedValidationManifestHash:s.validationManifestHash,nextAttemptOrdinal:2};return{session:u,retry:{...p,handoffHash:L(p)}}}finally{await r?.release(),await e.release()}}import{lstat as US,mkdir as qS,open as GS}from"node:fs/promises";import{dirname as $y,resolve as KS}from"node:path";import{createHash as OS}from"node:crypto";var Ja="kwikqa-report",Cy="1",Mt={"test-support":"Test code",application:"Application",environment:"Environment",undetermined:"Undetermined",inconclusive:"Inconclusive","not-diagnosed":"Not diagnosed"},$S=12,DS=800,Ty=`
30
30
  :root{color-scheme:light dark;--ink:#0B0F17;--paper:#F4F5F7;--text:#0B0F17;--bg:#FFFFFF;--panel:#F4F5F7;--line:#D9DDE5;--muted:#5B6578;--accent:#0E9F6E;--fail:#D9432F;--warn:#9A6700}
31
31
  @media (prefers-color-scheme:dark){:root{--text:#E8ECF4;--bg:#0B0F17;--panel:#131926;--line:#283044;--muted:#8A93A6;--accent:#34D399;--fail:#FF6B57;--warn:#E3B341}}
32
32
  *{box-sizing:border-box}
@@ -127,9 +127,9 @@ footer{margin-top:40px;padding-bottom:40px;color:var(--muted);font-size:13px;bor
127
127
  `))}function VS(t){if(t.requests.length===0)return On("sent","What was sent","<p>Nothing: no model request was made.</p>");let n=t.requests.map(e=>`<tr><td>${j(e.group)}</td><td>${j(e.purpose)}</td><td>${j(e.model)}${e.zeroDataRetention?", zero data retention":""}</td><td><code>${j(e.packetHash)}</code></td><td>${j(e.tokens??"")}</td><td>${j(e.outcome)}</td></tr>`).join("");return On("sent","What was sent",`<p>Each request carried only the redacted evidence of one group, as its preview showed.</p><table><thead><tr><th>For</th><th>Request</th><th>Model</th><th>Evidence packet</th><th>Tokens</th><th>Outcome</th></tr></thead><tbody>${n}</tbody></table>`)}function Ui(t){let n=["default-src 'none'",`style-src 'sha256-${Sy(Ty)}'`,`script-src 'sha256-${Sy(Py)}'`,"base-uri 'none'","form-action 'none'"].join("; "),e=t.flaky.length===0?"":On("flaky","Flaky tests",`<p>These tests failed and then passed. KwikQA reports them and doesn't repair them.</p>${_l(t.flaky)}`),r=t.notAnalyzed,i=r.unclassified.length===0&&r.runErrors.length===0?"":On("not-analyzed","Not analyzed",[r.runErrors.length===0?"":`<h4>Run-level errors</h4><ul>${r.runErrors.map(s=>`<li>${jl(s)}</li>`).join("")}</ul>`,r.unclassified.length===0?"":`<h4>Failures no rule could classify</h4>${_l(r.unclassified)}`].join(`
128
128
  `));return["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">','<meta name="viewport" content="width=device-width, initial-scale=1">',`<meta name="${Ja}" content="${Cy}">`,`<meta http-equiv="Content-Security-Policy" content="${n}">`,'<meta name="referrer" content="no-referrer">',`<title>${j(t.title)}</title>`,`<style>${Ty}</style>`,"</head>","<body>","<header>",'<p class="brand">KwikQA</p>',"<h1>Failure report</h1>",`<p class="lede">${j(t.title.replace(/^KwikQA report: /,""))}. ${j(t.run.diagnosedBy)}</p>`,"</header>","<main>",BS(t),FS(t.groups),`<section id="groups" aria-label="Failure group details">${t.groups.map(jS).join(`
129
129
  `)}</section>`,e,i,HS(t),zS(t),VS(t),"</main>",`<footer><p>Generated by KwikQA ${j(t.footer.kwikqaVersion)} from record <code>${j(t.footer.recordId)}</code> of run <code>${j(t.footer.runId)}</code>.</p><p>This page holds the same redacted evidence a request preview shows. Anyone who can open it can read it, so share it the way you share CI logs.</p></footer>`,`<script>${Py}</script>`,"</body>","</html>",""].join(`
130
- `)}var Ya="kwikqa-report.html",Dy=4096;async function WS(t){let n=await GS(t,"r");try{let e=Buffer.alloc(Dy),{bytesRead:r}=await n.read(e,0,Dy,0);return e.subarray(0,r).toString("utf8")}finally{await n.close()}}async function kr(t,n){let e=KS(t,n??Ya),r=await US(e).catch(i=>{if(i.code!=="ENOENT")throw i});return r===void 0?{kind:"writable",path:e}:r.isFile()?(await WS(e)).includes(`<meta name="${Ja}"`)?{kind:"writable",path:e}:{kind:"refused",path:e,message:`${e} exists and isn't a KwikQA report, so KwikQA won't replace it. Choose another path with --output.`}:{kind:"refused",path:e,message:`${e} exists and isn't a regular file, so KwikQA won't write a report there.`}}async function Fl(t,n){let e=await kr($y(t),t);return e.kind==="refused"||(await qS($y(t),{recursive:!0}),await ye(t,n,{mode:420,replace:!0})),e}import{basename as ZC}from"node:path";function Xa(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(Xa).join(",")}]`:`{${Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${Xa(r)}`).join(",")}}`}function we(t,n,e,r,i){return B("evd",[t,n,e,Xa(r),i])}function Ie(t,n,e){return B("art",["m2",t,n,e])}function Rr(t){return Ne(Buffer.from(Xa(t),"utf8"))}var Bl={policyVersion:"development-1",workspaceRoot:".",maxPacketBytes:256e3,maxArtifactBytes:16e6,maxTraceEntries:2e3,maxTraceEvents:2e3,maxReportFields:2e3,maxStackFrames:2e3,maxSteps:2e3,maxStdioChunks:2e3,maxStdioBytes:64e6,maxTraceExpandedBytes:64e6,maxConsoleEvents:100,maxNetworkEvents:200,includeNetworkBodies:!1,maxNetworkBodyBytes:0,maxDomDepth:6,maxDomNodes:200,maxDomTextBytes:16e3,maxSourceFiles:12,maxSourceBytes:128e3,maxSourceLinesPerFile:200,maxImportDepth:2,maxDiffBytes:128e3,maxDiffHunks:30,sensitiveNames:["authorization","cookie","set-cookie","password","passwd","secret","token","api-key","apikey"]},JS=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function Hl(t){if(t===null||typeof t!="object")return"policy must be an object";if(typeof t.policyVersion!="string")return"policyVersion must be a string";if(t.policyVersion.length===0)return"policyVersion must not be empty";if(typeof t.workspaceRoot!="string")return"workspaceRoot must be a string";if(t.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof t.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(t.sensitiveNames)||t.sensitiveNames.some(n=>typeof n!="string"||n.length===0))return"sensitiveNames must be an array of non-empty strings";if(t.sensitiveNames.some(n=>n.trim()!==n))return"sensitiveNames must not contain surrounding whitespace";for(let n of JS){let e=t[n];if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)return`${n} must be a positive safe integer`}if(!Number.isSafeInteger(t.maxNetworkBodyBytes)||t.maxNetworkBodyBytes<0||t.includeNetworkBodies&&t.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var YS={button:"button",nav:"navigation",main:"main",header:"banner",footer:"contentinfo",form:"form",table:"table",img:"img",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",ul:"list",ol:"list",li:"listitem",section:"region",article:"article",dialog:"dialog",select:"combobox",textarea:"textbox"},XS={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},QS=new Set(["script","style","head","title","meta","link"]);function Ue(t){let n=t[0];return typeof n=="string"?n.toLowerCase():void 0}function je(t){let n=t[1];if(typeof n!="object"||n===null||Array.isArray(n))return{};let e={};for(let[r,i]of Object.entries(n))typeof i=="string"&&(e[r.toLowerCase()]=i);return e}function Fe(t){let n=typeof t[1]=="object"&&t[1]!==null&&!Array.isArray(t[1]);return t.slice(n?2:1)}function _t(t,n=0){let e=Ue(t);if(e===void 0||QS.has(e)||n>12)return"";let r=[];for(let i of Fe(t))typeof i=="string"?r.push(i):Array.isArray(i)&&r.push(_t(i,n+1));return r.join(" ").replace(/\s+/g," ").trim()}function $n(t){let n=je(t),e=n.role;if(e!==void 0&&e.length>0)return e.toLowerCase();let r=Ue(t);if(r!==void 0)return r==="a"?n.href===void 0?void 0:"link":r==="input"?XS[(n.type??"text").toLowerCase()]:YS[r]}function eo(t){let n=je(t),e=n["aria-label"]??n.alt??n.title;return e!==void 0&&e.trim().length>0?e.trim():_t(t)}function Ly(t){return t.replace(/\s+/g," ").trim()}function Qa(t,n,e){let r=Ly(t),i=Ly(n);return e?r===i:r.toLowerCase().includes(i.toLowerCase())}var ZS=new Set(["input","textarea","select"]);function _y(t){let n=[];for(let e of Fe(t))if(typeof e=="string")n.push(e);else if(Array.isArray(e)){let r=Ue(e);if(r!==void 0&&ZS.has(r))continue;n.push(_t(e))}return n.join(" ").replace(/\s+/g," ").trim()}function e0(t,n){let e,r=i=>{if(e===void 0){if(Ue(i)==="label"&&je(i).for===n){e=_y(i);return}for(let s of Fe(i))Array.isArray(s)&&r(s)}};return r(t),e}function My(t,n){let e=je(t),r=[];for(let s of["aria-label","placeholder","title"]){let a=e[s];a!==void 0&&a.trim().length>0&&r.push(a.trim())}for(let s=n.path.length-1;s>=0;s-=1){let a=Fy(n.root,n.path.slice(0,s));if(a===void 0)break;if(Ue(a)==="label"){r.push(_y(a));break}}let i=e.id;if(i!==void 0){let s=e0(n.root,i);s!==void 0&&r.push(s)}return r}var t0=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function n0(t){return t.replace(/\\(.)/g,"$1")}function Za(t){let n=new RegExp(`^(?:${t0})([is])?$`).exec(t.trim());if(n===null)return;let e=n[1]??n[2];if(e!==void 0)return{value:n0(e),caseSensitive:n[3]!=="i"}}function r0(t){let n=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(t.trim());if(n===null)return;let e=n[1]?.toLowerCase(),r=Za(n[2]??"");if(!(e===void 0||r===void 0))return{describe:`[${e}]`,matches:i=>{let s=je(i)[e];return s!==void 0&&Qa(s,r.value,r.caseSensitive)}}}function i0(t,n){if(t==="role"){let e=/^([\w-]+)(?:\[(.*)\])?$/.exec(n.trim()),r=e?.[1]?.toLowerCase();if(r===void 0)return;let i=e?.[2];if(i===void 0||i.trim()==="")return{describe:`role=${r}`,matches:o=>$n(o)===r};let s=/^name\s*=\s*(.+)$/.exec(i.trim()),a=s===null?void 0:Za(s[1]??"");return a===void 0?void 0:{describe:`role=${r}[name]`,matches:(o,d)=>$n(o)===r&&[eo(o),...My(o,d)].some(c=>Qa(c,a.value,a.caseSensitive))}}if(t==="label"){let e=Za(n);return e===void 0?void 0:{describe:"label",matches:(r,i)=>My(r,i).some(s=>Qa(s,e.value,e.caseSensitive))}}if(t==="text"){let e=Za(n);if(e===void 0)return;let r=i=>Qa(_t(i),e.value,e.caseSensitive);return{describe:"text",matches:i=>r(i)&&!Fe(i).some(s=>Array.isArray(s)&&r(s))}}if(t==="testid"||t==="attr")return r0(n)}function s0(t){let n=t.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(n===null||n.join("")!==t)return;let e=[];for(let r of n)if(r.startsWith("#")){let i=r.slice(1);e.push(s=>je(s).id===i)}else if(r.startsWith(".")){let i=r.slice(1);e.push(s=>(je(s).class??"").split(/\s+/).includes(i))}else if(r.startsWith("[")){let i=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(r),s=i?.[1]?.toLowerCase();if(s===void 0)return;let a=i?.[2];e.push(o=>{let d=je(o)[s];return d===void 0?!1:a===void 0||a===""?!0:d===a})}else{let i=r.toLowerCase();e.push(s=>Ue(s)===i)}return{describe:t,matches:r=>e.every(i=>i(r))}}function a0(t){let n=t.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(n);if(e!==null)return i0(e[1]??"",e[2]??"");let r=/^role=([\w-]+)$/.exec(n);if(r!==null){let i=r[1]?.toLowerCase();return i===void 0?void 0:{describe:n,matches:s=>$n(s)===i}}return s0(n)}function o0(t){let n=[],e="",r;for(let i=0;i<t.length;i+=1){let s=t[i];if(s!==void 0){if(r!==void 0){if(s==="\\"){e+=s+(t[i+1]??""),i+=1;continue}s===r&&(r=void 0),e+=s;continue}if(s==='"'||s==="'"){r=s,e+=s;continue}if(s===">"&&t[i+1]===">"){n.push(e),e="",i+=1;continue}e+=s}}return n.push(e),n.map(i=>i.trim()).filter(i=>i.length>0)}function d0(t){if(/^(?:internal:|role=)/.test(t))return[t];let n=[],e="",r=0,i;for(let s of t){if(i!==void 0){s===i&&(i=void 0),e+=s;continue}if((s==='"'||s==="'")&&(i=s),(s==="["||s==="(")&&(r+=1),(s==="]"||s===")")&&(r=Math.max(0,r-1)),r===0&&(s===" "||s===">")){e.trim()!==""&&n.push(e.trim()),e="";continue}e+=s}return e.trim()!==""&&n.push(e.trim()),n.length===0?[t]:n}function jy(t,n){let e=[{node:t,path:n}];return Fe(t).forEach((r,i)=>{Array.isArray(r)&&e.push(...jy(r,[...n,i]))}),e}function Fy(t,n){let e=t;for(let r of n){let i=Fe(e)[r];if(!Array.isArray(i))return;e=i}return e}function qi(t,n){if(!Array.isArray(t))return{kind:"unsupported",reason:"snapshot root is not an element"};let e=o0(n).flatMap(d0);if(e.length===0)return{kind:"unsupported",reason:"empty selector"};let r=[{node:t,path:[]}];for(let i of e){if(i===".."){let o=new Map;for(let d of r){if(d.path.length===0)continue;let c=d.path.slice(0,-1),l=Fy(t,c);l!==void 0&&o.set(c.join("."),{node:l,path:c})}r=[...o.values()];continue}let s=a0(i);if(s===void 0)return{kind:"unsupported",reason:i};let a=new Map;for(let o of r)for(let d of jy(o.node,o.path))s.matches(d.node,{root:t,path:d.path})&&a.set(d.path.join("."),d);if(r=[...a.values()],r.length===0)break}return{kind:"resolved",matches:r}}function c0(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function H(t){return typeof t=="string"?t:void 0}function Pe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function By(t){return typeof t=="boolean"?t:void 0}function me(t){return c0(t)?t:void 0}function tt(t){return Array.isArray(t)?t:void 0}function qe(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}function to(t){let n=[];return t.split(/\r?\n/).forEach((e,r)=>{let i=e.trim();if(i.length!==0)try{n.push({line:r+1,value:JSON.parse(i),parsed:!0})}catch{n.push({line:r+1,value:void 0,parsed:!1})}}),n}function xe(t,n){let e;try{e=typeof t=="string"?t:JSON.stringify(t)??""}catch{return"[unserializable]"}let r=vt(e).replace(/\s+/g," ").trim(),i=Buffer.from(r,"utf8");if(i.byteLength<=n)return r;let s=n;for(;s>0&&((i[s]??0)&192)===128;)s-=1;return`${i.subarray(0,s).toString("utf8")}\u2026`}var zy=new Set(["script","style","noscript","template","head"]),Hy=120,l0=200,u0={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},p0=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),Vy=["data-testid","data-test-id","data-test","data-qa","data-cy"],f0=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function h0(t){let n=[];for(let[e,r]of Object.entries(je(t))){let i=u0[e];if(i!==void 0){n.push({name:i,value:xe(r,Hy)});continue}e.startsWith("__playwright")||/^on[a-z]+$/.test(e)||n.push({name:e,value:xe(r,Hy)})}return n.sort((e,r)=>e.name.localeCompare(r.name))}function Uy(t,n){let e,r=(i,s)=>{if(e===void 0){if(je(i).__playwright_target__===n){e={node:i,path:s};return}Fe(i).forEach((a,o)=>{Array.isArray(a)&&r(a,[...s,o])})}};return r(t,[]),e}function m0(t){return Fe(t).filter(n=>typeof n=="string").join(" ").replace(/\s+/g," ").trim()}function Gi(t,n,e){let r=[],i=[],s=0,a=0,o=!1,d=(c,l)=>{if(o)return;let u=Ue(c);if(u===void 0||zy.has(u))return;if(l>e.maxDepth||a>=e.maxNodes){o=!0;return}let p=`${n}/${a}`,f=h0(c),h=Nc(f,p,e.sensitiveNames),m=Cc(xe(m0(c),l0),f,p,e.sensitiveNames);i.push(...h.records,...m.records);let g=h.value.map(x=>` ${x.name}="${x.value}"`).join(""),y=`${" ".repeat(l)}<${u}${g}>${m.value===""?"":` ${m.value}`}`,w=Buffer.byteLength(y,"utf8")+1;if(s+w>e.maxBytes){o=!0;return}r.push(y),s+=w,a+=1;for(let x of Fe(c))Array.isArray(x)&&d(x,l+1)};return d(t,0),{text:r.join(`
131
- `),redactions:i,nodes:a,truncated:o}}function Ki(t,n=[],e){let r=je(t),i=$n(t),s=eo(t),a=xe(s===""&&e!==void 0?e:s,80),o=[i===void 0?`<${Ue(t)??"?"}>`:i];a!==""&&o.push(JSON.stringify(a));for(let c of[...new Set([...n,...Vy,"id","name"])]){let l=r[c];l!==void 0&&l!==""&&o.push(`${c}=${xe(l,60)}`)}let d=r.placeholder;return d!==void 0&&d!==""&&o.push(`placeholder=${JSON.stringify(xe(d,60))}`),o.join(" ")}function Ir(t){let n=t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!f0.has(e));return[...new Set(n)]}function y0(t){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(t)?.[1]?.toLowerCase()}function g0(t){return[...t.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(n=>n[1]?.toLowerCase()).filter(n=>n!==void 0&&n!=="name")}function no(t,n,e,r,i,s){let a=Ir(n),o=y0(n),d=g0(n),c=new Set(e.map(v=>v.path.join("."))),l=[],u=0,p=new Map,f=v=>{if(Ue(v)==="label"){let R=je(v).for;R!==void 0&&p.set(R,_t(v))}for(let R of Fe(v))Array.isArray(R)&&f(R)};f(t);let h=(v,R,P)=>{let C=Ue(v);if(C===void 0||zy.has(C))return;let E=je(v),M=(E.id===void 0?void 0:p.get(E.id))??P,A=$n(v),N=d.some(I=>E[I]!==void 0)||Vy.some(I=>E[I]!==void 0);if(A!==void 0&&p0.has(A)||N){let I=Ki(v,d,M),$=`${I} ${xe(_t(v),200)}`.toLowerCase(),D=c.has(R.join(".")),k=(D?100:0)+(o!==void 0&&A===o?2:0)+a.filter(S=>$.includes(S)).length*3;l.push({line:`${D?"match: ":""}${I}`,score:k,order:u++})}let T=C==="label"?_t(v):P;Fe(v).forEach((I,$)=>{Array.isArray(I)&&h(I,[...R,$],T)})};h(t,[],void 0);let m=[...l].sort((v,R)=>R.score-v.score||v.order-R.order),g=[],y=[],w=0,x=m.length>i.maxItems;for(let v of m.slice(0,i.maxItems)){let R=ce(v.line,"dom",r,s),P=Buffer.byteLength(R.value,"utf8")+1;if(w+P>i.maxBytes){x=!0;break}y.push(...R.records),g.push(R.value),w+=P}return{text:g.join(`
132
- `),redactions:y,nodes:g.length,truncated:x}}import{createRequire as w0}from"module";var b0=w0("/"),Sr,x0,v0;try{Sr=b0("worker_threads"),x0=Sr.Worker,v0=Sr.isMarkedAsUntransferable}catch{}var De=Uint8Array,Ar=Uint16Array,k0=Int32Array,qy=new De([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Gy=new De([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),R0=new De([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ky=function(t,n){for(var e=new Ar(31),r=0;r<31;++r)e[r]=n+=1<<t[r-1];for(var i=new k0(e[30]),r=1;r<30;++r)for(var s=e[r];s<e[r+1];++s)i[s]=s-e[r]<<5|r;return{b:e,r:i}},Sr=Ky(qy,2),Wy=Sr.b,I0=Sr.r;Wy[28]=258,I0[258]=28;var Jy=Ky(Gy,0),A0=Jy.b,PF=Jy.r,ql=new Ar(32768);for(ae=0;ae<32768;++ae)jt=(ae&43690)>>1|(ae&21845)<<1,jt=(jt&52428)>>2|(jt&13107)<<2,jt=(jt&61680)>>4|(jt&3855)<<4,ql[ae]=((jt&65280)>>8|(jt&255)<<8)>>1;var jt,ae,Ji=(function(t,n,e){for(var r=t.length,i=0,s=new Ar(n);i<r;++i)t[i]&&++s[t[i]-1];var a=new Ar(n);for(i=1;i<n;++i)a[i]=a[i-1]+s[i-1]<<1;var o;if(e){o=new Ar(1<<n);var d=15-n;for(i=0;i<r;++i)if(t[i])for(var c=i<<4|t[i],l=n-t[i],u=a[t[i]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[ql[u]>>d]=c}else for(o=new Ar(r),i=0;i<r;++i)t[i]&&(o[i]=ql[a[t[i]-1]++]>>15-t[i]);return o}),Xi=new De(288);for(ae=0;ae<144;++ae)Xi[ae]=8;var ae;for(ae=144;ae<256;++ae)Xi[ae]=9;var ae;for(ae=256;ae<280;++ae)Xi[ae]=7;var ae;for(ae=280;ae<288;++ae)Xi[ae]=8;var ae,Yy=new De(32);for(ae=0;ae<32;++ae)Yy[ae]=5;var ae;var T0=Ji(Xi,9,1);var P0=Ji(Yy,5,1),zl=function(t){for(var n=t[0],e=1;e<t.length;++e)t[e]>n&&(n=t[e]);return n},ut=function(t,n,e){var r=n/8|0;return(t[r]|t[r+1]<<8)>>(n&7)&e},Vl=function(t,n){var e=n/8|0;return(t[e]|t[e+1]<<8|t[e+2]<<16)>>(n&7)},S0=function(t){return(t+7)/8|0},Yi=function(t,n,e){return(n==null||n<0)&&(n=0),(e==null||e>t.length)&&(e=t.length),new De(t.subarray(n,e))};var E0=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Se=function(t,n,e){var r=new Error(n||E0[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,Se),!e)throw r;return r},C0=function(t,n,e,r){var i=t.length,s=r?r.length:0;if(!i||n.f&&!n.l)return e||new De(0);var a=!e,o=a||n.i!=2,d=n.i;a&&(e=new De(i*3));var c=function(ii){var si=e.length;if(ii>si){var ai=new De(Math.max(si*2,ii));ai.set(e),e=ai}},l=n.f||0,u=n.p||0,p=n.b||0,f=n.l,h=n.d,m=n.m,g=n.n,y=i*8;do{if(!f){l=ut(t,u,1);var w=ut(t,u+1,3);if(u+=3,w)if(w==1)f=T0,h=P0,m=9,g=5;else if(w==2){var P=ut(t,u,31)+257,C=ut(t,u+10,15)+4,E=P+ut(t,u+5,31)+1;u+=14;for(var M=new De(E),A=new De(19),N=0;N<C;++N)A[R0[N]]=ut(t,u+N*3,7);u+=C*3;for(var T=zl(A),I=(1<<T)-1,$=Ji(A,T,1),N=0;N<E;){var D=$[ut(t,u,I)];u+=D&15;var x=D>>4;if(x<16)M[N++]=x;else{var k=0,S=0;for(x==16?(S=3+ut(t,u,3),u+=2,k=M[N-1]):x==17?(S=3+ut(t,u,7),u+=3):x==18&&(S=11+ut(t,u,127),u+=7);S--;)M[N++]=k}}var _=M.subarray(0,P),q=M.subarray(P);m=zl(_),g=zl(q),f=Ji(_,m,1),h=Ji(q,g,1)}else Se(1);else{var x=S0(u)+4,v=t[x-4]|t[x-3]<<8,R=x+v;if(R>i){d&&Se(0);break}o&&c(p+v),e.set(t.subarray(x,R),p),n.b=p+=v,n.p=u=R*8,n.f=l;continue}if(u>y){d&&Se(0);break}}o&&c(p+131072);for(var K=(1<<m)-1,te=(1<<g)-1,le=u;;le=u){var k=f[Vl(t,u)&K],Y=k>>4;if(u+=k&15,u>y){d&&Se(0);break}if(k||Se(2),Y<256)e[p++]=Y;else if(Y==256){le=u,f=null;break}else{var Ae=Y-254;if(Y>264){var N=Y-257,Ee=qy[N];Ae=ut(t,u,(1<<Ee)-1)+Wy[N],u+=Ee}var St=h[Vl(t,u)&te],qt=St>>4;St||Se(3),u+=St&15;var q=A0[qt];if(qt>3){var Ee=Gy[qt];q+=Vl(t,u)&(1<<Ee)-1,u+=Ee}if(u>y){d&&Se(0);break}o&&c(p+131072);var ni=p+Ae;if(p<q){var ri=s-q,Fs=Math.min(q,ni);for(ri+p<0&&Se(3);p<Fs;++p)e[p]=r[ri+p]}for(;p<ni;++p)e[p]=e[p-q]}}n.l=f,n.p=le,n.b=p,n.f=l,f&&(l=1,n.m=m,n.d=h,n.n=g)}while(!l);return p!=e.length&&a?Yi(e,0,p):e.subarray(0,p)};var Wi=new De(0);var Tr=function(t,n){return t[n]|t[n+1]<<8},Pr=function(t,n){return(t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24)>>>0},Ul=function(t,n){return Pr(t,n)+Pr(t,n+4)*4294967296};var N0=(function(){function t(n,e){typeof n=="function"&&(e=n,n={}),this.ondata=e;var r=n&&n.dictionary&&n.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new De(32768),this.p=new De(0),r&&this.o.set(r)}return t.prototype.e=function(n){if(this.ondata||Se(5),this.d&&Se(4),!this.p.length)this.p=n;else if(n.length){var e=new De(this.p.length+n.length);e.set(this.p),e.set(n,this.p.length),this.p=e}},t.prototype.c=function(n){this.s.i=+(this.d=n||!1);var e=this.s.b,r=C0(this.p,this.s,this.o);this.ondata(Yi(r,e,this.s.b),this.d),this.o=Yi(r,this.s.b-32768),this.s.b=this.o.length,this.p=Yi(this.p,this.s.p/8|0),this.s.p&=7},t.prototype.push=function(n,e){this.e(n),this.c(e)},t})();var Gl=typeof TextDecoder<"u"&&new TextDecoder,O0=0;try{Gl.decode(Wi,{stream:!0}),O0=1}catch{}var $0=function(t){for(var n="",e=0;;){var r=t[e++],i=(r>127)+(r>223)+(r>239);if(e+i>t.length)return{s:n,r:Yi(t,e-1)};i?i==3?(r=((r&15)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,n+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?n+=String.fromCharCode((r&31)<<6|t[e++]&63):n+=String.fromCharCode((r&15)<<12|(t[e++]&63)<<6|t[e++]&63):n+=String.fromCharCode(r)}};function D0(t,n){if(n){for(var e="",r=0;r<t.length;r+=16384)e+=String.fromCharCode.apply(null,t.subarray(r,r+16384));return e}else{if(Gl)return Gl.decode(t);var i=$0(t),s=i.s,e=i.r;return e.length&&Se(8),s}}var L0=function(t,n,e,r,i,s,a){var o=i==4294967295,d=s==4294967295,c=a==4294967295,l=n+e,u=o+d+c;if(r&&u){for(;n+4<l;n+=4+Tr(t,n+2))if(Tr(t,n)==1)return[o?Ul(t,n+4+8*d):i,d?Ul(t,n+4):s,c?Ul(t,n+4+8*(d+o)):a,1];r<2&&Se(13)}return[i,s,a,0]};var M0=(function(){function t(){}return t.prototype.push=function(n,e){this.ondata(null,n,e)},t.compression=0,t})();var Xy=(function(){function t(){var n=this;this.i=new N0(function(e,r){n.ondata(null,e,r)})}return t.prototype.push=function(n,e){try{this.i.push(n,e)}catch(r){this.ondata(r,null,e)}},t.compression=8,t})();var Qy=(function(){function t(n){this.onfile=n,this.k=[],this.o={0:M0},this.p=Wi}return t.prototype.push=function(n,e){var r=this;if(this.onfile||Se(5),this.p||Se(4),this.c>0){var i=Math.min(this.c,n.length),s=n.subarray(0,i);if(this.c-=i,this.d?this.d.push(s,!this.c):this.k[0].push(s),n=n.subarray(i),n.length)return this.push(n,e)}else{var a=0,o=0,d=void 0,c=void 0;this.p.length?n.length?(c=new De(this.p.length+n.length),c.set(this.p),c.set(n,this.p.length)):c=this.p:c=n;for(var l=c.length,u=this.c,p=u&&this.d,f=function(){var y=Pr(c,o);if(y==67324752){a=1,d=o,h.d=null,h.c=0;var w=Tr(c,o+6),x=Tr(c,o+8),v=w&2048,R=w&8,P=Tr(c,o+26),C=Tr(c,o+28);if(l>o+30+P+C){var E=[];h.k.unshift(E),a=2;var M=Pr(c,o+18),A=Pr(c,o+22),N=D0(c.subarray(o+30,o+=30+P),!v),T=L0(c,o,C,2,M,A,0),I=T[0],$=T[1],D=T[3];R&&(I=-1-D),o+=C,h.c=I;var k,S={name:N,compression:x,start:function(){if(S.ondata||Se(5),!I)S.ondata(null,Wi,!0);else{var _=r.o[x];_||S.ondata(Se(14,"unknown compression type "+x,1),null,!1),k=I<0?new _(N):new _(N,I,$),k.ondata=function(le,Y,Ae){S.ondata(le,Y,Ae)};for(var q=0,K=E;q<K.length;q++){var te=K[q];k.push(te,!1)}r.k[0]==E&&r.c?r.d=k:k.push(Wi,!0)}},terminate:function(){k&&k.terminate&&k.terminate()}};I>=0&&(S.size=I,S.originalSize=$),h.onfile(S)}return"break"}else if(u){if(y==134695760)return d=o+=12+(u==-2&&8),a=3,h.c=0,"break";if(y==33639248)return d=o-=4,a=3,h.c=0,"break"}},h=this;o<l-4;++o){var m=f();if(m==="break")break}if(this.p=Wi,u<0){var g=a?c.subarray(0,d-12-(u==-2&&8)-(Pr(c,d-16)==134695760&&4)):c.subarray(0,o);p?p.push(g,!!a):this.k[+(a==2)].push(g)}if(a&2)return this.push(c.subarray(o),e);this.p=c.subarray(o)}e&&(this.c&&Se(13),this.p=null)},t.prototype.register=function(n){this.o[n.compression]=n},t})();var Zy=65536;function _0(t,n){let e=new Uint8Array(n),r=0;for(let i of t)e.set(i,r),r+=i.length;return e}function ro(t,n,e){if(t.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(t[0]!==80||t[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let r=new Map,i=[],s=0,a=0,o,d=new Set,c=new Qy;c.register(Xy),c.onfile=l=>{let u=l.name,p=typeof l.originalSize=="number"&&l.originalSize>0,f=l.originalSize??0;if(!Ic(u)){i.push({entry:u,reason:"unsafe-entry-name",declaredBytes:f});return}if(!e(u))return;if(d.has(u)){i.push({entry:u,reason:"duplicate-selected-name",declaredBytes:f});return}if(s>=n.maxEntries){i.push({entry:u,reason:"entry-budget-exceeded",declaredBytes:f});return}let h=n.maxExpandedBytes-a;if(p&&f>h){i.push({entry:u,reason:"expanded-budget-exceeded",declaredBytes:f});return}s+=1,d.add(u);let m=[],g=0,y=!1;l.ondata=(w,x,v)=>{if(o!==void 0||y)return;if(w!==null){o=`Archive entry ${u} could not be inflated.`;return}g+=x.length;let R=p&&g>f;if(R||g>h){y=!0,m.length=0,i.push({entry:u,reason:R?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:f});return}if(m.push(x.slice()),v){if(p&&g!==f){m.length=0,y=!0,i.push({entry:u,reason:"declared-size-mismatch",declaredBytes:f});return}a+=g,r.set(u,_0(m,g))}},l.start()};try{for(let l=0;l<t.byteLength;l+=Zy){let u=Math.min(l+Zy,t.byteLength);if(c.push(t.subarray(l,u),u===t.byteLength),o!==void 0)break}}catch{return{kind:"unreadable",message:"Archive could not be read as a ZIP container."}}return o!==void 0?{kind:"unreadable",message:o}:{kind:"read",contents:{entries:r,skipped:i}}}var eg=256,tg={before:"before",action:"action",input:"action",after:"after"};function Kl(t){return Array.isArray(t)&&typeof t[0]=="string"}function j0(t){return Array.isArray(t)&&Array.isArray(t[0])&&typeof t[0][0]=="number"&&typeof t[0][1]=="number"}function ng(t){let n=t[1],e=typeof n=="object"&&n!==null&&!Array.isArray(n);return t.slice(e?2:1)}function F0(t){let n=H(t.snapshotName),e=H(t.callId),r=tg[H(t.phase)??""];if(n!==void 0){let i=n.indexOf("@");i>0&&(r??=tg[n.slice(0,i)],e??=n.slice(i+1))}return{...e===void 0?{}:{callId:e},...r===void 0?{}:{phase:r},...n===void 0?{}:{name:n}}}var io=class{frames=new Map;literals=new Map;byCall=new Map;add(n,e,r){let i=me(r.snapshot);if(i===void 0||i.html===void 0)return;let s=F0(i),a=H(i.frameId)??H(i.pageId)??"unknown-frame",o=`${n}
130
+ `)}var Ya="kwikqa-report.html",Dy=4096;async function WS(t){let n=await GS(t,"r");try{let e=Buffer.alloc(Dy),{bytesRead:r}=await n.read(e,0,Dy,0);return e.subarray(0,r).toString("utf8")}finally{await n.close()}}async function Rr(t,n){let e=KS(t,n??Ya),r=await US(e).catch(i=>{if(i.code!=="ENOENT")throw i});return r===void 0?{kind:"writable",path:e}:r.isFile()?(await WS(e)).includes(`<meta name="${Ja}"`)?{kind:"writable",path:e}:{kind:"refused",path:e,message:`${e} exists and isn't a KwikQA report, so KwikQA won't replace it. Choose another path with --output.`}:{kind:"refused",path:e,message:`${e} exists and isn't a regular file, so KwikQA won't write a report there.`}}async function Fl(t,n){let e=await Rr($y(t),t);return e.kind==="refused"||(await qS($y(t),{recursive:!0}),await ye(t,n,{mode:420,replace:!0})),e}import{basename as ZC}from"node:path";function Xa(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(Xa).join(",")}]`:`{${Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${Xa(r)}`).join(",")}}`}function we(t,n,e,r,i){return B("evd",[t,n,e,Xa(r),i])}function Ie(t,n,e){return B("art",["m2",t,n,e])}function Ir(t){return Ne(Buffer.from(Xa(t),"utf8"))}var Bl={policyVersion:"development-1",workspaceRoot:".",maxPacketBytes:256e3,maxArtifactBytes:16e6,maxTraceEntries:2e3,maxTraceEvents:2e3,maxReportFields:2e3,maxStackFrames:2e3,maxSteps:2e3,maxStdioChunks:2e3,maxStdioBytes:64e6,maxTraceExpandedBytes:64e6,maxConsoleEvents:100,maxNetworkEvents:200,includeNetworkBodies:!1,maxNetworkBodyBytes:0,maxDomDepth:6,maxDomNodes:200,maxDomTextBytes:16e3,maxSourceFiles:12,maxSourceBytes:128e3,maxSourceLinesPerFile:200,maxImportDepth:2,maxDiffBytes:128e3,maxDiffHunks:30,sensitiveNames:["authorization","cookie","set-cookie","password","passwd","secret","token","api-key","apikey"]},JS=["maxPacketBytes","maxArtifactBytes","maxTraceEntries","maxTraceEvents","maxReportFields","maxStackFrames","maxSteps","maxStdioChunks","maxStdioBytes","maxTraceExpandedBytes","maxConsoleEvents","maxNetworkEvents","maxDomDepth","maxDomNodes","maxDomTextBytes","maxSourceFiles","maxSourceBytes","maxSourceLinesPerFile","maxImportDepth","maxDiffBytes","maxDiffHunks"];function Hl(t){if(t===null||typeof t!="object")return"policy must be an object";if(typeof t.policyVersion!="string")return"policyVersion must be a string";if(t.policyVersion.length===0)return"policyVersion must not be empty";if(typeof t.workspaceRoot!="string")return"workspaceRoot must be a string";if(t.workspaceRoot.length===0)return"workspaceRoot must not be empty";if(typeof t.includeNetworkBodies!="boolean")return"includeNetworkBodies must be a boolean";if(!Array.isArray(t.sensitiveNames)||t.sensitiveNames.some(n=>typeof n!="string"||n.length===0))return"sensitiveNames must be an array of non-empty strings";if(t.sensitiveNames.some(n=>n.trim()!==n))return"sensitiveNames must not contain surrounding whitespace";for(let n of JS){let e=t[n];if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)return`${n} must be a positive safe integer`}if(!Number.isSafeInteger(t.maxNetworkBodyBytes)||t.maxNetworkBodyBytes<0||t.includeNetworkBodies&&t.maxNetworkBodyBytes===0)return"maxNetworkBodyBytes must be positive when network bodies are enabled"}var YS={button:"button",nav:"navigation",main:"main",header:"banner",footer:"contentinfo",form:"form",table:"table",img:"img",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",ul:"list",ol:"list",li:"listitem",section:"region",article:"article",dialog:"dialog",select:"combobox",textarea:"textbox"},XS={button:"button",submit:"button",reset:"button",checkbox:"checkbox",radio:"radio",range:"slider",text:"textbox",search:"searchbox",email:"textbox",tel:"textbox",url:"textbox",password:"textbox"},QS=new Set(["script","style","head","title","meta","link"]);function Ue(t){let n=t[0];return typeof n=="string"?n.toLowerCase():void 0}function je(t){let n=t[1];if(typeof n!="object"||n===null||Array.isArray(n))return{};let e={};for(let[r,i]of Object.entries(n))typeof i=="string"&&(e[r.toLowerCase()]=i);return e}function Fe(t){let n=typeof t[1]=="object"&&t[1]!==null&&!Array.isArray(t[1]);return t.slice(n?2:1)}function _t(t,n=0){let e=Ue(t);if(e===void 0||QS.has(e)||n>12)return"";let r=[];for(let i of Fe(t))typeof i=="string"?r.push(i):Array.isArray(i)&&r.push(_t(i,n+1));return r.join(" ").replace(/\s+/g," ").trim()}function $n(t){let n=je(t),e=n.role;if(e!==void 0&&e.length>0)return e.toLowerCase();let r=Ue(t);if(r!==void 0)return r==="a"?n.href===void 0?void 0:"link":r==="input"?XS[(n.type??"text").toLowerCase()]:YS[r]}function eo(t){let n=je(t),e=n["aria-label"]??n.alt??n.title;return e!==void 0&&e.trim().length>0?e.trim():_t(t)}function Ly(t){return t.replace(/\s+/g," ").trim()}function Qa(t,n,e){let r=Ly(t),i=Ly(n);return e?r===i:r.toLowerCase().includes(i.toLowerCase())}var ZS=new Set(["input","textarea","select"]);function _y(t){let n=[];for(let e of Fe(t))if(typeof e=="string")n.push(e);else if(Array.isArray(e)){let r=Ue(e);if(r!==void 0&&ZS.has(r))continue;n.push(_t(e))}return n.join(" ").replace(/\s+/g," ").trim()}function e0(t,n){let e,r=i=>{if(e===void 0){if(Ue(i)==="label"&&je(i).for===n){e=_y(i);return}for(let s of Fe(i))Array.isArray(s)&&r(s)}};return r(t),e}function My(t,n){let e=je(t),r=[];for(let s of["aria-label","placeholder","title"]){let a=e[s];a!==void 0&&a.trim().length>0&&r.push(a.trim())}for(let s=n.path.length-1;s>=0;s-=1){let a=Fy(n.root,n.path.slice(0,s));if(a===void 0)break;if(Ue(a)==="label"){r.push(_y(a));break}}let i=e.id;if(i!==void 0){let s=e0(n.root,i);s!==void 0&&r.push(s)}return r}var t0=`"((?:[^"\\\\]|\\\\.)*)"|'((?:[^'\\\\]|\\\\.)*)'`;function n0(t){return t.replace(/\\(.)/g,"$1")}function Za(t){let n=new RegExp(`^(?:${t0})([is])?$`).exec(t.trim());if(n===null)return;let e=n[1]??n[2];if(e!==void 0)return{value:n0(e),caseSensitive:n[3]!=="i"}}function r0(t){let n=/^\[\s*([\w:-]+)\s*=\s*(.+?)\s*\]$/.exec(t.trim());if(n===null)return;let e=n[1]?.toLowerCase(),r=Za(n[2]??"");if(!(e===void 0||r===void 0))return{describe:`[${e}]`,matches:i=>{let s=je(i)[e];return s!==void 0&&Qa(s,r.value,r.caseSensitive)}}}function i0(t,n){if(t==="role"){let e=/^([\w-]+)(?:\[(.*)\])?$/.exec(n.trim()),r=e?.[1]?.toLowerCase();if(r===void 0)return;let i=e?.[2];if(i===void 0||i.trim()==="")return{describe:`role=${r}`,matches:o=>$n(o)===r};let s=/^name\s*=\s*(.+)$/.exec(i.trim()),a=s===null?void 0:Za(s[1]??"");return a===void 0?void 0:{describe:`role=${r}[name]`,matches:(o,d)=>$n(o)===r&&[eo(o),...My(o,d)].some(c=>Qa(c,a.value,a.caseSensitive))}}if(t==="label"){let e=Za(n);return e===void 0?void 0:{describe:"label",matches:(r,i)=>My(r,i).some(s=>Qa(s,e.value,e.caseSensitive))}}if(t==="text"){let e=Za(n);if(e===void 0)return;let r=i=>Qa(_t(i),e.value,e.caseSensitive);return{describe:"text",matches:i=>r(i)&&!Fe(i).some(s=>Array.isArray(s)&&r(s))}}if(t==="testid"||t==="attr")return r0(n)}function s0(t){let n=t.match(/^[A-Za-z][\w-]*|#[\w-]+|\.[\w-]+|\[[^\]]*\]/g);if(n===null||n.join("")!==t)return;let e=[];for(let r of n)if(r.startsWith("#")){let i=r.slice(1);e.push(s=>je(s).id===i)}else if(r.startsWith(".")){let i=r.slice(1);e.push(s=>(je(s).class??"").split(/\s+/).includes(i))}else if(r.startsWith("[")){let i=/^\[\s*([\w:-]+)\s*(?:=\s*["']?([^"'\]]*)["']?)?\s*\]$/.exec(r),s=i?.[1]?.toLowerCase();if(s===void 0)return;let a=i?.[2];e.push(o=>{let d=je(o)[s];return d===void 0?!1:a===void 0||a===""?!0:d===a})}else{let i=r.toLowerCase();e.push(s=>Ue(s)===i)}return{describe:t,matches:r=>e.every(i=>i(r))}}function a0(t){let n=t.trim(),e=/^internal:([\w-]+)=([\s\S]+)$/.exec(n);if(e!==null)return i0(e[1]??"",e[2]??"");let r=/^role=([\w-]+)$/.exec(n);if(r!==null){let i=r[1]?.toLowerCase();return i===void 0?void 0:{describe:n,matches:s=>$n(s)===i}}return s0(n)}function o0(t){let n=[],e="",r;for(let i=0;i<t.length;i+=1){let s=t[i];if(s!==void 0){if(r!==void 0){if(s==="\\"){e+=s+(t[i+1]??""),i+=1;continue}s===r&&(r=void 0),e+=s;continue}if(s==='"'||s==="'"){r=s,e+=s;continue}if(s===">"&&t[i+1]===">"){n.push(e),e="",i+=1;continue}e+=s}}return n.push(e),n.map(i=>i.trim()).filter(i=>i.length>0)}function d0(t){if(/^(?:internal:|role=)/.test(t))return[t];let n=[],e="",r=0,i;for(let s of t){if(i!==void 0){s===i&&(i=void 0),e+=s;continue}if((s==='"'||s==="'")&&(i=s),(s==="["||s==="(")&&(r+=1),(s==="]"||s===")")&&(r=Math.max(0,r-1)),r===0&&(s===" "||s===">")){e.trim()!==""&&n.push(e.trim()),e="";continue}e+=s}return e.trim()!==""&&n.push(e.trim()),n.length===0?[t]:n}function jy(t,n){let e=[{node:t,path:n}];return Fe(t).forEach((r,i)=>{Array.isArray(r)&&e.push(...jy(r,[...n,i]))}),e}function Fy(t,n){let e=t;for(let r of n){let i=Fe(e)[r];if(!Array.isArray(i))return;e=i}return e}function qi(t,n){if(!Array.isArray(t))return{kind:"unsupported",reason:"snapshot root is not an element"};let e=o0(n).flatMap(d0);if(e.length===0)return{kind:"unsupported",reason:"empty selector"};let r=[{node:t,path:[]}];for(let i of e){if(i===".."){let o=new Map;for(let d of r){if(d.path.length===0)continue;let c=d.path.slice(0,-1),l=Fy(t,c);l!==void 0&&o.set(c.join("."),{node:l,path:c})}r=[...o.values()];continue}let s=a0(i);if(s===void 0)return{kind:"unsupported",reason:i};let a=new Map;for(let o of r)for(let d of jy(o.node,o.path))s.matches(d.node,{root:t,path:d.path})&&a.set(d.path.join("."),d);if(r=[...a.values()],r.length===0)break}return{kind:"resolved",matches:r}}function c0(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function H(t){return typeof t=="string"?t:void 0}function Pe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function By(t){return typeof t=="boolean"?t:void 0}function me(t){return c0(t)?t:void 0}function tt(t){return Array.isArray(t)?t:void 0}function qe(t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}function to(t){let n=[];return t.split(/\r?\n/).forEach((e,r)=>{let i=e.trim();if(i.length!==0)try{n.push({line:r+1,value:JSON.parse(i),parsed:!0})}catch{n.push({line:r+1,value:void 0,parsed:!1})}}),n}function xe(t,n){let e;try{e=typeof t=="string"?t:JSON.stringify(t)??""}catch{return"[unserializable]"}let r=vt(e).replace(/\s+/g," ").trim(),i=Buffer.from(r,"utf8");if(i.byteLength<=n)return r;let s=n;for(;s>0&&((i[s]??0)&192)===128;)s-=1;return`${i.subarray(0,s).toString("utf8")}\u2026`}var zy=new Set(["script","style","noscript","template","head"]),Hy=120,l0=200,u0={__playwright_value_:"value",__playwright_checked_:"checked",__playwright_selected_:"selected"},p0=new Set(["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","menuitem","tab","switch","slider","spinbutton","heading","dialog","img","cell","row"]),Vy=["data-testid","data-test-id","data-test","data-qa","data-cy"],f0=new Set(["internal","role","testid","data","name","text","label","attr","has","nth","visible","true","false","exact","css","xpath","and","the"]);function h0(t){let n=[];for(let[e,r]of Object.entries(je(t))){let i=u0[e];if(i!==void 0){n.push({name:i,value:xe(r,Hy)});continue}e.startsWith("__playwright")||/^on[a-z]+$/.test(e)||n.push({name:e,value:xe(r,Hy)})}return n.sort((e,r)=>e.name.localeCompare(r.name))}function Uy(t,n){let e,r=(i,s)=>{if(e===void 0){if(je(i).__playwright_target__===n){e={node:i,path:s};return}Fe(i).forEach((a,o)=>{Array.isArray(a)&&r(a,[...s,o])})}};return r(t,[]),e}function m0(t){return Fe(t).filter(n=>typeof n=="string").join(" ").replace(/\s+/g," ").trim()}function Gi(t,n,e){let r=[],i=[],s=0,a=0,o=!1,d=(c,l)=>{if(o)return;let u=Ue(c);if(u===void 0||zy.has(u))return;if(l>e.maxDepth||a>=e.maxNodes){o=!0;return}let p=`${n}/${a}`,f=h0(c),h=Nc(f,p,e.sensitiveNames),m=Cc(xe(m0(c),l0),f,p,e.sensitiveNames);i.push(...h.records,...m.records);let g=h.value.map(x=>` ${x.name}="${x.value}"`).join(""),y=`${" ".repeat(l)}<${u}${g}>${m.value===""?"":` ${m.value}`}`,w=Buffer.byteLength(y,"utf8")+1;if(s+w>e.maxBytes){o=!0;return}r.push(y),s+=w,a+=1;for(let x of Fe(c))Array.isArray(x)&&d(x,l+1)};return d(t,0),{text:r.join(`
131
+ `),redactions:i,nodes:a,truncated:o}}function Ki(t,n=[],e){let r=je(t),i=$n(t),s=eo(t),a=xe(s===""&&e!==void 0?e:s,80),o=[i===void 0?`<${Ue(t)??"?"}>`:i];a!==""&&o.push(JSON.stringify(a));for(let c of[...new Set([...n,...Vy,"id","name"])]){let l=r[c];l!==void 0&&l!==""&&o.push(`${c}=${xe(l,60)}`)}let d=r.placeholder;return d!==void 0&&d!==""&&o.push(`placeholder=${JSON.stringify(xe(d,60))}`),o.join(" ")}function Ar(t){let n=t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!f0.has(e));return[...new Set(n)]}function y0(t){return/(?:^|>>\s*)(?:internal:)?role=([\w-]+)/.exec(t)?.[1]?.toLowerCase()}function g0(t){return[...t.matchAll(/\[\s*([\w:-]+)\s*=/g)].map(n=>n[1]?.toLowerCase()).filter(n=>n!==void 0&&n!=="name")}function no(t,n,e,r,i,s){let a=Ar(n),o=y0(n),d=g0(n),c=new Set(e.map(v=>v.path.join("."))),l=[],u=0,p=new Map,f=v=>{if(Ue(v)==="label"){let R=je(v).for;R!==void 0&&p.set(R,_t(v))}for(let R of Fe(v))Array.isArray(R)&&f(R)};f(t);let h=(v,R,P)=>{let C=Ue(v);if(C===void 0||zy.has(C))return;let E=je(v),M=(E.id===void 0?void 0:p.get(E.id))??P,A=$n(v),N=d.some(I=>E[I]!==void 0)||Vy.some(I=>E[I]!==void 0);if(A!==void 0&&p0.has(A)||N){let I=Ki(v,d,M),$=`${I} ${xe(_t(v),200)}`.toLowerCase(),D=c.has(R.join(".")),k=(D?100:0)+(o!==void 0&&A===o?2:0)+a.filter(S=>$.includes(S)).length*3;l.push({line:`${D?"match: ":""}${I}`,score:k,order:u++})}let T=C==="label"?_t(v):P;Fe(v).forEach((I,$)=>{Array.isArray(I)&&h(I,[...R,$],T)})};h(t,[],void 0);let m=[...l].sort((v,R)=>R.score-v.score||v.order-R.order),g=[],y=[],w=0,x=m.length>i.maxItems;for(let v of m.slice(0,i.maxItems)){let R=ce(v.line,"dom",r,s),P=Buffer.byteLength(R.value,"utf8")+1;if(w+P>i.maxBytes){x=!0;break}y.push(...R.records),g.push(R.value),w+=P}return{text:g.join(`
132
+ `),redactions:y,nodes:g.length,truncated:x}}import{createRequire as w0}from"module";var b0=w0("/"),Er,x0,v0;try{Er=b0("worker_threads"),x0=Er.Worker,v0=Er.isMarkedAsUntransferable}catch{}var De=Uint8Array,Tr=Uint16Array,k0=Int32Array,qy=new De([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Gy=new De([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),R0=new De([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ky=function(t,n){for(var e=new Tr(31),r=0;r<31;++r)e[r]=n+=1<<t[r-1];for(var i=new k0(e[30]),r=1;r<30;++r)for(var s=e[r];s<e[r+1];++s)i[s]=s-e[r]<<5|r;return{b:e,r:i}},Er=Ky(qy,2),Wy=Er.b,I0=Er.r;Wy[28]=258,I0[258]=28;var Jy=Ky(Gy,0),A0=Jy.b,EF=Jy.r,ql=new Tr(32768);for(ae=0;ae<32768;++ae)jt=(ae&43690)>>1|(ae&21845)<<1,jt=(jt&52428)>>2|(jt&13107)<<2,jt=(jt&61680)>>4|(jt&3855)<<4,ql[ae]=((jt&65280)>>8|(jt&255)<<8)>>1;var jt,ae,Ji=(function(t,n,e){for(var r=t.length,i=0,s=new Tr(n);i<r;++i)t[i]&&++s[t[i]-1];var a=new Tr(n);for(i=1;i<n;++i)a[i]=a[i-1]+s[i-1]<<1;var o;if(e){o=new Tr(1<<n);var d=15-n;for(i=0;i<r;++i)if(t[i])for(var c=i<<4|t[i],l=n-t[i],u=a[t[i]-1]++<<l,p=u|(1<<l)-1;u<=p;++u)o[ql[u]>>d]=c}else for(o=new Tr(r),i=0;i<r;++i)t[i]&&(o[i]=ql[a[t[i]-1]++]>>15-t[i]);return o}),Xi=new De(288);for(ae=0;ae<144;++ae)Xi[ae]=8;var ae;for(ae=144;ae<256;++ae)Xi[ae]=9;var ae;for(ae=256;ae<280;++ae)Xi[ae]=7;var ae;for(ae=280;ae<288;++ae)Xi[ae]=8;var ae,Yy=new De(32);for(ae=0;ae<32;++ae)Yy[ae]=5;var ae;var T0=Ji(Xi,9,1);var P0=Ji(Yy,5,1),zl=function(t){for(var n=t[0],e=1;e<t.length;++e)t[e]>n&&(n=t[e]);return n},ut=function(t,n,e){var r=n/8|0;return(t[r]|t[r+1]<<8)>>(n&7)&e},Vl=function(t,n){var e=n/8|0;return(t[e]|t[e+1]<<8|t[e+2]<<16)>>(n&7)},S0=function(t){return(t+7)/8|0},Yi=function(t,n,e){return(n==null||n<0)&&(n=0),(e==null||e>t.length)&&(e=t.length),new De(t.subarray(n,e))};var E0=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Se=function(t,n,e){var r=new Error(n||E0[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,Se),!e)throw r;return r},C0=function(t,n,e,r){var i=t.length,s=r?r.length:0;if(!i||n.f&&!n.l)return e||new De(0);var a=!e,o=a||n.i!=2,d=n.i;a&&(e=new De(i*3));var c=function(ii){var si=e.length;if(ii>si){var ai=new De(Math.max(si*2,ii));ai.set(e),e=ai}},l=n.f||0,u=n.p||0,p=n.b||0,f=n.l,h=n.d,m=n.m,g=n.n,y=i*8;do{if(!f){l=ut(t,u,1);var w=ut(t,u+1,3);if(u+=3,w)if(w==1)f=T0,h=P0,m=9,g=5;else if(w==2){var P=ut(t,u,31)+257,C=ut(t,u+10,15)+4,E=P+ut(t,u+5,31)+1;u+=14;for(var M=new De(E),A=new De(19),N=0;N<C;++N)A[R0[N]]=ut(t,u+N*3,7);u+=C*3;for(var T=zl(A),I=(1<<T)-1,$=Ji(A,T,1),N=0;N<E;){var D=$[ut(t,u,I)];u+=D&15;var x=D>>4;if(x<16)M[N++]=x;else{var k=0,S=0;for(x==16?(S=3+ut(t,u,3),u+=2,k=M[N-1]):x==17?(S=3+ut(t,u,7),u+=3):x==18&&(S=11+ut(t,u,127),u+=7);S--;)M[N++]=k}}var _=M.subarray(0,P),q=M.subarray(P);m=zl(_),g=zl(q),f=Ji(_,m,1),h=Ji(q,g,1)}else Se(1);else{var x=S0(u)+4,v=t[x-4]|t[x-3]<<8,R=x+v;if(R>i){d&&Se(0);break}o&&c(p+v),e.set(t.subarray(x,R),p),n.b=p+=v,n.p=u=R*8,n.f=l;continue}if(u>y){d&&Se(0);break}}o&&c(p+131072);for(var K=(1<<m)-1,te=(1<<g)-1,le=u;;le=u){var k=f[Vl(t,u)&K],Y=k>>4;if(u+=k&15,u>y){d&&Se(0);break}if(k||Se(2),Y<256)e[p++]=Y;else if(Y==256){le=u,f=null;break}else{var Ae=Y-254;if(Y>264){var N=Y-257,Ee=qy[N];Ae=ut(t,u,(1<<Ee)-1)+Wy[N],u+=Ee}var St=h[Vl(t,u)&te],qt=St>>4;St||Se(3),u+=St&15;var q=A0[qt];if(qt>3){var Ee=Gy[qt];q+=Vl(t,u)&(1<<Ee)-1,u+=Ee}if(u>y){d&&Se(0);break}o&&c(p+131072);var ni=p+Ae;if(p<q){var ri=s-q,Fs=Math.min(q,ni);for(ri+p<0&&Se(3);p<Fs;++p)e[p]=r[ri+p]}for(;p<ni;++p)e[p]=e[p-q]}}n.l=f,n.p=le,n.b=p,n.f=l,f&&(l=1,n.m=m,n.d=h,n.n=g)}while(!l);return p!=e.length&&a?Yi(e,0,p):e.subarray(0,p)};var Wi=new De(0);var Pr=function(t,n){return t[n]|t[n+1]<<8},Sr=function(t,n){return(t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24)>>>0},Ul=function(t,n){return Sr(t,n)+Sr(t,n+4)*4294967296};var N0=(function(){function t(n,e){typeof n=="function"&&(e=n,n={}),this.ondata=e;var r=n&&n.dictionary&&n.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new De(32768),this.p=new De(0),r&&this.o.set(r)}return t.prototype.e=function(n){if(this.ondata||Se(5),this.d&&Se(4),!this.p.length)this.p=n;else if(n.length){var e=new De(this.p.length+n.length);e.set(this.p),e.set(n,this.p.length),this.p=e}},t.prototype.c=function(n){this.s.i=+(this.d=n||!1);var e=this.s.b,r=C0(this.p,this.s,this.o);this.ondata(Yi(r,e,this.s.b),this.d),this.o=Yi(r,this.s.b-32768),this.s.b=this.o.length,this.p=Yi(this.p,this.s.p/8|0),this.s.p&=7},t.prototype.push=function(n,e){this.e(n),this.c(e)},t})();var Gl=typeof TextDecoder<"u"&&new TextDecoder,O0=0;try{Gl.decode(Wi,{stream:!0}),O0=1}catch{}var $0=function(t){for(var n="",e=0;;){var r=t[e++],i=(r>127)+(r>223)+(r>239);if(e+i>t.length)return{s:n,r:Yi(t,e-1)};i?i==3?(r=((r&15)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,n+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?n+=String.fromCharCode((r&31)<<6|t[e++]&63):n+=String.fromCharCode((r&15)<<12|(t[e++]&63)<<6|t[e++]&63):n+=String.fromCharCode(r)}};function D0(t,n){if(n){for(var e="",r=0;r<t.length;r+=16384)e+=String.fromCharCode.apply(null,t.subarray(r,r+16384));return e}else{if(Gl)return Gl.decode(t);var i=$0(t),s=i.s,e=i.r;return e.length&&Se(8),s}}var L0=function(t,n,e,r,i,s,a){var o=i==4294967295,d=s==4294967295,c=a==4294967295,l=n+e,u=o+d+c;if(r&&u){for(;n+4<l;n+=4+Pr(t,n+2))if(Pr(t,n)==1)return[o?Ul(t,n+4+8*d):i,d?Ul(t,n+4):s,c?Ul(t,n+4+8*(d+o)):a,1];r<2&&Se(13)}return[i,s,a,0]};var M0=(function(){function t(){}return t.prototype.push=function(n,e){this.ondata(null,n,e)},t.compression=0,t})();var Xy=(function(){function t(){var n=this;this.i=new N0(function(e,r){n.ondata(null,e,r)})}return t.prototype.push=function(n,e){try{this.i.push(n,e)}catch(r){this.ondata(r,null,e)}},t.compression=8,t})();var Qy=(function(){function t(n){this.onfile=n,this.k=[],this.o={0:M0},this.p=Wi}return t.prototype.push=function(n,e){var r=this;if(this.onfile||Se(5),this.p||Se(4),this.c>0){var i=Math.min(this.c,n.length),s=n.subarray(0,i);if(this.c-=i,this.d?this.d.push(s,!this.c):this.k[0].push(s),n=n.subarray(i),n.length)return this.push(n,e)}else{var a=0,o=0,d=void 0,c=void 0;this.p.length?n.length?(c=new De(this.p.length+n.length),c.set(this.p),c.set(n,this.p.length)):c=this.p:c=n;for(var l=c.length,u=this.c,p=u&&this.d,f=function(){var y=Sr(c,o);if(y==67324752){a=1,d=o,h.d=null,h.c=0;var w=Pr(c,o+6),x=Pr(c,o+8),v=w&2048,R=w&8,P=Pr(c,o+26),C=Pr(c,o+28);if(l>o+30+P+C){var E=[];h.k.unshift(E),a=2;var M=Sr(c,o+18),A=Sr(c,o+22),N=D0(c.subarray(o+30,o+=30+P),!v),T=L0(c,o,C,2,M,A,0),I=T[0],$=T[1],D=T[3];R&&(I=-1-D),o+=C,h.c=I;var k,S={name:N,compression:x,start:function(){if(S.ondata||Se(5),!I)S.ondata(null,Wi,!0);else{var _=r.o[x];_||S.ondata(Se(14,"unknown compression type "+x,1),null,!1),k=I<0?new _(N):new _(N,I,$),k.ondata=function(le,Y,Ae){S.ondata(le,Y,Ae)};for(var q=0,K=E;q<K.length;q++){var te=K[q];k.push(te,!1)}r.k[0]==E&&r.c?r.d=k:k.push(Wi,!0)}},terminate:function(){k&&k.terminate&&k.terminate()}};I>=0&&(S.size=I,S.originalSize=$),h.onfile(S)}return"break"}else if(u){if(y==134695760)return d=o+=12+(u==-2&&8),a=3,h.c=0,"break";if(y==33639248)return d=o-=4,a=3,h.c=0,"break"}},h=this;o<l-4;++o){var m=f();if(m==="break")break}if(this.p=Wi,u<0){var g=a?c.subarray(0,d-12-(u==-2&&8)-(Sr(c,d-16)==134695760&&4)):c.subarray(0,o);p?p.push(g,!!a):this.k[+(a==2)].push(g)}if(a&2)return this.push(c.subarray(o),e);this.p=c.subarray(o)}e&&(this.c&&Se(13),this.p=null)},t.prototype.register=function(n){this.o[n.compression]=n},t})();var Zy=65536;function _0(t,n){let e=new Uint8Array(n),r=0;for(let i of t)e.set(i,r),r+=i.length;return e}function ro(t,n,e){if(t.byteLength===0)return{kind:"unreadable",message:"Archive is empty."};if(t[0]!==80||t[1]!==75)return{kind:"unreadable",message:"Archive does not begin with a ZIP signature."};let r=new Map,i=[],s=0,a=0,o,d=new Set,c=new Qy;c.register(Xy),c.onfile=l=>{let u=l.name,p=typeof l.originalSize=="number"&&l.originalSize>0,f=l.originalSize??0;if(!Ic(u)){i.push({entry:u,reason:"unsafe-entry-name",declaredBytes:f});return}if(!e(u))return;if(d.has(u)){i.push({entry:u,reason:"duplicate-selected-name",declaredBytes:f});return}if(s>=n.maxEntries){i.push({entry:u,reason:"entry-budget-exceeded",declaredBytes:f});return}let h=n.maxExpandedBytes-a;if(p&&f>h){i.push({entry:u,reason:"expanded-budget-exceeded",declaredBytes:f});return}s+=1,d.add(u);let m=[],g=0,y=!1;l.ondata=(w,x,v)=>{if(o!==void 0||y)return;if(w!==null){o=`Archive entry ${u} could not be inflated.`;return}g+=x.length;let R=p&&g>f;if(R||g>h){y=!0,m.length=0,i.push({entry:u,reason:R?"declared-size-mismatch":"expanded-budget-exceeded",declaredBytes:f});return}if(m.push(x.slice()),v){if(p&&g!==f){m.length=0,y=!0,i.push({entry:u,reason:"declared-size-mismatch",declaredBytes:f});return}a+=g,r.set(u,_0(m,g))}},l.start()};try{for(let l=0;l<t.byteLength;l+=Zy){let u=Math.min(l+Zy,t.byteLength);if(c.push(t.subarray(l,u),u===t.byteLength),o!==void 0)break}}catch{return{kind:"unreadable",message:"Archive could not be read as a ZIP container."}}return o!==void 0?{kind:"unreadable",message:o}:{kind:"read",contents:{entries:r,skipped:i}}}var eg=256,tg={before:"before",action:"action",input:"action",after:"after"};function Kl(t){return Array.isArray(t)&&typeof t[0]=="string"}function j0(t){return Array.isArray(t)&&Array.isArray(t[0])&&typeof t[0][0]=="number"&&typeof t[0][1]=="number"}function ng(t){let n=t[1],e=typeof n=="object"&&n!==null&&!Array.isArray(n);return t.slice(e?2:1)}function F0(t){let n=H(t.snapshotName),e=H(t.callId),r=tg[H(t.phase)??""];if(n!==void 0){let i=n.indexOf("@");i>0&&(r??=tg[n.slice(0,i)],e??=n.slice(i+1))}return{...e===void 0?{}:{callId:e},...r===void 0?{}:{phase:r},...n===void 0?{}:{name:n}}}var io=class{frames=new Map;literals=new Map;byCall=new Map;add(n,e,r){let i=me(r.snapshot);if(i===void 0||i.html===void 0)return;let s=F0(i),a=H(i.frameId)??H(i.pageId)??"unknown-frame",o=`${n}
133
133
  ${a}`,d=this.frames.get(o)??[],c=H(i.frameUrl),l={entry:n,line:e,frameId:a,index:d.length,snapshotId:s.name??(s.callId===void 0?`${n}#line=${e}`:`${s.phase??"snapshot"}@${s.callId}`),...s.callId===void 0?{}:{callId:s.callId},...s.phase===void 0?{}:{phase:s.phase},...c===void 0?{}:{frameUrl:c},isMainFrame:By(i.isMainFrame)??!0,html:i.html};if(d.push(l),this.frames.set(o,d),l.callId!==void 0){let u=this.byCall.get(l.callId)??[];u.push(l),this.byCall.set(l.callId,u)}return l}forCall(n){return this.byCall.get(n)??[]}get size(){let n=0;for(let e of this.frames.values())n+=e.length;return n}literalNodes(n){let e=this.literals.get(n);if(e!==void 0)return e;let r=[],i=(s,a)=>{if(typeof s=="string"){r.push(s);return}if(!(!Kl(s)||a>eg)){for(let o of ng(s))i(o,a+1);r.push(s)}};return i(n.html,0),this.literals.set(n,r),r}rebuild(n,e){let r=this.frames.get(`${n.entry}
134
134
  ${n.frameId}`)??[],i=0,s=!1,a=(d,c,l)=>{if(i>=e||l>eg){s=!0;return}if(typeof d=="string")return i+=1,d;if(j0(d)){let[h,m]=d[0],g=c-h,y=r[g];if(h<1||y===void 0)return;let w=this.literalNodes(y)[m];return w===void 0?void 0:a(w,g,l)}if(!Kl(d))return;i+=1;let u=d[1],p=typeof u=="object"&&u!==null&&!Array.isArray(u)?u:{},f=[];for(let h of ng(d)){let m=a(h,c,l+1);m!==void 0&&f.push(m)}return[d[0],p,...f]},o=a(n.html,n.index,0);return{...Kl(o)?{root:o}:{},truncated:s,nodes:i}}};var Dn=["trace","console","network","dom","accessibility"],Wl=/(?:^|\/)(?:\d+-)?(?:trace|test)\.trace$/,so=/(?:^|\/)(?:\d+-)?trace\.network$/,Jl=/(?:^|\/)(?:\d+-)?trace\.stacks$/,Ln=512,Ql=2e3,og=200,B0=2,Yl=5e4,Xl=25,H0=new Set(["screencast-frame","object","resource","input"]),re={failure:5,failedCall:4,significant:3,context:2,ordinary:1,afterFailure:0};function z0(t,n){switch(n){case"console":return t.maxConsoleEvents;case"network":return t.maxNetworkEvents;case"dom":case"accessibility":return t.maxDomNodes;default:return t.maxTraceEvents}}function oe(t,n,e,r,i,s){t.omissions.push({omissionId:B("omi",[t.input.attemptId,n,e,i??"",r]),channel:n,reason:e,message:r,...i===void 0?{}:{locator:i},...s===void 0?{}:{cap:s}})}function ao(t,n,e,r,i,s,a){let o=t.channels[n].artifact,d=we(t.runId,o.artifactId,e,r,i);t.evidence.push({evidenceId:d,kind:e,artifactId:o.artifactId,logicalTestId:t.input.logicalTestId,attemptId:t.input.attemptId,locator:r,observation:i,availability:i.length===0?"empty":"present",redactionIds:s.map(c=>c.redactionId)}),t.redactions.push(...s),t.priorities.set(d,a),t.channels[n].included+=1}function Qi(t,n,e,r){let i=ce(r,n,e,t.policy.sensitiveNames);return{value:i.value,records:i.records}}function rg(t){let n=tt(t);if(n===void 0)return[];let e=[];for(let r of n){let i=me(r),s=H(i?.name);s!==void 0&&e.push({name:s,value:H(i?.value)??""})}return e}function V0(t){let n=H(t.type);if(n==="console")return{type:H(t.messageType)??"log",text:H(t.text)??xe(t.args,Ql)};if(n!=="event"||!(H(t.class)==="ConsoleMessage"||H(t.method)==="console"))return;let r=me(t.params);return{type:H(r?.type)??H(r?.messageType)??"log",text:H(r?.text)??xe(r,Ql)}}function Zi(t){let n=me(t.error);return H(n?.message)??H(me(n?.error)?.message)}function dg(t){return t===void 0?"unknown":H(t.apiName)??([H(t.class),H(t.method)].filter(Boolean).join(".")||"unknown")}function U0(t){let n=me(t?.params);return H(n?.selector)}function q0(t,n){let e=H(t.type),r=dg(e==="after"?n??t:t),i=H(t.title),s=t.params===void 0?"":` params=${xe(t.params,Ln)}`,a=Zi(t),o=a===void 0?"":` error=${xe(a,Ln)}`;switch(e){case"before":return`action started: ${r}${i===void 0?"":` "${xe(i,120)}"`}${s}`;case"after":return`action finished: ${r}${o}`;case"action":return`action: ${r}${s}${o}`;case"log":return`log: ${xe(t.message,Ln)}`;case"error":return`error: ${xe(t.message,Ln)}`;case"stdout":case"stderr":return`${e}: ${xe(t.text,Ln)}`;case"context-options":return`context options: ${xe({browserName:H(t.browserName),platform:H(t.platform),playwrightVersion:H(t.playwrightVersion),sdkLanguage:H(t.sdkLanguage)},Ln)}`;case"event":return`event: ${r}${s}`;default:return}}function G0(t){return Pe(t.startTime)??Pe(t.endTime)??Pe(t.time)}function K0(t,n,e){let r=qe(e);if(r===void 0){t.channels.trace.failed=!0,oe(t,"trace","unreadable",`${n} is not valid UTF-8.`,n);return}let i=to(r);i.length===0&&(t.channels.trace.parsed=!0);let s=new Set;for(let a of i){let o=`${n}#line=${a.line}`;if(!a.parsed){t.channels.trace.failed=!0,oe(t,"trace","parse-failed",`${o} is not valid JSON.`,o);continue}let d=me(a.value),c=H(d?.type);if(d===void 0||c===void 0){t.channels.trace.failed=!0,oe(t,"trace","unrecognized",`${o} is not a typed trace event.`,o);continue}if(t.channels.trace.parsed=!0,c==="frame-snapshot"){t.snapshots.add(n,a.line,d)===void 0&&oe(t,"dom","unrecognized",`${o} does not carry a readable frame snapshot.`,o);continue}if(c==="resource-snapshot"){lg(t,n,a.line,d,new Map);continue}let l=G0(d);if(c==="error"){l!==void 0&&t.errorTimes.push(l);for(let y of tt(d.stack)??[]){if(t.seeds.length>=og)break;let w=me(y),x=H(w?.file),v=Pe(w?.line);if(x===void 0||v===void 0)continue;let R=Pe(w?.column);t.seeds.push({file:x,line:v,...R===void 0?{}:{column:R},origin:`${n}#line=${a.line}:error`,logicalTestId:t.input.logicalTestId,attemptId:t.input.attemptId})}}let u=V0(d);if(u!==void 0){let y=Qi(t,"console",o,`console.${u.type}: ${xe(u.text,Ql)}`);t.candidates.push({channel:"console",kind:"console-event",locator:{type:"trace-event",entry:n,line:a.line,eventType:"console",...l===void 0?{}:{timestamp:l}},locatorText:o,observation:y.value,redactions:y.records,order:t.candidates.length,...l===void 0?{}:{time:l},error:u.type==="error"||u.type==="warning"});continue}if(H0.has(c))continue;let p=H(d.callId),f=p===void 0?void 0:`${n}
135
135
  ${p}`;if(f!==void 0&&p!==void 0){if(c==="before")t.actions.set(f,{callId:p,entry:n,before:{line:a.line,event:d}});else if(c==="after"){let y=t.actions.get(f)??{callId:p,entry:n};y.after={line:a.line,event:d},t.actions.set(f,y);let w=Pe(d.endTime);Zi(d)!==void 0&&w!==void 0&&t.errorTimes.push(w)}}let h=f===void 0?void 0:t.actions.get(f)?.before,m=q0(d,h?.event);if(m===void 0){s.add(c);continue}let g=Qi(t,"trace",o,m);t.candidates.push({channel:"trace",kind:"trace-event",locator:{type:"trace-event",entry:n,line:a.line,eventType:c,...p===void 0?{}:{eventId:p},...l===void 0?{}:{timestamp:l}},locatorText:o,observation:g.value,redactions:g.records,order:t.candidates.length,...l===void 0?{}:{time:l},...p===void 0?{}:{callId:p},error:c==="error"||Zi(d)!==void 0})}for(let a of[...s].sort())oe(t,"trace","unrecognized",`Trace event type ${a} is not interpreted by this adapter.`,n)}function W0(t){let n=[];for(let e of t.actions.values()){let r=U0(e.before?.event);if(r===void 0||e.before===void 0||H(e.before.event.class)==="Test")continue;let i=e.after!==void 0&&Zi(e.after.event)!==void 0,s=e.after===void 0;!i&&!s||n.push({callId:e.callId,entry:e.entry,selector:r,apiName:dg(e.before.event),time:Pe(e.before.event.startTime)??0,unfinished:s})}return n.sort((e,r)=>r.time-e.time||e.callId.localeCompare(r.callId))}function J0(t){let n={after:3,action:2,before:1};return[...t].filter(e=>e.isMainFrame||t.length===1).sort((e,r)=>(n[r.phase??"before"]??0)-(n[e.phase??"before"]??0)||r.line-e.line)[0]}function Y0(t,n){let e=J0(t.snapshots.forCall(n.callId)),r=`${n.apiName} on ${n.selector}`;if(e===void 0){oe(t,"dom","unavailable",`No DOM snapshot was recorded for the failed ${r}.`,`${n.entry}#${n.callId}`);return}let i=t.snapshots.rebuild(e,Yl),s=`${e.entry}#${e.snapshotId}`;if(i.root===void 0){oe(t,"dom","unreadable",`Snapshot ${e.snapshotId} could not be rebuilt.`,s);return}i.truncated&&oe(t,"dom","budget-exceeded",`Snapshot ${e.snapshotId} was rebuilt only up to ${Yl} nodes.`,s,Yl);let a={maxDepth:t.policy.maxDomDepth,maxNodes:t.policy.maxDomNodes,maxBytes:t.policy.maxDomTextBytes,sensitiveNames:t.policy.sensitiveNames},o=Uy(i.root,n.callId),d=qi(i.root,n.selector),c=d.kind==="resolved"?d.matches:void 0,l=o!==void 0&&(c===void 0||c.length<=1)?[o]:c??[],u=e.phase??"snapshot";if(l.length===1&&l[0]!==void 0){let h=l[0],m=Gi(h.node,s,a);ao(t,"dom","dom-subtree",{type:"dom-node",snapshotId:e.snapshotId,nodePath:h.path},`${u} snapshot of the element targeted by the failed ${r}:
@@ -141,102 +141,102 @@ ${S.text}`,S.redactions,re.significant),S.truncated&&p("dom","budget-exceeded",`
141
141
  `)}),r=void 0};for(let s of t.split(/\r?\n/)){if(s.startsWith("diff --git ")){i(),e=void 0;continue}if(s.startsWith("+++ ")){i();let o=s.slice(4).trim();e=o==="/dev/null"?void 0:o.replace(/^b\//,"");continue}let a=fE.exec(s);if(a!==null){i(),r={header:a,lines:[s]};continue}r!==void 0&&r.lines.push(s)}return i(),n}function Mn(t,n,e,r){return{omissionId:B("omi",["diff",t,e??"",n]),channel:"diff",reason:t,message:n,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function mE(t,n,e){let r=["-C",t,"--no-optional-locks","-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-renames","--unified=3","HEAD","--",...n];try{return{text:(await pE("git",r,{timeout:hE,maxBuffer:e,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(i){let s=i;if(s.code==="ENOENT")return{error:"git executable was not found."};let a=(s.stderr??s.message??"").trim().split(`
142
142
  `)[0]??"";return{error:a===""?"git diff failed.":a}}}async function mg(t,n,e,r){let i=Ie(t,"diff",r.gitRoot??n.workspaceRoot),s=(v,R=[])=>({artifactId:i,channel:"diff",availability:v,...r.gitRoot===void 0?{}:{path:r.gitRoot},format:"git-unified-diff",warnings:R});if(!r.authorized)return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[Mn("policy-disabled","Current-diff selection was not authorized for this run.")]};if(r.gitRoot===void 0)return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[Mn("unavailable","The workspace has no containing git repository root.")]};let a=oo(r.workspaceRoot??r.gitRoot),o=oo(r.gitRoot),d=tu(o,a);if(d===".."||d.startsWith(`..${nu}`))return{artifacts:[s("unavailable")],evidence:[],redactions:[],omissions:[Mn("unauthorized-path","The authorized workspace is outside the configured git root.",a)]};let c=[...new Set(e.map(v=>{let R=uE(v)?oo(v):oo(a,v),P=tu(o,R).split(nu).join("/");return P===""||P.startsWith("../")||P===".."?void 0:P}).filter(v=>v!==void 0))].sort();if(c.length===0)return{artifacts:[s("empty")],evidence:[],redactions:[],omissions:[Mn("irrelevant","No evidence-bearing file was eligible for diff selection.")]};let l=Math.max(n.maxDiffBytes*4,1e6),u=await mE(o,c,l);if("error"in u)return{artifacts:[s("unreadable",[u.error])],evidence:[],redactions:[],omissions:[Mn("unreadable",u.error,r.gitRoot)]};let p=a===o?"":`${tu(o,a).split(nu).join("/")}/`,f=co(u.text).map(v=>({...v,path:p!==""&&v.path.startsWith(p)?v.path.slice(p.length):v.path}));if(f.length===0)return{artifacts:[s("empty")],evidence:[],redactions:[],omissions:[]};let h=[],m=[],g=[],y=0,w=!1,x=!1;for(let v of f){if(h.length>=n.maxDiffHunks){w||(w=!0,g.push(Mn("budget-exceeded",`Reached the ${n.maxDiffHunks}-hunk limit; later hunks were not included.`,v.path,n.maxDiffHunks)));break}let R=`${v.path}@${v.newStart}`,P=ce(v.body,"diff",R,n.sensitiveNames),C=Buffer.byteLength(P.value,"utf8");if(y+C>n.maxDiffBytes){x||(x=!0,g.push(Mn("budget-exceeded",`Reached the ${n.maxDiffBytes}-byte diff limit; later hunks were not included.`,v.path,n.maxDiffBytes)));break}y+=C,m.push(...P.records);let E={type:"diff-hunk",path:v.path,oldStart:v.oldStart,oldLines:v.oldLines,newStart:v.newStart,newLines:v.newLines};h.push({evidenceId:we(t,i,"diff-hunk",E,P.value),kind:"diff-hunk",artifactId:i,locator:E,observation:P.value,availability:"present",redactionIds:P.records.map(M=>M.redactionId)})}return{artifacts:[s("present")],evidence:h,redactions:m,omissions:g}}var xE=bE(yE),vE=1e4,kE=4e6,RE=16,Tg=3,IE=120,gg=50,wg=20,bg=30,ru=12,xg=24e3,iu=40,Pg=20,vg=120,Sg=1440*60*1e3,AE=new Set(["alert","article","button","cell","checkbox","combobox","dialog","false","heading","hidden","img","link","list","listitem","main","menu","menuitem","navigation","null","option","radio","region","row","status","tab","table","textbox","true","undefined","visible"]),Eg=/\.(?:[cm]?[jt]sx?|vue|svelte|astro|html?|css|scss|sass|less|json|ya?ml|py|rb|php|java|kt|cs|go|rs|swift|erb|hbs|ejs|pug|liquid|twig|jinja2?|properties|po|xliff|xlf|strings|resx)$/i,Cg=/(?:^|\/)(?:node_modules|dist|build|out|coverage|vendor|\.next|\.nuxt|\.svelte-kit|\.kwikqa|__snapshots__|test-results|playwright-report|\.git)\/|(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock)$|\.min\.[cm]?js$|\.map$/,TE=/\u001b\[[0-9;]*m/g,kg=/"([^"\n]{3,120})"|'([^'\n]{3,120})'|`([^`\n]{3,120})`/g,PE=/^\s*(?:Expected|Received)(?: string| pattern| value)?:\s*(.+)$/gm,SE=/^(?:[A-Z]+|request) (\S+) (?:-> (\d{3})|failure=)/;function EE(t){let n=t.trim();return/^(["'`])(.*)\1$/.exec(n)?.[2]??n}function Rg(t){let n=t.trim();if(!(n.length<Tg||n.length>IE)&&!AE.has(n.toLowerCase())&&!(/^[\d\s.,:%$-]+$/.test(n)&&!/^[$€£]?\d+[.,]\d+$/.test(n))&&!/^(?:\/|[A-Za-z]:\\|file:)|\.(?:spec|test|cy)\.[cm]?[jt]sx?\b|node_modules|:\d+:\d+/.test(n))return n}function su(t){let n=[];for(let e of t.matchAll(/\[[\w-]+[~|^$*]?=\s*["']?([^"'\]]+)["']?\]/g))n.push(e[1]??"");for(let e of t.matchAll(/[#.]([A-Za-z][\w-]{2,})/g))n.push(e[1]??"");return n}var CE=8;function NE(t){let n=t.trim().split(/\s+/);if(n.length<3)return[];let e=[];for(let r=0;r+1<n.length;r+=1){let i=`${n[r]} ${n[r+1]}`;(i.match(new RegExp("\\p{L}","gu"))??[]).length>=CE&&e.push(i)}return e}function OE(t){let n;try{n=new URL(t,"http://localhost").pathname}catch{return}if(/\.(?:js|css|png|jpe?g|gif|svg|ico|woff2?|map)$/i.test(n))return;let e=[];for(let i of n.split("/").filter(Boolean)){if(/^\d+$|^[0-9a-f-]{16,}$|^[0-9a-f]{8,}$/i.test(i))break;e.push(i)}let r=`/${e.join("/")}`;return e.length===0?void 0:r}function Ng(t,n,e=[]){let r=[],i=[];for(let c of t){for(let l of n(c)){for(let u of l.matchAll(kg)){let p=u[1]??u[2]??u[3]??"";r.push(p,...su(p))}/[('"`]/.test(l)||r.push(...su(l))}for(let l of c.errors){let u=(l.message??"").replace(TE,"");for(let f of u.matchAll(PE)){let h=EE(f[1]??"");r.push(h),i.push(h)}let p=u.split(`
143
143
  `).slice(0,6).join(`
144
- `);for(let f of p.matchAll(kg)){let h=f[1]??f[2]??f[3]??"",m=/^[[#.]/.test(h)?su(h):[];r.push(...m.length>0?m:[h]),m.length===0&&i.push(h)}}}let s=[];for(let c of e){let l=SE.exec(c);if(l===null)continue;let u=l[2]===void 0?void 0:Number(l[2]);if(u!==void 0&&u<400)continue;let p=OE(l[1]??"");p!==void 0&&p.length>=Tg&&s.push(p)}let a=c=>[...new Set(c)].sort((l,u)=>u.length-l.length||l.localeCompare(u)),o=a([...r.map(Rg).filter(c=>c!==void 0),...s]),d=a(i.flatMap(NE).map(Rg).filter(c=>c!==void 0&&!o.includes(c)));return[...o,...d].slice(0,RE)}function $E(t){return t.map(n=>n.replace(/[.[\]{}()\\*+?^$|]/g,"\\$&")).join("|")}async function Er(t,n){try{return{text:(await xE("git",["-C",t,"--no-optional-locks","-c","core.quotePath=false",...n],{timeout:vE,maxBuffer:kE,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(e){let r=e;if(r.code==="ENOENT")return{error:"git executable was not found."};if(r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{error:"The matching changes are too large to read."};let i=(r.stderr??r.message??"").trim().split(`
145
- `)[0]??"";return{error:i===""?"git failed.":i}}}async function es(t,n){let e=await Er(t,n);if("error"in e)return;let r=e.text.trim();return r===""?void 0:r}async function DE(t){let n=await es(t,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]);if(n!==void 0)return n;for(let e of["main","master","origin/main","origin/master"])if(await es(t,["rev-parse","--verify","--quiet",`${e}^{commit}`])!==void 0)return e}async function LE(t,n){let e=await es(t,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(e===void 0)return;let r=await DE(t),i=r===void 0?void 0:await es(t,["merge-base","HEAD",r]);if(r!==void 0&&i!==void 0&&i!==e)return{logArgs:[`--max-count=${gg}`,`${i}..HEAD`],description:`the commits on this branch since it left ${r} (at most ${gg})`};let s=Date.parse(n),a=new Date((Number.isNaN(s)?0:s)-bg*Sg).toISOString();return{logArgs:[`--max-count=${wg}`,`--since=${a}`,"HEAD"],description:`the last ${wg} commits from the ${bg} days before the run`}}function Og(t,n){let e=Date.parse(n);if(Number.isNaN(e))return"";let r=Math.floor((e-t)/Sg);return r<0?", after the run":r===0?", the day of the run":`, ${r} day${r===1?"":"s"} before the run`}function ME(t,n){let e=t.split(`
144
+ `);for(let f of p.matchAll(kg)){let h=f[1]??f[2]??f[3]??"",m=/^[[#.]/.test(h)?su(h):[];r.push(...m.length>0?m:[h]),m.length===0&&i.push(h)}}}let s=[];for(let c of e){let l=SE.exec(c);if(l===null)continue;let u=l[2]===void 0?void 0:Number(l[2]);if(u!==void 0&&u<400)continue;let p=OE(l[1]??"");p!==void 0&&p.length>=Tg&&s.push(p)}let a=c=>[...new Set(c)].sort((l,u)=>u.length-l.length||l.localeCompare(u)),o=a([...r.map(Rg).filter(c=>c!==void 0),...s]),d=a(i.flatMap(NE).map(Rg).filter(c=>c!==void 0&&!o.includes(c)));return[...o,...d].slice(0,RE)}function $E(t){return t.map(n=>n.replace(/[.[\]{}()\\*+?^$|]/g,"\\$&")).join("|")}async function Cr(t,n){try{return{text:(await xE("git",["-C",t,"--no-optional-locks","-c","core.quotePath=false",...n],{timeout:vE,maxBuffer:kE,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}}catch(e){let r=e;if(r.code==="ENOENT")return{error:"git executable was not found."};if(r.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{error:"The matching changes are too large to read."};let i=(r.stderr??r.message??"").trim().split(`
145
+ `)[0]??"";return{error:i===""?"git failed.":i}}}async function es(t,n){let e=await Cr(t,n);if("error"in e)return;let r=e.text.trim();return r===""?void 0:r}async function DE(t){let n=await es(t,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]);if(n!==void 0)return n;for(let e of["main","master","origin/main","origin/master"])if(await es(t,["rev-parse","--verify","--quiet",`${e}^{commit}`])!==void 0)return e}async function LE(t,n){let e=await es(t,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(e===void 0)return;let r=await DE(t),i=r===void 0?void 0:await es(t,["merge-base","HEAD",r]);if(r!==void 0&&i!==void 0&&i!==e)return{logArgs:[`--max-count=${gg}`,`${i}..HEAD`],description:`the commits on this branch since it left ${r} (at most ${gg})`};let s=Date.parse(n),a=new Date((Number.isNaN(s)?0:s)-bg*Sg).toISOString();return{logArgs:[`--max-count=${wg}`,`--since=${a}`,"HEAD"],description:`the last ${wg} commits from the ${bg} days before the run`}}function Og(t,n){let e=Date.parse(n);if(Number.isNaN(e))return"";let r=Math.floor((e-t)/Sg);return r<0?", after the run":r===0?", the day of the run":`, ${r} day${r===1?"":"s"} before the run`}function ME(t,n){let e=t.split(`
146
146
  `);if(e.length<=iu+1)return t;let[r,...i]=e,s=Math.max(0,i.findIndex(n)),a=Math.max(0,Math.min(s-10,i.length-iu)),o=i.slice(a,a+iu),d=a,c=i.length-a-o.length;return[r??"",...d>0?[`\u2026 ${d} earlier line${d===1?"":"s"} of this hunk left out`]:[],...o,...c>0?[`\u2026 ${c} later line${c===1?"":"s"} of this hunk left out`]:[]].join(`
147
147
  `)}function $g(t,n,e){let r=au(t,e),i=wE(n,r);if(!(i===""||i===".."||i.startsWith(`..${yg}`)||gE(i)))return i.split(yg).join("/")}function Ig(t,n,e,r,i){let s=a=>(a.startsWith("+")||a.startsWith("-"))&&r.some(o=>a.includes(o));return co(t).flatMap(a=>{let o=$g(n,e,a.path);return o===void 0||!Eg.test(o)||Cg.test(o)?[]:a.body.split(`
148
- `).slice(1).some(s)?[{...i===void 0?{}:{commit:i.id},heading:i?.heading??"Uncommitted change",path:o,oldStart:a.oldStart,oldLines:a.oldLines,newStart:a.newStart,newLines:a.newLines,body:ME(a.body,s)}]:[]})}async function _E(t,n,e){let r=await Er(t,["log","--no-merges","--no-show-signature","--format=%h%x1f%ct%x1f%s",...n.logArgs,"--"]);if("error"in r)return{listed:[],total:0};let i=r.text.split(`
149
- `).filter(a=>a.includes(""));return{listed:i.slice(0,Pg).map(a=>{let[o="",d="0",c=""]=a.split(""),l=c.length>vg?`${c.slice(0,vg)}\u2026`:c;return`${o}${Og(Number(d)*1e3,e)}: ${l}`}),total:i.length}}async function jE(t,n){let e=await Er(t,["diff","--name-only","--no-renames","HEAD","--"]),r=await Er(t,["ls-files","--others","--exclude-standard","--"]),i=[e,r].flatMap(s=>"error"in s?[]:s.text.split(`
150
- `).filter(a=>a!==""));return[...new Set(i.map(s=>$g(t,n,s)).filter(s=>s!==void 0&&Eg.test(s)&&!Cg.test(s)))].sort().slice(0,Pg)}var Ag=["--no-color","--no-ext-diff","--no-renames","--unified=3","--src-prefix=a/","--dst-prefix=b/"];function lo(t,n,e,r){return{omissionId:B("omi",["changes",t,e??"",n]),channel:"diff",reason:t,message:n,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function Dg(t,n,e,r,i){let s=Ie(t,"diff",`changes:${i.gitRoot??i.workspaceRoot}`),a=(T,I=[])=>({artifactId:s,channel:"diff",availability:T,...i.gitRoot===void 0?{}:{path:i.gitRoot},format:"git-change-search",warnings:I}),o=(T,I)=>({artifacts:[a(T==="irrelevant"?"empty":"unavailable")],evidence:[],redactions:[],omissions:[lo(T,I)]});if(!i.authorized)return o("policy-disabled","Recent changes were not included (--no-changes).");if(i.gitRoot===void 0)return o("unavailable","The workspace is not in a git repository, so no changes were searched.");if(r.length===0)return o("irrelevant","The failures name no locator, value, or request path to look for in recent changes.");let d=au(i.gitRoot),c=au(i.workspaceRoot),l=$E(r),u=[];await es(d,["rev-parse","--is-shallow-repository"])==="true"&&u.push("This is a shallow clone; only the history it has was searched.");let p=[],f=[],h=await Er(d,["diff",...Ag,`-G${l}`,"HEAD","--"]);"error"in h?f.push(h.error):p.push(...Ig(h.text,d,c,r,void 0));let m=await LE(d,n),g=0;if(m!==void 0){let T=await Er(d,["log",...Ag,"--no-merges","--no-show-signature","--format=%x1e%h%x1f%ct%x1f%s",`-G${l}`,...m.logArgs,"--"]);if("error"in T)f.push(T.error);else for(let I of T.text.split("").slice(1)){let $=I.indexOf(`
148
+ `).slice(1).some(s)?[{...i===void 0?{}:{commit:i.id},heading:i?.heading??"Uncommitted change",path:o,oldStart:a.oldStart,oldLines:a.oldLines,newStart:a.newStart,newLines:a.newLines,body:ME(a.body,s)}]:[]})}async function _E(t,n,e){let r=await Cr(t,["log","--no-merges","--no-show-signature","--format=%h%x1f%ct%x1f%s",...n.logArgs,"--"]);if("error"in r)return{listed:[],total:0};let i=r.text.split(`
149
+ `).filter(a=>a.includes(""));return{listed:i.slice(0,Pg).map(a=>{let[o="",d="0",c=""]=a.split(""),l=c.length>vg?`${c.slice(0,vg)}\u2026`:c;return`${o}${Og(Number(d)*1e3,e)}: ${l}`}),total:i.length}}async function jE(t,n){let e=await Cr(t,["diff","--name-only","--no-renames","HEAD","--"]),r=await Cr(t,["ls-files","--others","--exclude-standard","--"]),i=[e,r].flatMap(s=>"error"in s?[]:s.text.split(`
150
+ `).filter(a=>a!==""));return[...new Set(i.map(s=>$g(t,n,s)).filter(s=>s!==void 0&&Eg.test(s)&&!Cg.test(s)))].sort().slice(0,Pg)}var Ag=["--no-color","--no-ext-diff","--no-renames","--unified=3","--src-prefix=a/","--dst-prefix=b/"];function lo(t,n,e,r){return{omissionId:B("omi",["changes",t,e??"",n]),channel:"diff",reason:t,message:n,...e===void 0?{}:{locator:e},...r===void 0?{}:{cap:r}}}async function Dg(t,n,e,r,i){let s=Ie(t,"diff",`changes:${i.gitRoot??i.workspaceRoot}`),a=(T,I=[])=>({artifactId:s,channel:"diff",availability:T,...i.gitRoot===void 0?{}:{path:i.gitRoot},format:"git-change-search",warnings:I}),o=(T,I)=>({artifacts:[a(T==="irrelevant"?"empty":"unavailable")],evidence:[],redactions:[],omissions:[lo(T,I)]});if(!i.authorized)return o("policy-disabled","Recent changes were not included (--no-changes).");if(i.gitRoot===void 0)return o("unavailable","The workspace is not in a git repository, so no changes were searched.");if(r.length===0)return o("irrelevant","The failures name no locator, value, or request path to look for in recent changes.");let d=au(i.gitRoot),c=au(i.workspaceRoot),l=$E(r),u=[];await es(d,["rev-parse","--is-shallow-repository"])==="true"&&u.push("This is a shallow clone; only the history it has was searched.");let p=[],f=[],h=await Cr(d,["diff",...Ag,`-G${l}`,"HEAD","--"]);"error"in h?f.push(h.error):p.push(...Ig(h.text,d,c,r,void 0));let m=await LE(d,n),g=0;if(m!==void 0){let T=await Cr(d,["log",...Ag,"--no-merges","--no-show-signature","--format=%x1e%h%x1f%ct%x1f%s",`-G${l}`,...m.logArgs,"--"]);if("error"in T)f.push(T.error);else for(let I of T.text.split("").slice(1)){let $=I.indexOf(`
151
151
  `),[D="",k="0",S=""]=($===-1?I:I.slice(0,$)).split(""),_=Ig(I.slice($+1),d,c,r,{id:D,heading:`Commit ${D}${Og(Number(k)*1e3,n)}: ${S}`});_.length>0&&(g+=1),p.push(..._)}}if(f.length>0&&p.length===0)return{artifacts:[a("unreadable",f)],evidence:[],redactions:[],omissions:f.map(T=>lo("unreadable",T,i.gitRoot))};let y=[],w=[],x=f.map(T=>lo("unreadable",T,i.gitRoot)),v=0;for(let T of p){if(y.length>=ru||v>=xg){let k=p.length-y.length;x.push(lo("budget-exceeded",`${k} more matching hunk${k===1?" was":"s were"} left out at the ${ru}-hunk, ${xg}-byte limit for recent changes.`,void 0,ru));break}let I=`${T.commit??"worktree"}:${T.path}@${T.newStart}`,$=ce(`${T.heading}
152
152
  ${T.path}
153
- ${T.body}`,"diff",I,e.sensitiveNames);v+=Buffer.byteLength($.value,"utf8"),w.push(...$.records);let D={type:"diff-hunk",...T.commit===void 0?{}:{commit:T.commit},path:T.path,oldStart:T.oldStart,oldLines:T.oldLines,newStart:T.newStart,newLines:T.newLines};y.push({evidenceId:we(t,s,"diff-hunk",D,$.value),kind:"diff-hunk",artifactId:s,locator:D,observation:$.value,availability:"present",redactionIds:$.records.map(k=>k.redactionId)})}let R=["uncommitted changes",...m===void 0?[]:[m.description]].join(" and "),P=m===void 0?{listed:[],total:0}:await _E(d,m,n),C=await jE(d,c),E=[...P.listed.length===0?[]:[`${P.total>P.listed.length?`The newest ${P.listed.length} of the ${P.total} commits searched`:"Commits searched, newest first"}: ${P.listed.join("; ")}.`],...C.length===0?[]:[`Source files with uncommitted changes: ${C.join(", ")}.`]],M=y.length,A=ce(`Searched ${R} for changed lines containing any of: ${r.map(T=>JSON.stringify(T)).join(", ")}. ${M===0?"No change mentioned them.":`${M} changed hunk${M===1?"":"s"} matched${g>0?`, from ${g} commit${g===1?"":"s"}`:""}${p.some(T=>T.commit===void 0)?" and uncommitted changes":""}.`}${E.map(T=>` ${T}`).join("")} A matching change shows what changed, not who owns the failure.`,"diff","changes:search",e.sensitiveNames);w.push(...A.records);let N={type:"report-field",path:"changes"};return y.push({evidenceId:we(t,s,"change-search",N,A.value),kind:"change-search",artifactId:s,locator:N,observation:A.value,availability:"present",redactionIds:A.records.map(T=>T.redactionId)}),{artifacts:[a(M===0?"empty":"present",u)],evidence:y,redactions:w,omissions:x}}var FE=[137,80,78,71,13,10,26,10];function BE(t){return t<192||t>207?!1:t!==196&&t!==200&&t!==204}function HE(t){if(t.byteLength<24||FE.some((e,r)=>t[r]!==e))return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength);if(String.fromCharCode(...t.subarray(12,16))==="IHDR")return{width:n.getUint32(16,!1),height:n.getUint32(20,!1)}}function zE(t){if(t.byteLength<4||t[0]!==255||t[1]!==216)return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),e=2;for(;e+9<t.byteLength;){if(t[e]!==255){e+=1;continue}let r=t[e+1];if(r===void 0)return;if(r===216||r===1||r>=208&&r<=215){e+=2;continue}let i=n.getUint16(e+2,!1);if(BE(r))return{height:n.getUint16(e+5,!1),width:n.getUint16(e+7,!1)};if(i<2)return;e+=2+i}}function VE(t){if(t.byteLength<30)return;let n=(i,s)=>String.fromCharCode(...t.subarray(i,s));if(n(0,4)!=="RIFF"||n(8,12)!=="WEBP")return;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n(12,16);if(r==="VP8X"){let i=1+(e.getUint16(24,!0)|e.getUint8(26)<<16),s=1+(e.getUint16(27,!0)|e.getUint8(29)<<16);return{width:i,height:s}}if(r==="VP8 ")return{width:e.getUint16(26,!0)&16383,height:e.getUint16(28,!0)&16383};if(r==="VP8L"){let i=e.getUint32(21,!0);return{width:1+(i&16383),height:1+(i>>14&16383)}}}function Mg(t){return HE(t)??zE(t)??VE(t)}function UE(t){let n=t.toLowerCase().split(";")[0]?.trim()??"";if(n.startsWith("image/"))return"screenshot";if(n.startsWith("video/"))return"video"}function Lg(t,n,e,r,i){return{omissionId:B("omi",[t.attemptId,n,e,i,r]),channel:n,reason:e,message:r,locator:i}}async function _g(t,n,e,r){let{attachment:i}=e,s=UE(i.contentType);if(s===void 0)return{artifacts:[],evidence:[],redactions:[],omissions:[]};let a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o=Ie(t,s,`${e.attemptId}:${i.attachmentId}`),d={artifactId:o,channel:s,attemptId:e.attemptId,format:i.contentType},c,l,u;if(i.path!==void 0){let x=await X(r,i.path,n.maxArtifactBytes);x.kind==="read"?(c=x.bytes,l=x.relativePath):u={reason:x.kind==="over-budget"?"budget-exceeded":x.kind==="unauthorized"?"unauthorized-path":x.kind,message:x.message}}else if(i.bodyBase64!==void 0&&i.bodyBase64.length>0){let x=Buffer.from(i.bodyBase64,"base64");x.byteLength>n.maxArtifactBytes?u={reason:"budget-exceeded",message:`Inline attachment exceeds the ${n.maxArtifactBytes}-byte limit.`}:c=new Uint8Array(x)}else u={reason:"unavailable",message:"Attachment supplied neither a path nor a body."};let p=ce(i.name,s,a,n.sensitiveNames);if(c===void 0){let x=u?.reason??"unavailable";return{artifacts:[{...d,availability:x==="unavailable"?"unavailable":"unreadable",...i.path===void 0?{}:{path:i.path},warnings:u===void 0?[]:[u.message]}],evidence:[],redactions:p.records,omissions:[Lg(e,s,x,u?.message??"Attachment is unavailable.",a)]}}let f=Ne(c),h=s==="screenshot"?Mg(c):void 0,m=[`${s} name=${p.value}`,`contentType=${i.contentType}`,`bytes=${c.byteLength}`,...s==="screenshot"?[h===void 0?"dimensions=unknown":`dimensions=${h.width}x${h.height}`]:[],`sha256=${f}`],g={type:"media",attachmentId:i.attachmentId,sha256:f},y=m.join(" "),w=[];return s==="screenshot"&&h===void 0&&w.push(Lg(e,s,"unreadable","Image dimensions could not be read from the container header.",a)),{artifacts:[{...d,availability:"present",...l===void 0?{}:{path:l},sha256:f,warnings:[]}],evidence:[{evidenceId:we(t,o,s==="screenshot"?"image-metadata":"video-metadata",g,y),kind:s==="screenshot"?"image-metadata":"video-metadata",artifactId:o,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:g,observation:y,availability:"present",redactionIds:p.records.map(x=>x.redactionId)}],redactions:p.records,omissions:w}}var qE=new Set(["textbox","searchbox","combobox","spinbutton"]),GE=/\s\[(?:ref=[^\]]+|cursor=[^\]]+)\]/g,jg=/^#{1,3}\s+page snapshot\s*$/i,KE=/^#{1,3}\s+\S/,Fg=2;function Bg(t){let n=t.contentType.toLowerCase().split(";")[0]?.trim()??"";return t.name==="error-context"?!0:n==="text/markdown"&&(t.path?.endsWith("error-context.md")??!1)}function WE(t){let n=t.split(/\r?\n/),e=n.some(s=>jg.test(s.trim())),r=!e,i;for(let s=0;s<n.length;s+=1){let o=(n[s]??"").trim();if(i===void 0){if(jg.test(o)){r=!0;continue}if(KE.test(o)){if(r&&e)break;continue}r&&/^```ya?ml\s*$/i.test(o)&&(i=s+1);continue}if(o==="```")return{scope:e?"page":"element",lines:n.slice(i,s),startLine:i+1,endLine:s}}}function ou(t){return t.length-t.trimStart().length}function du(t,n,e){let r=[],i=t,s=/^(\s*-\s+)([\w-]+)(\s+"((?:[^"\\]|\\.)*)")(.*?):\s+(.+)$/.exec(i);if(s!==null&&qE.has(s[2]??"")){let d=(s[4]??"").toLowerCase(),c=[...e].map(l=>l.toLowerCase()).sort().find(l=>d.includes(l));c!==void 0&&(i=`${s[1]}${s[2]}${s[3]}${s[5]}: [REDACTED]`,r.push({redactionId:B("red",["accessibility",n,`field:${c}`]),ruleId:`sensitive-field:${c}`,channel:"accessibility",locator:n,action:"mask",count:1}))}let a=/^(\s*-\s+\/url:\s+)(.+)$/.exec(i);if(a!==null){let d=(a[2]??"").replace(/^"(.*)"$/,"$1"),c=Xt(d,"accessibility",n,e);i=`${a[1]}${c.value}`,r.push(...c.records)}let o=ce(i,"accessibility",n,e);return{value:o.value,records:[...r,...o.records]}}function JE(t,n,e){if(t.reduce((u,p)=>u+Buffer.byteLength(p,"utf8")+1,0)<=e)return{lines:t,dropped:0};let i=[...new Set(n.flatMap(u=>Ir(u)))],s=new Set,a=u=>{s.add(u);let p=ou(t[u]??"");for(let f=u-1;f>=0&&p>0;f-=1){let h=ou(t[f]??"");h<p&&(s.add(f),p=h)}};t.forEach((u,p)=>{let f=u.toLowerCase();if(i.some(h=>f.includes(h)))for(let h=Math.max(0,p-Fg);h<=Math.min(t.length-1,p+Fg);h+=1)a(h)});let o=[...s].reduce((u,p)=>u+Buffer.byteLength(t[p]??"","utf8")+1,0);for(let u=0;u<t.length&&o<e;u+=1){if(s.has(u))continue;let p=Buffer.byteLength(t[u]??"","utf8")+1;if(o+p>e)break;s.add(u),o+=p}let d=[],c=!1,l=0;for(let u=0;u<t.length;u+=1){if(!s.has(u)){c=!0;continue}let p=t[u]??"",f=Buffer.byteLength(p,"utf8")+1;if(l+f>e){c=!0;break}c&&d.push(`${" ".repeat(ou(p))}\u2026`),c=!1,d.push(p),l+=f}return c&&d.push("\u2026"),{lines:d,dropped:t.length-d.filter(u=>u.trim()!=="\u2026").length}}async function Hg(t,n,e,r){let{attachment:i}=e,s=Ie(t,"accessibility",`${e.attemptId}:${i.attachmentId}`),a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o={artifactId:s,channel:"accessibility",availability:"present",format:"playwright-error-context",attemptId:e.attemptId,warnings:[]},d=(R,P,C)=>({omissionId:B("omi",[e.attemptId,"accessibility",R,a,P]),channel:"accessibility",reason:R,message:P,locator:a,...C===void 0?{}:{cap:C}}),c,l;if(i.path!==void 0){let R=await X(r,i.path,n.maxArtifactBytes);if(R.kind!=="read"){let P=R.kind==="over-budget"?"budget-exceeded":R.kind==="unauthorized"?"unauthorized-path":R.kind;return{artifacts:[{...o,availability:R.kind==="unavailable"?"unavailable":"unreadable",path:i.path,warnings:[R.message]}],evidence:[],redactions:[],omissions:[d(P,R.message)]}}c=R.bytes,l=R.relativePath}else i.bodyBase64!==void 0&&i.bodyBase64.length>0&&(c=new Uint8Array(Buffer.from(i.bodyBase64,"base64")));if(c===void 0)return{artifacts:[{...o,availability:"unavailable"}],evidence:[],redactions:[],omissions:[d("unavailable","The error context attachment has no path or body.")]};let u=Ne(c),p={...o,sha256:u,...l===void 0?{}:{path:l}},f=qe(c),h=f===void 0?void 0:WE(vt(f));if(h===void 0||h.lines.every(R=>R.trim()===""))return{artifacts:[{...p,availability:f===void 0?"unreadable":"empty"}],evidence:[],redactions:[],omissions:[d(f===void 0?"unreadable":"unrecognized",f===void 0?"The error context is not valid UTF-8.":"The error context has no page snapshot section.")]};let m=[],g=h.lines.map((R,P)=>{let C=du(R.replace(GE,""),`${a}#line=${h.startLine+P}`,n.sensitiveNames);return m.push(...C.records),C.value}),y=JE(g,e.focus,n.maxDomTextBytes),w=[];y.dropped>0&&w.push(d("budget-exceeded",`Kept ${g.length-y.dropped} of ${g.length} page snapshot lines, favouring those that mention the failed locator.`,n.maxDomTextBytes));let x=`${h.scope==="page"?"Accessibility snapshot of the page when the test failed":"Accessibility snapshot of the element the failed assertion checked"}:
153
+ ${T.body}`,"diff",I,e.sensitiveNames);v+=Buffer.byteLength($.value,"utf8"),w.push(...$.records);let D={type:"diff-hunk",...T.commit===void 0?{}:{commit:T.commit},path:T.path,oldStart:T.oldStart,oldLines:T.oldLines,newStart:T.newStart,newLines:T.newLines};y.push({evidenceId:we(t,s,"diff-hunk",D,$.value),kind:"diff-hunk",artifactId:s,locator:D,observation:$.value,availability:"present",redactionIds:$.records.map(k=>k.redactionId)})}let R=["uncommitted changes",...m===void 0?[]:[m.description]].join(" and "),P=m===void 0?{listed:[],total:0}:await _E(d,m,n),C=await jE(d,c),E=[...P.listed.length===0?[]:[`${P.total>P.listed.length?`The newest ${P.listed.length} of the ${P.total} commits searched`:"Commits searched, newest first"}: ${P.listed.join("; ")}.`],...C.length===0?[]:[`Source files with uncommitted changes: ${C.join(", ")}.`]],M=y.length,A=ce(`Searched ${R} for changed lines containing any of: ${r.map(T=>JSON.stringify(T)).join(", ")}. ${M===0?"No change mentioned them.":`${M} changed hunk${M===1?"":"s"} matched${g>0?`, from ${g} commit${g===1?"":"s"}`:""}${p.some(T=>T.commit===void 0)?" and uncommitted changes":""}.`}${E.map(T=>` ${T}`).join("")} A matching change shows what changed, not who owns the failure.`,"diff","changes:search",e.sensitiveNames);w.push(...A.records);let N={type:"report-field",path:"changes"};return y.push({evidenceId:we(t,s,"change-search",N,A.value),kind:"change-search",artifactId:s,locator:N,observation:A.value,availability:"present",redactionIds:A.records.map(T=>T.redactionId)}),{artifacts:[a(M===0?"empty":"present",u)],evidence:y,redactions:w,omissions:x}}var FE=[137,80,78,71,13,10,26,10];function BE(t){return t<192||t>207?!1:t!==196&&t!==200&&t!==204}function HE(t){if(t.byteLength<24||FE.some((e,r)=>t[r]!==e))return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength);if(String.fromCharCode(...t.subarray(12,16))==="IHDR")return{width:n.getUint32(16,!1),height:n.getUint32(20,!1)}}function zE(t){if(t.byteLength<4||t[0]!==255||t[1]!==216)return;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),e=2;for(;e+9<t.byteLength;){if(t[e]!==255){e+=1;continue}let r=t[e+1];if(r===void 0)return;if(r===216||r===1||r>=208&&r<=215){e+=2;continue}let i=n.getUint16(e+2,!1);if(BE(r))return{height:n.getUint16(e+5,!1),width:n.getUint16(e+7,!1)};if(i<2)return;e+=2+i}}function VE(t){if(t.byteLength<30)return;let n=(i,s)=>String.fromCharCode(...t.subarray(i,s));if(n(0,4)!=="RIFF"||n(8,12)!=="WEBP")return;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n(12,16);if(r==="VP8X"){let i=1+(e.getUint16(24,!0)|e.getUint8(26)<<16),s=1+(e.getUint16(27,!0)|e.getUint8(29)<<16);return{width:i,height:s}}if(r==="VP8 ")return{width:e.getUint16(26,!0)&16383,height:e.getUint16(28,!0)&16383};if(r==="VP8L"){let i=e.getUint32(21,!0);return{width:1+(i&16383),height:1+(i>>14&16383)}}}function Mg(t){return HE(t)??zE(t)??VE(t)}function UE(t){let n=t.toLowerCase().split(";")[0]?.trim()??"";if(n.startsWith("image/"))return"screenshot";if(n.startsWith("video/"))return"video"}function Lg(t,n,e,r,i){return{omissionId:B("omi",[t.attemptId,n,e,i,r]),channel:n,reason:e,message:r,locator:i}}async function _g(t,n,e,r){let{attachment:i}=e,s=UE(i.contentType);if(s===void 0)return{artifacts:[],evidence:[],redactions:[],omissions:[]};let a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o=Ie(t,s,`${e.attemptId}:${i.attachmentId}`),d={artifactId:o,channel:s,attemptId:e.attemptId,format:i.contentType},c,l,u;if(i.path!==void 0){let x=await X(r,i.path,n.maxArtifactBytes);x.kind==="read"?(c=x.bytes,l=x.relativePath):u={reason:x.kind==="over-budget"?"budget-exceeded":x.kind==="unauthorized"?"unauthorized-path":x.kind,message:x.message}}else if(i.bodyBase64!==void 0&&i.bodyBase64.length>0){let x=Buffer.from(i.bodyBase64,"base64");x.byteLength>n.maxArtifactBytes?u={reason:"budget-exceeded",message:`Inline attachment exceeds the ${n.maxArtifactBytes}-byte limit.`}:c=new Uint8Array(x)}else u={reason:"unavailable",message:"Attachment supplied neither a path nor a body."};let p=ce(i.name,s,a,n.sensitiveNames);if(c===void 0){let x=u?.reason??"unavailable";return{artifacts:[{...d,availability:x==="unavailable"?"unavailable":"unreadable",...i.path===void 0?{}:{path:i.path},warnings:u===void 0?[]:[u.message]}],evidence:[],redactions:p.records,omissions:[Lg(e,s,x,u?.message??"Attachment is unavailable.",a)]}}let f=Ne(c),h=s==="screenshot"?Mg(c):void 0,m=[`${s} name=${p.value}`,`contentType=${i.contentType}`,`bytes=${c.byteLength}`,...s==="screenshot"?[h===void 0?"dimensions=unknown":`dimensions=${h.width}x${h.height}`]:[],`sha256=${f}`],g={type:"media",attachmentId:i.attachmentId,sha256:f},y=m.join(" "),w=[];return s==="screenshot"&&h===void 0&&w.push(Lg(e,s,"unreadable","Image dimensions could not be read from the container header.",a)),{artifacts:[{...d,availability:"present",...l===void 0?{}:{path:l},sha256:f,warnings:[]}],evidence:[{evidenceId:we(t,o,s==="screenshot"?"image-metadata":"video-metadata",g,y),kind:s==="screenshot"?"image-metadata":"video-metadata",artifactId:o,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:g,observation:y,availability:"present",redactionIds:p.records.map(x=>x.redactionId)}],redactions:p.records,omissions:w}}var qE=new Set(["textbox","searchbox","combobox","spinbutton"]),GE=/\s\[(?:ref=[^\]]+|cursor=[^\]]+)\]/g,jg=/^#{1,3}\s+page snapshot\s*$/i,KE=/^#{1,3}\s+\S/,Fg=2;function Bg(t){let n=t.contentType.toLowerCase().split(";")[0]?.trim()??"";return t.name==="error-context"?!0:n==="text/markdown"&&(t.path?.endsWith("error-context.md")??!1)}function WE(t){let n=t.split(/\r?\n/),e=n.some(s=>jg.test(s.trim())),r=!e,i;for(let s=0;s<n.length;s+=1){let o=(n[s]??"").trim();if(i===void 0){if(jg.test(o)){r=!0;continue}if(KE.test(o)){if(r&&e)break;continue}r&&/^```ya?ml\s*$/i.test(o)&&(i=s+1);continue}if(o==="```")return{scope:e?"page":"element",lines:n.slice(i,s),startLine:i+1,endLine:s}}}function ou(t){return t.length-t.trimStart().length}function du(t,n,e){let r=[],i=t,s=/^(\s*-\s+)([\w-]+)(\s+"((?:[^"\\]|\\.)*)")(.*?):\s+(.+)$/.exec(i);if(s!==null&&qE.has(s[2]??"")){let d=(s[4]??"").toLowerCase(),c=[...e].map(l=>l.toLowerCase()).sort().find(l=>d.includes(l));c!==void 0&&(i=`${s[1]}${s[2]}${s[3]}${s[5]}: [REDACTED]`,r.push({redactionId:B("red",["accessibility",n,`field:${c}`]),ruleId:`sensitive-field:${c}`,channel:"accessibility",locator:n,action:"mask",count:1}))}let a=/^(\s*-\s+\/url:\s+)(.+)$/.exec(i);if(a!==null){let d=(a[2]??"").replace(/^"(.*)"$/,"$1"),c=Xt(d,"accessibility",n,e);i=`${a[1]}${c.value}`,r.push(...c.records)}let o=ce(i,"accessibility",n,e);return{value:o.value,records:[...r,...o.records]}}function JE(t,n,e){if(t.reduce((u,p)=>u+Buffer.byteLength(p,"utf8")+1,0)<=e)return{lines:t,dropped:0};let i=[...new Set(n.flatMap(u=>Ar(u)))],s=new Set,a=u=>{s.add(u);let p=ou(t[u]??"");for(let f=u-1;f>=0&&p>0;f-=1){let h=ou(t[f]??"");h<p&&(s.add(f),p=h)}};t.forEach((u,p)=>{let f=u.toLowerCase();if(i.some(h=>f.includes(h)))for(let h=Math.max(0,p-Fg);h<=Math.min(t.length-1,p+Fg);h+=1)a(h)});let o=[...s].reduce((u,p)=>u+Buffer.byteLength(t[p]??"","utf8")+1,0);for(let u=0;u<t.length&&o<e;u+=1){if(s.has(u))continue;let p=Buffer.byteLength(t[u]??"","utf8")+1;if(o+p>e)break;s.add(u),o+=p}let d=[],c=!1,l=0;for(let u=0;u<t.length;u+=1){if(!s.has(u)){c=!0;continue}let p=t[u]??"",f=Buffer.byteLength(p,"utf8")+1;if(l+f>e){c=!0;break}c&&d.push(`${" ".repeat(ou(p))}\u2026`),c=!1,d.push(p),l+=f}return c&&d.push("\u2026"),{lines:d,dropped:t.length-d.filter(u=>u.trim()!=="\u2026").length}}async function Hg(t,n,e,r){let{attachment:i}=e,s=Ie(t,"accessibility",`${e.attemptId}:${i.attachmentId}`),a=`${e.attemptId}.attachments[${i.sourceIndex}]`,o={artifactId:s,channel:"accessibility",availability:"present",format:"playwright-error-context",attemptId:e.attemptId,warnings:[]},d=(R,P,C)=>({omissionId:B("omi",[e.attemptId,"accessibility",R,a,P]),channel:"accessibility",reason:R,message:P,locator:a,...C===void 0?{}:{cap:C}}),c,l;if(i.path!==void 0){let R=await X(r,i.path,n.maxArtifactBytes);if(R.kind!=="read"){let P=R.kind==="over-budget"?"budget-exceeded":R.kind==="unauthorized"?"unauthorized-path":R.kind;return{artifacts:[{...o,availability:R.kind==="unavailable"?"unavailable":"unreadable",path:i.path,warnings:[R.message]}],evidence:[],redactions:[],omissions:[d(P,R.message)]}}c=R.bytes,l=R.relativePath}else i.bodyBase64!==void 0&&i.bodyBase64.length>0&&(c=new Uint8Array(Buffer.from(i.bodyBase64,"base64")));if(c===void 0)return{artifacts:[{...o,availability:"unavailable"}],evidence:[],redactions:[],omissions:[d("unavailable","The error context attachment has no path or body.")]};let u=Ne(c),p={...o,sha256:u,...l===void 0?{}:{path:l}},f=qe(c),h=f===void 0?void 0:WE(vt(f));if(h===void 0||h.lines.every(R=>R.trim()===""))return{artifacts:[{...p,availability:f===void 0?"unreadable":"empty"}],evidence:[],redactions:[],omissions:[d(f===void 0?"unreadable":"unrecognized",f===void 0?"The error context is not valid UTF-8.":"The error context has no page snapshot section.")]};let m=[],g=h.lines.map((R,P)=>{let C=du(R.replace(GE,""),`${a}#line=${h.startLine+P}`,n.sensitiveNames);return m.push(...C.records),C.value}),y=JE(g,e.focus,n.maxDomTextBytes),w=[];y.dropped>0&&w.push(d("budget-exceeded",`Kept ${g.length-y.dropped} of ${g.length} page snapshot lines, favouring those that mention the failed locator.`,n.maxDomTextBytes));let x=`${h.scope==="page"?"Accessibility snapshot of the page when the test failed":"Accessibility snapshot of the element the failed assertion checked"}:
154
154
  ${y.lines.join(`
155
155
  `)}`,v={type:"attachment-text",attachmentId:i.attachmentId,sha256:u,startLine:h.startLine,endLine:h.endLine};return{artifacts:[p],evidence:[{evidenceId:we(t,s,"page-snapshot",v,x),kind:"page-snapshot",artifactId:s,logicalTestId:e.logicalTestId,attemptId:e.attemptId,locator:v,observation:x,availability:"present",redactionIds:m.map(R=>R.redactionId)}],redactions:m,omissions:w}}var YE=256*1024,XE=10,zg=200;async function Vg(t,n,e,r){let i=Ie(t.runId,"probe",e),s=(h,m,g=e)=>({omissionId:B("omi",[t.runId,"probe",h,g,m]),channel:"probe",reason:h,message:m,locator:g}),a=await X(r,e,YE);if(a.kind!=="read")return{artifacts:[{artifactId:i,channel:"probe",availability:"unavailable",warnings:[a.message]}],evidence:[],redactions:[],omissions:[s("unavailable",a.message)]};let o={artifactId:i,channel:"probe",availability:"present",path:a.relativePath,sha256:a.sha256,format:"kwikqa-playwright-cli-probe",warnings:[]},d;try{d=me(JSON.parse(qe(a.bytes)??""))}catch{d=void 0}if(d===void 0||H(d.schemaVersion)!=="1.0")return{artifacts:[{...o,availability:"unreadable"}],evidence:[],redactions:[],omissions:[s("unrecognized","The probe results are not in a recognized format.")]};let c=me(d.tool),l=`Playwright CLI ${H(c?.version)??"unknown"}, Playwright ${H(d.playwrightVersion)??"unknown"}`,u=[],p=[],f=[];return tt(d.results)?.forEach((h,m)=>{let g=me(h);if(g===void 0)return;let y=H(g.logicalTestId),w=t.logicalTests.find(T=>T.logicalTestId===y)??t.logicalTests.find(T=>T.title===H(g.title)&&T.location.file===H(g.file)&&T.location.line===Pe(g.line)),x=w?.attempts.at(-1),v=`${a.relativePath}#results[${m}]`;for(let T of tt(g.issues)??[]){let I=H(T);I!==void 0&&f.push(s("unavailable",`Live probe of "${H(g.title)??"a test"}": ${I}`,v))}let R=(tt(g.candidates)??[]).map(T=>me(T)).filter(T=>T!==void 0).slice(0,XE);if(w===void 0||R.length===0)return;let P=[],C=[];R.forEach((T,I)=>{let $=du(`- ${(H(T.element)??"").slice(0,zg)}`,`${v}/candidates[${I}]`,n.sensitiveNames),D=ce((H(T.locator)??"").slice(0,zg),"probe",`${v}/candidates[${I}]/locator`,n.sensitiveNames);p.push(...$.records,...D.records),C.push(...$.records.map(k=>k.redactionId),...D.records.map(k=>k.redactionId)),P.push(`${$.value.replace(/^- /,"")} \u2192 ${D.value}`)});let E=H(g.locator),A=[`Live page paused at ${`${H(g.file)??w.location.file}:${Pe(g.failingLine)??"?"}`}, before the failing step (${l}).${E===void 0?"":` The failed locator was ${E}.`} Locators Playwright generated for the elements most like it:`,...P].join(`
156
- `),N={type:"report-field",path:`probe.results[${m}]`};u.push({evidenceId:we(t.runId,i,"locator-suggestion",N,A),kind:"locator-suggestion",artifactId:i,logicalTestId:w.logicalTestId,...x===void 0?{}:{attemptId:x.attemptId},locator:N,observation:A,availability:"present",redactionIds:C})}),{artifacts:[{...o,availability:u.length>0?"present":"empty"}],evidence:u,redactions:p,omissions:f}}var QE=/(?:\(|\bat\s+|^)((?:[A-Za-z]:)?[^():\s][^():]*?):(\d+):(\d+)\)?\s*$/,ZE=/^File "([^"]+\.py)", line (\d+)/,eC=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/,tC=/(?:^|[\\/])(?:node_modules|site-packages|\.venv|venv)[\\/]|[\\/]lib[\\/]python\d|^node:|^internal\//;function cu(t,n,e){let r=[];return t.split(/\r?\n/).forEach((i,s)=>{let a=i.trim().replace(/webpack:\/\/[^/\s()]*\//g,"").replace(/^❯\s+/,""),o=gr(a);if(o!==void 0){r.push({file:o.file,line:o.line,origin:`${n}#frame=${s+1}`,...e});return}let d=ZE.exec(a)??eC.exec(a),c=d===null?QE.exec(a):[d[0],d[1],d[2],"1"];if(c===null)return;let[,l,u,p]=c;l===void 0||u===void 0||p===void 0||tC.test(l)||r.push({file:l.replace(/^file:\/\//,"").replace(/^(?:\.\/)+/,""),line:Number.parseInt(u,10),column:Number.parseInt(p,10),origin:`${n}#frame=${s+1}`,...e})}),r}async function Ug(t,n){if(!t.some(i=>Aa(i.file)))return t;let e=new yr(n);return(await Promise.all(t.map(async i=>{if(!Aa(i.file))return i;let s=await e.find(i.file);return s===void 0?void 0:{...i,file:s}}))).filter(i=>i!==void 0)}function ts(t,n,e,r,i,s,a){let o=`${r}:${i}`;if(e.reported.has(o))return;e.reported.add(o);let d=`Reached the ${s}-${i} limit; later observations were not included.`;n.push({omissionId:B("omi",[t.runId,r,"budget-exceeded",a,d]),channel:r,reason:"budget-exceeded",message:d,locator:a,cap:s})}function lu(t,n,e){return t===void 0?[]:[{file:t.file,line:t.line??1,...t.column===void 0?{}:{column:t.column},origin:n,...e}]}function uu(t,n,e){let r=[...lu(t.location,`${n}.location`,e)];return t.stack!==void 0&&r.push(...cu(t.stack,`${n}.stack`,e)),r}function qg(t,n,e){let r=[];return t.forEach((i,s)=>{let a=`${n}[${s}]`;i.error!==void 0&&r.push(...uu(i.error,a,e)),r.push(...qg(i.steps,`${a}.steps`,e))}),r}function nC(t){let n=[];for(let e of t.logicalTests){for(let r of e.attempts){let i={logicalTestId:e.logicalTestId,attemptId:r.attemptId};n.push(...lu(r.errorLocation,`${r.attemptId}.errorLocation`,i));for(let s of r.errors)n.push(...uu(s,s.source,i));n.push(...qg(r.steps,`${r.attemptId}.steps`,i))}n.push(...lu(e.location,`${e.logicalTestId}.location`,{logicalTestId:e.logicalTestId}))}for(let e of t.reportErrors)n.push(...uu(e,e.source,{}));return n}function uo(t,n,e,r,i,s,a,o,d,c,l){if(c.reportFields>=n.maxReportFields){ts(t,d,c,"report","field",n.maxReportFields,i);return}c.reportFields+=1;let u=ce(s,e.channel,i,n.sensitiveNames);o.push(...u.records);let p={type:"report-field",path:i};a.push({evidenceId:we(t.runId,e.artifactId,r,p,u.value),kind:r,artifactId:e.artifactId,...l,locator:p,observation:u.value,availability:u.value.length===0?"empty":"present",redactionIds:u.records.map(f=>f.redactionId)})}function pu(t,n,e,r,i,s,a,o,d){let c=[["name",r.name],["message",r.message],["value",r.value],["snippet",r.snippet]];for(let[l,u]of c)u!==void 0&&uo(t,n,e,"error-field",`${r.source}.${l}`,u,i,s,a,o,d);r.stack!==void 0&&(uo(t,n,e,"error-field",`${r.source}.stack`,r.stack,i,s,a,o,d),r.stack.split(/\r?\n/).forEach((l,u)=>{if(l.trim().length===0)return;let p=`${r.source}.stack#line=${u+1}`;if(o.stackFrames>=n.maxStackFrames){ts(t,a,o,"report","stack-frame",n.maxStackFrames,p);return}o.stackFrames+=1,uo(t,n,e,"stack-frame",p,l,i,s,a,o,d)}))}function Gg(t,n,e,r,i,s,a,o,d,c){r.forEach((l,u)=>{let p=`${i}[${u}]`;if(d.steps>=n.maxSteps){ts(t,o,d,"report","step",n.maxSteps,p);return}d.steps+=1,uo(t,n,e,"step",`${p}.title`,l.title,s,a,o,d,c),l.error!==void 0&&pu(t,n,e,l.error,s,a,o,d,c),Gg(t,n,e,l.steps,`${p}.steps`,s,a,o,d,c)})}function rC(t){if(t.kind==="text")return t.text;let n=Buffer.from(t.base64,"base64");return`binary stdio: sha256=${Ne(n)} bytes=${n.byteLength}`}function Kg(t,n){let e={artifactId:Ie(t.runId,"report",t.artifact.artifactId),channel:"report",availability:t.artifact.availability,...t.artifact.path===void 0?{}:{path:t.artifact.path},...t.artifact.sha256===void 0?{}:{sha256:t.artifact.sha256},...t.artifact.formatVersion===void 0?{}:{producerVersion:t.artifact.formatVersion},warnings:t.artifact.warnings},r=[e],i=[],s=[],a=[],o={reportFields:0,stackFrames:0,steps:0,stdioChunks:0,stdioBytes:0,reported:new Set};t.reportErrors.forEach(d=>{pu(t,n,e,d,i,s,a,o,{})});for(let d of t.logicalTests)for(let c of d.attempts){let l={logicalTestId:d.logicalTestId,attemptId:c.attemptId};c.errors.forEach(u=>{pu(t,n,e,u,i,s,a,o,l)}),Gg(t,n,e,c.steps,`${c.attemptId}.steps`,i,s,a,o,l);for(let u of["stdout","stderr"]){let p=c[u],f={artifactId:Ie(t.runId,u,c.attemptId),channel:u,availability:p.length===0?"empty":"present",attemptId:c.attemptId,warnings:[]};r.push(f);let h=0;p.forEach((m,g)=>{let y=m.kind==="text"?Buffer.byteLength(m.text,"utf8"):Buffer.from(m.base64,"base64").byteLength,w=`${c.attemptId}.${u}[${g}]`;if(o.stdioChunks>=n.maxStdioChunks){ts(t,a,o,u,"stdio-chunk",n.maxStdioChunks,w),h+=y;return}if(o.stdioBytes+y>n.maxStdioBytes){ts(t,a,o,u,"stdio-byte",n.maxStdioBytes,w),h+=y;return}o.stdioChunks+=1,o.stdioBytes+=y;let x=rC(m),v=ce(x,u,w,n.sensitiveNames);s.push(...v.records);let R={type:"stdio",stream:u,chunk:g,startByte:h,endByte:h+y};h+=y,i.push({evidenceId:we(t.runId,f.artifactId,"stdio-chunk",R,v.value),kind:"stdio-chunk",artifactId:f.artifactId,...l,locator:R,observation:v.value,availability:x.length===0?"empty":"present",redactionIds:v.records.map(P=>P.redactionId)})})}}return{artifacts:r,evidence:i,redactions:s,omissions:a,seeds:nC(t)}}var Zg=Bs(vi(),1);import{dirname as iC,extname as Qg,join as Wg}from"node:path/posix";var sC=new Set(["test","it","describe","suite","step","beforeEach","afterEach","beforeAll","afterAll"]),Jg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],aC=new Set([".js",".mjs",".cjs"]),oC=[".ts",".tsx",".mts",".cts"];function dC(t){return t.split("/").includes("node_modules")}function nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function ns(t,n,e=new Set){if(!e.has(t)){e.add(t),n(t);for(let r of Object.keys(t)){if(r==="loc")continue;let i=t[r];if(Array.isArray(i))for(let s of i)nt(s)&&ns(s,n,e);else nt(i)&&ns(i,n,e)}}}function _n(t){if(nt(t)&&t.type==="Identifier")return typeof t.name=="string"?t.name:void 0}function Cr(t){if(nt(t)){if(t.type==="Identifier"&&typeof t.name=="string")return t.name;if(t.type==="StringLiteral"&&typeof t.value=="string")return t.value}}function ew(t){if(nt(t)){if(t.type==="Identifier")return typeof t.name=="string"?t.name:void 0;if(t.type==="MemberExpression"){let n=ew(t.object),e=Cr(t.property);return n===void 0||e===void 0?void 0:`${n}.${e}`}}}function cC(t){let n=ew(t.callee);if(n===void 0)return;let e=n.split(".").pop()??n;if(!sC.has(e))return;let i=(Array.isArray(t.arguments)?t.arguments:[])[0];if(!(!nt(i)||i.type!=="StringLiteral"||typeof i.value!="string"))return`${n}("${i.value}")`}function tw(t){switch(t.type){case"FunctionDeclaration":case"ClassDeclaration":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":return _n(t.id);case"ClassMethod":case"ObjectMethod":case"ClassProperty":case"PropertyDefinition":return Cr(t.key);case"VariableDeclarator":return _n(t.id);case"CallExpression":return cC(t);default:return}}function lC(t,n){let e=t.loc;return e==null?!1:e.start.line<=n&&e.end.line>=n}function uC(t,n){let e;return ns(t,r=>{let i=tw(r);if(i===void 0||!lC(r,n))return;let s=r.loc;if(s==null)return;let a={name:i,startLine:s.start.line,endLine:s.end.line};if(e===void 0){e=a;return}let o=a.endLine-a.startLine,d=e.endLine-e.startLine;o<d&&(e=a)}),e}function pC(t){let n=tw(t);return n!==void 0&&t.type!=="CallExpression"?[n]:t.type==="VariableDeclaration"&&Array.isArray(t.declarations)?t.declarations.map(e=>nt(e)?_n(e.id):void 0).filter(e=>e!==void 0):[]}function fC(t,n){let e=Array.isArray(t.program)?[]:t.program?.body,r=Array.isArray(e)?e:[],i=[];for(let s of r){if(!nt(s))continue;let a=s.loc;if(a==null)continue;if(s.type==="ExportDefaultDeclaration"&&n.has("default")){i.push({name:"default",startLine:a.start.line,endLine:a.end.line});continue}if(s.type==="ExportNamedDeclaration"&&Array.isArray(s.specifiers))for(let d of s.specifiers){if(!nt(d))continue;let c=Cr(d.exported);c!==void 0&&n.has(c)&&i.push({name:c,startLine:a.start.line,endLine:a.end.line})}let o=s.type==="ExportNamedDeclaration"&&nt(s.declaration)?s.declaration:s;for(let d of pC(o))n.has(d)&&i.push({name:d,startLine:a.start.line,endLine:a.end.line})}return i}function hC(t){let n=[];return ns(t,e=>{if(e.type!=="ImportDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="ExportAllDeclaration")return;let r=nt(e.source)?e.source.value:void 0;if(typeof r!="string")return;let i=[],s;for(let a of Array.isArray(e.specifiers)?e.specifiers:[])if(nt(a)){if(e.type==="ExportNamedDeclaration"){let o=Cr(a.exported),d=Cr(a.local);o!==void 0&&d!==void 0&&i.push({imported:d,local:o})}else if(a.type==="ImportDefaultSpecifier"){let o=_n(a.local);o!==void 0&&i.push({imported:"default",local:o})}else if(a.type==="ImportNamespaceSpecifier")s=_n(a.local);else if(a.type==="ImportSpecifier"){let o=Cr(a.imported)??_n(a.local),d=_n(a.local);o!==void 0&&d!==void 0&&i.push({imported:o,local:d})}}n.push({specifier:r,bindings:i,...s===void 0?{}:{namespaceLocal:s},exportStar:e.type==="ExportAllDeclaration"})}),n}function Yg(t,n,e){let r=new Set;return ns(t,i=>{let s=i.loc;s==null||s.end.line<n||s.start.line>e||i.type==="Identifier"&&typeof i.name=="string"&&r.add(i.name)}),r}function mC(t){let n=Qg(t).toLowerCase();return n===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(n)?["typescript"]:["jsx"]}var nw=/\.[cm]?[jt]sx?$/i,yC=10;function gC(t,n){if(!nw.test(n))return{};try{return{ast:(0,Zg.parse)(t,{sourceType:"module",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:mC(n)})}}catch(e){return{error:e instanceof Error?e.message:"Source could not be parsed."}}}function wC(t,n){if(!t.startsWith("./")&&!t.startsWith("../"))return[];let e=Wg(n,t),r=[e],i=Qg(e).toLowerCase();if(aC.has(i)){let s=e.slice(0,e.length-i.length);for(let a of oC)r.push(`${s}${a}`)}if(i===""){for(let s of Jg)r.push(`${e}${s}`);for(let s of Jg)r.push(Wg(e,`index${s}`))}return r}function pt(t,n,e,r,i){t.omissions.push({omissionId:B("omi",["source",n,r,e]),channel:"source",reason:n,message:e,locator:r,...i===void 0?{}:{cap:i}})}async function rw(t,n){let e=await ki(t.workspaceRoot,n);if(e.kind!=="authorized"){pt(t,e.kind==="unauthorized"?"unauthorized-path":e.kind,e.message,n);return}if(dC(e.relativePath)){pt(t,"policy-disabled","Dependency source under node_modules is out of scope for evidence.",e.relativePath);return}let r=t.files.get(e.relativePath);if(r!==void 0)return r;if(t.files.size>=t.policy.maxSourceFiles){t.filesReported||(t.filesReported=!0,pt(t,"budget-exceeded",`Reached the ${t.policy.maxSourceFiles}-file source limit; later files were not read.`,e.relativePath,t.policy.maxSourceFiles));return}let i=await X(t.workspaceRoot,e.relativePath,t.policy.maxArtifactBytes);if(i.kind!=="read"){let c=i.kind==="over-budget"?"budget-exceeded":i.kind==="unauthorized"?"unauthorized-path":i.kind;pt(t,c,i.message,e.relativePath);return}let s=qe(i.bytes);if(s===void 0){pt(t,"unreadable","Source file is not valid UTF-8.",i.relativePath);return}let a=gC(s,i.relativePath);a.error!==void 0&&pt(t,"parse-failed",`Symbol boundaries are unavailable: ${a.error}`,i.relativePath);let o={artifactId:Ie(t.runId,"source",i.relativePath),channel:"source",availability:"present",path:i.relativePath,sha256:i.sha256,warnings:a.error===void 0?[]:[a.error]},d={relativePath:i.relativePath,sha256:i.sha256,lines:s.split(/\r?\n/),ast:a.ast,artifact:o};return t.files.set(i.relativePath,d),t.artifacts.push(o),d}function Xg(t,n,e,r,i){let s=t.policy.maxSourceLinesPerFile,a=Math.max(1,e.startLine),o=Math.min(n.lines.length,e.endLine);if(o<a)return;o-a+1>s&&(o=a+s-1,pt(t,"budget-exceeded",`Symbol context in ${n.relativePath} was truncated to ${s} lines.`,`${n.relativePath}:${a}`,s));let d=`${n.relativePath}:${a}:${o}:${i.logicalTestId??""}:${i.attemptId??""}:${r}`;if(t.emitted.has(d))return;t.emitted.add(d);let c=n.lines.slice(a-1,o).join(`
156
+ `),N={type:"report-field",path:`probe.results[${m}]`};u.push({evidenceId:we(t.runId,i,"locator-suggestion",N,A),kind:"locator-suggestion",artifactId:i,logicalTestId:w.logicalTestId,...x===void 0?{}:{attemptId:x.attemptId},locator:N,observation:A,availability:"present",redactionIds:C})}),{artifacts:[{...o,availability:u.length>0?"present":"empty"}],evidence:u,redactions:p,omissions:f}}var QE=/(?:\(|\bat\s+|^)((?:[A-Za-z]:)?[^():\s][^():]*?):(\d+):(\d+)\)?\s*$/,ZE=/^File "([^"]+\.py)", line (\d+)/,eC=/^((?:[A-Za-z]:)?[^\s:][^:]*\.py):(\d+):(?:\s|$)/,tC=/(?:^|[\\/])(?:node_modules|site-packages|\.venv|venv)[\\/]|[\\/]lib[\\/]python\d|^node:|^internal\//;function cu(t,n,e){let r=[];return t.split(/\r?\n/).forEach((i,s)=>{let a=i.trim().replace(/webpack:\/\/[^/\s()]*\//g,"").replace(/^❯\s+/,""),o=wr(a);if(o!==void 0){r.push({file:o.file,line:o.line,origin:`${n}#frame=${s+1}`,...e});return}let d=ZE.exec(a)??eC.exec(a),c=d===null?QE.exec(a):[d[0],d[1],d[2],"1"];if(c===null)return;let[,l,u,p]=c;l===void 0||u===void 0||p===void 0||tC.test(l)||r.push({file:l.replace(/^file:\/\//,"").replace(/^(?:\.\/)+/,""),line:Number.parseInt(u,10),column:Number.parseInt(p,10),origin:`${n}#frame=${s+1}`,...e})}),r}async function Ug(t,n){if(!t.some(i=>Aa(i.file)))return t;let e=new gr(n);return(await Promise.all(t.map(async i=>{if(!Aa(i.file))return i;let s=await e.find(i.file);return s===void 0?void 0:{...i,file:s}}))).filter(i=>i!==void 0)}function ts(t,n,e,r,i,s,a){let o=`${r}:${i}`;if(e.reported.has(o))return;e.reported.add(o);let d=`Reached the ${s}-${i} limit; later observations were not included.`;n.push({omissionId:B("omi",[t.runId,r,"budget-exceeded",a,d]),channel:r,reason:"budget-exceeded",message:d,locator:a,cap:s})}function lu(t,n,e){return t===void 0?[]:[{file:t.file,line:t.line??1,...t.column===void 0?{}:{column:t.column},origin:n,...e}]}function uu(t,n,e){let r=[...lu(t.location,`${n}.location`,e)];return t.stack!==void 0&&r.push(...cu(t.stack,`${n}.stack`,e)),r}function qg(t,n,e){let r=[];return t.forEach((i,s)=>{let a=`${n}[${s}]`;i.error!==void 0&&r.push(...uu(i.error,a,e)),r.push(...qg(i.steps,`${a}.steps`,e))}),r}function nC(t){let n=[];for(let e of t.logicalTests){for(let r of e.attempts){let i={logicalTestId:e.logicalTestId,attemptId:r.attemptId};n.push(...lu(r.errorLocation,`${r.attemptId}.errorLocation`,i));for(let s of r.errors)n.push(...uu(s,s.source,i));n.push(...qg(r.steps,`${r.attemptId}.steps`,i))}n.push(...lu(e.location,`${e.logicalTestId}.location`,{logicalTestId:e.logicalTestId}))}for(let e of t.reportErrors)n.push(...uu(e,e.source,{}));return n}function uo(t,n,e,r,i,s,a,o,d,c,l){if(c.reportFields>=n.maxReportFields){ts(t,d,c,"report","field",n.maxReportFields,i);return}c.reportFields+=1;let u=ce(s,e.channel,i,n.sensitiveNames);o.push(...u.records);let p={type:"report-field",path:i};a.push({evidenceId:we(t.runId,e.artifactId,r,p,u.value),kind:r,artifactId:e.artifactId,...l,locator:p,observation:u.value,availability:u.value.length===0?"empty":"present",redactionIds:u.records.map(f=>f.redactionId)})}function pu(t,n,e,r,i,s,a,o,d){let c=[["name",r.name],["message",r.message],["value",r.value],["snippet",r.snippet]];for(let[l,u]of c)u!==void 0&&uo(t,n,e,"error-field",`${r.source}.${l}`,u,i,s,a,o,d);r.stack!==void 0&&(uo(t,n,e,"error-field",`${r.source}.stack`,r.stack,i,s,a,o,d),r.stack.split(/\r?\n/).forEach((l,u)=>{if(l.trim().length===0)return;let p=`${r.source}.stack#line=${u+1}`;if(o.stackFrames>=n.maxStackFrames){ts(t,a,o,"report","stack-frame",n.maxStackFrames,p);return}o.stackFrames+=1,uo(t,n,e,"stack-frame",p,l,i,s,a,o,d)}))}function Gg(t,n,e,r,i,s,a,o,d,c){r.forEach((l,u)=>{let p=`${i}[${u}]`;if(d.steps>=n.maxSteps){ts(t,o,d,"report","step",n.maxSteps,p);return}d.steps+=1,uo(t,n,e,"step",`${p}.title`,l.title,s,a,o,d,c),l.error!==void 0&&pu(t,n,e,l.error,s,a,o,d,c),Gg(t,n,e,l.steps,`${p}.steps`,s,a,o,d,c)})}function rC(t){if(t.kind==="text")return t.text;let n=Buffer.from(t.base64,"base64");return`binary stdio: sha256=${Ne(n)} bytes=${n.byteLength}`}function Kg(t,n){let e={artifactId:Ie(t.runId,"report",t.artifact.artifactId),channel:"report",availability:t.artifact.availability,...t.artifact.path===void 0?{}:{path:t.artifact.path},...t.artifact.sha256===void 0?{}:{sha256:t.artifact.sha256},...t.artifact.formatVersion===void 0?{}:{producerVersion:t.artifact.formatVersion},warnings:t.artifact.warnings},r=[e],i=[],s=[],a=[],o={reportFields:0,stackFrames:0,steps:0,stdioChunks:0,stdioBytes:0,reported:new Set};t.reportErrors.forEach(d=>{pu(t,n,e,d,i,s,a,o,{})});for(let d of t.logicalTests)for(let c of d.attempts){let l={logicalTestId:d.logicalTestId,attemptId:c.attemptId};c.errors.forEach(u=>{pu(t,n,e,u,i,s,a,o,l)}),Gg(t,n,e,c.steps,`${c.attemptId}.steps`,i,s,a,o,l);for(let u of["stdout","stderr"]){let p=c[u],f={artifactId:Ie(t.runId,u,c.attemptId),channel:u,availability:p.length===0?"empty":"present",attemptId:c.attemptId,warnings:[]};r.push(f);let h=0;p.forEach((m,g)=>{let y=m.kind==="text"?Buffer.byteLength(m.text,"utf8"):Buffer.from(m.base64,"base64").byteLength,w=`${c.attemptId}.${u}[${g}]`;if(o.stdioChunks>=n.maxStdioChunks){ts(t,a,o,u,"stdio-chunk",n.maxStdioChunks,w),h+=y;return}if(o.stdioBytes+y>n.maxStdioBytes){ts(t,a,o,u,"stdio-byte",n.maxStdioBytes,w),h+=y;return}o.stdioChunks+=1,o.stdioBytes+=y;let x=rC(m),v=ce(x,u,w,n.sensitiveNames);s.push(...v.records);let R={type:"stdio",stream:u,chunk:g,startByte:h,endByte:h+y};h+=y,i.push({evidenceId:we(t.runId,f.artifactId,"stdio-chunk",R,v.value),kind:"stdio-chunk",artifactId:f.artifactId,...l,locator:R,observation:v.value,availability:x.length===0?"empty":"present",redactionIds:v.records.map(P=>P.redactionId)})})}}return{artifacts:r,evidence:i,redactions:s,omissions:a,seeds:nC(t)}}var Zg=Bs(vi(),1);import{dirname as iC,extname as Qg,join as Wg}from"node:path/posix";var sC=new Set(["test","it","describe","suite","step","beforeEach","afterEach","beforeAll","afterAll"]),Jg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],aC=new Set([".js",".mjs",".cjs"]),oC=[".ts",".tsx",".mts",".cts"];function dC(t){return t.split("/").includes("node_modules")}function nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.type=="string"}function ns(t,n,e=new Set){if(!e.has(t)){e.add(t),n(t);for(let r of Object.keys(t)){if(r==="loc")continue;let i=t[r];if(Array.isArray(i))for(let s of i)nt(s)&&ns(s,n,e);else nt(i)&&ns(i,n,e)}}}function _n(t){if(nt(t)&&t.type==="Identifier")return typeof t.name=="string"?t.name:void 0}function Nr(t){if(nt(t)){if(t.type==="Identifier"&&typeof t.name=="string")return t.name;if(t.type==="StringLiteral"&&typeof t.value=="string")return t.value}}function ew(t){if(nt(t)){if(t.type==="Identifier")return typeof t.name=="string"?t.name:void 0;if(t.type==="MemberExpression"){let n=ew(t.object),e=Nr(t.property);return n===void 0||e===void 0?void 0:`${n}.${e}`}}}function cC(t){let n=ew(t.callee);if(n===void 0)return;let e=n.split(".").pop()??n;if(!sC.has(e))return;let i=(Array.isArray(t.arguments)?t.arguments:[])[0];if(!(!nt(i)||i.type!=="StringLiteral"||typeof i.value!="string"))return`${n}("${i.value}")`}function tw(t){switch(t.type){case"FunctionDeclaration":case"ClassDeclaration":case"TSInterfaceDeclaration":case"TSTypeAliasDeclaration":case"TSEnumDeclaration":case"TSModuleDeclaration":return _n(t.id);case"ClassMethod":case"ObjectMethod":case"ClassProperty":case"PropertyDefinition":return Nr(t.key);case"VariableDeclarator":return _n(t.id);case"CallExpression":return cC(t);default:return}}function lC(t,n){let e=t.loc;return e==null?!1:e.start.line<=n&&e.end.line>=n}function uC(t,n){let e;return ns(t,r=>{let i=tw(r);if(i===void 0||!lC(r,n))return;let s=r.loc;if(s==null)return;let a={name:i,startLine:s.start.line,endLine:s.end.line};if(e===void 0){e=a;return}let o=a.endLine-a.startLine,d=e.endLine-e.startLine;o<d&&(e=a)}),e}function pC(t){let n=tw(t);return n!==void 0&&t.type!=="CallExpression"?[n]:t.type==="VariableDeclaration"&&Array.isArray(t.declarations)?t.declarations.map(e=>nt(e)?_n(e.id):void 0).filter(e=>e!==void 0):[]}function fC(t,n){let e=Array.isArray(t.program)?[]:t.program?.body,r=Array.isArray(e)?e:[],i=[];for(let s of r){if(!nt(s))continue;let a=s.loc;if(a==null)continue;if(s.type==="ExportDefaultDeclaration"&&n.has("default")){i.push({name:"default",startLine:a.start.line,endLine:a.end.line});continue}if(s.type==="ExportNamedDeclaration"&&Array.isArray(s.specifiers))for(let d of s.specifiers){if(!nt(d))continue;let c=Nr(d.exported);c!==void 0&&n.has(c)&&i.push({name:c,startLine:a.start.line,endLine:a.end.line})}let o=s.type==="ExportNamedDeclaration"&&nt(s.declaration)?s.declaration:s;for(let d of pC(o))n.has(d)&&i.push({name:d,startLine:a.start.line,endLine:a.end.line})}return i}function hC(t){let n=[];return ns(t,e=>{if(e.type!=="ImportDeclaration"&&e.type!=="ExportNamedDeclaration"&&e.type!=="ExportAllDeclaration")return;let r=nt(e.source)?e.source.value:void 0;if(typeof r!="string")return;let i=[],s;for(let a of Array.isArray(e.specifiers)?e.specifiers:[])if(nt(a)){if(e.type==="ExportNamedDeclaration"){let o=Nr(a.exported),d=Nr(a.local);o!==void 0&&d!==void 0&&i.push({imported:d,local:o})}else if(a.type==="ImportDefaultSpecifier"){let o=_n(a.local);o!==void 0&&i.push({imported:"default",local:o})}else if(a.type==="ImportNamespaceSpecifier")s=_n(a.local);else if(a.type==="ImportSpecifier"){let o=Nr(a.imported)??_n(a.local),d=_n(a.local);o!==void 0&&d!==void 0&&i.push({imported:o,local:d})}}n.push({specifier:r,bindings:i,...s===void 0?{}:{namespaceLocal:s},exportStar:e.type==="ExportAllDeclaration"})}),n}function Yg(t,n,e){let r=new Set;return ns(t,i=>{let s=i.loc;s==null||s.end.line<n||s.start.line>e||i.type==="Identifier"&&typeof i.name=="string"&&r.add(i.name)}),r}function mC(t){let n=Qg(t).toLowerCase();return n===".tsx"?["typescript","jsx"]:[".ts",".mts",".cts"].includes(n)?["typescript"]:["jsx"]}var nw=/\.[cm]?[jt]sx?$/i,yC=10;function gC(t,n){if(!nw.test(n))return{};try{return{ast:(0,Zg.parse)(t,{sourceType:"module",allowReturnOutsideFunction:!0,errorRecovery:!1,plugins:mC(n)})}}catch(e){return{error:e instanceof Error?e.message:"Source could not be parsed."}}}function wC(t,n){if(!t.startsWith("./")&&!t.startsWith("../"))return[];let e=Wg(n,t),r=[e],i=Qg(e).toLowerCase();if(aC.has(i)){let s=e.slice(0,e.length-i.length);for(let a of oC)r.push(`${s}${a}`)}if(i===""){for(let s of Jg)r.push(`${e}${s}`);for(let s of Jg)r.push(Wg(e,`index${s}`))}return r}function pt(t,n,e,r,i){t.omissions.push({omissionId:B("omi",["source",n,r,e]),channel:"source",reason:n,message:e,locator:r,...i===void 0?{}:{cap:i}})}async function rw(t,n){let e=await ki(t.workspaceRoot,n);if(e.kind!=="authorized"){pt(t,e.kind==="unauthorized"?"unauthorized-path":e.kind,e.message,n);return}if(dC(e.relativePath)){pt(t,"policy-disabled","Dependency source under node_modules is out of scope for evidence.",e.relativePath);return}let r=t.files.get(e.relativePath);if(r!==void 0)return r;if(t.files.size>=t.policy.maxSourceFiles){t.filesReported||(t.filesReported=!0,pt(t,"budget-exceeded",`Reached the ${t.policy.maxSourceFiles}-file source limit; later files were not read.`,e.relativePath,t.policy.maxSourceFiles));return}let i=await X(t.workspaceRoot,e.relativePath,t.policy.maxArtifactBytes);if(i.kind!=="read"){let c=i.kind==="over-budget"?"budget-exceeded":i.kind==="unauthorized"?"unauthorized-path":i.kind;pt(t,c,i.message,e.relativePath);return}let s=qe(i.bytes);if(s===void 0){pt(t,"unreadable","Source file is not valid UTF-8.",i.relativePath);return}let a=gC(s,i.relativePath);a.error!==void 0&&pt(t,"parse-failed",`Symbol boundaries are unavailable: ${a.error}`,i.relativePath);let o={artifactId:Ie(t.runId,"source",i.relativePath),channel:"source",availability:"present",path:i.relativePath,sha256:i.sha256,warnings:a.error===void 0?[]:[a.error]},d={relativePath:i.relativePath,sha256:i.sha256,lines:s.split(/\r?\n/),ast:a.ast,artifact:o};return t.files.set(i.relativePath,d),t.artifacts.push(o),d}function Xg(t,n,e,r,i){let s=t.policy.maxSourceLinesPerFile,a=Math.max(1,e.startLine),o=Math.min(n.lines.length,e.endLine);if(o<a)return;o-a+1>s&&(o=a+s-1,pt(t,"budget-exceeded",`Symbol context in ${n.relativePath} was truncated to ${s} lines.`,`${n.relativePath}:${a}`,s));let d=`${n.relativePath}:${a}:${o}:${i.logicalTestId??""}:${i.attemptId??""}:${r}`;if(t.emitted.has(d))return;t.emitted.add(d);let c=n.lines.slice(a-1,o).join(`
157
157
  `),l=ce(c,"source",`${n.relativePath}:${a}-${o}`,t.policy.sensitiveNames),u=Buffer.byteLength(l.value,"utf8");if(t.emittedBytes+u>t.policy.maxSourceBytes){t.bytesReported||(t.bytesReported=!0,pt(t,"budget-exceeded",`Reached the ${t.policy.maxSourceBytes}-byte source limit; later ranges were not included.`,n.relativePath,t.policy.maxSourceBytes));return}t.emittedBytes+=u,t.redactions.push(...l.records);let p=n.lines[o-1]??"",f={type:"source-range",path:n.relativePath,sha256:n.sha256,startLine:a,startColumn:1,endLine:o,endColumn:p.length+1,...e.symbol===void 0?{}:{symbol:e.symbol}},h=`${r}
158
- ${l.value}`;t.evidence.push({evidenceId:we(t.runId,n.artifact.artifactId,"source-range",f,h),kind:"source-range",artifactId:n.artifact.artifactId,...i,locator:f,observation:h,availability:"present",redactionIds:l.records.map(m=>m.redactionId)})}async function bC(t,n,e){for(let r of wC(n,e)){let i=await ki(t.workspaceRoot,r);if(i.kind==="authorized")return await rw(t,i.relativePath)}pt(t,"unavailable",`Relative import ${n} did not resolve to a readable workspace file.`,e)}async function iw(t,n,e,r){let i={runId:t,policy:n,workspaceRoot:r,files:new Map,artifacts:[],evidence:[],redactions:[],omissions:[],emitted:new Set,traversed:new Set,emittedBytes:0,filesReported:!1,bytesReported:!1},s=new Set,a=[];for(let d of e){let c=`${d.file}:${d.line}:${d.logicalTestId??""}:${d.attemptId??""}:${d.origin}`;if(s.has(c))continue;s.add(c);let l=await rw(i,d.file);if(l===void 0)continue;let u={...d.logicalTestId===void 0?{}:{logicalTestId:d.logicalTestId},...d.attemptId===void 0?{}:{attemptId:d.attemptId}},p=l.ast===void 0?void 0:uC(l.ast,d.line),f=nw.test(l.relativePath)?Math.floor(n.maxSourceLinesPerFile/2):yC,h=p??{name:void 0,startLine:Math.max(1,d.line-f),endLine:d.line+f};a.push({file:l,linkage:u,referenced:l.ast===void 0?new Set:Yg(l.ast,h.startLine,h.endLine)}),Xg(i,l,{startLine:h.startLine,endLine:h.endLine,...p===void 0?{}:{symbol:p.name}},`${l.relativePath}:${d.line} via ${d.origin}`,u)}let o=a;for(let d=1;d<=n.maxImportDepth;d+=1){let c=[];for(let l of o){let u=l.file;if(u.ast!==void 0)for(let p of hC(u.ast)){let f=new Set(p.bindings.filter(x=>l.referenced.has(x.local)).map(x=>x.imported));if(p.namespaceLocal!==void 0&&l.referenced.has(p.namespaceLocal)){pt(i,"policy-disabled",`Namespace import of ${p.specifier} was not expanded; only named symbols are followed.`,u.relativePath);continue}if(p.exportStar){pt(i,"unrecognized",`Export-star from ${p.specifier} was not expanded because the exported symbol is ambiguous.`,u.relativePath);continue}if(f.size===0||!p.specifier.startsWith("."))continue;let h=await bC(i,p.specifier,iC(u.relativePath));if(h===void 0||h.ast===void 0)continue;let m=l.linkage,g=`${h.relativePath}:${[...f].sort().join(",")}:${m.logicalTestId??""}:${m.attemptId??""}`;if(i.traversed.has(g))continue;i.traversed.add(g);let y=fC(h.ast,f),w=new Set;for(let x of y){for(let v of Yg(h.ast,x.startLine,x.endLine))w.add(v);Xg(i,h,{startLine:x.startLine,endLine:x.endLine,symbol:x.name},`${h.relativePath} exports ${x.name}, imported by ${u.relativePath} (depth ${d})`,m)}c.some(x=>x.file===h&&x.linkage.attemptId===m.attemptId)||c.push({file:h,linkage:m,referenced:w})}}if(o=c,o.length===0)break}return{artifacts:i.artifacts,evidence:i.evidence,redactions:i.redactions,omissions:i.omissions}}var xC=["report","trace","stdout","stderr","screenshot","video","dom","accessibility","console","network","source","diff","probe"],vC=["trace","console","network","dom","accessibility"],kC=8,RC=12,IC=5,AC=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/g,TC=[/Unable to locate element: \{"method":"[^"]+","selector":"((?:[^"\\]|\\.)+)"\}/g,/\b(By\.\w+: [^,\s)]+)/g,/Expected to find element: `([^`]+)`/g,/within the selector: '([^']+)'/g,/expected '<([a-z][\w-]*(?:[#.][\w-]+)*)>'/gi,/\bselector "([^"]+)"/g,/\belement \("([^"]+)"\)/g,/\${1,2}\(`([^`]+)`\)/g];function rs(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function po(t,n){return[...t].sort((e,r)=>n(e).localeCompare(n(r)))}function PC(t){return t.length===0?"unavailable":t.some(n=>n.availability==="present")?"present":t.some(n=>n.availability==="empty")?"empty":t.some(n=>n.availability==="unreadable")?"unreadable":"unavailable"}function SC(t,n,e,r,i){let s=n.filter(l=>l.channel===t),a=new Set(s.map(l=>l.artifactId)),o=e.filter(l=>a.has(l.artifactId)),d=r.filter(l=>l.channel===t),c=i.filter(l=>l.channel===t);return{channel:t,availability:PC(s),examined:o.length+d.length,included:o.length,omitted:d.length,observationBytes:o.reduce((l,u)=>l+Buffer.byteLength(u.observation,"utf8"),0),redactionCount:c.reduce((l,u)=>l+u.count,0),serializedBytes:rs({artifacts:s,evidence:o,redactions:c,omissions:d})}}function sw(t,n,e){return{omissionId:B("omi",[t,n,"unavailable",e]),channel:n,reason:"unavailable",message:e,locator:t}}function aw(t,n){return n?.[t.attachmentId]!==void 0?!0:t.name==="trace"&&t.contentType==="application/zip"}function Nr(t){return t.attempts.filter(n=>n.status==="interrupted"?!0:t.status==="unexpected"?n.status!=="skipped":t.status==="flaky"?n.status!=="passed"&&n.status!=="skipped":!1)}function EC(t){return{...t,logicalTests:t.logicalTests.map(n=>({...n,attempts:Nr(n)})).filter(n=>n.attempts.length>0)}}function CC(t,n){let e={expected:0,unexpected:0,flaky:0,skipped:0};for(let a of t.logicalTests)e[a.status]+=1;let r=n.logicalTests.reduce((a,o)=>a+o.attempts.length,0),i=[...new Set(t.logicalTests.map(a=>a.projectId))].length,s=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`;return[`${Rt[t.framework]}${s} run of ${t.logicalTests.length} tests in ${i} project${i===1?"":"s"}`,`${e.expected} passed, ${e.unexpected} failed, ${e.flaky} flaky, ${e.skipped} skipped`,`evidence covers the ${r} failing attempt${r===1?"":"s"} of ${n.logicalTests.length} test${n.logicalTests.length===1?"":"s"}; passing tests are only counted.`].join("; ")}function is(t){let n=t.errors.map(r=>`${r.message??""}
159
- ${r.stack??""}`),e=n.flatMap(r=>TC.flatMap(i=>[...r.matchAll(i)].map(s=>(s[1]??"").replace(/\\(.)/g,"$1"))));return[...new Set([...n.flatMap(r=>r.match(AC)??[]),...e.filter(r=>r!=="")])]}function NC(t,n,e,r,i){let s=t.attemptId===void 0?0:r.get(t.attemptId)??0;if(i.has(t.evidenceId))return re.afterFailure;switch(t.kind){case"error-field":case"run-summary":case"change-search":return re.failure;case"locator-suggestion":return re.failedCall+.95-Math.min(.5,s/1e3);case"page-snapshot":case"dom-subtree":case"dom-candidates":case"accessibility-node":{let o=t.kind==="accessibility-node"?.5:.9;return s<IC?re.failedCall+o-s/1e3:re.context+o-Math.min(.8,s/1e3)}default:break}let a=n.get(t.evidenceId);if(a!==void 0)return a;switch(t.kind){case"stack-frame":return/node_modules|node:internal/.test(t.observation)?re.ordinary:re.failedCall;case"source-range":{let o=e.get(t.evidenceId)??0;return re.significant-Math.min(.9,o/100)}case"diff-hunk":return re.failedCall+.9;case"step":return re.context;default:return re.ordinary}}async function fo(t,n,e){let r=Hl(e);if(r!==void 0)return{kind:"invalid-policy",message:r};if(e.workspaceRoot!==t.workspace.root)return{kind:"invalid-policy",message:"Evidence policy workspaceRoot must match the normalized run workspace root."};let i=n.artifactRoot??t.workspace.root,s=EC(t),a=Kg(s,e),o=[...a.artifacts],d=[...a.evidence],c=[...a.redactions],l=[...a.omissions],u=[...a.seeds],p=new Map,f=a.artifacts.find(E=>E.channel==="report");if(f!==void 0&&t.logicalTests.length>0){let E={type:"report-field",path:"stats"},M=CC(t,s);d.push({evidenceId:we(t.runId,f.artifactId,"run-summary",E,M),kind:"run-summary",artifactId:f.artifactId,locator:E,observation:M,availability:"present",redactionIds:[]})}for(let E of s.logicalTests)for(let M of E.attempts){let A=0,N=0,T=0,I=[...is(M)];for(let $ of M.attachments){if(!aw($,n.tracePaths))continue;let D=n.tracePaths?.[$.attachmentId]??$.path;if(D===void 0){l.push(sw(M.attemptId,"trace","Trace attachment supplied no path; inline trace bodies are not read."));continue}A+=1;let k=await ug(t.runId,e,{attachmentId:$.attachmentId,logicalTestId:E.logicalTestId,attemptId:M.attemptId,path:D,info:{...t.artifact.formatVersion===void 0?{}:{producerVersion:t.artifact.formatVersion},format:"playwright-trace-zip"}},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions),u.push(...k.seeds),I.push(...k.failedSelectors);for(let[S,_]of k.priorities)p.set(S,_)}for(let $ of M.attachments){if(!eu($))continue;N+=1;let D=await hg(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},i);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions),I.push(...D.failedSelectors);for(let[k,S]of D.priorities)p.set(k,S)}for(let $ of M.attachments){if(aw($,n.tracePaths)||eu($))continue;if(Bg($)){T+=1;let k=await Hg(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions);continue}let D=await _g(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$},i);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions)}if(A===0&&N===0){let $=t.framework==="playwright"?"Attempt produced no trace attachment.":"Attempt has no KwikQA failure capture; run `kwikqa analyze --capture` to record the page.";for(let D of vC)D==="accessibility"&&T>0||l.push(sw(M.attemptId,D,$))}}if(n.probePath!==void 0){let E=await Vg(s,e,n.probePath,t.workspace.root);o.push(...E.artifacts),d.push(...E.evidence),c.push(...E.redactions),l.push(...E.omissions)}let h=await iw(t.runId,e,await Ug(u,t.workspace.root),t.workspace.root);o.push(...h.artifacts),d.push(...h.evidence),c.push(...h.redactions),l.push(...h.omissions);let m=new Map(h.evidence.map((E,M)=>[E.evidenceId,M])),g=h.artifacts.map(E=>E.path).filter(E=>E!==void 0),y=await mg(t.runId,e,g,{authorized:n.includeCurrentDiff===!0,workspaceRoot:t.workspace.root,...t.workspace.gitRoot===void 0?{}:{gitRoot:t.workspace.gitRoot}});o.push(...y.artifacts),d.push(...y.evidence),c.push(...y.redactions),l.push(...y.omissions);let w=await Dg(t.runId,t.createdAt,e,Ng(s.logicalTests.flatMap(E=>E.attempts),is,d.filter(E=>E.kind==="network-event").map(E=>E.observation)),{authorized:n.includeChangeHistory===!0,workspaceRoot:t.workspace.root,...t.workspace.gitRoot===void 0?{}:{gitRoot:t.workspace.gitRoot}});o.push(...w.artifacts),d.push(...w.evidence),c.push(...w.redactions),l.push(...w.omissions);let x=po(o,E=>E.artifactId),v=new Map(x.map(E=>[E.artifactId,E.channel])),R=(E,M,A)=>{let N=po(E,S=>S.evidenceId),T=po(M,S=>S.redactionId),I=po(A,S=>S.omissionId),$=xC.map(S=>SC(S,x,N,I,T)),D=S=>{let _={schemaVersion:"1.2",runId:t.runId,framework:t.framework,createdAt:t.createdAt,workspace:t.workspace,sourceHashes:t.sourceHashes,policy:e,artifacts:x,evidence:N,redactions:T,omissions:I,accounting:$,totals:{artifacts:x.length,evidence:N.length,redactions:T.length,omissions:I.length,serializedBytes:S}};return{..._,packetHash:Rr(_)}},k=D(0);for(let S=0;S<kC;S+=1){let _=rs(k);if(k.totals.serializedBytes===_)break;k=D(_)}return k},P=R(d,c,l),C=rs(P);if(C>e.maxPacketBytes){let E=new Set(d.flatMap(k=>k.redactionIds)),M=new Map(d.map(k=>[k.evidenceId,k])),A=new Map(s.logicalTests.flatMap(k=>k.attempts).map((k,S)=>[k.attemptId,S])),N=new Set,T=new Set;for(let k of[...d].sort((S,_)=>(A.get(S.attemptId??"")??0)-(A.get(_.attemptId??"")??0)||S.evidenceId.localeCompare(_.evidenceId))){if(k.kind==="error-field"||k.kind==="run-summary"||k.kind==="change-search")continue;let S=`${k.kind}
158
+ ${l.value}`;t.evidence.push({evidenceId:we(t.runId,n.artifact.artifactId,"source-range",f,h),kind:"source-range",artifactId:n.artifact.artifactId,...i,locator:f,observation:h,availability:"present",redactionIds:l.records.map(m=>m.redactionId)})}async function bC(t,n,e){for(let r of wC(n,e)){let i=await ki(t.workspaceRoot,r);if(i.kind==="authorized")return await rw(t,i.relativePath)}pt(t,"unavailable",`Relative import ${n} did not resolve to a readable workspace file.`,e)}async function iw(t,n,e,r){let i={runId:t,policy:n,workspaceRoot:r,files:new Map,artifacts:[],evidence:[],redactions:[],omissions:[],emitted:new Set,traversed:new Set,emittedBytes:0,filesReported:!1,bytesReported:!1},s=new Set,a=[];for(let d of e){let c=`${d.file}:${d.line}:${d.logicalTestId??""}:${d.attemptId??""}:${d.origin}`;if(s.has(c))continue;s.add(c);let l=await rw(i,d.file);if(l===void 0)continue;let u={...d.logicalTestId===void 0?{}:{logicalTestId:d.logicalTestId},...d.attemptId===void 0?{}:{attemptId:d.attemptId}},p=l.ast===void 0?void 0:uC(l.ast,d.line),f=nw.test(l.relativePath)?Math.floor(n.maxSourceLinesPerFile/2):yC,h=p??{name:void 0,startLine:Math.max(1,d.line-f),endLine:d.line+f};a.push({file:l,linkage:u,referenced:l.ast===void 0?new Set:Yg(l.ast,h.startLine,h.endLine)}),Xg(i,l,{startLine:h.startLine,endLine:h.endLine,...p===void 0?{}:{symbol:p.name}},`${l.relativePath}:${d.line} via ${d.origin}`,u)}let o=a;for(let d=1;d<=n.maxImportDepth;d+=1){let c=[];for(let l of o){let u=l.file;if(u.ast!==void 0)for(let p of hC(u.ast)){let f=new Set(p.bindings.filter(x=>l.referenced.has(x.local)).map(x=>x.imported));if(p.namespaceLocal!==void 0&&l.referenced.has(p.namespaceLocal)){pt(i,"policy-disabled",`Namespace import of ${p.specifier} was not expanded; only named symbols are followed.`,u.relativePath);continue}if(p.exportStar){pt(i,"unrecognized",`Export-star from ${p.specifier} was not expanded because the exported symbol is ambiguous.`,u.relativePath);continue}if(f.size===0||!p.specifier.startsWith("."))continue;let h=await bC(i,p.specifier,iC(u.relativePath));if(h===void 0||h.ast===void 0)continue;let m=l.linkage,g=`${h.relativePath}:${[...f].sort().join(",")}:${m.logicalTestId??""}:${m.attemptId??""}`;if(i.traversed.has(g))continue;i.traversed.add(g);let y=fC(h.ast,f),w=new Set;for(let x of y){for(let v of Yg(h.ast,x.startLine,x.endLine))w.add(v);Xg(i,h,{startLine:x.startLine,endLine:x.endLine,symbol:x.name},`${h.relativePath} exports ${x.name}, imported by ${u.relativePath} (depth ${d})`,m)}c.some(x=>x.file===h&&x.linkage.attemptId===m.attemptId)||c.push({file:h,linkage:m,referenced:w})}}if(o=c,o.length===0)break}return{artifacts:i.artifacts,evidence:i.evidence,redactions:i.redactions,omissions:i.omissions}}var xC=["report","trace","stdout","stderr","screenshot","video","dom","accessibility","console","network","source","diff","probe"],vC=["trace","console","network","dom","accessibility"],kC=8,RC=12,IC=5,AC=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/g,TC=[/Unable to locate element: \{"method":"[^"]+","selector":"((?:[^"\\]|\\.)+)"\}/g,/\b(By\.\w+: [^,\s)]+)/g,/Expected to find element: `([^`]+)`/g,/within the selector: '([^']+)'/g,/expected '<([a-z][\w-]*(?:[#.][\w-]+)*)>'/gi,/\bselector "([^"]+)"/g,/\belement \("([^"]+)"\)/g,/\${1,2}\(`([^`]+)`\)/g];function rs(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function po(t,n){return[...t].sort((e,r)=>n(e).localeCompare(n(r)))}function PC(t){return t.length===0?"unavailable":t.some(n=>n.availability==="present")?"present":t.some(n=>n.availability==="empty")?"empty":t.some(n=>n.availability==="unreadable")?"unreadable":"unavailable"}function SC(t,n,e,r,i){let s=n.filter(l=>l.channel===t),a=new Set(s.map(l=>l.artifactId)),o=e.filter(l=>a.has(l.artifactId)),d=r.filter(l=>l.channel===t),c=i.filter(l=>l.channel===t);return{channel:t,availability:PC(s),examined:o.length+d.length,included:o.length,omitted:d.length,observationBytes:o.reduce((l,u)=>l+Buffer.byteLength(u.observation,"utf8"),0),redactionCount:c.reduce((l,u)=>l+u.count,0),serializedBytes:rs({artifacts:s,evidence:o,redactions:c,omissions:d})}}function sw(t,n,e){return{omissionId:B("omi",[t,n,"unavailable",e]),channel:n,reason:"unavailable",message:e,locator:t}}function aw(t,n){return n?.[t.attachmentId]!==void 0?!0:t.name==="trace"&&t.contentType==="application/zip"}function Or(t){return t.attempts.filter(n=>n.status==="interrupted"?!0:t.status==="unexpected"?n.status!=="skipped":t.status==="flaky"?n.status!=="passed"&&n.status!=="skipped":!1)}function EC(t){return{...t,logicalTests:t.logicalTests.map(n=>({...n,attempts:Or(n)})).filter(n=>n.attempts.length>0)}}function CC(t,n){let e={expected:0,unexpected:0,flaky:0,skipped:0};for(let a of t.logicalTests)e[a.status]+=1;let r=n.logicalTests.reduce((a,o)=>a+o.attempts.length,0),i=[...new Set(t.logicalTests.map(a=>a.projectId))].length,s=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`;return[`${Rt[t.framework]}${s} run of ${t.logicalTests.length} tests in ${i} project${i===1?"":"s"}`,`${e.expected} passed, ${e.unexpected} failed, ${e.flaky} flaky, ${e.skipped} skipped`,`evidence covers the ${r} failing attempt${r===1?"":"s"} of ${n.logicalTests.length} test${n.logicalTests.length===1?"":"s"}; passing tests are only counted.`].join("; ")}function is(t){let n=t.errors.map(r=>`${r.message??""}
159
+ ${r.stack??""}`),e=n.flatMap(r=>TC.flatMap(i=>[...r.matchAll(i)].map(s=>(s[1]??"").replace(/\\(.)/g,"$1"))));return[...new Set([...n.flatMap(r=>r.match(AC)??[]),...e.filter(r=>r!=="")])]}function NC(t,n,e,r,i){let s=t.attemptId===void 0?0:r.get(t.attemptId)??0;if(i.has(t.evidenceId))return re.afterFailure;switch(t.kind){case"error-field":case"run-summary":case"change-search":return re.failure;case"locator-suggestion":return re.failedCall+.95-Math.min(.5,s/1e3);case"page-snapshot":case"dom-subtree":case"dom-candidates":case"accessibility-node":{let o=t.kind==="accessibility-node"?.5:.9;return s<IC?re.failedCall+o-s/1e3:re.context+o-Math.min(.8,s/1e3)}default:break}let a=n.get(t.evidenceId);if(a!==void 0)return a;switch(t.kind){case"stack-frame":return/node_modules|node:internal/.test(t.observation)?re.ordinary:re.failedCall;case"source-range":{let o=e.get(t.evidenceId)??0;return re.significant-Math.min(.9,o/100)}case"diff-hunk":return re.failedCall+.9;case"step":return re.context;default:return re.ordinary}}async function fo(t,n,e){let r=Hl(e);if(r!==void 0)return{kind:"invalid-policy",message:r};if(e.workspaceRoot!==t.workspace.root)return{kind:"invalid-policy",message:"Evidence policy workspaceRoot must match the normalized run workspace root."};let i=n.artifactRoot??t.workspace.root,s=EC(t),a=Kg(s,e),o=[...a.artifacts],d=[...a.evidence],c=[...a.redactions],l=[...a.omissions],u=[...a.seeds],p=new Map,f=a.artifacts.find(E=>E.channel==="report");if(f!==void 0&&t.logicalTests.length>0){let E={type:"report-field",path:"stats"},M=CC(t,s);d.push({evidenceId:we(t.runId,f.artifactId,"run-summary",E,M),kind:"run-summary",artifactId:f.artifactId,locator:E,observation:M,availability:"present",redactionIds:[]})}for(let E of s.logicalTests)for(let M of E.attempts){let A=0,N=0,T=0,I=[...is(M)];for(let $ of M.attachments){if(!aw($,n.tracePaths))continue;let D=n.tracePaths?.[$.attachmentId]??$.path;if(D===void 0){l.push(sw(M.attemptId,"trace","Trace attachment supplied no path; inline trace bodies are not read."));continue}A+=1;let k=await ug(t.runId,e,{attachmentId:$.attachmentId,logicalTestId:E.logicalTestId,attemptId:M.attemptId,path:D,info:{...t.artifact.formatVersion===void 0?{}:{producerVersion:t.artifact.formatVersion},format:"playwright-trace-zip"}},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions),u.push(...k.seeds),I.push(...k.failedSelectors);for(let[S,_]of k.priorities)p.set(S,_)}for(let $ of M.attachments){if(!eu($))continue;N+=1;let D=await hg(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},i);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions),I.push(...D.failedSelectors);for(let[k,S]of D.priorities)p.set(k,S)}for(let $ of M.attachments){if(aw($,n.tracePaths)||eu($))continue;if(Bg($)){T+=1;let k=await Hg(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$,focus:I},i);o.push(...k.artifacts),d.push(...k.evidence),c.push(...k.redactions),l.push(...k.omissions);continue}let D=await _g(t.runId,e,{logicalTestId:E.logicalTestId,attemptId:M.attemptId,attachment:$},i);o.push(...D.artifacts),d.push(...D.evidence),c.push(...D.redactions),l.push(...D.omissions)}if(A===0&&N===0){let $=t.framework==="playwright"?"Attempt produced no trace attachment.":"Attempt has no KwikQA failure capture; run `kwikqa analyze --capture` to record the page.";for(let D of vC)D==="accessibility"&&T>0||l.push(sw(M.attemptId,D,$))}}if(n.probePath!==void 0){let E=await Vg(s,e,n.probePath,t.workspace.root);o.push(...E.artifacts),d.push(...E.evidence),c.push(...E.redactions),l.push(...E.omissions)}let h=await iw(t.runId,e,await Ug(u,t.workspace.root),t.workspace.root);o.push(...h.artifacts),d.push(...h.evidence),c.push(...h.redactions),l.push(...h.omissions);let m=new Map(h.evidence.map((E,M)=>[E.evidenceId,M])),g=h.artifacts.map(E=>E.path).filter(E=>E!==void 0),y=await mg(t.runId,e,g,{authorized:n.includeCurrentDiff===!0,workspaceRoot:t.workspace.root,...t.workspace.gitRoot===void 0?{}:{gitRoot:t.workspace.gitRoot}});o.push(...y.artifacts),d.push(...y.evidence),c.push(...y.redactions),l.push(...y.omissions);let w=await Dg(t.runId,t.createdAt,e,Ng(s.logicalTests.flatMap(E=>E.attempts),is,d.filter(E=>E.kind==="network-event").map(E=>E.observation)),{authorized:n.includeChangeHistory===!0,workspaceRoot:t.workspace.root,...t.workspace.gitRoot===void 0?{}:{gitRoot:t.workspace.gitRoot}});o.push(...w.artifacts),d.push(...w.evidence),c.push(...w.redactions),l.push(...w.omissions);let x=po(o,E=>E.artifactId),v=new Map(x.map(E=>[E.artifactId,E.channel])),R=(E,M,A)=>{let N=po(E,S=>S.evidenceId),T=po(M,S=>S.redactionId),I=po(A,S=>S.omissionId),$=xC.map(S=>SC(S,x,N,I,T)),D=S=>{let _={schemaVersion:"1.2",runId:t.runId,framework:t.framework,createdAt:t.createdAt,workspace:t.workspace,sourceHashes:t.sourceHashes,policy:e,artifacts:x,evidence:N,redactions:T,omissions:I,accounting:$,totals:{artifacts:x.length,evidence:N.length,redactions:T.length,omissions:I.length,serializedBytes:S}};return{..._,packetHash:Ir(_)}},k=D(0);for(let S=0;S<kC;S+=1){let _=rs(k);if(k.totals.serializedBytes===_)break;k=D(_)}return k},P=R(d,c,l),C=rs(P);if(C>e.maxPacketBytes){let E=new Set(d.flatMap(k=>k.redactionIds)),M=new Map(d.map(k=>[k.evidenceId,k])),A=new Map(s.logicalTests.flatMap(k=>k.attempts).map((k,S)=>[k.attemptId,S])),N=new Set,T=new Set;for(let k of[...d].sort((S,_)=>(A.get(S.attemptId??"")??0)-(A.get(_.attemptId??"")??0)||S.evidenceId.localeCompare(_.evidenceId))){if(k.kind==="error-field"||k.kind==="run-summary"||k.kind==="change-search")continue;let S=`${k.kind}
160
160
  ${k.observation}`;T.has(S)?N.add(k.evidenceId):T.add(S)}let I=d.map(k=>({item:k,priority:NC(k,p,m,A,N)})).filter(k=>k.priority<re.failure).sort((k,S)=>k.priority-S.priority||k.item.evidenceId.localeCompare(S.item.evidenceId)),$=new Set,D=0;for(let k=0;k<RC&&C>e.maxPacketBytes;k+=1){let S=C-e.maxPacketBytes*.97;for(;S>0&&D<I.length;){let Y=I[D++];if(Y===void 0)break;$.add(Y.item.evidenceId),S-=rs(Y.item)+64}let _=d.filter(Y=>!$.has(Y.evidenceId)),q=new Set(_.flatMap(Y=>Y.redactionIds)),K=c.filter(Y=>!E.has(Y.redactionId)||q.has(Y.redactionId)),te=new Map;for(let Y of $){let Ae=M.get(Y),Ee=Ae===void 0?void 0:v.get(Ae.artifactId);Ee!==void 0&&te.set(Ee,(te.get(Ee)??0)+1)}let le=[...te.entries()].map(([Y,Ae])=>{let Ee=`Dropped ${Ae} lower-priority ${Y} observation${Ae===1?"":"s"} to fit the ${e.maxPacketBytes}-byte packet budget; observations closest to the failure were kept.`;return{omissionId:B("omi",[t.runId,Y,"budget-exceeded","packet",Ee]),channel:Y,reason:"budget-exceeded",message:Ee,locator:"packet",cap:e.maxPacketBytes}});if(P=R(_,K,[...l,...le]),C=rs(P),D>=I.length)break}}return C>e.maxPacketBytes?{kind:"budget-exceeded",message:`Even the evidence closest to the failure is ${C} bytes, exceeding maxPacketBytes=${e.maxPacketBytes}; raise the explicit policy limit or narrow the authorized inputs.`}:{kind:"built",packet:P}}var OC=[[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>"],[/\b0x[0-9a-f]+\b/gi,"<hex>"],[/\b[0-9a-f]{16,}\b/gi,"<hex>"],[/\d+(?:\.\d+)?\s*(?:ms|milliseconds?)\b/gi,"<duration>"],[/\d+(?:\.\d+)?\s*(?:s|seconds?)\b/gi,"<duration>"],[/:\d+:\d+\b/g,":<line>:<col>"],[/\b(?:localhost|127\.0\.0\.1|\[::1\])(:\d+)?/gi,"<localhost>"],[/:\d{2,5}\b/g,":<port>"],[/\b\d+\b/g,"<n>"]];function ss(t){return t.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"").split("/").filter(r=>r.length>0).slice(-2).join("/")}function ho(t,n=200){let e=t.replace(/\r\n/g,`
161
- `).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,r=>ss(r));for(let[r,i]of OC)e=e.replace(r,i);return e=e.replace(/\s+/g," ").trim().toLowerCase(),e.length<=n?e:e.slice(0,n)}function dw(t){return t.replace(/['`]/g,'"').replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\{\s*/g,"{ ").replace(/\s*\}/g," }").trim()}function as(t,n){return`${ss(t)}:${n}`}var Or=["error-field","stack-frame","step"],fu=["error-field","stack-frame"],hu=["trace-event","console-event"];function Bt(t,n,e){return t.evidence.filter(r=>{if(!n.includes(r.kind))return!1;let i=t.normalized.get(r.evidenceId)??"";return e.some(s=>s.test(i))})}function $C(t,n,e){return t.evidence.filter(r=>n.includes(r.kind)&&e.some(i=>i.test(r.observation)))}var DC=[/timeouterror/,/timeout of <duration> exceeded/,/timeout <duration> exceeded/,/exceeded.{0,40}timeout/,/timed out/,/still not (?:existing|displayed|clickable|enabled|visible|selected) after/,/because element wasn't found/,/no such element: unable to locate element/,/expected condition failed: waiting for/],LC=[/\bexpect\(/,/\bassertion\b/,/\bexpect \$\$?\(/,/\bexpected .{0,200} to (?:have|be|equal|eq|contain|include|exist|match|deep)\b/,/\bassertionerror: assert\b/,/\bexpected: .{0,200}? but was: /,/\bexpected \[.{0,200}?\] but found \[/],MC=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],_C=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],jC=[/net::err_/,/navigation timeout/,/failed to navigate/,/navigation failed/,/err_(?:aborted|connection|name_not_resolved|empty_response|ssl)/,/cy\.visit\(\) failed/,/failed trying to load/],FC=[/target (?:page, context or browser )?(?:has been )?closed/,/browser has been closed/,/page crashed/,/target closed/,/browser closed unexpectedly/,/invalid session id/,/session deleted because of page crash/,/chrome not reachable/,/renderer process (?:just )?crashed/,/browser process (?:just )?crashed/],BC=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],HC=[/"(?:before|after) (?:each|all)" hook/,/\bglobal (?:setup|teardown)\b/,/\bteardown\b/,/\bin (?:before|after)(?:each|all)? hook\b/,/\bbefore hooks\b/,/\bafter hooks\b/,/\bbeforeall\b/,/\bbeforeeach\b/,/\bafterall\b/,/\baftereach\b/,/\bfixture\b/,/\bfailed on (?:setup|teardown) with\b/,/configinvoker\.invokeconfiguration/,/^container \S+ failed(?:, tests inside it did not run)?:/,/^(?:before|after) hook failed: /],zC=[/^(?:undefined|ambiguous|pending) step: /],mu=[{ruleId:"action-timeout/timeout-text",category:"action-timeout",description:"Failure text reports an expired action, element wait, or test timeout.",match:t=>Bt(t,Or,DC)},{ruleId:"action-timeout/timed-out-status",category:"action-timeout",description:"The attempt status is timedOut and failure text is present to cite.",match:t=>t.attempt?.status==="timedOut"?t.evidence.filter(n=>n.kind==="error-field"):[]},{ruleId:"assertion-mismatch/expect-failure",category:"assertion-mismatch",description:"Failure text reports an expectation that did not hold.",match:t=>{let n=Bt(t,Or,LC);return n.length>0?n:Bt(t,Or,MC)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:t=>Bt(t,[...Or,...hu],_C)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:t=>Bt(t,[...Or,...hu],jC)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:t=>$C(t,["network-event"],[/-> [45]\d\d\b/,/\bfailure=/])},{ruleId:"http-failure/request-error",category:"http-failure",description:"Failure text reports a request the test made that returned an error status.",match:t=>Bt(t,fu,BC)},{ruleId:"browser-crash/target-closed",category:"browser-crash",description:"The page, context, or browser was closed or crashed during the attempt.",match:t=>Bt(t,[...Or,...hu],FC)},{ruleId:"setup-failure/hook-or-fixture",category:"setup-failure",description:"The failure is attributed to a hook or fixture rather than the test body.",match:t=>Bt(t,fu,HC)},{ruleId:"unimplemented-step/no-runnable-definition",category:"unimplemented-step",description:"A Cucumber step had no step definition, several, or one marked pending.",match:t=>Bt(t,fu,zC)}];var jn={"action-timeout":"Action timeout","assertion-mismatch":"Assertion mismatch","page-exception":"Page exception","navigation-failure":"Navigation failure","http-failure":"HTTP failure","browser-crash":"Browser crash","setup-failure":"Setup failure","unimplemented-step":"Unimplemented step","artifact-failure":"Artifact failure",unclassified:"Unclassified failure"},VC=new Set(["failed","timedOut","interrupted"]),cw=160;function pw(t){let n=t.replace(/\s+/g," ").trim();return n.length<=cw?n:`${n.slice(0,cw)}\u2026`}function UC(t){for(let n of t){if(n.kind!=="trace-event")continue;let r=/^action(?: started| finished)?: ([\w.]+)/.exec(n.observation)?.[1];if(r!==void 0&&r!=="unknown")return r}}function qC(t){for(let n of t){if(n.kind!=="network-event")continue;let e=/^(\w+) (\S+) -> (\d{3})/.exec(n.observation);if(e===null)continue;let[,r,i,s]=e;if(r===void 0||i===void 0||s===void 0)continue;let a=i;try{a=new URL(i).host}catch{}return`${r} ${a} -> ${s}`}}function GC(t,n){if(t?.errorLocation!==void 0)return as(t.errorLocation.file,t.errorLocation.line??1);for(let e of n)if(e.locator.type==="source-range")return as(e.locator.path,e.locator.startLine);for(let e of n){if(e.kind!=="stack-frame")continue;let r=/([^\s():]+):(\d+):\d+/.exec(e.observation),i=r?.[1],s=r?.[2];if(i!==void 0&&s!==void 0)return as(i,Number.parseInt(s,10))}}function fw(t){let n=e=>t.find(r=>r.kind==="error-field"&&r.locator.type==="report-field"&&r.locator.path.endsWith(e));return n(".message")??n(".value")??t.find(e=>e.kind==="error-field")??t[0]}function KC(t,n,e){let r=fw(n),i=r===void 0?void 0:ho(r.observation),s=GC(t,n),a=UC(n),o=qC(n),[d]=t===void 0?[]:is(t),c=d===void 0?void 0:dw(d),l=s!==void 0&&e!==void 0&&!s.startsWith(`${ss(e)}:`)?s:void 0;return{...i===void 0||i===""?{}:{errorFingerprint:i},...s===void 0?{}:{sourceLocation:s},...a===void 0?{}:{actionApi:a},...o===void 0?{}:{networkEndpoint:o},...c===void 0||c===""?{}:{targetLocator:c},...l===void 0?{}:{supportLocation:l}}}function mo(t,n,e,r,i){let s=[...new Set(r.map(c=>c.evidenceId))].sort(),a=KC(i.attempt,r,i.specFile),o=fw(r),d=i.attempt?.attemptId??"run";return{symptomId:B("sym",[t,d,n,a.errorFingerprint??""]),category:n,ruleId:e,...i.logicalTestId===void 0?{}:{logicalTestId:i.logicalTestId},...i.attempt===void 0?{}:{attemptId:i.attempt.attemptId},evidenceIds:s,artifactIds:[],summary:`${jn[n]}: ${pw(o?.observation??"")}`,signals:a}}function lw(t){let n=new Map;for(let e of mu){let r=e.match(t);if(r.length===0)continue;let i=n.get(e.category);i===void 0?n.set(e.category,{ruleId:e.ruleId,cited:[...r]}):i.cited.push(...r)}return n}function uw(t){return new Map(t.map(n=>[n.evidenceId,ho(n.observation,400)]))}function go(t,n){let e=new Map;for(let s of n.evidence){if(s.attemptId===void 0)continue;let a=e.get(s.attemptId);a===void 0?e.set(s.attemptId,[s]):a.push(s)}let r=[],i=[];for(let s of t.logicalTests)for(let a of s.attempts){if(!VC.has(a.status))continue;let o=e.get(a.attemptId)??[],d={attempt:a,evidence:o,normalized:uw(o)},c=lw(d);if(c.size===0){if(o.length===0){i.push(a.attemptId);continue}r.push(mo(t.runId,"unclassified","unclassified/no-rule-matched",o.filter(l=>l.kind==="error-field").slice(0,3),{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}));continue}for(let[l,{ruleId:u,cited:p}]of c)r.push(mo(t.runId,l,u,p,{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}))}if(t.reportErrors.length>0){let s=n.evidence.filter(a=>a.attemptId===void 0&&a.logicalTestId===void 0);if(s.length>0){let a=lw({evidence:s,normalized:uw(s)});a.size===0&&r.push(mo(t.runId,"unclassified","unclassified/no-rule-matched",s.filter(o=>o.kind==="error-field").slice(0,3),{}));for(let[o,{ruleId:d,cited:c}]of a)r.push(mo(t.runId,o,d,c,{}))}}for(let s of n.artifacts)s.availability==="unreadable"&&r.push({symptomId:B("sym",[t.runId,s.artifactId,"artifact-failure"]),category:"artifact-failure",ruleId:"artifact-failure/unreadable-artifact",...s.attemptId===void 0?{}:{attemptId:s.attemptId},evidenceIds:[],artifactIds:[s.artifactId],summary:`${jn["artifact-failure"]}: ${s.channel} artifact could not be read${s.warnings[0]===void 0?"":` (${pw(s.warnings[0])})`}`,signals:{}});return{schemaVersion:"1.1",runId:t.runId,packetHash:n.packetHash,symptoms:[...r].sort((s,a)=>s.symptomId.localeCompare(a.symptomId)),unclassifiedAttemptIds:[...i].sort()}}var WC=new Set(["error-fingerprint","network-endpoint","failing-source-location","target-locator","support-location"]);var nn="<absent>";function yu(t,n){switch(n){case"symptom-category":return t.category;case"action-api":return t.signals.actionApi??nn;case"error-fingerprint":return t.signals.errorFingerprint??nn;case"network-endpoint":return t.signals.networkEndpoint??nn;case"failing-source-location":return t.signals.sourceLocation??nn;case"target-locator":return t.signals.targetLocator??nn;case"support-location":return t.signals.supportLocation??nn}}function JC(t,n){if(n.length<2)return{supported:!1,rationale:"A single logical test provides no shared behavior for a common cause."};let e=t.filter(r=>WC.has(r.kind)&&r.value!==nn);return e.length===0?{supported:!1,rationale:"Members share only broad signals, which group failures by shape rather than by origin."}:{supported:!0,rationale:`Members share ${e.map(r=>`${r.kind}=${r.value}`).join(" and ")}, which is specific enough to be consistent with one cause. This is a statement about evidence specificity, not proof that one cause produced every member.`}}var hw=["target-locator","support-location","network-endpoint"],mw=["symptom-category","error-fingerprint"];function gu(t){let n=new Map;for(let i of t.symptoms){if(i.logicalTestId===void 0)continue;let s=n.get(i.logicalTestId);s===void 0?n.set(i.logicalTestId,[i]):s.push(i)}let e=new Map;for(let i of n.values()){let s=[...i].sort((l,u)=>l.symptomId.localeCompare(u.symptomId)),a;for(let l of hw){let u=s.find(p=>yu(p,l)!==nn);if(u!==void 0){a=[{kind:l,value:yu(u,l)}];break}}let o=s[0];if(a===void 0&&o!==void 0&&(a=mw.map(l=>({kind:l,value:yu(o,l)}))),a===void 0)continue;let d=a.map(l=>`${l.kind}=${l.value}`).join("|"),c=e.get(d);c===void 0?e.set(d,{signals:a,members:[...i]}):c.members.push(...i)}let r=[...e.values()].map(({signals:i,members:s})=>{let a=[...new Set(s.map(d=>d.logicalTestId).filter(d=>d!==void 0))].sort(),o=JC(i,a);return{clusterId:B("clu",[t.runId,...i.map(d=>`${d.kind}=${d.value}`)]),logicalTestIds:a,symptomIds:s.map(d=>d.symptomId).sort(),signals:i,commonCauseSupported:o.supported,commonCauseRationale:o.rationale}});return{schemaVersion:"1.1",runId:t.runId,clusters:r.sort((i,s)=>i.clusterId.localeCompare(s.clusterId)),signalKinds:[...hw,...mw]}}function he(t,n,e,r,i={}){return{graderId:t,code:n,severity:e,message:r,...i.hypothesisId===void 0?{}:{hypothesisId:i.hypothesisId},...i.reference===void 0?{}:{reference:i.reference}}}function rn(t,n,e){return{graderId:t,passed:!e.some(r=>r.severity==="violation"),checked:n,findings:e}}var os={insufficient:0,weak:1,moderate:2,strong:3},wu={graderId:"abstention",description:"Diagnosis status matches evidence strength, and insufficient evidence abstains.",grade:t=>{let n=[],{diagnosis:e}=t,i=[...e.hypotheses].sort((o,d)=>o.rank-d.rank)[0],s=i===void 0?-1:os[i.evidenceGrade],a=1;return i===void 0||s===os.insufficient?e.status!=="inconclusive"&&n.push(he("abstention","failed-to-abstain","violation",`Evidence cannot rank a cause, but the diagnosis claims ${e.status}.`)):e.status==="conclusive"&&s<os.strong?n.push(he("abstention","conclusive-without-strong-evidence","violation",`Diagnosis claims conclusive on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})):e.status==="probable"&&s<os.moderate&&n.push(he("abstention","probable-without-moderate-evidence","violation",`Diagnosis claims probable on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})),a+=1,e.status==="inconclusive"&&e.repairEligibility==="eligible"&&n.push(he("abstention","repair-eligible-while-inconclusive","violation","Repair was marked eligible while the diagnosis is inconclusive.")),a+=1,e.status==="inconclusive"&&s>=os.strong&&n.push(he("abstention","abstained-with-strong-evidence","warning","Diagnosis abstained although the leading hypothesis carries strong evidence.",{...i===void 0?{}:{hypothesisId:i.hypothesisId}})),a+=1,e.status==="inconclusive"&&e.missingEvidence.length===0&&n.push(he("abstention","abstained-without-naming-gaps","warning","Diagnosis abstained without naming the evidence that was missing.")),rn("abstention",a,n)}};var bu={graderId:"citation-validity",description:"Every cited evidence, artifact, and symptom id exists in the graded packet.",grade:t=>{let n=[],e=0;t.diagnosis.packetHash!==t.packetHash&&n.push(he("citation-validity","packet-hash-mismatch","violation","The diagnosis was produced from a different evidence packet than the one being graded.",{reference:t.diagnosis.packetHash}));let r=s=>t.evidenceIds.has(s)||t.artifactIds.has(s),i=[["ownershipEvidenceIds",t.diagnosis.ownershipEvidenceIds,void 0],...t.diagnosis.hypotheses.flatMap(s=>[["supportingEvidenceIds",s.supportingEvidenceIds,s.hypothesisId],["contradictingEvidenceIds",s.contradictingEvidenceIds,s.hypothesisId]])];for(let[s,a,o]of i)for(let d of a)e+=1,!r(d)&&n.push(he("citation-validity","unknown-evidence-id","violation",`${s} cites ${d}, which the evidence packet does not contain.`,{...o===void 0?{}:{hypothesisId:o},reference:d}));for(let s of t.diagnosis.symptomIds)e+=1,!t.symptomIds.has(s)&&n.push(he("citation-validity","unknown-symptom-id","violation",`The diagnosis cites symptom ${s}, which this run did not produce.`,{reference:s}));return rn("citation-validity",e,n)}};var YC=new Set(["strong","moderate"]),xu={graderId:"ownership",description:"A named owner rests on cited positive evidence, and eligibility proves it.",grade:t=>{let n=[],{diagnosis:e}=t,r=0;for(let i of e.hypotheses)r+=1,i.probableOwner!=="undetermined"&&i.supportingEvidenceIds.length===0&&n.push(he("ownership","ownership-from-absence","violation",`Hypothesis assigns the ${i.probableOwner} owner without citing any supporting evidence.`,{hypothesisId:i.hypothesisId}));if(e.repairEligibility==="eligible"){r+=1,e.ownershipEvidenceIds.length===0&&n.push(he("ownership","eligible-without-ownership-evidence","violation","Repair was marked eligible without identifying the evidence that proves test-side ownership."));let i=[...e.hypotheses].sort((s,a)=>s.rank-a.rank)[0];i===void 0?n.push(he("ownership","eligible-without-hypothesis","violation","Repair was marked eligible without an accepted hypothesis.")):(i.probableOwner!=="test-support"&&n.push(he("ownership","eligible-without-test-ownership","violation",`Repair was marked eligible while the accepted hypothesis assigns the ${i.probableOwner} owner.`,{hypothesisId:i.hypothesisId})),YC.has(i.evidenceGrade)||n.push(he("ownership","eligible-on-insufficient-grade","violation",`Repair was marked eligible on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})))}return rn("ownership",r,n)}};var XC=/\b(?:evd|art|sym|clu|omi|red)_[a-f0-9]{8,}\b/g,vu={graderId:"unsupported-claims",description:"Claims are backed by citations, and grades match the evidence offered.",grade:t=>{let n=[],e=0;for(let i of t.diagnosis.hypotheses){e+=1;let{hypothesisId:s,supportingEvidenceIds:a,contradictingEvidenceIds:o}=i;i.evidenceGrade!=="insufficient"&&a.length===0&&n.push(he("unsupported-claims","claim-without-evidence","violation",`Hypothesis is graded ${i.evidenceGrade} but cites no supporting evidence.`,{hypothesisId:s})),i.evidenceGrade==="strong"&&(a.length<2&&n.push(he("unsupported-claims","strong-grade-underspecified","violation","A strong grade requires multiple specific observations, but only one was cited.",{hypothesisId:s})),o.length>0&&n.push(he("unsupported-claims","strong-grade-with-contradiction","violation","A strong grade requires no material unresolved contradiction, but contradicting evidence was cited.",{hypothesisId:s})),i.unresolvedAssumptions.length>0&&n.push(he("unsupported-claims","strong-grade-with-unresolved-assumptions","warning","A strong grade carries unresolved assumptions.",{hypothesisId:s})));let d=a.filter(l=>o.includes(l));for(let l of d)n.push(he("unsupported-claims","contradictory-citation","violation",`Evidence ${l} is cited as both supporting and contradicting the same hypothesis.`,{hypothesisId:s,reference:l}));let c=new Set([...a,...o]);for(let l of[i.statement,i.nextAction])for(let u of l.matchAll(XC)){let p=u[0];e+=1,!c.has(p)&&n.push(he("unsupported-claims","uncited-identifier-in-prose","violation",`Prose references ${p}, which this hypothesis does not cite.`,{hypothesisId:s,reference:p}))}}e+=1;let r=t.diagnosis.hypotheses.map(i=>i.rank);return new Set(r).size!==r.length&&n.push(he("unsupported-claims","duplicate-hypothesis-rank","violation","Hypotheses do not carry a distinct rank, so the accepted hypothesis is ambiguous.")),t.diagnosis.hypotheses.length>3&&n.push(he("unsupported-claims","too-many-hypotheses","violation",`A diagnosis returns at most three ranked hypotheses; ${t.diagnosis.hypotheses.length} were supplied.`)),rn("unsupported-claims",e,n)}};var gw=[bu,xu,wu,vu];function QC(t){return[...t].sort((n,e)=>{if(n.severity!==e.severity)return n.severity==="violation"?-1:1;let r=n.graderId.localeCompare(e.graderId);if(r!==0)return r;let i=n.code.localeCompare(e.code);return i!==0?i:(n.reference??"").localeCompare(e.reference??"")})}function ds(t,n,e){let r={diagnosis:t,evidenceIds:new Set(n.evidence.map(s=>s.evidenceId)),artifactIds:new Set(n.artifacts.map(s=>s.artifactId)),symptomIds:new Set(e.symptoms.map(s=>s.symptomId)),packetHash:n.packetHash},i=gw.map(s=>s.grade(r));return{schemaVersion:"1.0",packetHash:n.packetHash,passed:i.every(s=>s.passed),outcomes:i,findings:QC(i.flatMap(s=>s.findings))}}var ww=50,bw=24,Rw="<absent>",e1={"error-field":"Error","stack-frame":"Stack frame",step:"Step","stdio-chunk":"Output","trace-event":"Browser event","image-metadata":"Screenshot (metadata only)","video-metadata":"Video (metadata only)","dom-subtree":"Page elements","dom-candidates":"Similar elements","accessibility-node":"Accessibility","page-snapshot":"Page snapshot","console-event":"Console","network-event":"Network","source-range":"Source","diff-hunk":"Code change","change-search":"Change search","run-summary":"Run summary","locator-suggestion":"Locator suggestion"},t1={report:"Test report",trace:"Trace or failure capture",stdout:"Standard output",stderr:"Standard error",screenshot:"Screenshots",video:"Video",dom:"Page DOM",accessibility:"Accessibility tree",console:"Browser console",network:"Network",source:"Test source",diff:"Code changes",probe:"Live probe"},n1={unavailable:"not captured",unreadable:"unreadable","unsupported-version":"unsupported version","unauthorized-path":"outside the authorized paths","policy-disabled":"turned off by policy",redacted:"redacted","budget-exceeded":"over the size budget",irrelevant:"not relevant to the failures",unrecognized:"not recognized","parse-failed":"could not be parsed"},r1={"symptom-category":"Symptom","action-api":"Action","error-fingerprint":"Error","network-endpoint":"Request","support-location":"Support code","target-locator":"Locator","failing-source-location":"Failing line"},i1={expected:"passed",unexpected:"failed",flaky:"flaky",skipped:"skipped"};function Iw(t,n){return`${t} ${n}${t===1?"":"s"}`}function xw(t,n){let e=t.replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function s1(t){if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;return n<60?`${n.toFixed(1)} s`:`${Math.floor(n/60)} min ${Math.round(n%60)} s`}function vw(t){return t.replace("T"," ").replace(/(?:\.\d+)?Z$/," UTC")}var a1="1970-01-01T00:00:00.000Z";function o1(t){return t.replace(/^sha256:/,"").slice(0,12)}function Ru(t,n){let e=n.location.file,r=n.titlePath.filter(s=>s!==""&&s!==e&&s!==ZC(e)),i=t.projects.find(s=>s.projectId===n.projectId)?.name;return{title:r.join(" \u203A ")||n.title,location:n.location.line===void 0?e:`${e}:${n.location.line}`,...i===void 0||i===""||t.projects.length<2?{}:{project:i},status:i1[n.status],attempts:n.attempts.map(s=>s.retry===0?s.status:`${s.status} (retry ${s.retry})`)}}function Aw(t,n){let e=new Set(n);return t.logicalTests.filter(r=>e.has(r.logicalTestId)).map(r=>Ru(t,r))}function sn(t,n){let e=t.signals.find(r=>r.kind===n)?.value;return e===void 0||e===Rw?void 0:e}function d1(t,n){let e=sn(t,"symptom-category");return(e!==void 0?[e]:[...new Set((n?.symptoms.symptoms??[]).filter(s=>t.symptomIds.includes(s.symptomId)).map(s=>s.category))]).map(s=>jn[s]??s).join(", ")||jn.unclassified}function Tw(t,n){return t.evidence.filter(e=>e.kind==="error-field"&&e.attemptId!==void 0&&n.has(e.attemptId)&&e.locator.type==="report-field"&&/\.(?:message|value)$/.test(e.locator.path))}function c1(t,n){let e=n?.symptoms.symptoms.find(a=>t.symptomIds.includes(a.symptomId));if(n===void 0||e===void 0)return;let r=Tw(n.packet,new Set(e.attemptId===void 0?[]:[e.attemptId])).map(a=>a.observation.split(`
162
- `).find(o=>o.trim()!=="")?.trim()).find(a=>a!==void 0);if(r!==void 0)return r;let i=`${jn[e.category]}: `,s=e.summary.startsWith(i)?e.summary.slice(i.length):e.summary;return s.trim()===""?void 0:s}function l1(t,n,e){let r=sn(t,"target-locator"),i=sn(t,"network-endpoint"),s=sn(t,"support-location"),a=sn(t,"failing-source-location"),o=c1(t,e)??sn(t,"error-fingerprint");return r!==void 0?`Locator ${xw(r,90)}`:i!==void 0?`Request ${i}`:s!==void 0?`Failing in ${s}`:a!==void 0?`Failing at ${a}`:o!==void 0?xw(o,90):n}function u1(t,n){let e=sn(t,"support-location")??sn(t,"failing-source-location");if(e!==void 0)return e;let r=new Set(n.map(i=>i.location.replace(/:\d+$/,"")));return r.size===1?[...r][0]:void 0}function p1(t){return[...t.hypotheses].sort((n,e)=>n.rank-e.rank)[0]}function f1(t){let n=t?.diagnosis;if(t===void 0||n===void 0)return{owner:"not-diagnosed"};let e=p1(n);return t.outcome!=="diagnosed"||e===void 0?{owner:"inconclusive"}:{owner:e.probableOwner,grade:e.evidenceGrade}}function h1(t){let n=t.diagnosis;if(n!==void 0)return{status:n.status,hypotheses:[...n.hypotheses].sort((e,r)=>e.rank-r.rank).map(e=>({rank:e.rank,statement:e.statement,owner:e.probableOwner,grade:e.evidenceGrade,category:e.causalCategory,supporting:e.supportingEvidenceIds,contradicting:e.contradictingEvidenceIds,missing:e.missingEvidence,assumptions:e.unresolvedAssumptions,nextAction:e.nextAction})),missing:n.missingEvidence,nextAction:n.recommendedNextAction,repairEligibility:n.repairEligibility,escalated:t.escalated===!0}}function m1(t){let n=t.locator;switch(n.type){case"source-range":{let e=n.endLine===n.startLine?`${n.startLine}`:`${n.startLine}-${n.endLine}`;return`${n.path}:${e}${n.symbol===void 0?"":` (${n.symbol})`}`}case"diff-hunk":return`${n.commit===void 0?"uncommitted":`commit ${n.commit}`}, ${n.path}:${n.newStart}`;default:return}}function y1(t){let n=m1(t);return{evidenceId:t.evidenceId,label:e1[t.kind]??t.kind,...n===void 0?{}:{where:n},text:t.observation}}function Pw(t,n){let e=new Map(t.evidence.map(r=>[r.evidenceId,r]));return[...new Set(n)].flatMap(r=>{let i=e.get(r);return i===void 0?[]:[i]})}function g1(t){return[...[...t.hypotheses].sort((n,e)=>n.rank-e.rank).flatMap(n=>[...n.supportingEvidenceIds,...n.contradictingEvidenceIds]),...t.ownershipEvidenceIds]}function w1(t,n){let e=n.symptoms.symptoms.filter(s=>t.symptomIds.includes(s.symptomId)),r=new Set(e.flatMap(s=>s.attemptId??[])),i=[...Tw(n.packet,r).map(s=>s.evidenceId),...e.flatMap(s=>s.evidenceIds)];return Pw(n.packet,i)}function b1(t,n,e){if(e===void 0)return{evidence:[],evidenceCut:0};let r=n?.diagnosis,i;if(r!==void 0){let s=e.groupPackets[t.clusterId];if(s?.packetHash!==r.packetHash)return{evidence:[],evidenceCut:0,evidenceNote:"This group's evidence has changed since it was diagnosed, so the evidence its diagnosis cites can't be shown."};i=Pw(s,g1(r))}else i=w1(t,e);return{evidence:i.slice(0,bw).map(y1),evidenceCut:Math.max(0,i.length-bw)}}function x1(t,n){return t===void 0?n?"Not diagnosed: this was a local analysis, so no model was asked.":"Not sent: an analysis asks about at most 6 groups, the largest first.":t.outcome==="diagnosed"?t.escalated===!0?"Diagnosed, by the stronger model after the first answer failed its checks.":"Diagnosed.":`${t.outcome} (${t.reasonCode}): ${t.message}`}function ku(t,n,e,r,i,s){let a=d1(n,r),o=Aw(t,n.logicalTestIds),d=f1(e),c=e===void 0?void 0:h1(e),l=l1(n,a,r),u=n.logicalTestIds.length,p=u1(n,o);return{...i===void 0?{}:{number:i},anchor:i===void 0?`group-${n.clusterId}`:`group-${i}`,title:`${l} \xB7 ${Iw(u,"test")}`,subject:l,size:u,...p===void 0?{}:{place:p},category:a,signals:n.signals.filter(f=>f.value!==Rw).map(f=>({kind:r1[f.kind]??f.kind,value:f.value})),commonCause:{supported:n.commonCauseSupported,rationale:n.commonCauseRationale},...d,status:x1(e,s),tests:o.slice(0,ww),testsCut:Math.max(0,o.length-ww),...c===void 0?{}:{diagnosis:c},...b1(n,e,r)}}function v1(t){return{clusterId:t.clusterId,logicalTestIds:t.logicalTestIds,symptomIds:[],signals:t.signals,commonCauseSupported:!1,commonCauseRationale:"The evidence that grouped these tests could not be rebuilt."}}function kw(t,n){return n.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(n.clusterId)}function k1(t){let{run:n,record:e,detail:r}=t,i=r?.clusters.clusters??[],s=e.clusters??[];if(s.length===0)return[...i].sort(kw).map((u,p)=>ku(n,u,void 0,r,p+1,!0));let o=new Map(i.map(u=>[u.clusterId,u])),d=s.map((u,p)=>ku(n,o.get(u.clusterId)??v1(u),u,r,p+1,!1)),c=new Set(s.map(u=>u.clusterId)),l=i.filter(u=>!c.has(u.clusterId)).sort(kw).map(u=>ku(n,u,void 0,r,void 0,!1));return[...d,...l]}function Sw(t){let n=t.record.clusters??[],e=n.length>0?n.flatMap((i,s)=>i.diagnosisAudit===void 0?[]:[{group:`Group ${s+1}`,audit:i.diagnosisAudit}]):t.record.diagnosisAudit===void 0?[]:[{group:"Run",audit:t.record.diagnosisAudit}],r=t.repair?.repairAudit===void 0?[]:[{group:"Repair",audit:t.repair.repairAudit}];return[...e,...r]}function Ew(t){return`${t.model.modelId} via ${t.reportedProvider??t.model.providerId}`}function R1(t){return Sw(t).map(({group:n,audit:e})=>({group:n,purpose:e.purpose,model:Ew(e),zeroDataRetention:e.model.zeroDataRetention===!0,packetHash:o1(e.packetHash),...e.usage===void 0?{}:{tokens:`${e.usage.promptTokens.toLocaleString("en-US")} in, ${e.usage.completionTokens.toLocaleString("en-US")} out`},outcome:e.outcome.kind}))}function I1(t){let n=Sw(t).filter(({audit:r})=>r.outcome.kind==="diagnosed"||r.outcome.kind==="abstained"),e=[...new Set(n.map(({audit:r})=>Ew(r)))];return e.length>0?`Diagnosed with ${e.join(" and ")}.`:t.record.reasonCode==="remote-diagnosis-not-configured"?"Local analysis: no model was asked.":"No model answered this analysis."}function A1(t){let n=t.repair?.confirmation;if(n===void 0)return[];if(n.status!=="reproduced"&&n.status!=="not-reproduced")return[];let e=new Set(n.failedAgain??[]);return n.logicalTestIds.filter(r=>!e.has(r))}function T1(t){let{run:n}=t,e=n.logicalTests.filter(i=>i.status==="flaky").map(i=>Ru(n,i)),r=Aw(n,A1(t)).map(i=>({...i,status:"passed when fix re-ran it"}));return[...e,...r]}function P1(t){let{run:n,detail:e}=t,r=new Set(e?.symptoms.unclassifiedAttemptIds??[]),i=n.logicalTests.filter(o=>o.attempts.some(d=>r.has(d.attemptId))),s=(e?.symptoms.symptoms??[]).filter(o=>o.logicalTestId===void 0).map(o=>o.summary),a=s.length===0&&n.reportErrors.length>0?[`${Iw(n.reportErrors.length,"run-level error")} in the test report, not shown here because its evidence could not be built.`]:[];return{unclassified:i.map(o=>Ru(n,o)),runErrors:[...new Set([...s,...a])]}}function S1(t,n){let e=t.repair;if(e===void 0)return;let r=(t.record.clusters??[]).findIndex(a=>a.diagnosis!==void 0&&a.diagnosis.packetHash===e.diagnosis?.packetHash),i=r<0?void 0:n.find(a=>a.number===r+1),s=e.repairProposal;return{...i===void 0?{}:{groupAnchor:i.anchor,groupTitle:i.title},command:e.command,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message,phases:[{phase:"Proposal",status:e.proposal.status},{phase:"Application",status:e.application.status},{phase:"Validation",status:e.validation.status}],...s===void 0?{}:{intent:{statement:s.intent.statement,preserved:s.intent.preservedBehavior},diff:s.diff}}}function wo(t){let{run:n,record:e,detail:r}=t,i=p=>n.logicalTests.filter(f=>f.status===p).length,s=i("unexpected"),a=i("flaky"),o=Rt[n.framework],d=n.artifact.formatVersion===void 0?"":` ${n.artifact.formatVersion}`,c=k1(t),l=new Map;for(let p of r?.packet.omissions??[]){let f=n1[p.reason]??p.reason;l.set(f,(l.get(f)??0)+1)}let u=S1(t,c);return{title:`KwikQA report: ${n.framework==="unknown"?"run from an unidentified framework":`${o} run`}, ${s} failed${a===0?"":`, ${a} flaky`}`,recordedAt:vw(e.recordedAt),run:{framework:`${o}${d}`,...n.artifact.format===void 0?{}:{format:Zt[n.artifact.format]},counts:[{label:"Tests",value:n.logicalTests.length},{label:"Failed",value:s},{label:"Flaky",value:a},{label:"Passed",value:i("expected")},{label:"Skipped",value:i("skipped")}],duration:s1(n.stats.duration),...e.inputs===void 0?{}:{report:e.inputs.report},createdAt:n.createdAt===a1?"not recorded in the report":vw(n.createdAt),diagnosedBy:I1(t),outcome:`${e.outcome} (${e.reasonCode})`,message:e.message},groups:c,flaky:T1(t),notAnalyzed:P1(t),coverage:(r?.packet.accounting??[]).map(p=>({channel:t1[p.channel]??p.channel,availability:p.availability,included:p.included,omitted:p.omitted})),omissions:[...l].map(([p,f])=>({reason:p,count:f})).sort((p,f)=>f.count-p.count||p.reason.localeCompare(f.reason)),redactions:r?.packet.totals.redactions??0,requests:R1(t),...u===void 0?{}:{repair:u},...r===void 0?{evidenceNote:"The evidence this analysis read could not be rebuilt, so only its recorded results are shown."}:{},footer:{runId:e.runId,recordId:e.recordId,kwikqaVersion:t.kwikqaVersion}}}import{appendFile as E1,readFile as C1}from"node:fs/promises";var N1=30,Cw=100,O1=3e4,$1=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,D1=/^(?!.*\.\.)(?!\/)(?!.*\/$)[^\s\0~^:?*[\\]{1,255}$/;async function L1(t){if(t===void 0||t==="")return{};try{let n=JSON.parse(await C1(t,"utf8"));return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function bo(t){if(t.GITHUB_ACTIONS!=="true")return;let n=$1.test(t.GITHUB_REPOSITORY??"")?t.GITHUB_REPOSITORY:void 0,e=st(t.GITHUB_API_URL,"https://api.github.com"),r=st(t.GITHUB_SERVER_URL,"https://github.com"),i=/^\d+$/.test(t.GITHUB_RUN_ID??"")?t.GITHUB_RUN_ID:void 0,s=Number(t.GITHUB_RUN_ATTEMPT),a=/^\d+$/.test(t.GITHUB_RUN_ATTEMPT??"")&&Number.isSafeInteger(s)&&s>0?s:void 0,o=(await L1(t.GITHUB_EVENT_PATH)).pull_request,d=o?.number,c=o?.head?.repo?.full_name,l=o?.base?.repo?.full_name,u=o?.head?.ref,p=o?.head?.sha,f=/^refs\/[^\s\0]+$/.test(t.GITHUB_REF??"")?t.GITHUB_REF:void 0,h=(t.GITHUB_TOKEN??"").trim(),m=r===void 0||n===void 0?void 0:`${r}/${n}`,g=t.GITHUB_HEAD_REF||t.GITHUB_REF_NAME||void 0,y=/^[0-9a-f]{40}$/.test(t.GITHUB_SHA??"")?t.GITHUB_SHA:void 0;return{...e===void 0?{}:{apiUrl:e},...n===void 0?{}:{repository:n},...m===void 0||i===void 0?{}:{runUrl:`${m}/actions/runs/${i}`},workflow:t.GITHUB_WORKFLOW??"",job:t.GITHUB_JOB??"",...i===void 0?{}:{runId:i},...a===void 0?{}:{runAttempt:a},...f===void 0?{}:{ref:f},...typeof u=="string"&&D1.test(u)&&typeof p=="string"&&/^[0-9a-f]{40}$/.test(p)?{pullRequestHead:{ref:u,sha:p}}:{},...g===void 0?{}:{branch:g},...y===void 0?{}:{commit:{sha:y,...m===void 0?{}:{url:`${m}/commit/${y}`}}},...t.GITHUB_STEP_SUMMARY===void 0||t.GITHUB_STEP_SUMMARY===""?{}:{summaryPath:t.GITHUB_STEP_SUMMARY},...h===""?{}:{token:h},...typeof d=="number"&&Number.isSafeInteger(d)&&d>0?{pullRequest:{number:d,...m===void 0?{}:{url:`${m}/pull/${d}`},fork:t.GITHUB_EVENT_NAME!=="pull_request_target"&&(typeof c!="string"||c!==l)}}:{}}}function Nw(t){return`<!-- kwikqa-ci workflow=${encodeURIComponent(t.workflow)} job=${encodeURIComponent(t.job)} -->`}async function Iu(t,n){if(t.status===429||t.status===403&&(t.headers.get("x-ratelimit-remaining")==="0"||t.headers.has("retry-after")))return"GitHub's rate limit was reached";if(t.status===403)return n;if(t.status===401)return"GitHub refused the token";if(t.status===404)return"GitHub found no such pull request with this token";let e=await t.json().catch(()=>{}),r=typeof e?.message=="string"?`: ${e.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitHub answered ${t.status}${r}`}var Dr=class{constructor(n,e,r){this.send=n;this.apiUrl=e;this.token=r}send;apiUrl;token;call(n,e,r){return this.send(`${this.apiUrl}${e}`,{method:n,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(O1)})}},$r=class extends Error{};async function M1(t,n,e,r){for(let i=1;i<=N1;i+=1){let s=await t.call("GET",`${n}/comments?per_page=${Cw}&page=${i}`);if(!s.ok)throw new $r(await Iu(s,r));let a=await s.json(),o=a.find(d=>typeof d.body=="string"&&d.body.startsWith(e));if(typeof o?.id=="number")return o.id;if(a.length<Cw)return}}async function cs(t,n,e,r,i){let s=new Dr(n,e.apiUrl,e.token),a=`/repos/${e.repository}/issues/${e.number}`,o={body:`${e.marker}
163
- ${r}`},d=e.noun??"pull-request comment",c=`${d.charAt(0).toUpperCase()}${d.slice(1)}`;try{let l=await M1(s,a,e.marker,e.forbidden);if(l!==void 0){let p=await s.call("PATCH",`/repos/${e.repository}/issues/comments/${l}`,o);if(p.ok)return t.print(`${c}: updated.`);if(p.status!==403&&p.status!==404)throw new $r(await Iu(p,e.forbidden))}if(l===void 0&&!i)return t.print(`No ${d}: nothing failed, and there is no earlier comment to update.`);let u=await s.call("POST",`${a}/comments`,o);if(!u.ok)throw new $r(await Iu(u,e.forbidden));t.print(`${c}: posted.`)}catch(l){let u=l instanceof $r?l.message:`GitHub couldn't be reached (${l instanceof Error?l.message:String(l)})`;t.error(`No ${d}: ${u}.`)}}async function _1(t,n,e,r,i){let s=o=>t.print(`No pull-request comment: ${o}.`),a=e.pullRequest;if(a===void 0)return s("this run isn't for a pull request");if(a.fork)return s("the pull request comes from a fork, and GitHub gives its workflows a read-only token");if(e.token===void 0)return s("GITHUB_TOKEN isn't set; add `GITHUB_TOKEN: ${{ github.token }}` to the step's env");if(e.apiUrl===void 0||e.repository===void 0)return s("GITHUB_API_URL or GITHUB_REPOSITORY isn't what GitHub Actions sets");await cs(t,n,{apiUrl:e.apiUrl,repository:e.repository,number:a.number,token:e.token,marker:Nw(e),forbidden:"the token can't comment on this pull request; give the job `pull-requests: write` permission"},r,i)}async function Au(t,n,e,r,i){if(e.summaryPath===void 0)t.print("No job summary: GITHUB_STEP_SUMMARY isn't set.");else try{await E1(e.summaryPath,`${r}
164
- `),t.print("Job summary: written.")}catch(s){t.error(`No job summary: ${s.message}`)}await _1(t,n,e,r,i.failures)}var j1=20,Ow=10,F1=100;function Lr(t,n){return`${t} ${n}${t===1?"":"s"}`}function $w(t,n){let e=t.replace(/[\p{Cc}\u202a-\u202e\u2066-\u2069]/gu," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function ge(t,n={}){let e=$w(t,F1)||"(empty)",r=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),i="`".repeat(r+1),s=e.startsWith("`")||e.endsWith("`")?" ":"",a=n.table===!0?e.replace(/\|/g,"\\|"):e;return`${i}${s}${a}${s}${i}`}function ls(t){return $w(t,1e3).replace(/[\\`*_{}[\]()#+!|<>~&]/g,"\\$&")}function B1(t){return`| ${[t.number===void 0?"\u2013":String(t.number),String(t.size),ge(t.subject,{table:!0}),Mt[t.owner],t.grade===void 0?"\u2013":ls(t.grade)].join(" | ")} |`}function H1(t,n){return t>0?`### KwikQA: ${Lr(t,"test")} failed${n===0?"":`, ${n} flaky`}`:n===0?"### KwikQA: no failures":`### KwikQA: no failures, ${Lr(n,"flaky test")}`}function Tu(t){let{model:n}=t;if(n===void 0)return`### KwikQA: no analysis
161
+ `).replace(/(?:file:\/\/)?(?:[A-Za-z]:)?(?:\/[\w.@+-]+){2,}/g,r=>ss(r));for(let[r,i]of OC)e=e.replace(r,i);return e=e.replace(/\s+/g," ").trim().toLowerCase(),e.length<=n?e:e.slice(0,n)}function dw(t){return t.replace(/['`]/g,'"').replace(/\s+/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\{\s*/g,"{ ").replace(/\s*\}/g," }").trim()}function as(t,n){return`${ss(t)}:${n}`}var $r=["error-field","stack-frame","step"],fu=["error-field","stack-frame"],hu=["trace-event","console-event"];function Bt(t,n,e){return t.evidence.filter(r=>{if(!n.includes(r.kind))return!1;let i=t.normalized.get(r.evidenceId)??"";return e.some(s=>s.test(i))})}function $C(t,n,e){return t.evidence.filter(r=>n.includes(r.kind)&&e.some(i=>i.test(r.observation)))}var DC=[/timeouterror/,/timeout of <duration> exceeded/,/timeout <duration> exceeded/,/exceeded.{0,40}timeout/,/timed out/,/still not (?:existing|displayed|clickable|enabled|visible|selected) after/,/because element wasn't found/,/no such element: unable to locate element/,/expected condition failed: waiting for/],LC=[/\bexpect\(/,/\bassertion\b/,/\bexpect \$\$?\(/,/\bexpected .{0,200} to (?:have|be|equal|eq|contain|include|exist|match|deep)\b/,/\bassertionerror: assert\b/,/\bexpected: .{0,200}? but was: /,/\bexpected \[.{0,200}?\] but found \[/],MC=[/expected:.{0,80}received:/s,/received:.{0,80}expected:/s],_C=[/uncaught \w*error/,/\bpageerror\b/,/unhandled (?:promise )?rejection/,/uncaught page error/,/originated from your application code/],jC=[/net::err_/,/navigation timeout/,/failed to navigate/,/navigation failed/,/err_(?:aborted|connection|name_not_resolved|empty_response|ssl)/,/cy\.visit\(\) failed/,/failed trying to load/],FC=[/target (?:page, context or browser )?(?:has been )?closed/,/browser has been closed/,/page crashed/,/target closed/,/browser closed unexpectedly/,/invalid session id/,/session deleted because of page crash/,/chrome not reachable/,/renderer process (?:just )?crashed/,/browser process (?:just )?crashed/],BC=[/cy\.request\(\) failed/,/response we received from your web server was/,/request failed with status code/],HC=[/"(?:before|after) (?:each|all)" hook/,/\bglobal (?:setup|teardown)\b/,/\bteardown\b/,/\bin (?:before|after)(?:each|all)? hook\b/,/\bbefore hooks\b/,/\bafter hooks\b/,/\bbeforeall\b/,/\bbeforeeach\b/,/\bafterall\b/,/\baftereach\b/,/\bfixture\b/,/\bfailed on (?:setup|teardown) with\b/,/configinvoker\.invokeconfiguration/,/^container \S+ failed(?:, tests inside it did not run)?:/,/^(?:before|after) hook failed: /],zC=[/^(?:undefined|ambiguous|pending) step: /],mu=[{ruleId:"action-timeout/timeout-text",category:"action-timeout",description:"Failure text reports an expired action, element wait, or test timeout.",match:t=>Bt(t,$r,DC)},{ruleId:"action-timeout/timed-out-status",category:"action-timeout",description:"The attempt status is timedOut and failure text is present to cite.",match:t=>t.attempt?.status==="timedOut"?t.evidence.filter(n=>n.kind==="error-field"):[]},{ruleId:"assertion-mismatch/expect-failure",category:"assertion-mismatch",description:"Failure text reports an expectation that did not hold.",match:t=>{let n=Bt(t,$r,LC);return n.length>0?n:Bt(t,$r,MC)}},{ruleId:"page-exception/uncaught-error",category:"page-exception",description:"An uncaught page error or unhandled rejection was observed.",match:t=>Bt(t,[...$r,...hu],_C)},{ruleId:"navigation-failure/net-error",category:"navigation-failure",description:"Navigation reported a network-level or navigation timeout error.",match:t=>Bt(t,[...$r,...hu],jC)},{ruleId:"http-failure/error-status",category:"http-failure",description:"A recorded request returned a 4xx or 5xx status, or reported a failure.",match:t=>$C(t,["network-event"],[/-> [45]\d\d\b/,/\bfailure=/])},{ruleId:"http-failure/request-error",category:"http-failure",description:"Failure text reports a request the test made that returned an error status.",match:t=>Bt(t,fu,BC)},{ruleId:"browser-crash/target-closed",category:"browser-crash",description:"The page, context, or browser was closed or crashed during the attempt.",match:t=>Bt(t,[...$r,...hu],FC)},{ruleId:"setup-failure/hook-or-fixture",category:"setup-failure",description:"The failure is attributed to a hook or fixture rather than the test body.",match:t=>Bt(t,fu,HC)},{ruleId:"unimplemented-step/no-runnable-definition",category:"unimplemented-step",description:"A Cucumber step had no step definition, several, or one marked pending.",match:t=>Bt(t,fu,zC)}];var jn={"action-timeout":"Action timeout","assertion-mismatch":"Assertion mismatch","page-exception":"Page exception","navigation-failure":"Navigation failure","http-failure":"HTTP failure","browser-crash":"Browser crash","setup-failure":"Setup failure","unimplemented-step":"Unimplemented step","artifact-failure":"Artifact failure",unclassified:"Unclassified failure"},VC=new Set(["failed","timedOut","interrupted"]),cw=160;function pw(t){let n=t.replace(/\s+/g," ").trim();return n.length<=cw?n:`${n.slice(0,cw)}\u2026`}function UC(t){for(let n of t){if(n.kind!=="trace-event")continue;let r=/^action(?: started| finished)?: ([\w.]+)/.exec(n.observation)?.[1];if(r!==void 0&&r!=="unknown")return r}}function qC(t){for(let n of t){if(n.kind!=="network-event")continue;let e=/^(\w+) (\S+) -> (\d{3})/.exec(n.observation);if(e===null)continue;let[,r,i,s]=e;if(r===void 0||i===void 0||s===void 0)continue;let a=i;try{a=new URL(i).host}catch{}return`${r} ${a} -> ${s}`}}function GC(t,n){if(t?.errorLocation!==void 0)return as(t.errorLocation.file,t.errorLocation.line??1);for(let e of n)if(e.locator.type==="source-range")return as(e.locator.path,e.locator.startLine);for(let e of n){if(e.kind!=="stack-frame")continue;let r=/([^\s():]+):(\d+):\d+/.exec(e.observation),i=r?.[1],s=r?.[2];if(i!==void 0&&s!==void 0)return as(i,Number.parseInt(s,10))}}function fw(t){let n=e=>t.find(r=>r.kind==="error-field"&&r.locator.type==="report-field"&&r.locator.path.endsWith(e));return n(".message")??n(".value")??t.find(e=>e.kind==="error-field")??t[0]}function KC(t,n,e){let r=fw(n),i=r===void 0?void 0:ho(r.observation),s=GC(t,n),a=UC(n),o=qC(n),[d]=t===void 0?[]:is(t),c=d===void 0?void 0:dw(d),l=s!==void 0&&e!==void 0&&!s.startsWith(`${ss(e)}:`)?s:void 0;return{...i===void 0||i===""?{}:{errorFingerprint:i},...s===void 0?{}:{sourceLocation:s},...a===void 0?{}:{actionApi:a},...o===void 0?{}:{networkEndpoint:o},...c===void 0||c===""?{}:{targetLocator:c},...l===void 0?{}:{supportLocation:l}}}function mo(t,n,e,r,i){let s=[...new Set(r.map(c=>c.evidenceId))].sort(),a=KC(i.attempt,r,i.specFile),o=fw(r),d=i.attempt?.attemptId??"run";return{symptomId:B("sym",[t,d,n,a.errorFingerprint??""]),category:n,ruleId:e,...i.logicalTestId===void 0?{}:{logicalTestId:i.logicalTestId},...i.attempt===void 0?{}:{attemptId:i.attempt.attemptId},evidenceIds:s,artifactIds:[],summary:`${jn[n]}: ${pw(o?.observation??"")}`,signals:a}}function lw(t){let n=new Map;for(let e of mu){let r=e.match(t);if(r.length===0)continue;let i=n.get(e.category);i===void 0?n.set(e.category,{ruleId:e.ruleId,cited:[...r]}):i.cited.push(...r)}return n}function uw(t){return new Map(t.map(n=>[n.evidenceId,ho(n.observation,400)]))}function go(t,n){let e=new Map;for(let s of n.evidence){if(s.attemptId===void 0)continue;let a=e.get(s.attemptId);a===void 0?e.set(s.attemptId,[s]):a.push(s)}let r=[],i=[];for(let s of t.logicalTests)for(let a of s.attempts){if(!VC.has(a.status))continue;let o=e.get(a.attemptId)??[],d={attempt:a,evidence:o,normalized:uw(o)},c=lw(d);if(c.size===0){if(o.length===0){i.push(a.attemptId);continue}r.push(mo(t.runId,"unclassified","unclassified/no-rule-matched",o.filter(l=>l.kind==="error-field").slice(0,3),{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}));continue}for(let[l,{ruleId:u,cited:p}]of c)r.push(mo(t.runId,l,u,p,{logicalTestId:s.logicalTestId,attempt:a,specFile:s.location.file}))}if(t.reportErrors.length>0){let s=n.evidence.filter(a=>a.attemptId===void 0&&a.logicalTestId===void 0);if(s.length>0){let a=lw({evidence:s,normalized:uw(s)});a.size===0&&r.push(mo(t.runId,"unclassified","unclassified/no-rule-matched",s.filter(o=>o.kind==="error-field").slice(0,3),{}));for(let[o,{ruleId:d,cited:c}]of a)r.push(mo(t.runId,o,d,c,{}))}}for(let s of n.artifacts)s.availability==="unreadable"&&r.push({symptomId:B("sym",[t.runId,s.artifactId,"artifact-failure"]),category:"artifact-failure",ruleId:"artifact-failure/unreadable-artifact",...s.attemptId===void 0?{}:{attemptId:s.attemptId},evidenceIds:[],artifactIds:[s.artifactId],summary:`${jn["artifact-failure"]}: ${s.channel} artifact could not be read${s.warnings[0]===void 0?"":` (${pw(s.warnings[0])})`}`,signals:{}});return{schemaVersion:"1.1",runId:t.runId,packetHash:n.packetHash,symptoms:[...r].sort((s,a)=>s.symptomId.localeCompare(a.symptomId)),unclassifiedAttemptIds:[...i].sort()}}var WC=new Set(["error-fingerprint","network-endpoint","failing-source-location","target-locator","support-location"]);var nn="<absent>";function yu(t,n){switch(n){case"symptom-category":return t.category;case"action-api":return t.signals.actionApi??nn;case"error-fingerprint":return t.signals.errorFingerprint??nn;case"network-endpoint":return t.signals.networkEndpoint??nn;case"failing-source-location":return t.signals.sourceLocation??nn;case"target-locator":return t.signals.targetLocator??nn;case"support-location":return t.signals.supportLocation??nn}}function JC(t,n){if(n.length<2)return{supported:!1,rationale:"A single logical test provides no shared behavior for a common cause."};let e=t.filter(r=>WC.has(r.kind)&&r.value!==nn);return e.length===0?{supported:!1,rationale:"Members share only broad signals, which group failures by shape rather than by origin."}:{supported:!0,rationale:`Members share ${e.map(r=>`${r.kind}=${r.value}`).join(" and ")}, which is specific enough to be consistent with one cause. This is a statement about evidence specificity, not proof that one cause produced every member.`}}var hw=["target-locator","support-location","network-endpoint"],mw=["symptom-category","error-fingerprint"];function gu(t){let n=new Map;for(let i of t.symptoms){if(i.logicalTestId===void 0)continue;let s=n.get(i.logicalTestId);s===void 0?n.set(i.logicalTestId,[i]):s.push(i)}let e=new Map;for(let i of n.values()){let s=[...i].sort((l,u)=>l.symptomId.localeCompare(u.symptomId)),a;for(let l of hw){let u=s.find(p=>yu(p,l)!==nn);if(u!==void 0){a=[{kind:l,value:yu(u,l)}];break}}let o=s[0];if(a===void 0&&o!==void 0&&(a=mw.map(l=>({kind:l,value:yu(o,l)}))),a===void 0)continue;let d=a.map(l=>`${l.kind}=${l.value}`).join("|"),c=e.get(d);c===void 0?e.set(d,{signals:a,members:[...i]}):c.members.push(...i)}let r=[...e.values()].map(({signals:i,members:s})=>{let a=[...new Set(s.map(d=>d.logicalTestId).filter(d=>d!==void 0))].sort(),o=JC(i,a);return{clusterId:B("clu",[t.runId,...i.map(d=>`${d.kind}=${d.value}`)]),logicalTestIds:a,symptomIds:s.map(d=>d.symptomId).sort(),signals:i,commonCauseSupported:o.supported,commonCauseRationale:o.rationale}});return{schemaVersion:"1.1",runId:t.runId,clusters:r.sort((i,s)=>i.clusterId.localeCompare(s.clusterId)),signalKinds:[...hw,...mw]}}function he(t,n,e,r,i={}){return{graderId:t,code:n,severity:e,message:r,...i.hypothesisId===void 0?{}:{hypothesisId:i.hypothesisId},...i.reference===void 0?{}:{reference:i.reference}}}function rn(t,n,e){return{graderId:t,passed:!e.some(r=>r.severity==="violation"),checked:n,findings:e}}var os={insufficient:0,weak:1,moderate:2,strong:3},wu={graderId:"abstention",description:"Diagnosis status matches evidence strength, and insufficient evidence abstains.",grade:t=>{let n=[],{diagnosis:e}=t,i=[...e.hypotheses].sort((o,d)=>o.rank-d.rank)[0],s=i===void 0?-1:os[i.evidenceGrade],a=1;return i===void 0||s===os.insufficient?e.status!=="inconclusive"&&n.push(he("abstention","failed-to-abstain","violation",`Evidence cannot rank a cause, but the diagnosis claims ${e.status}.`)):e.status==="conclusive"&&s<os.strong?n.push(he("abstention","conclusive-without-strong-evidence","violation",`Diagnosis claims conclusive on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})):e.status==="probable"&&s<os.moderate&&n.push(he("abstention","probable-without-moderate-evidence","violation",`Diagnosis claims probable on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})),a+=1,e.status==="inconclusive"&&e.repairEligibility==="eligible"&&n.push(he("abstention","repair-eligible-while-inconclusive","violation","Repair was marked eligible while the diagnosis is inconclusive.")),a+=1,e.status==="inconclusive"&&s>=os.strong&&n.push(he("abstention","abstained-with-strong-evidence","warning","Diagnosis abstained although the leading hypothesis carries strong evidence.",{...i===void 0?{}:{hypothesisId:i.hypothesisId}})),a+=1,e.status==="inconclusive"&&e.missingEvidence.length===0&&n.push(he("abstention","abstained-without-naming-gaps","warning","Diagnosis abstained without naming the evidence that was missing.")),rn("abstention",a,n)}};var bu={graderId:"citation-validity",description:"Every cited evidence, artifact, and symptom id exists in the graded packet.",grade:t=>{let n=[],e=0;t.diagnosis.packetHash!==t.packetHash&&n.push(he("citation-validity","packet-hash-mismatch","violation","The diagnosis was produced from a different evidence packet than the one being graded.",{reference:t.diagnosis.packetHash}));let r=s=>t.evidenceIds.has(s)||t.artifactIds.has(s),i=[["ownershipEvidenceIds",t.diagnosis.ownershipEvidenceIds,void 0],...t.diagnosis.hypotheses.flatMap(s=>[["supportingEvidenceIds",s.supportingEvidenceIds,s.hypothesisId],["contradictingEvidenceIds",s.contradictingEvidenceIds,s.hypothesisId]])];for(let[s,a,o]of i)for(let d of a)e+=1,!r(d)&&n.push(he("citation-validity","unknown-evidence-id","violation",`${s} cites ${d}, which the evidence packet does not contain.`,{...o===void 0?{}:{hypothesisId:o},reference:d}));for(let s of t.diagnosis.symptomIds)e+=1,!t.symptomIds.has(s)&&n.push(he("citation-validity","unknown-symptom-id","violation",`The diagnosis cites symptom ${s}, which this run did not produce.`,{reference:s}));return rn("citation-validity",e,n)}};var YC=new Set(["strong","moderate"]),xu={graderId:"ownership",description:"A named owner rests on cited positive evidence, and eligibility proves it.",grade:t=>{let n=[],{diagnosis:e}=t,r=0;for(let i of e.hypotheses)r+=1,i.probableOwner!=="undetermined"&&i.supportingEvidenceIds.length===0&&n.push(he("ownership","ownership-from-absence","violation",`Hypothesis assigns the ${i.probableOwner} owner without citing any supporting evidence.`,{hypothesisId:i.hypothesisId}));if(e.repairEligibility==="eligible"){r+=1,e.ownershipEvidenceIds.length===0&&n.push(he("ownership","eligible-without-ownership-evidence","violation","Repair was marked eligible without identifying the evidence that proves test-side ownership."));let i=[...e.hypotheses].sort((s,a)=>s.rank-a.rank)[0];i===void 0?n.push(he("ownership","eligible-without-hypothesis","violation","Repair was marked eligible without an accepted hypothesis.")):(i.probableOwner!=="test-support"&&n.push(he("ownership","eligible-without-test-ownership","violation",`Repair was marked eligible while the accepted hypothesis assigns the ${i.probableOwner} owner.`,{hypothesisId:i.hypothesisId})),YC.has(i.evidenceGrade)||n.push(he("ownership","eligible-on-insufficient-grade","violation",`Repair was marked eligible on ${i.evidenceGrade} evidence.`,{hypothesisId:i.hypothesisId})))}return rn("ownership",r,n)}};var XC=/\b(?:evd|art|sym|clu|omi|red)_[a-f0-9]{8,}\b/g,vu={graderId:"unsupported-claims",description:"Claims are backed by citations, and grades match the evidence offered.",grade:t=>{let n=[],e=0;for(let i of t.diagnosis.hypotheses){e+=1;let{hypothesisId:s,supportingEvidenceIds:a,contradictingEvidenceIds:o}=i;i.evidenceGrade!=="insufficient"&&a.length===0&&n.push(he("unsupported-claims","claim-without-evidence","violation",`Hypothesis is graded ${i.evidenceGrade} but cites no supporting evidence.`,{hypothesisId:s})),i.evidenceGrade==="strong"&&(a.length<2&&n.push(he("unsupported-claims","strong-grade-underspecified","violation","A strong grade requires multiple specific observations, but only one was cited.",{hypothesisId:s})),o.length>0&&n.push(he("unsupported-claims","strong-grade-with-contradiction","violation","A strong grade requires no material unresolved contradiction, but contradicting evidence was cited.",{hypothesisId:s})),i.unresolvedAssumptions.length>0&&n.push(he("unsupported-claims","strong-grade-with-unresolved-assumptions","warning","A strong grade carries unresolved assumptions.",{hypothesisId:s})));let d=a.filter(l=>o.includes(l));for(let l of d)n.push(he("unsupported-claims","contradictory-citation","violation",`Evidence ${l} is cited as both supporting and contradicting the same hypothesis.`,{hypothesisId:s,reference:l}));let c=new Set([...a,...o]);for(let l of[i.statement,i.nextAction])for(let u of l.matchAll(XC)){let p=u[0];e+=1,!c.has(p)&&n.push(he("unsupported-claims","uncited-identifier-in-prose","violation",`Prose references ${p}, which this hypothesis does not cite.`,{hypothesisId:s,reference:p}))}}e+=1;let r=t.diagnosis.hypotheses.map(i=>i.rank);return new Set(r).size!==r.length&&n.push(he("unsupported-claims","duplicate-hypothesis-rank","violation","Hypotheses do not carry a distinct rank, so the accepted hypothesis is ambiguous.")),t.diagnosis.hypotheses.length>3&&n.push(he("unsupported-claims","too-many-hypotheses","violation",`A diagnosis returns at most three ranked hypotheses; ${t.diagnosis.hypotheses.length} were supplied.`)),rn("unsupported-claims",e,n)}};var gw=[bu,xu,wu,vu];function QC(t){return[...t].sort((n,e)=>{if(n.severity!==e.severity)return n.severity==="violation"?-1:1;let r=n.graderId.localeCompare(e.graderId);if(r!==0)return r;let i=n.code.localeCompare(e.code);return i!==0?i:(n.reference??"").localeCompare(e.reference??"")})}function ds(t,n,e){let r={diagnosis:t,evidenceIds:new Set(n.evidence.map(s=>s.evidenceId)),artifactIds:new Set(n.artifacts.map(s=>s.artifactId)),symptomIds:new Set(e.symptoms.map(s=>s.symptomId)),packetHash:n.packetHash},i=gw.map(s=>s.grade(r));return{schemaVersion:"1.0",packetHash:n.packetHash,passed:i.every(s=>s.passed),outcomes:i,findings:QC(i.flatMap(s=>s.findings))}}var ww=50,bw=24,Rw="<absent>",e1={"error-field":"Error","stack-frame":"Stack frame",step:"Step","stdio-chunk":"Output","trace-event":"Browser event","image-metadata":"Screenshot (metadata only)","video-metadata":"Video (metadata only)","dom-subtree":"Page elements","dom-candidates":"Similar elements","accessibility-node":"Accessibility","page-snapshot":"Page snapshot","console-event":"Console","network-event":"Network","source-range":"Source","diff-hunk":"Code change","change-search":"Change search","run-summary":"Run summary","locator-suggestion":"Locator suggestion"},t1={report:"Test report",trace:"Trace or failure capture",stdout:"Standard output",stderr:"Standard error",screenshot:"Screenshots",video:"Video",dom:"Page DOM",accessibility:"Accessibility tree",console:"Browser console",network:"Network",source:"Test source",diff:"Code changes",probe:"Live probe"},n1={unavailable:"not captured",unreadable:"unreadable","unsupported-version":"unsupported version","unauthorized-path":"outside the authorized paths","policy-disabled":"turned off by policy",redacted:"redacted","budget-exceeded":"over the size budget",irrelevant:"not relevant to the failures",unrecognized:"not recognized","parse-failed":"could not be parsed"},r1={"symptom-category":"Symptom","action-api":"Action","error-fingerprint":"Error","network-endpoint":"Request","support-location":"Support code","target-locator":"Locator","failing-source-location":"Failing line"},i1={expected:"passed",unexpected:"failed",flaky:"flaky",skipped:"skipped"};function Iw(t,n){return`${t} ${n}${t===1?"":"s"}`}function xw(t,n){let e=t.replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function s1(t){if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;return n<60?`${n.toFixed(1)} s`:`${Math.floor(n/60)} min ${Math.round(n%60)} s`}function vw(t){return t.replace("T"," ").replace(/(?:\.\d+)?Z$/," UTC")}var a1="1970-01-01T00:00:00.000Z";function o1(t){return t.replace(/^sha256:/,"").slice(0,12)}function Ru(t,n){let e=n.location.file,r=n.titlePath.filter(s=>s!==""&&s!==e&&s!==ZC(e)),i=t.projects.find(s=>s.projectId===n.projectId)?.name;return{title:r.join(" \u203A ")||n.title,location:n.location.line===void 0?e:`${e}:${n.location.line}`,...i===void 0||i===""||t.projects.length<2?{}:{project:i},status:i1[n.status],attempts:n.attempts.map(s=>s.retry===0?s.status:`${s.status} (retry ${s.retry})`)}}function Aw(t,n){let e=new Set(n);return t.logicalTests.filter(r=>e.has(r.logicalTestId)).map(r=>Ru(t,r))}function sn(t,n){let e=t.signals.find(r=>r.kind===n)?.value;return e===void 0||e===Rw?void 0:e}function d1(t,n){let e=sn(t,"symptom-category");return(e!==void 0?[e]:[...new Set((n?.symptoms.symptoms??[]).filter(s=>t.symptomIds.includes(s.symptomId)).map(s=>s.category))]).map(s=>jn[s]??s).join(", ")||jn.unclassified}function Tw(t,n){return t.evidence.filter(e=>e.kind==="error-field"&&e.attemptId!==void 0&&n.has(e.attemptId)&&e.locator.type==="report-field"&&/\.(?:message|value)$/.test(e.locator.path))}function c1(t,n){let e=n?.symptoms.symptoms.find(a=>t.symptomIds.includes(a.symptomId));if(n===void 0||e===void 0)return;let r=Tw(n.packet,new Set(e.attemptId===void 0?[]:[e.attemptId])).map(a=>a.observation.split(`
162
+ `).find(o=>o.trim()!=="")?.trim()).find(a=>a!==void 0);if(r!==void 0)return r;let i=`${jn[e.category]}: `,s=e.summary.startsWith(i)?e.summary.slice(i.length):e.summary;return s.trim()===""?void 0:s}function l1(t,n,e){let r=sn(t,"target-locator"),i=sn(t,"network-endpoint"),s=sn(t,"support-location"),a=sn(t,"failing-source-location"),o=c1(t,e)??sn(t,"error-fingerprint");return r!==void 0?`Locator ${xw(r,90)}`:i!==void 0?`Request ${i}`:s!==void 0?`Failing in ${s}`:a!==void 0?`Failing at ${a}`:o!==void 0?xw(o,90):n}function u1(t,n){let e=sn(t,"support-location")??sn(t,"failing-source-location");if(e!==void 0)return e;let r=new Set(n.map(i=>i.location.replace(/:\d+$/,"")));return r.size===1?[...r][0]:void 0}function p1(t){return[...t.hypotheses].sort((n,e)=>n.rank-e.rank)[0]}function f1(t){let n=t?.diagnosis;if(t===void 0||n===void 0)return{owner:"not-diagnosed"};let e=p1(n);return t.outcome!=="diagnosed"||e===void 0?{owner:"inconclusive"}:{owner:e.probableOwner,grade:e.evidenceGrade}}function h1(t){let n=t.diagnosis;if(n!==void 0)return{status:n.status,hypotheses:[...n.hypotheses].sort((e,r)=>e.rank-r.rank).map(e=>({rank:e.rank,statement:e.statement,owner:e.probableOwner,grade:e.evidenceGrade,category:e.causalCategory,supporting:e.supportingEvidenceIds,contradicting:e.contradictingEvidenceIds,missing:e.missingEvidence,assumptions:e.unresolvedAssumptions,nextAction:e.nextAction})),missing:n.missingEvidence,nextAction:n.recommendedNextAction,repairEligibility:n.repairEligibility,escalated:t.escalated===!0}}function m1(t){let n=t.locator;switch(n.type){case"source-range":{let e=n.endLine===n.startLine?`${n.startLine}`:`${n.startLine}-${n.endLine}`;return`${n.path}:${e}${n.symbol===void 0?"":` (${n.symbol})`}`}case"diff-hunk":return`${n.commit===void 0?"uncommitted":`commit ${n.commit}`}, ${n.path}:${n.newStart}`;default:return}}function y1(t){let n=m1(t);return{evidenceId:t.evidenceId,label:e1[t.kind]??t.kind,...n===void 0?{}:{where:n},text:t.observation}}function Pw(t,n){let e=new Map(t.evidence.map(r=>[r.evidenceId,r]));return[...new Set(n)].flatMap(r=>{let i=e.get(r);return i===void 0?[]:[i]})}function g1(t){return[...[...t.hypotheses].sort((n,e)=>n.rank-e.rank).flatMap(n=>[...n.supportingEvidenceIds,...n.contradictingEvidenceIds]),...t.ownershipEvidenceIds]}function w1(t,n){let e=n.symptoms.symptoms.filter(s=>t.symptomIds.includes(s.symptomId)),r=new Set(e.flatMap(s=>s.attemptId??[])),i=[...Tw(n.packet,r).map(s=>s.evidenceId),...e.flatMap(s=>s.evidenceIds)];return Pw(n.packet,i)}function b1(t,n,e){if(e===void 0)return{evidence:[],evidenceCut:0};let r=n?.diagnosis,i;if(r!==void 0){let s=e.groupPackets[t.clusterId];if(s?.packetHash!==r.packetHash)return{evidence:[],evidenceCut:0,evidenceNote:"This group's evidence has changed since it was diagnosed, so the evidence its diagnosis cites can't be shown."};i=Pw(s,g1(r))}else i=w1(t,e);return{evidence:i.slice(0,bw).map(y1),evidenceCut:Math.max(0,i.length-bw)}}function x1(t,n){return t===void 0?n?"Not diagnosed: this was a local analysis, so no model was asked.":"Not sent: an analysis asks about at most 6 groups, the largest first.":t.outcome==="diagnosed"?t.escalated===!0?"Diagnosed, by the stronger model after the first answer failed its checks.":"Diagnosed.":`${t.outcome} (${t.reasonCode}): ${t.message}`}function ku(t,n,e,r,i,s){let a=d1(n,r),o=Aw(t,n.logicalTestIds),d=f1(e),c=e===void 0?void 0:h1(e),l=l1(n,a,r),u=n.logicalTestIds.length,p=u1(n,o);return{...i===void 0?{}:{number:i},anchor:i===void 0?`group-${n.clusterId}`:`group-${i}`,title:`${l} \xB7 ${Iw(u,"test")}`,subject:l,size:u,...p===void 0?{}:{place:p},category:a,signals:n.signals.filter(f=>f.value!==Rw).map(f=>({kind:r1[f.kind]??f.kind,value:f.value})),commonCause:{supported:n.commonCauseSupported,rationale:n.commonCauseRationale},...d,status:x1(e,s),tests:o.slice(0,ww),testsCut:Math.max(0,o.length-ww),...c===void 0?{}:{diagnosis:c},...b1(n,e,r)}}function v1(t){return{clusterId:t.clusterId,logicalTestIds:t.logicalTestIds,symptomIds:[],signals:t.signals,commonCauseSupported:!1,commonCauseRationale:"The evidence that grouped these tests could not be rebuilt."}}function kw(t,n){return n.logicalTestIds.length-t.logicalTestIds.length||t.clusterId.localeCompare(n.clusterId)}function k1(t){let{run:n,record:e,detail:r}=t,i=r?.clusters.clusters??[],s=e.clusters??[];if(s.length===0)return[...i].sort(kw).map((u,p)=>ku(n,u,void 0,r,p+1,!0));let o=new Map(i.map(u=>[u.clusterId,u])),d=s.map((u,p)=>ku(n,o.get(u.clusterId)??v1(u),u,r,p+1,!1)),c=new Set(s.map(u=>u.clusterId)),l=i.filter(u=>!c.has(u.clusterId)).sort(kw).map(u=>ku(n,u,void 0,r,void 0,!1));return[...d,...l]}function Sw(t){let n=t.record.clusters??[],e=n.length>0?n.flatMap((i,s)=>i.diagnosisAudit===void 0?[]:[{group:`Group ${s+1}`,audit:i.diagnosisAudit}]):t.record.diagnosisAudit===void 0?[]:[{group:"Run",audit:t.record.diagnosisAudit}],r=t.repair?.repairAudit===void 0?[]:[{group:"Repair",audit:t.repair.repairAudit}];return[...e,...r]}function Ew(t){return`${t.model.modelId} via ${t.reportedProvider??t.model.providerId}`}function R1(t){return Sw(t).map(({group:n,audit:e})=>({group:n,purpose:e.purpose,model:Ew(e),zeroDataRetention:e.model.zeroDataRetention===!0,packetHash:o1(e.packetHash),...e.usage===void 0?{}:{tokens:`${e.usage.promptTokens.toLocaleString("en-US")} in, ${e.usage.completionTokens.toLocaleString("en-US")} out`},outcome:e.outcome.kind}))}function I1(t){let n=Sw(t).filter(({audit:r})=>r.outcome.kind==="diagnosed"||r.outcome.kind==="abstained"),e=[...new Set(n.map(({audit:r})=>Ew(r)))];return e.length>0?`Diagnosed with ${e.join(" and ")}.`:t.record.reasonCode==="remote-diagnosis-not-configured"?"Local analysis: no model was asked.":"No model answered this analysis."}function A1(t){let n=t.repair?.confirmation;if(n===void 0)return[];if(n.status!=="reproduced"&&n.status!=="not-reproduced")return[];let e=new Set(n.failedAgain??[]);return n.logicalTestIds.filter(r=>!e.has(r))}function T1(t){let{run:n}=t,e=n.logicalTests.filter(i=>i.status==="flaky").map(i=>Ru(n,i)),r=Aw(n,A1(t)).map(i=>({...i,status:"passed when fix re-ran it"}));return[...e,...r]}function P1(t){let{run:n,detail:e}=t,r=new Set(e?.symptoms.unclassifiedAttemptIds??[]),i=n.logicalTests.filter(o=>o.attempts.some(d=>r.has(d.attemptId))),s=(e?.symptoms.symptoms??[]).filter(o=>o.logicalTestId===void 0).map(o=>o.summary),a=s.length===0&&n.reportErrors.length>0?[`${Iw(n.reportErrors.length,"run-level error")} in the test report, not shown here because its evidence could not be built.`]:[];return{unclassified:i.map(o=>Ru(n,o)),runErrors:[...new Set([...s,...a])]}}function S1(t,n){let e=t.repair;if(e===void 0)return;let r=(t.record.clusters??[]).findIndex(a=>a.diagnosis!==void 0&&a.diagnosis.packetHash===e.diagnosis?.packetHash),i=r<0?void 0:n.find(a=>a.number===r+1),s=e.repairProposal;return{...i===void 0?{}:{groupAnchor:i.anchor,groupTitle:i.title},command:e.command,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message,phases:[{phase:"Proposal",status:e.proposal.status},{phase:"Application",status:e.application.status},{phase:"Validation",status:e.validation.status}],...s===void 0?{}:{intent:{statement:s.intent.statement,preserved:s.intent.preservedBehavior},diff:s.diff}}}function wo(t){let{run:n,record:e,detail:r}=t,i=p=>n.logicalTests.filter(f=>f.status===p).length,s=i("unexpected"),a=i("flaky"),o=Rt[n.framework],d=n.artifact.formatVersion===void 0?"":` ${n.artifact.formatVersion}`,c=k1(t),l=new Map;for(let p of r?.packet.omissions??[]){let f=n1[p.reason]??p.reason;l.set(f,(l.get(f)??0)+1)}let u=S1(t,c);return{title:`KwikQA report: ${n.framework==="unknown"?"run from an unidentified framework":`${o} run`}, ${s} failed${a===0?"":`, ${a} flaky`}`,recordedAt:vw(e.recordedAt),run:{framework:`${o}${d}`,...n.artifact.format===void 0?{}:{format:Zt[n.artifact.format]},counts:[{label:"Tests",value:n.logicalTests.length},{label:"Failed",value:s},{label:"Flaky",value:a},{label:"Passed",value:i("expected")},{label:"Skipped",value:i("skipped")}],duration:s1(n.stats.duration),...e.inputs===void 0?{}:{report:e.inputs.report},createdAt:n.createdAt===a1?"not recorded in the report":vw(n.createdAt),diagnosedBy:I1(t),outcome:`${e.outcome} (${e.reasonCode})`,message:e.message},groups:c,flaky:T1(t),notAnalyzed:P1(t),coverage:(r?.packet.accounting??[]).map(p=>({channel:t1[p.channel]??p.channel,availability:p.availability,included:p.included,omitted:p.omitted})),omissions:[...l].map(([p,f])=>({reason:p,count:f})).sort((p,f)=>f.count-p.count||p.reason.localeCompare(f.reason)),redactions:r?.packet.totals.redactions??0,requests:R1(t),...u===void 0?{}:{repair:u},...r===void 0?{evidenceNote:"The evidence this analysis read could not be rebuilt, so only its recorded results are shown."}:{},footer:{runId:e.runId,recordId:e.recordId,kwikqaVersion:t.kwikqaVersion}}}import{appendFile as E1,readFile as C1}from"node:fs/promises";var N1=30,Cw=100,O1=3e4,$1=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,D1=/^(?!.*\.\.)(?!\/)(?!.*\/$)[^\s\0~^:?*[\\]{1,255}$/;async function L1(t){if(t===void 0||t==="")return{};try{let n=JSON.parse(await C1(t,"utf8"));return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function bo(t){if(t.GITHUB_ACTIONS!=="true")return;let n=$1.test(t.GITHUB_REPOSITORY??"")?t.GITHUB_REPOSITORY:void 0,e=st(t.GITHUB_API_URL,"https://api.github.com"),r=st(t.GITHUB_SERVER_URL,"https://github.com"),i=/^\d+$/.test(t.GITHUB_RUN_ID??"")?t.GITHUB_RUN_ID:void 0,s=Number(t.GITHUB_RUN_ATTEMPT),a=/^\d+$/.test(t.GITHUB_RUN_ATTEMPT??"")&&Number.isSafeInteger(s)&&s>0?s:void 0,o=(await L1(t.GITHUB_EVENT_PATH)).pull_request,d=o?.number,c=o?.head?.repo?.full_name,l=o?.base?.repo?.full_name,u=o?.head?.ref,p=o?.head?.sha,f=/^refs\/[^\s\0]+$/.test(t.GITHUB_REF??"")?t.GITHUB_REF:void 0,h=(t.GITHUB_TOKEN??"").trim(),m=r===void 0||n===void 0?void 0:`${r}/${n}`,g=t.GITHUB_HEAD_REF||t.GITHUB_REF_NAME||void 0,y=/^[0-9a-f]{40}$/.test(t.GITHUB_SHA??"")?t.GITHUB_SHA:void 0;return{...e===void 0?{}:{apiUrl:e},...n===void 0?{}:{repository:n},...m===void 0||i===void 0?{}:{runUrl:`${m}/actions/runs/${i}`},workflow:t.GITHUB_WORKFLOW??"",job:t.GITHUB_JOB??"",...i===void 0?{}:{runId:i},...a===void 0?{}:{runAttempt:a},...f===void 0?{}:{ref:f},...typeof u=="string"&&D1.test(u)&&typeof p=="string"&&/^[0-9a-f]{40}$/.test(p)?{pullRequestHead:{ref:u,sha:p}}:{},...g===void 0?{}:{branch:g},...y===void 0?{}:{commit:{sha:y,...m===void 0?{}:{url:`${m}/commit/${y}`}}},...t.GITHUB_STEP_SUMMARY===void 0||t.GITHUB_STEP_SUMMARY===""?{}:{summaryPath:t.GITHUB_STEP_SUMMARY},...h===""?{}:{token:h},...typeof d=="number"&&Number.isSafeInteger(d)&&d>0?{pullRequest:{number:d,...m===void 0?{}:{url:`${m}/pull/${d}`},fork:t.GITHUB_EVENT_NAME!=="pull_request_target"&&(typeof c!="string"||c!==l)}}:{}}}function Nw(t){return`<!-- kwikqa-ci workflow=${encodeURIComponent(t.workflow)} job=${encodeURIComponent(t.job)} -->`}async function Iu(t,n){if(t.status===429||t.status===403&&(t.headers.get("x-ratelimit-remaining")==="0"||t.headers.has("retry-after")))return"GitHub's rate limit was reached";if(t.status===403)return n;if(t.status===401)return"GitHub refused the token";if(t.status===404)return"GitHub found no such pull request with this token";let e=await t.json().catch(()=>{}),r=typeof e?.message=="string"?`: ${e.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitHub answered ${t.status}${r}`}var Lr=class{constructor(n,e,r){this.send=n;this.apiUrl=e;this.token=r}send;apiUrl;token;call(n,e,r){return this.send(`${this.apiUrl}${e}`,{method:n,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(O1)})}},Dr=class extends Error{};async function M1(t,n,e,r){for(let i=1;i<=N1;i+=1){let s=await t.call("GET",`${n}/comments?per_page=${Cw}&page=${i}`);if(!s.ok)throw new Dr(await Iu(s,r));let a=await s.json(),o=a.find(d=>typeof d.body=="string"&&d.body.startsWith(e));if(typeof o?.id=="number")return o.id;if(a.length<Cw)return}}async function cs(t,n,e,r,i){let s=new Lr(n,e.apiUrl,e.token),a=`/repos/${e.repository}/issues/${e.number}`,o={body:`${e.marker}
163
+ ${r}`},d=e.noun??"pull-request comment",c=`${d.charAt(0).toUpperCase()}${d.slice(1)}`;try{let l=await M1(s,a,e.marker,e.forbidden);if(l!==void 0){let p=await s.call("PATCH",`/repos/${e.repository}/issues/comments/${l}`,o);if(p.ok)return t.print(`${c}: updated.`);if(p.status!==403&&p.status!==404)throw new Dr(await Iu(p,e.forbidden))}if(l===void 0&&!i)return t.print(`No ${d}: nothing failed, and there is no earlier comment to update.`);let u=await s.call("POST",`${a}/comments`,o);if(!u.ok)throw new Dr(await Iu(u,e.forbidden));t.print(`${c}: posted.`)}catch(l){let u=l instanceof Dr?l.message:`GitHub couldn't be reached (${l instanceof Error?l.message:String(l)})`;t.error(`No ${d}: ${u}.`)}}async function _1(t,n,e,r,i){let s=o=>t.print(`No pull-request comment: ${o}.`),a=e.pullRequest;if(a===void 0)return s("this run isn't for a pull request");if(a.fork)return s("the pull request comes from a fork, and GitHub gives its workflows a read-only token");if(e.token===void 0)return s("GITHUB_TOKEN isn't set; add `GITHUB_TOKEN: ${{ github.token }}` to the step's env");if(e.apiUrl===void 0||e.repository===void 0)return s("GITHUB_API_URL or GITHUB_REPOSITORY isn't what GitHub Actions sets");await cs(t,n,{apiUrl:e.apiUrl,repository:e.repository,number:a.number,token:e.token,marker:Nw(e),forbidden:"the token can't comment on this pull request; give the job `pull-requests: write` permission"},r,i)}async function Au(t,n,e,r,i){if(e.summaryPath===void 0)t.print("No job summary: GITHUB_STEP_SUMMARY isn't set.");else try{await E1(e.summaryPath,`${r}
164
+ `),t.print("Job summary: written.")}catch(s){t.error(`No job summary: ${s.message}`)}await _1(t,n,e,r,i.failures)}var j1=20,Ow=10,F1=100;function Mr(t,n){return`${t} ${n}${t===1?"":"s"}`}function $w(t,n){let e=t.replace(/[\p{Cc}\u202a-\u202e\u2066-\u2069]/gu," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function ge(t,n={}){let e=$w(t,F1)||"(empty)",r=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),i="`".repeat(r+1),s=e.startsWith("`")||e.endsWith("`")?" ":"",a=n.table===!0?e.replace(/\|/g,"\\|"):e;return`${i}${s}${a}${s}${i}`}function ls(t){return $w(t,1e3).replace(/[\\`*_{}[\]()#+!|<>~&]/g,"\\$&")}function B1(t){return`| ${[t.number===void 0?"\u2013":String(t.number),String(t.size),ge(t.subject,{table:!0}),Mt[t.owner],t.grade===void 0?"\u2013":ls(t.grade)].join(" | ")} |`}function H1(t,n){return t>0?`### KwikQA: ${Mr(t,"test")} failed${n===0?"":`, ${n} flaky`}`:n===0?"### KwikQA: no failures":`### KwikQA: no failures, ${Mr(n,"flaky test")}`}function Tu(t){let{model:n}=t;if(n===void 0)return`### KwikQA: no analysis
165
165
 
166
166
  ${ls(t.message)}
167
- `;let e=l=>n.run.counts.find(u=>u.label===l)?.value??0,r=e("Failed"),i=e("Flaky"),s=n.run.counts.filter(l=>l.label==="Tests"||l.value>0).map(l=>l.label==="Tests"?Lr(l.value,"test"):`${l.value} ${l.label.toLowerCase()}`),a=[H1(r,i),"",`${ls(n.run.framework)} run: ${s.join(", ")}.`],o=n.groups.slice(0,j1);if(o.length>0){a.push("","| Group | Tests | Failure | Owner | Evidence |","| ---: | ---: | --- | --- | --- |",...o.map(B1));let l=n.groups.length-o.length;l>0&&a.push("",`${Lr(l,"more group")} in the report.`)}let d=n.notAnalyzed.unclassified.length,c=n.notAnalyzed.runErrors.length;if(d>0||c>0){let l=[...d===0?[]:[`${Lr(d,"failed test")} not grouped`],...c===0?[]:[Lr(c,"run-level error")]];a.push("",`Also ${l.join(" and ")}; the report lists them.`)}if(n.flaky.length>0){a.push("","Flaky, passed on a retry:");for(let u of n.flaky.slice(0,Ow))a.push(`- ${ge(u.title)} at ${ge(u.location)}`);let l=n.flaky.length-Ow;l>0&&a.push(`- and ${l} more in the report`)}return t.notDiagnosed!==void 0&&a.push("",`Not diagnosed: ${ls(t.notDiagnosed)}`),t.reportFile!==void 0&&a.push("",`Full report, with each group's evidence: ${ge(t.reportFile)}${t.runUrl===void 0?"":`, in the artifacts of [this run](${t.runUrl})`}.`),`${a.join(`
167
+ `;let e=l=>n.run.counts.find(u=>u.label===l)?.value??0,r=e("Failed"),i=e("Flaky"),s=n.run.counts.filter(l=>l.label==="Tests"||l.value>0).map(l=>l.label==="Tests"?Mr(l.value,"test"):`${l.value} ${l.label.toLowerCase()}`),a=[H1(r,i),"",`${ls(n.run.framework)} run: ${s.join(", ")}.`],o=n.groups.slice(0,j1);if(o.length>0){a.push("","| Group | Tests | Failure | Owner | Evidence |","| ---: | ---: | --- | --- | --- |",...o.map(B1));let l=n.groups.length-o.length;l>0&&a.push("",`${Mr(l,"more group")} in the report.`)}let d=n.notAnalyzed.unclassified.length,c=n.notAnalyzed.runErrors.length;if(d>0||c>0){let l=[...d===0?[]:[`${Mr(d,"failed test")} not grouped`],...c===0?[]:[Mr(c,"run-level error")]];a.push("",`Also ${l.join(" and ")}; the report lists them.`)}if(n.flaky.length>0){a.push("","Flaky, passed on a retry:");for(let u of n.flaky.slice(0,Ow))a.push(`- ${ge(u.title)} at ${ge(u.location)}`);let l=n.flaky.length-Ow;l>0&&a.push(`- and ${l} more in the report`)}return t.notDiagnosed!==void 0&&a.push("",`Not diagnosed: ${ls(t.notDiagnosed)}`),t.reportFile!==void 0&&a.push("",`Full report, with each group's evidence: ${ge(t.reportFile)}${t.runUrl===void 0?"":`, in the artifacts of [this run](${t.runUrl})`}.`),`${a.join(`
168
168
  `)}
169
- `}var an="kwikqa",Lw=2e3;function ft(t){return`kwikqa/fix-${t.slice(0,12)}`}function Mw(t){return Dw("sha256").update(["kwikqa-fix-group",...[...t].sort()].join("\0")).digest("hex")}function jr(t){return Mw(t.map(n=>`${n.kind}=${n.value}`))}function ps(t){let n=t.clusters?.[0]?.signals;return n===void 0||n.length===0?Mw(t.repairProposal?.targets.map(e=>`target=${e.path}`)??[]):jr(n)}function Fn(t){return`<!-- kwikqa-fix group=${t} -->`}async function Pu(t,n,e){let r=new Dr(t,n.apiUrl,n.token),i=`/repos/${n.repository}`,s=n.repository.split("/")[0]??"",a=ft(e);try{let o=await r.call("GET",`${i}/pulls?state=open&head=${encodeURIComponent(`${s}:${a}`)}&per_page=100`);if(!o.ok)return{kind:"unknown",reason:await us(o)};let d=(await o.json()).find(l=>typeof l.number=="number"&&typeof l.body=="string"&&l.body.startsWith(Fn(e)));if(typeof d?.number=="number")return{kind:"open",number:d.number,...typeof d.html_url=="string"?{url:d.html_url}:{}};let c=await r.call("GET",`${i}/git/ref/heads/${a}`);return c.status===404?{kind:"none"}:c.ok?{kind:"branch"}:{kind:"unknown",reason:await us(c)}}catch(o){return{kind:"unknown",reason:`GitHub couldn't be reached (${o instanceof Error?o.message:String(o)})`}}}async function Su(t,n,e,r,i){let s=i.runUrl===void 0?"a later run":`[a later run](${i.runUrl})`;await cs(t,n,{apiUrl:e.apiUrl,repository:e.repository,number:r.number,token:e.token,marker:`<!-- kwikqa-fix-seen group=${r.fingerprint} -->`,forbidden:"the token can't comment on the fix pull request; give the job `pull-requests: write`",noun:"note on the fix pull request"},`This failure group failed again in ${s}, at commit ${ge(i.commit.slice(0,12))}. KwikQA asks for no other repair while this pull request is open.
170
- `,!0)}function _w(t,n){let e=t.replace(new RegExp("\\p{Cc}+","gu")," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function K1(t){return t.clusters?.[0]?.signals.find(n=>n.kind==="symptom-category")?.value}function Bn(t){let n=t.repairProposal?.targets[0]?.path??"a test";return _w(`KwikQA: repair ${K1(t)??"a failing test"} in ${n}`,120)}function fs(t,n){return[Bn(t),"","KwikQA validated this repair on a CI runner before committing it.","",`KwikQA-Run: ${t.runId}`,`KwikQA-Group: ${n}`,""].join(`
171
- `)}function W1(t,n=Lw){let e=t.length<=n?t:`${t.slice(0,n-1)}\u2026`,r=Math.max(2,...(e.match(/`+/g)??[]).map(s=>s.length)),i="`".repeat(r+1);return`${i}text
169
+ `}var an="kwikqa",Lw=2e3;function ft(t){return`kwikqa/fix-${t.slice(0,12)}`}function Mw(t){return Dw("sha256").update(["kwikqa-fix-group",...[...t].sort()].join("\0")).digest("hex")}function jr(t){return Mw(t.map(n=>`${n.kind}=${n.value}`))}function ps(t){let n=t.clusters?.[0]?.signals;return n===void 0||n.length===0?Mw(t.repairProposal?.targets.map(e=>`target=${e.path}`)??[]):jr(n)}function Bn(t){return`<!-- kwikqa-fix group=${t} -->`}async function Pu(t,n,e){let r=new Lr(t,n.apiUrl,n.token),i=`/repos/${n.repository}`,s=n.repository.split("/")[0]??"",a=ft(e);try{let o=await r.call("GET",`${i}/pulls?state=open&head=${encodeURIComponent(`${s}:${a}`)}&per_page=100`);if(!o.ok)return{kind:"unknown",reason:await us(o)};let d=(await o.json()).find(l=>typeof l.number=="number"&&typeof l.body=="string"&&l.body.startsWith(Bn(e)));if(typeof d?.number=="number")return{kind:"open",number:d.number,...typeof d.html_url=="string"?{url:d.html_url}:{}};let c=await r.call("GET",`${i}/git/ref/heads/${a}`);return c.status===404?{kind:"none"}:c.ok?{kind:"branch"}:{kind:"unknown",reason:await us(c)}}catch(o){return{kind:"unknown",reason:`GitHub couldn't be reached (${o instanceof Error?o.message:String(o)})`}}}async function Su(t,n,e,r,i){let s=i.runUrl===void 0?"a later run":`[a later run](${i.runUrl})`;await cs(t,n,{apiUrl:e.apiUrl,repository:e.repository,number:r.number,token:e.token,marker:`<!-- kwikqa-fix-seen group=${r.fingerprint} -->`,forbidden:"the token can't comment on the fix pull request; give the job `pull-requests: write`",noun:"note on the fix pull request"},`This failure group failed again in ${s}, at commit ${ge(i.commit.slice(0,12))}. KwikQA asks for no other repair while this pull request is open.
170
+ `,!0)}function _w(t,n){let e=t.replace(new RegExp("\\p{Cc}+","gu")," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function K1(t){return t.clusters?.[0]?.signals.find(n=>n.kind==="symptom-category")?.value}var W1={"target-locator":"a failure on a locator","support-location":"a failure in shared test code","network-endpoint":"a failed network request"};function J1(t){for(let n of t.clusters?.[0]?.signals??[]){let e=W1[n.kind];if(e!==void 0)return e}}function Hn(t){let n=t.repairProposal?.targets[0]?.path??"a test",e=t.clusters?.[0]?.logicalTestIds.length??t.failingLogicalTestIds.length,r=K1(t)??J1(t)??(e>1?Fn(e,"failing test"):"a failing test");return _w(`KwikQA: repair ${r} in ${n}`,120)}function fs(t,n){return[Hn(t),"","KwikQA validated this repair on a CI runner before committing it.","",`KwikQA-Run: ${t.runId}`,`KwikQA-Group: ${n}`,""].join(`
171
+ `)}function Y1(t,n=Lw){let e=t.length<=n?t:`${t.slice(0,n-1)}\u2026`,r=Math.max(2,...(e.match(/`+/g)??[]).map(s=>s.length)),i="`".repeat(r+1);return`${i}text
172
172
  ${e}
173
- ${i}`}function Mr(t,n){return`${t} ${n}${t===1?"":"s"}`}function J1(t){let n=t.executable.split(/[\\/]/).at(-1)??t.executable,e=t.args.map(r=>/\s/.test(r)?JSON.stringify(r):r);return[n,...e].join(" ")}function hs(t){let{fix:n}=t,e=t.host??"github",r=e==="azure-repos",i=y=>W1(y,r?400:Lw),s=n.clusters?.[0],a=[...n.diagnosis?.hypotheses??[]].sort((y,w)=>y.rank-w.rank),o=a[0],d=n.repairProposal,c=[Fn(t.fingerprint),`## ${_w(Bn(n),120)}`,"","KwikQA diagnosed this failure as the test's own, repaired the test, and validated the repair on the CI runner. Nothing lands until a person reviews and merges this pull request.",""],l=s?.logicalTestIds.length??n.failingLogicalTestIds.length,u=[Mr(l,"failing test")];if(o!==void 0&&u.push(`owner: ${Mt[o.probableOwner]??ge(o.probableOwner)}`,`evidence: ${ge(o.evidenceGrade)}`,`cause: ${ge(o.causalCategory)}`),c.push(`**The failure group:** ${u.join(", ")}.`,""),a.length>0){c.push("### Diagnosis","");for(let y of a.slice(0,r?1:3))c.push(`**#${y.rank}**, ${ge(y.probableOwner)}, evidence ${ge(y.evidenceGrade)}, citing ${Mr(y.supportingEvidenceIds.length,"evidence item")}:`,"",i(y.statement),"")}d!==void 0&&c.push("### The repair","","Its intent:","",i(d.intent.statement),"","What it keeps:","",i(d.intent.preservedBehavior),"",`It changes ${Mr(d.changedFiles,"file")}, ${Mr(d.changedLines,"line")}: ${d.targets.map(y=>ge(y.path)).join(", ")}. KwikQA's repair rules checked it: it edits only test code the repository's policy allows, keeps every assertion, and adds no skip, wait, or retry.`,""),c.push("### Validation","");let p=t.plan?.commands.filter(y=>y.timing==="post-patch")??[],f=[...new Set(p.map(J1))];c.push(`On the runner, at commit ${ge(t.commit.slice(0,12))}, the repaired test passed ${Fi} times in a row with retries off, and every required check passed:`,"",...f.length===0?["- (the commands are in the run's log)"]:f.map(y=>`- ${ge(y)}`),"");let h=t.validation?.groupCheck;if(h?.status==="rerun"){let y=h.stillFailing?.length??0;c.push(y===0?`The group's ${Mr(h.logicalTestIds.length,"other test")} passed when re-run with the repair.`:`Of the group's ${Mr(h.logicalTestIds.length,"other test")}, ${y} still failed with the repair; they need a look of their own.`,"")}let g=[["diagnosis",n.diagnosisAudit],["repair",n.repairAudit]].flatMap(([y,w])=>w===void 0?[]:[`- The ${y} request: ${ge(w.model.modelId)} via ${ge(w.reportedProvider??w.model.providerId)}.`]);return g.length>0&&c.push("### What was sent","","Only the redacted evidence each request's preview showed in the run's log:","",...g,""),c.push(t.runUrl===void 0?"The failure report, with each group's evidence, is in the run's artifacts.":`The failure report, with each group's evidence, is in the artifacts of [this run](${t.runUrl}).`,"",...e==="github"?["If the job's `GITHUB_TOKEN` opened this pull request, GitHub doesn't start its checks. To run them, close and reopen it, or push to it.",""]:[]),c.join(`
174
- `)}var Ht=class extends Error{};async function us(t){let n=await t.json().catch(()=>{}),e=typeof n?.message=="string"?n.message:"";if(t.status===429||t.status===403&&/rate limit/i.test(e))return"GitHub's rate limit was reached";if(t.status===401)return"GitHub refused the token";if(t.status===403&&/create or approve pull requests/i.test(e))return`GitHub Actions may not create pull requests here; turn on "Allow GitHub Actions to create and approve pull requests" in the repository's or organization's Actions settings`;if(t.status===403)return"the token can't push a branch or open a pull request; give the job `contents: write` and `pull-requests: write`";if(t.status===404)return"GitHub found no such repository or commit with this token";let r=e===""?"":`: ${e.replace(/\s+/g," ").slice(0,200)}`;return`GitHub answered ${t.status}${r}`}async function _r(t){if(!t.ok)throw new Ht(await us(t));return await t.json()}function jw(t){return Dw("sha256").update(t).digest("hex")}async function ms(t){let n=[];for(let e of t.targets){let r=U1(t.workspaceRoot,e.path),i=await z1(r);if(jw(i)!==e.resultSha256)return{failure:`${e.path} on the runner is no longer the validated repair`};n.push({path:q1(t.gitRoot,r).split(G1).join("/"),workspacePath:e.path,bytes:i,mode:((await V1(r)).mode&73)===0?"100644":"100755",sourceSha256:e.sourceSha256})}return{files:n}}function Hn(t,n){return`${t.workspacePath} on ${n} isn't the file the repair was validated against, so the repair isn't committed there`}function ys(t,n){return jw(t)===n.sourceSha256}async function Eu(t,n,e){let r=new Dr(n,e.apiUrl,e.token),i=`/repos/${e.repository}`,s=ft(e.fingerprint),a=!1;try{let o=await ms(e);if("failure"in o)return{kind:"failed",reason:o.failure};let{files:d}=o,l=(await _r(await r.call("GET",`${i}/git/commits/${e.base.commit}`))).tree?.sha;if(typeof l!="string")throw new Ht("GitHub returned no tree for the base");for(let w of d){let x=await r.call("GET",`${i}/contents/${w.path.split("/").map(encodeURIComponent).join("/")}?ref=${e.base.commit}`),v=await _r(x),R=typeof v.content=="string"&&v.encoding==="base64"?Buffer.from(v.content,"base64"):void 0;if(R===void 0||!ys(R,w))return{kind:"skipped",reason:Hn(w,e.base.branch)}}let u=[];for(let w of d){let x=await _r(await r.call("POST",`${i}/git/blobs`,{content:Buffer.from(w.bytes).toString("base64"),encoding:"base64"}));if(typeof x.sha!="string")throw new Ht("GitHub returned no blob");u.push({path:w.path,mode:w.mode,type:"blob",sha:x.sha})}let p=await _r(await r.call("POST",`${i}/git/trees`,{base_tree:l,tree:u})),f=await _r(await r.call("POST",`${i}/git/commits`,{message:e.commitMessage,tree:p.sha,parents:[e.base.commit]}));if(typeof f.sha!="string")throw new Ht("GitHub returned no commit");let h=await r.call("POST",`${i}/git/refs`,{ref:`refs/heads/${s}`,sha:f.sha});if(h.status===422)return{kind:"skipped",reason:`${s} already exists, from an earlier run; KwikQA never pushes to a branch it didn't create`};await _r(h),a=!0;let m=await r.call("POST",`${i}/pulls`,{title:e.title,head:s,base:e.base.branch,body:e.body,draft:!0});if(!m.ok){let w=await m.clone().json().catch(()=>{}),x=JSON.stringify(w??{});throw new Ht(m.status===422&&/draft/i.test(x)?"this repository doesn't take draft pull requests, and KwikQA opens only drafts (on GitHub Free, a private repository has none)":await us(m))}let g=await m.json();if(typeof g.number!="number")throw new Ht("GitHub returned no pull request");a=!1;let y=await r.call("POST",`${i}/issues/${g.number}/labels`,{labels:[an]});return y.ok||t.print(`The fix pull request has no \`${an}\` label: ${await us(y)}.`),{kind:"opened",number:g.number,...typeof g.html_url=="string"?{url:g.html_url}:{}}}catch(o){let d=o instanceof Ht?o.message:`GitHub couldn't be reached (${o instanceof Error?o.message:String(o)})`;return a&&await r.call("DELETE",`${i}/git/refs/heads/${s}`).catch(()=>{}),{kind:"failed",reason:d}}}var Y1=3e4,X1="7.1",Q1="0".repeat(40),Cu=4e3,xo=class{constructor(n,e){this.send=n;this.repository=e;this.base=`${e.collectionUrl}/${e.projectId}/_apis/git/repositories/${e.repositoryId}`}send;repository;base;call(n,e,r={}){let i=new URLSearchParams({...r.query,"api-version":X1});return this.send(`${this.base}${e}?${i}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.repository.token}`,...r.body===void 0?{}:{"Content-Type":"application/json"}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},redirect:"error",signal:AbortSignal.timeout(Y1)})}},It=class extends Error{};async function Fr(t,n){if(t.status===429)return"Azure DevOps's rate limit was reached";if(t.status===401||t.status===203)return"Azure DevOps refused the token";let e=await Hs(t),r=e===void 0?"":` (${e})`;return t.status===403?`${n}${r}`:t.status===404?`Azure DevOps found no such repository or commit with this token${r}`:`Azure DevOps answered ${t.status}${e===void 0?"":`: ${e}`}`}async function Fw(t,n){let e=await t.call("GET","/refs",{query:{filter:`heads/${n}`}});if(!gt(e))throw new It(await Fr(e,"the build service can't read branches"));let i=(await e.json()).value?.find(s=>s.name===`refs/heads/${n}`);return typeof i?.objectId=="string"?i.objectId:void 0}async function Nu(t,n,e){let r=new xo(t,n),i=ft(e);try{let s=await r.call("GET","/pullrequests",{query:{"searchCriteria.sourceRefName":`refs/heads/${i}`,"searchCriteria.status":"active"}});if(!gt(s))return{kind:"unknown",reason:await Fr(s,"the build service can't read pull requests")};let o=(await s.json()).value?.find(d=>typeof d.pullRequestId=="number"&&typeof d.description=="string"&&d.description.startsWith(Fn(e)));return typeof o?.pullRequestId=="number"?{kind:"open",number:o.pullRequestId}:await Fw(r,i)===void 0?{kind:"none"}:{kind:"branch"}}catch(s){return{kind:"unknown",reason:s instanceof It?s.message:`Azure DevOps couldn't be reached (${s instanceof Error?s.message:String(s)})`}}}async function Ou(t,n,e,r,i){let s=i.runUrl===void 0?"a later run":`[a later run](${i.runUrl})`;await Dd(t,n,{...e,pullRequest:r.number,marker:`kwikqa-fix-seen group=${r.fingerprint}`,noun:"note on the fix pull request"},`This failure group failed again in ${s}, at commit ${ge(i.commit.slice(0,12))}. KwikQA asks for no other repair while this pull request is open.
173
+ ${i}`}function Fn(t,n){return`${t} ${n}${t===1?"":"s"}`}function X1(t){let n=t.executable.split(/[\\/]/).at(-1)??t.executable,e=t.args.map(r=>/\s/.test(r)?JSON.stringify(r):r);return[n,...e].join(" ")}function hs(t){let{fix:n}=t,e=t.host??"github",r=e==="azure-repos",i=y=>Y1(y,r?400:Lw),s=n.clusters?.[0],a=[...n.diagnosis?.hypotheses??[]].sort((y,w)=>y.rank-w.rank),o=a[0],d=n.repairProposal,c=[Bn(t.fingerprint),`## ${_w(Hn(n),120)}`,"","KwikQA diagnosed this failure as the test's own, repaired the test, and validated the repair on the CI runner. Nothing lands until a person reviews and merges this pull request.",""],l=s?.logicalTestIds.length??n.failingLogicalTestIds.length,u=[Fn(l,"failing test")];if(o!==void 0&&u.push(`owner: ${Mt[o.probableOwner]??ge(o.probableOwner)}`,`evidence: ${ge(o.evidenceGrade)}`,`cause: ${ge(o.causalCategory)}`),c.push(`**The failure group:** ${u.join(", ")}.`,""),a.length>0){c.push("### Diagnosis","");for(let y of a.slice(0,r?1:3))c.push(`**#${y.rank}**, ${ge(y.probableOwner)}, evidence ${ge(y.evidenceGrade)}, citing ${Fn(y.supportingEvidenceIds.length,"evidence item")}:`,"",i(y.statement),"")}d!==void 0&&c.push("### The repair","","Its intent:","",i(d.intent.statement),"","What it keeps:","",i(d.intent.preservedBehavior),"",`It changes ${Fn(d.changedFiles,"file")}, ${Fn(d.changedLines,"line")}: ${d.targets.map(y=>ge(y.path)).join(", ")}. KwikQA's repair rules checked it: it edits only test code the repository's policy allows, keeps every assertion, and adds no skip, wait, or retry.`,""),c.push("### Validation","");let p=t.plan?.commands.filter(y=>y.timing==="post-patch")??[],f=[...new Set(p.map(X1))];c.push(`On the runner, at commit ${ge(t.commit.slice(0,12))}, the repaired test passed ${Fi} times in a row with retries off, and every required check passed:`,"",...f.length===0?["- (the commands are in the run's log)"]:f.map(y=>`- ${ge(y)}`),"");let h=t.validation?.groupCheck;if(h?.status==="rerun"){let y=h.stillFailing?.length??0;c.push(y===0?`The group's ${Fn(h.logicalTestIds.length,"other test")} passed when re-run with the repair.`:`Of the group's ${Fn(h.logicalTestIds.length,"other test")}, ${y} still failed with the repair; they need a look of their own.`,"")}let g=[["diagnosis",n.diagnosisAudit],["repair",n.repairAudit]].flatMap(([y,w])=>w===void 0?[]:[`- The ${y} request: ${ge(w.model.modelId)} via ${ge(w.reportedProvider??w.model.providerId)}.`]);return g.length>0&&c.push("### What was sent","","Only the redacted evidence each request's preview showed in the run's log:","",...g,""),c.push(t.runUrl===void 0?"The failure report, with each group's evidence, is in the run's artifacts.":`The failure report, with each group's evidence, is in the artifacts of [this run](${t.runUrl}).`,"",...e==="github"?["If the job's `GITHUB_TOKEN` opened this pull request, GitHub doesn't start its checks. To run them, close and reopen it, or push to it.",""]:[]),c.join(`
174
+ `)}var Ht=class extends Error{};async function us(t){let n=await t.json().catch(()=>{}),e=typeof n?.message=="string"?n.message:"";if(t.status===429||t.status===403&&/rate limit/i.test(e))return"GitHub's rate limit was reached";if(t.status===401)return"GitHub refused the token";if(t.status===403&&/create or approve pull requests/i.test(e))return`GitHub Actions may not create pull requests here; turn on "Allow GitHub Actions to create and approve pull requests" in the repository's or organization's Actions settings`;if(t.status===403)return"the token can't push a branch or open a pull request; give the job `contents: write` and `pull-requests: write`";if(t.status===404)return"GitHub found no such repository or commit with this token";let r=e===""?"":`: ${e.replace(/\s+/g," ").slice(0,200)}`;return`GitHub answered ${t.status}${r}`}async function _r(t){if(!t.ok)throw new Ht(await us(t));return await t.json()}function jw(t){return Dw("sha256").update(t).digest("hex")}async function ms(t){let n=[];for(let e of t.targets){let r=U1(t.workspaceRoot,e.path),i=await z1(r);if(jw(i)!==e.resultSha256)return{failure:`${e.path} on the runner is no longer the validated repair`};n.push({path:q1(t.gitRoot,r).split(G1).join("/"),workspacePath:e.path,bytes:i,mode:((await V1(r)).mode&73)===0?"100644":"100755",sourceSha256:e.sourceSha256})}return{files:n}}function zn(t,n){return`${t.workspacePath} on ${n} isn't the file the repair was validated against, so the repair isn't committed there`}function ys(t,n){return jw(t)===n.sourceSha256}async function Eu(t,n,e){let r=new Lr(n,e.apiUrl,e.token),i=`/repos/${e.repository}`,s=ft(e.fingerprint),a=!1;try{let o=await ms(e);if("failure"in o)return{kind:"failed",reason:o.failure};let{files:d}=o,l=(await _r(await r.call("GET",`${i}/git/commits/${e.base.commit}`))).tree?.sha;if(typeof l!="string")throw new Ht("GitHub returned no tree for the base");for(let w of d){let x=await r.call("GET",`${i}/contents/${w.path.split("/").map(encodeURIComponent).join("/")}?ref=${e.base.commit}`),v=await _r(x),R=typeof v.content=="string"&&v.encoding==="base64"?Buffer.from(v.content,"base64"):void 0;if(R===void 0||!ys(R,w))return{kind:"skipped",reason:zn(w,e.base.branch)}}let u=[];for(let w of d){let x=await _r(await r.call("POST",`${i}/git/blobs`,{content:Buffer.from(w.bytes).toString("base64"),encoding:"base64"}));if(typeof x.sha!="string")throw new Ht("GitHub returned no blob");u.push({path:w.path,mode:w.mode,type:"blob",sha:x.sha})}let p=await _r(await r.call("POST",`${i}/git/trees`,{base_tree:l,tree:u})),f=await _r(await r.call("POST",`${i}/git/commits`,{message:e.commitMessage,tree:p.sha,parents:[e.base.commit]}));if(typeof f.sha!="string")throw new Ht("GitHub returned no commit");let h=await r.call("POST",`${i}/git/refs`,{ref:`refs/heads/${s}`,sha:f.sha});if(h.status===422)return{kind:"skipped",reason:`${s} already exists, from an earlier run; KwikQA never pushes to a branch it didn't create`};await _r(h),a=!0;let m=await r.call("POST",`${i}/pulls`,{title:e.title,head:s,base:e.base.branch,body:e.body,draft:!0});if(!m.ok){let w=await m.clone().json().catch(()=>{}),x=JSON.stringify(w??{});throw new Ht(m.status===422&&/draft/i.test(x)?"this repository doesn't take draft pull requests, and KwikQA opens only drafts (on GitHub Free, a private repository has none)":await us(m))}let g=await m.json();if(typeof g.number!="number")throw new Ht("GitHub returned no pull request");a=!1;let y=await r.call("POST",`${i}/issues/${g.number}/labels`,{labels:[an]});return y.ok||t.print(`The fix pull request has no \`${an}\` label: ${await us(y)}.`),{kind:"opened",number:g.number,...typeof g.html_url=="string"?{url:g.html_url}:{}}}catch(o){let d=o instanceof Ht?o.message:`GitHub couldn't be reached (${o instanceof Error?o.message:String(o)})`;return a&&await r.call("DELETE",`${i}/git/refs/heads/${s}`).catch(()=>{}),{kind:"failed",reason:d}}}var Q1=3e4,Z1="7.1",eN="0".repeat(40),Cu=4e3,xo=class{constructor(n,e){this.send=n;this.repository=e;this.base=`${e.collectionUrl}/${e.projectId}/_apis/git/repositories/${e.repositoryId}`}send;repository;base;call(n,e,r={}){let i=new URLSearchParams({...r.query,"api-version":Z1});return this.send(`${this.base}${e}?${i}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.repository.token}`,...r.body===void 0?{}:{"Content-Type":"application/json"}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},redirect:"error",signal:AbortSignal.timeout(Q1)})}},It=class extends Error{};async function Fr(t,n){if(t.status===429)return"Azure DevOps's rate limit was reached";if(t.status===401||t.status===203)return"Azure DevOps refused the token";let e=await Hs(t),r=e===void 0?"":` (${e})`;return t.status===403?`${n}${r}`:t.status===404?`Azure DevOps found no such repository or commit with this token${r}`:`Azure DevOps answered ${t.status}${e===void 0?"":`: ${e}`}`}async function Fw(t,n){let e=await t.call("GET","/refs",{query:{filter:`heads/${n}`}});if(!gt(e))throw new It(await Fr(e,"the build service can't read branches"));let i=(await e.json()).value?.find(s=>s.name===`refs/heads/${n}`);return typeof i?.objectId=="string"?i.objectId:void 0}async function Nu(t,n,e){let r=new xo(t,n),i=ft(e);try{let s=await r.call("GET","/pullrequests",{query:{"searchCriteria.sourceRefName":`refs/heads/${i}`,"searchCriteria.status":"active"}});if(!gt(s))return{kind:"unknown",reason:await Fr(s,"the build service can't read pull requests")};let o=(await s.json()).value?.find(d=>typeof d.pullRequestId=="number"&&typeof d.description=="string"&&d.description.startsWith(Bn(e)));return typeof o?.pullRequestId=="number"?{kind:"open",number:o.pullRequestId}:await Fw(r,i)===void 0?{kind:"none"}:{kind:"branch"}}catch(s){return{kind:"unknown",reason:s instanceof It?s.message:`Azure DevOps couldn't be reached (${s instanceof Error?s.message:String(s)})`}}}async function Ou(t,n,e,r,i){let s=i.runUrl===void 0?"a later run":`[a later run](${i.runUrl})`;await Dd(t,n,{...e,pullRequest:r.number,marker:`kwikqa-fix-seen group=${r.fingerprint}`,noun:"note on the fix pull request"},`This failure group failed again in ${s}, at commit ${ge(i.commit.slice(0,12))}. KwikQA asks for no other repair while this pull request is open.
175
175
  `,!0)}function Bw(t){if(t.length<=Cu)return t;let n=`
176
176
 
177
177
  \u2026The rest is in the run's log and its report.`,e=t.slice(0,Cu-n.length-12),r;for(let i of e.split(`
178
178
  `)){let s=/^(`{3,})/.exec(i)?.[1];s!==void 0&&(r===void 0?r=s:s===r&&i===s&&(r=void 0))}return`${e}${r===void 0?"":`
179
- ${r}`}${n}`}async function $u(t,n,e){let r=new xo(n,e),i=ft(e.fingerprint),s;try{let a=await ms(e);if("failure"in a)return{kind:"failed",reason:a.failure};let{files:o}=a;for(let m of o){let g=await r.call("GET","/items",{query:{path:`/${m.path}`,"versionDescriptor.version":e.base.commit,"versionDescriptor.versionType":"commit",$format:"octetStream",download:"true"}});if(g.status===404)return{kind:"skipped",reason:Hn(m,e.base.branch)};if(!gt(g))throw new It(await Fr(g,"the build service can't read the repository"));if(!ys(new Uint8Array(await g.arrayBuffer()),m))return{kind:"skipped",reason:Hn(m,e.base.branch)}}if(await Fw(r,i)!==void 0)return{kind:"skipped",reason:`${i} already exists, from an earlier run; KwikQA never pushes to a branch it didn't create`};let d=await r.call("POST","/pushes",{body:{refUpdates:[{name:`refs/heads/${i}`,oldObjectId:e.base.commit}],commits:[{comment:e.commitMessage,changes:o.map(m=>({changeType:"edit",item:{path:`/${m.path}`},newContent:{content:Buffer.from(m.bytes).toString("base64"),contentType:"base64encoded"}}))}]}});if(!gt(d))throw new It(await Fr(d,`the build service can't push a branch; give it "Contribute" and "Create branch" on the repository`));let l=(await d.json()).refUpdates?.find(m=>m.name===`refs/heads/${i}`)?.newObjectId;if(typeof l!="string")throw new It("Azure DevOps returned no new branch");s=l;let u=await r.call("POST","/pullrequests",{body:{sourceRefName:`refs/heads/${i}`,targetRefName:`refs/heads/${e.base.branch}`,title:e.title,description:Bw(e.description),isDraft:!0}});if(!gt(u))throw new It(await Fr(u,`the build service can't open a pull request; give it "Contribute to pull requests" on the repository`));let p=await u.json();if(typeof p.pullRequestId!="number")throw new It("Azure DevOps returned no pull request");s=void 0;let f=await r.call("POST",`/pullRequests/${p.pullRequestId}/labels`,{body:{name:an}});gt(f)||t.print(`The fix pull request has no \`${an}\` label: ${await Fr(f,"the build service can't label it")}.`);let h=p.repository?.webUrl;return{kind:"opened",number:p.pullRequestId,...typeof h=="string"&&h.startsWith("https://")?{url:`${h}/pullrequest/${p.pullRequestId}`}:{}}}catch(a){let o=a instanceof It?a.message:`Azure DevOps couldn't be reached (${a instanceof Error?a.message:String(a)})`;return s!==void 0&&await r.call("POST","/refs",{body:[{name:`refs/heads/${i}`,oldObjectId:s,newObjectId:Q1}]}).catch(()=>{}),{kind:"failed",reason:o}}}var vo=["on-failure","always"],Hw=10,Z1=3e4,eN=2e3,tN=6e4;function gs(t,n){return`${t} ${n}${t===1?"":"s"}`}function Br(t,n=150){let e=t.replace(new RegExp("\\p{Cc}","gu")," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function Du(t){let{model:n,run:e}=t,r=n?.run.counts.find(l=>l.label==="Failed")?.value??0,i=n?.run.counts.find(l=>l.label==="Flaky")?.value??0,s=e?.repository===void 0?"":` in ${e.repository}`,a=n===void 0?`KwikQA: no analysis${s}`:r>0?`KwikQA: ${gs(r,"test")} failed${s}`:`KwikQA: no failures${s}`,o=[...e?.pullRequest?.url===void 0?e?.commit?.url===void 0?[]:[{label:`Commit ${e.commit.sha.slice(0,7)}`,url:e.commit.url}]:[{label:e.pullRequest.name??`Pull request #${e.pullRequest.number}`,url:e.pullRequest.url}],...e?.runUrl===void 0?[]:[{label:"Open the run",url:e.runUrl}]],d=e?.branch===void 0?void 0:`Branch ${Br(e.branch,100)}`,c=[];if(n===void 0)c.push(Br(t.message,300));else{let l=n.run.counts.filter(p=>p.label==="Tests"||p.value>0).map(p=>p.label==="Tests"?gs(p.value,"test"):`${p.value} ${p.label.toLowerCase()}`);c.push(`${Br(n.run.framework,60)} run: ${l.join(", ")}.`);for(let p of n.groups.slice(0,Hw)){let f=p.place===void 0?"":` in ${Br(p.place,120)}`;c.push(`${p.number===void 0?"\u2013":`${p.number}.`} ${p.category}${f} \xB7 ${gs(p.size,"test")} \xB7 ${Mt[p.owner]}`)}let u=n.groups.length-Hw;u>0&&c.push(`and ${gs(u,"more group")} in the report`),i>0&&c.push(`${gs(i,"flaky test")} passed on a retry.`)}return t.notDiagnosed!==void 0&&c.push(`Not diagnosed: ${Br(t.notDiagnosed,300)}`),{headline:a,...d===void 0?{}:{source:d},links:o,lines:c}}function zw(t){let n=(r,i=!1)=>({type:"text",text:r,...i?{style:{bold:!0}}:{}}),e=[...t.source===void 0?[]:[n(t.source)],...t.links.map(r=>({type:"link",url:r.url,text:r.label}))].flatMap((r,i)=>i===0?[r]:[n(" \xB7 "),r]);return{text:t.headline,blocks:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[n(Br(t.headline,150),!0),...e.length===0?[]:[n(`
179
+ ${r}`}${n}`}async function $u(t,n,e){let r=new xo(n,e),i=ft(e.fingerprint),s;try{let a=await ms(e);if("failure"in a)return{kind:"failed",reason:a.failure};let{files:o}=a;for(let m of o){let g=await r.call("GET","/items",{query:{path:`/${m.path}`,"versionDescriptor.version":e.base.commit,"versionDescriptor.versionType":"commit",$format:"octetStream",download:"true"}});if(g.status===404)return{kind:"skipped",reason:zn(m,e.base.branch)};if(!gt(g))throw new It(await Fr(g,"the build service can't read the repository"));if(!ys(new Uint8Array(await g.arrayBuffer()),m))return{kind:"skipped",reason:zn(m,e.base.branch)}}if(await Fw(r,i)!==void 0)return{kind:"skipped",reason:`${i} already exists, from an earlier run; KwikQA never pushes to a branch it didn't create`};let d=await r.call("POST","/pushes",{body:{refUpdates:[{name:`refs/heads/${i}`,oldObjectId:e.base.commit}],commits:[{comment:e.commitMessage,changes:o.map(m=>({changeType:"edit",item:{path:`/${m.path}`},newContent:{content:Buffer.from(m.bytes).toString("base64"),contentType:"base64encoded"}}))}]}});if(!gt(d))throw new It(await Fr(d,`the build service can't push a branch; give it "Contribute" and "Create branch" on the repository`));let l=(await d.json()).refUpdates?.find(m=>m.name===`refs/heads/${i}`)?.newObjectId;if(typeof l!="string")throw new It("Azure DevOps returned no new branch");s=l;let u=await r.call("POST","/pullrequests",{body:{sourceRefName:`refs/heads/${i}`,targetRefName:`refs/heads/${e.base.branch}`,title:e.title,description:Bw(e.description),isDraft:!0}});if(!gt(u))throw new It(await Fr(u,`the build service can't open a pull request; give it "Contribute to pull requests" on the repository`));let p=await u.json();if(typeof p.pullRequestId!="number")throw new It("Azure DevOps returned no pull request");s=void 0;let f=await r.call("POST",`/pullRequests/${p.pullRequestId}/labels`,{body:{name:an}});gt(f)||t.print(`The fix pull request has no \`${an}\` label: ${await Fr(f,"the build service can't label it")}.`);let h=p.repository?.webUrl;return{kind:"opened",number:p.pullRequestId,...typeof h=="string"&&h.startsWith("https://")?{url:`${h}/pullrequest/${p.pullRequestId}`}:{}}}catch(a){let o=a instanceof It?a.message:`Azure DevOps couldn't be reached (${a instanceof Error?a.message:String(a)})`;return s!==void 0&&await r.call("POST","/refs",{body:[{name:`refs/heads/${i}`,oldObjectId:s,newObjectId:eN}]}).catch(()=>{}),{kind:"failed",reason:o}}}var vo=["on-failure","always"],Hw=10,tN=3e4,nN=2e3,rN=6e4;function gs(t,n){return`${t} ${n}${t===1?"":"s"}`}function Br(t,n=150){let e=t.replace(new RegExp("\\p{Cc}","gu")," ").replace(/\s+/g," ").trim();return e.length<=n?e:`${e.slice(0,n-1)}\u2026`}function Du(t){let{model:n,run:e}=t,r=n?.run.counts.find(l=>l.label==="Failed")?.value??0,i=n?.run.counts.find(l=>l.label==="Flaky")?.value??0,s=e?.repository===void 0?"":` in ${e.repository}`,a=n===void 0?`KwikQA: no analysis${s}`:r>0?`KwikQA: ${gs(r,"test")} failed${s}`:`KwikQA: no failures${s}`,o=[...e?.pullRequest?.url===void 0?e?.commit?.url===void 0?[]:[{label:`Commit ${e.commit.sha.slice(0,7)}`,url:e.commit.url}]:[{label:e.pullRequest.name??`Pull request #${e.pullRequest.number}`,url:e.pullRequest.url}],...e?.runUrl===void 0?[]:[{label:"Open the run",url:e.runUrl}]],d=e?.branch===void 0?void 0:`Branch ${Br(e.branch,100)}`,c=[];if(n===void 0)c.push(Br(t.message,300));else{let l=n.run.counts.filter(p=>p.label==="Tests"||p.value>0).map(p=>p.label==="Tests"?gs(p.value,"test"):`${p.value} ${p.label.toLowerCase()}`);c.push(`${Br(n.run.framework,60)} run: ${l.join(", ")}.`);for(let p of n.groups.slice(0,Hw)){let f=p.place===void 0?"":` in ${Br(p.place,120)}`;c.push(`${p.number===void 0?"\u2013":`${p.number}.`} ${p.category}${f} \xB7 ${gs(p.size,"test")} \xB7 ${Mt[p.owner]}`)}let u=n.groups.length-Hw;u>0&&c.push(`and ${gs(u,"more group")} in the report`),i>0&&c.push(`${gs(i,"flaky test")} passed on a retry.`)}return t.notDiagnosed!==void 0&&c.push(`Not diagnosed: ${Br(t.notDiagnosed,300)}`),{headline:a,...d===void 0?{}:{source:d},links:o,lines:c}}function zw(t){let n=(r,i=!1)=>({type:"text",text:r,...i?{style:{bold:!0}}:{}}),e=[...t.source===void 0?[]:[n(t.source)],...t.links.map(r=>({type:"link",url:r.url,text:r.label}))].flatMap((r,i)=>i===0?[r]:[n(" \xB7 "),r]);return{text:t.headline,blocks:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[n(Br(t.headline,150),!0),...e.length===0?[]:[n(`
180
180
  `),...e],n(`
181
181
 
182
182
  ${t.lines.join(`
183
- `).slice(0,3e3)}`)]}]}]}}function Vw(t){let n=(e,r={})=>({type:"RichTextBlock",inlines:[{type:"TextRun",text:e,...r}]});return{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",msteams:{width:"Full"},body:[n(t.headline,{weight:"Bolder",size:"Medium"}),...t.source===void 0?[]:[n(t.source,{isSubtle:!0})],...t.lines.map(e=>n(e))],actions:t.links.map(e=>({type:"Action.OpenUrl",title:e.label,url:e.url}))}}]}}function nN(t){if(!(t===void 0||t.trim()===""))try{let n=new URL(t.trim());return n.protocol==="https:"&&n.username===""&&n.password===""?n:void 0}catch{return}}function rN(t){let n=Number(t?.headers.get("retry-after"));return Number.isFinite(n)&&n>0?Math.min(n*1e3,tN):eN}async function iN(t,n,e,r,i,s){let a="";for(let o=1;o<=2;o+=1){let d;try{d=await n(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),redirect:"error",signal:AbortSignal.timeout(Z1)})}catch(c){a=`the webhook couldn't be reached (${c instanceof Error?c.message:String(c)})`}if(d?.ok===!0){t.print(`${r}: posted.`);return}if(d!==void 0&&(a=`the webhook answered ${d.status}`,d.status!==429&&d.status<500))break;o===1&&await e(rN(d))}t.error(`${r}: not posted; ${a}.`)}async function Lu(t,n,e,r,i,s){let a=[{name:"Slack",variable:"KWIKQA_SLACK_WEBHOOK_URL",message:zw},{name:"Teams",variable:"KWIKQA_TEAMS_WEBHOOK_URL",message:Vw}];for(let o of a){let d=r[o.variable];if(d===void 0||d.trim()==="")continue;let c=nN(d);if(c===void 0){t.error(`${o.name}: not posted; ${o.variable} isn't an https URL.`);continue}if(s.when==="on-failure"&&!s.failures){t.print(`${o.name}: nothing failed, so nothing was posted (--notify always posts).`);continue}await iN(t,n,e,o.name,c,o.message(i))}}var sN=30,Uw=100,aN=3e4,oN=/^[\w.-]+(?:\/[\w.-]+)+$/;function Hr(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function dN(t,n){let e=(t??"").split(",").filter(i=>i.trim()!=="");if(e.length!==1)return;let r=/^(.+)!(\d+)$/.exec(e[0]?.trim()??"");return r?.[1]===n?Hr(r[2]):void 0}function ko(t){if(t.GITLAB_CI!=="true")return;let n=st(t.CI_API_V4_URL),e=oN.test(t.CI_PROJECT_PATH??"")?t.CI_PROJECT_PATH:void 0,r=st(t.CI_PROJECT_URL),i=Hr(t.CI_PROJECT_ID),s=Hr(t.CI_MERGE_REQUEST_IID),a=s??(e===void 0?void 0:dN(t.CI_OPEN_MERGE_REQUESTS,e)),o=s===void 0?i:Hr(t.CI_MERGE_REQUEST_PROJECT_ID),d=s===void 0?i:Hr(t.CI_MERGE_REQUEST_SOURCE_PROJECT_ID),c=s===void 0?r:st(t.CI_MERGE_REQUEST_PROJECT_URL),l=/^[0-9a-f]{40}$/.test(t.CI_COMMIT_SHA??"")?t.CI_COMMIT_SHA:void 0,u=t.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME||t.CI_COMMIT_BRANCH||t.CI_COMMIT_TAG||t.CI_COMMIT_REF_NAME||void 0,p=st(t.CI_JOB_URL),f=(t.GITLAB_TOKEN??"").trim(),h=Hr(t.CI_JOB_ID),m=t.CI_MERGE_REQUEST_EVENT_TYPE==="merged_result"||t.CI_MERGE_REQUEST_EVENT_TYPE==="merge_train",g=/^[0-9a-f]{40}$/.test(t.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA??"")?t.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA:m?void 0:l,y=t.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME||void 0,w=s!==void 0&&d!==o;return{...n===void 0?{}:{apiUrl:n},...e===void 0?{}:{repository:e},...p===void 0?{}:{runUrl:p},...o===void 0?{}:{projectId:o},job:t.CI_JOB_NAME??"",...u===void 0?{}:{branch:u},...l===void 0?{}:{commit:{sha:l,...r===void 0?{}:{url:`${r}/-/commit/${l}`}}},...f===""?{}:{token:f},...h===void 0?{}:{jobId:String(h)},...t.CI_COMMIT_BRANCH?{commitBranch:t.CI_COMMIT_BRANCH}:{},...s!==void 0&&!w&&y!==void 0&&g!==void 0?{pullRequestHead:{ref:y,sha:g}}:{},...w?{sourceInOtherProject:!0}:{},...a===void 0?{}:{pullRequest:{number:a,name:`Merge request !${a}`,...c===void 0?{}:{url:`${c}/-/merge_requests/${a}`},fork:d!==o&&i!==o}}}}function qw(t){return`<!-- kwikqa-ci gitlab job=${encodeURIComponent(t.job)} -->`}async function Mu(t){if(t.status===429)return"GitLab's rate limit was reached";if(t.status===401)return"GitLab refused GITLAB_TOKEN";if(t.status===403)return"GITLAB_TOKEN can't comment on this merge request; it needs at least the Reporter role, and Work Item read, create, and update on this project if it's a fine-grained token, or else the `api` scope";if(t.status===404)return"GitLab found no such merge request with GITLAB_TOKEN";let n=await t.json().catch(()=>{}),e=typeof n?.message=="string"?`: ${n.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitLab answered ${t.status}${e}`}var Vr=class{constructor(n,e,r){this.send=n;this.apiUrl=e;this.token=r}send;apiUrl;token;call(n,e,r){return this.send(`${this.apiUrl}${e}`,{method:n,headers:{Accept:"application/json","PRIVATE-TOKEN":this.token,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(aN)})}},zr=class extends Error{};async function cN(t,n,e){for(let r=1;r<=sN;r+=1){let i=await t.call("GET",`${n}?sort=asc&order_by=created_at&per_page=${Uw}&page=${r}`);if(!i.ok)throw new zr(await Mu(i));let s=await i.json(),a=s.find(o=>o.system!==!0&&typeof o.body=="string"&&o.body.startsWith(e));if(typeof a?.id=="number")return a.id;if(s.length<Uw)return}}async function ws(t,n,e,r,i){let s=new Vr(n,e.apiUrl,e.token),o=`/projects/${encodeURIComponent(String(e.project))}/merge_requests/${e.number}/notes`,{marker:d}=e,c={body:`${d}
184
- ${r}`},l=e.noun??"merge-request note",u=`${l.charAt(0).toUpperCase()}${l.slice(1)}`;try{let p=await cN(s,o,d);if(p!==void 0){let h=await s.call("PUT",`${o}/${p}`,c);if(h.ok)return t.print(`${u}: updated.`);if(h.status!==403&&h.status!==404)throw new zr(await Mu(h))}if(p===void 0&&!i)return t.print(`No ${l}: nothing failed, and there is no earlier note to update.`);let f=await s.call("POST",o,c);if(!f.ok)throw new zr(await Mu(f));t.print(`${u}: posted.`)}catch(p){let f=p instanceof zr?p.message:`GitLab couldn't be reached (${p instanceof Error?p.message:String(p)})`;t.error(`No ${l}: ${f}.`)}}async function lN(t,n,e,r,i){let s=o=>t.print(`No merge-request note: ${o}.`),a=e.pullRequest;if(a===void 0)return s("this pipeline isn't for a merge request, or its branch has more than one");if(a.fork)return s("the merge request comes from a fork, whose pipeline gets none of this project's variables");if(e.token===void 0)return s("GITLAB_TOKEN isn't set; CI_JOB_TOKEN can't write notes, so add a token that can as a masked CI/CD variable: a fine-grained token with Work Item read, create, and update, or one with the `api` scope");if(e.apiUrl===void 0||e.projectId===void 0)return s("CI_API_V4_URL or the merge request's project isn't what GitLab sets");await ws(t,n,{apiUrl:e.apiUrl,project:e.projectId,number:a.number,token:e.token,marker:qw(e)},r,i)}async function _u(t,n,e,r,i){t.print("");for(let s of r.trimEnd().split(`
185
- `))t.print(s);t.print(""),await lN(t,n,e,r,i.failures)}var zn=class extends Error{};async function bs(t,n){if(t.status===429)return"GitLab's rate limit was reached";if(t.status===401)return"GitLab refused GITLAB_TOKEN";if(t.status===403)return n;if(t.status===404)return"GitLab found no such project or commit with GITLAB_TOKEN";let e=await t.json().catch(()=>{}),r=typeof e?.message=="string"?e.message:e?.message===void 0?"":JSON.stringify(e.message),i=r===""?"":`: ${r.replace(/\s+/g," ").slice(0,200)}`;return`GitLab answered ${t.status}${i}`}function Vn(t,n){return`/projects/${t}${n}`}function ju(t){return`/repository/branches/${encodeURIComponent(t)}`}async function Fu(t,n,e){let r=new Vr(t,n.apiUrl,n.token),i=ft(e);try{let s=await r.call("GET",Vn(n.project,`/merge_requests?state=opened&source_branch=${encodeURIComponent(i)}&per_page=100`));if(!s.ok)return{kind:"unknown",reason:await bs(s,"GITLAB_TOKEN can't read merge requests")};let a=(await s.json()).find(d=>typeof d.iid=="number"&&typeof d.description=="string"&&d.description.startsWith(Fn(e)));if(typeof a?.iid=="number")return{kind:"open",number:a.iid,...typeof a.web_url=="string"?{url:a.web_url}:{}};let o=await r.call("GET",Vn(n.project,ju(i)));return o.status===404?{kind:"none"}:o.ok?{kind:"branch"}:{kind:"unknown",reason:await bs(o,"GITLAB_TOKEN can't read branches")}}catch(s){return{kind:"unknown",reason:`GitLab couldn't be reached (${s instanceof Error?s.message:String(s)})`}}}async function Bu(t,n,e,r,i){let s=i.runUrl===void 0?"a later pipeline":`[a later pipeline](${i.runUrl})`;await ws(t,n,{apiUrl:e.apiUrl,project:e.project,number:r.number,token:e.token,marker:`<!-- kwikqa-fix-seen group=${r.fingerprint} -->`,noun:"note on the fix merge request"},`This failure group failed again in ${s}, at commit ${ge(i.commit.slice(0,12))}. KwikQA asks for no other repair while this merge request is open.
186
- `,!0)}async function Hu(t,n,e){let r=new Vr(n,e.apiUrl,e.token),i=ft(e.fingerprint),s=!1;try{let a=await ms(e);if("failure"in a)return{kind:"failed",reason:a.failure};let{files:o}=a;for(let p of o){let f=await r.call("GET",Vn(e.project,`/repository/files/${encodeURIComponent(p.path)}?ref=${e.base.commit}`));if(f.status===404)return{kind:"skipped",reason:Hn(p,e.base.branch)};if(!f.ok)throw new zn(await bs(f,"GITLAB_TOKEN can't read the repository"));let h=await f.json(),m=typeof h.content=="string"&&h.encoding==="base64"?Buffer.from(h.content,"base64"):void 0;if(m===void 0||!ys(m,p))return{kind:"skipped",reason:Hn(p,e.base.branch)}}if((await r.call("GET",Vn(e.project,ju(i)))).ok)return{kind:"skipped",reason:`${i} already exists, from an earlier pipeline; KwikQA never pushes to a branch it didn't create`};let c=await r.call("POST",Vn(e.project,"/repository/commits"),{branch:i,start_sha:e.base.commit,commit_message:e.commitMessage,actions:o.map(p=>({action:"update",file_path:p.path,content:Buffer.from(p.bytes).toString("base64"),encoding:"base64"}))});if(!c.ok)throw new zn(await bs(c,"GITLAB_TOKEN can't push a branch; it needs the `api` scope and at least the Developer role"));s=!0;let l=await r.call("POST",Vn(e.project,"/merge_requests"),{source_branch:i,target_branch:e.base.branch,title:`Draft: ${e.title}`,description:e.description,labels:an,remove_source_branch:!0});if(!l.ok)throw new zn(await bs(l,"GITLAB_TOKEN can't open a merge request; it needs the `api` scope and at least the Developer role"));let u=await l.json();if(typeof u.iid!="number")throw new zn("GitLab returned no merge request");return s=!1,{kind:"opened",number:u.iid,...typeof u.web_url=="string"&&u.web_url.startsWith("https://")?{url:u.web_url}:{}}}catch(a){let o=a instanceof zn?a.message:`GitLab couldn't be reached (${a instanceof Error?a.message:String(a)})`;return s&&await r.call("DELETE",Vn(e.project,ju(i))).catch(()=>{}),{kind:"failed",reason:o}}}var uN=/^[\w.-]+(?:\/[\w.-]+)+$/,pN=/^\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/,fN=/^\/([\w.-]+(?:\/[\w.-]+)+)\/-\/merge_requests\/(\d+)$/;function Gw(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function hN(t,n){if(t===void 0||!t.startsWith("https:"))return;let e=new URL(t),r=pN.exec(e.pathname);if(r?.[1]!==void 0&&Number(r[2])===n)return{kind:"github",apiUrl:e.host==="github.com"?"https://api.github.com":e.host.endsWith(".ghe.com")?`https://api.${e.host}`:`${e.origin}/api/v3`,repository:r[1]};let i=fN.exec(e.pathname);if(i?.[1]!==void 0&&Number(i[2])===n)return{kind:"gitlab",apiUrl:`${e.origin}/api/v4`,project:i[1]}}function mN(t){let n=t??"",r=/^[\w.-]+@[\w.-]+:(?!\/)(.+)$/.exec(n)?.[1];if(r===void 0)try{r=new URL(n).pathname}catch{return}let i=r.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"");return uN.test(i)?i:void 0}function Ro(t){if(!t.JENKINS_URL&&!t.JENKINS_HOME||Gw(t.BUILD_NUMBER)===void 0)return;let n=Gw(t.CHANGE_ID),e=Ed(t.CHANGE_URL),r=n===void 0?void 0:hN(e,n),i=r?.kind==="github"?r.repository:r?.kind==="gitlab"?r.project:mN(t.GIT_URL),s=Ed(t.BUILD_URL),a=t.CHANGE_BRANCH||t.BRANCH_NAME||t.GIT_LOCAL_BRANCH||t.GIT_BRANCH?.replace(/^origin\//,"")||void 0,o=/^[0-9a-f]{40}$/.test(t.GIT_COMMIT??"")?t.GIT_COMMIT:void 0,d=(t.GITHUB_TOKEN??"").trim(),c=(t.GITLAB_TOKEN??"").trim();return{...i===void 0?{}:{repository:i},...s===void 0?{}:{runUrl:s},job:t.JOB_NAME??"",...t.STAGE_NAME?{stage:t.STAGE_NAME}:{},...a===void 0?{}:{branch:a},...o===void 0?{}:{commit:{sha:o}},...r===void 0?{}:{host:r},...d===""?{}:{githubToken:d},...c===""?{}:{gitlabToken:c},...n===void 0?{}:{pullRequest:{number:n,...r?.kind==="gitlab"?{name:`Merge request !${n}`}:{},...e===void 0?{}:{url:e},fork:!1}}}}function Kw(t){let n=t.stage===void 0?"":` stage=${encodeURIComponent(t.stage)}`;return`<!-- kwikqa-ci jenkins job=${encodeURIComponent(t.job)}${n} -->`}async function yN(t,n,e,r,i){let s=e.pullRequest,a=e.host;if(s===void 0)return t.print("No pull-request comment: this build isn't for a pull request.");if(a===void 0)return t.print(s.url?.startsWith("http:")===!0?"No pull-request comment: the pull request's page isn't https, and KwikQA sends tokens only over https.":"No pull-request comment: the pull request isn't on GitHub or GitLab, the hosts KwikQA comments on from Jenkins so far.");let o=Kw(e);return a.kind==="github"?e.githubToken===void 0?t.print("No pull-request comment: GITHUB_TOKEN isn't set; bind a token that can comment on pull requests with withCredentials."):cs(t,n,{apiUrl:a.apiUrl,repository:a.repository,number:s.number,token:e.githubToken,marker:o,forbidden:"GITHUB_TOKEN can't comment on this pull request; it needs Pull requests read and write, or a classic token's `repo` scope"},r,i):e.gitlabToken===void 0?t.print("No merge-request note: GITLAB_TOKEN isn't set; bind a token that can write notes with withCredentials: a fine-grained token with Work Item read, create, and update, or one with the `api` scope."):ws(t,n,{apiUrl:a.apiUrl,project:a.project,number:s.number,token:e.gitlabToken,marker:o},r,i)}async function zu(t,n,e,r,i){t.print("");for(let s of r.trimEnd().split(`
187
- `))t.print(s);t.print(""),await yN(t,n,e,r,i.failures)}import{createHash as gv}from"node:crypto";import{access as gD,appendFile as wD,mkdir as bD,readdir as xD,readFile as kd,realpath as Ut,stat as wv,writeFile as vv}from"node:fs/promises";import{isAbsolute as Rd,join as He,relative as ei,resolve as Id,sep as lf}from"node:path";import{mkdir as nO,writeFile as rO}from"node:fs/promises";import{join as Ib}from"node:path";import{lstat as gN,readFile as Ww,realpath as Gu}from"node:fs/promises";import{dirname as Vu,isAbsolute as wN,join as Ao,relative as To,resolve as Io,sep as Jw}from"node:path";var Yw=["ts","mts","cts","js","mjs","cjs"],Xw={playwright:"playwright.config",cypress:"cypress.config",webdriverio:"wdio.conf"},bN={playwright:["@playwright/test"],cypress:["cypress"],webdriverio:["@wdio/cli","webdriverio"]},So={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function Uu(t,n){let e=To(t,n);return e===""||!wN(e)&&e!==".."&&!e.startsWith(`..${Jw}`)}async function Po(t){return(await gN(t).catch(()=>{}))?.isFile()===!0}function qu(t){return t.split(Jw).join("/")}async function Qw(t){let n=await Gu(t),e={};try{let i=JSON.parse(await Ww(Ao(n,"package.json"),"utf8"));e={...i.dependencies,...i.devDependencies}}catch{e={}}let r=[];for(let i of["playwright","cypress","webdriverio"]){let s=bN[i].find(o=>o in e),a;for(let o of Yw){let d=`${Xw[i]}.${o}`;if(await Po(Ao(n,d))){a=d;break}}(s!==void 0||a!==void 0)&&r.push({framework:i,...a===void 0?{}:{configFile:a},...s===void 0?{}:{packageName:s}})}return r}async function Eo(t,n,e){let r=await Gu(t),i=Vu(Io(r,e));for(Uu(r,i)||(i=r);;){for(let a of Yw){let o=Ao(i,`${Xw[n]}.${a}`);if(await Po(o))return qu(To(r,o))}if(i===r)return;let s=Vu(i);if(!Uu(r,s))return;i=s}}async function Co(t,n){let e=await Gu(t),r=n===void 0?e:Vu(Io(e,n));if(n!==void 0){let i=await Ww(Io(e,n),"utf8").catch(()=>"");if(/\bsupportFile\s*:\s*false\b/.test(i))return null;let s=/\bsupportFile\s*:\s*["'`]([^"'`]+)["'`]/.exec(i)?.[1];if(s!==void 0){let a=Io(r,s);return Uu(e,a)&&await Po(a)?qu(To(e,a)):void 0}}for(let i of["ts","js","tsx","jsx"]){let s=Ao(r,"cypress","support",`e2e.${i}`);if(await Po(s))return qu(To(e,s))}}import{readFile as RN,realpath as IN}from"node:fs/promises";import{createRequire as AN}from"node:module";import{delimiter as TN,dirname as ib,isAbsolute as PN,join as Un}from"node:path";import{spawn as nb}from"node:child_process";var xN=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],Zw=256*1024,vN=8e3;function No(t,n={}){let e={...t,...n};for(let r of xN)delete e[r];return e}function eb(t){return t.pid===void 0||t.exitCode!==null||t.signalCode!==null}function tb(t,n){if(t.pid!==void 0)try{process.kill(-t.pid,n)}catch{t.kill(n)}}async function kN(t,n){if(!eb(t)){if(process.platform==="win32"){await new Promise(e=>{let r=nb("taskkill",["/pid",String(t.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>e()),r.on("error",()=>e())});return}tb(t,"SIGINT"),await Promise.race([n,new Promise(e=>setTimeout(e,vN))]),eb(t)||tb(t,"SIGKILL")}}function Ku(t,n,e){let r=nb(t,[...n],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),i="",s=o=>{i+=o.toString("utf8"),i.length>Zw&&(i=i.slice(-Zw))};r.stdout?.on("data",s),r.stderr?.on("data",s);let a=new Promise(o=>{r.on("exit",d=>o(d??void 0)),r.on("error",()=>o(void 0))});return{child:r,output:()=>i,exited:a,stop:async()=>{await kN(r,a),await Promise.race([a,new Promise(o=>setTimeout(o,2e3))])}}}async function Oo(t,n,e){let r=Ku(t,n,e),i=!1,s=setTimeout(()=>{i=!0,r.stop()},e.timeoutMs),a=await r.exited;return clearTimeout(s),{...a===void 0?{}:{exitCode:a},timedOut:i,output:r.output()}}async function rb(t,n,e){let r=Date.now()+e,i=!1;for(t.exited.then(()=>{i=!0});Date.now()<r;){let s=n.exec(t.output());if(s!==null)return s;if(i)return n.exec(t.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var ab="1.0",Wu=[1,59],SN=5,EN=6e4,CN=3e4,NN=12e4,ON=new Set(["generic","text","list","group","none","presentation"]),$N=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function Ju(t){let[n=0,e=0]=t.split(".").map(r=>Number.parseInt(r,10));return n>Wu[0]||n===Wu[0]&&e>=Wu[1]}async function sb(t){try{let n=JSON.parse(await RN(Un(t,"package.json"),"utf8"));return n.name==="@playwright/cli"&&typeof n.version=="string"?n.version:void 0}catch{return}}async function ob(t,n){try{let r=AN(Un(t,"package.json")).resolve("@playwright/cli/package.json"),i=ib(r),s=await sb(i);if(s!==void 0)return{entryPath:Un(i,"playwright-cli.js"),version:s,source:"project"}}catch{}let e=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(n.PATH??"").split(TN).filter(Boolean))for(let i of e){let s=Un(r,i);try{let a=process.platform==="win32"?Un(r,"node_modules","@playwright","cli"):ib(await IN(s)),o=await sb(a);if(o!==void 0)return{entryPath:Un(a,"playwright-cli.js"),version:o,source:"path"}}catch{}}}function Yu(t){return t.split(/\r?\n/).filter(n=>!/[║╔╚═]/.test(n)).join(`
188
- `)}function db(t){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(Yu(t))?.[1]?.split(/\r?\n/)}function cb(t){let n=Yu(t).split(/\r?\n/),e=n.findIndex(r=>r.trim()==="### Result");if(!(e<0))return n.slice(e+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function DN(t){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(t??"")?.[1]?.toLowerCase()}function lb(t){return t.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function ub(t,n,e=SN){let r=Ir(n??""),i=DN(n);return t.map((a,o)=>{let d=/\[ref=(e\d+)\]/.exec(a)?.[1],c=lb(a),l=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(d===void 0||ON.has(l))return;let u=c.toLowerCase(),p=r.filter(f=>u.includes(f)).length*3+(i!==void 0&&l===i?2:0);if(!($N.has(l)&&p===0))return{ref:d,element:c,score:p,order:o}}).filter(a=>a!==void 0).sort((a,o)=>o.score-a.score||a.order-o.order).slice(0,e).map(({ref:a,element:o})=>({ref:a,element:o}))}async function pb(t){let{target:n}=t,e=[],r={logicalTestId:n.logicalTestId,title:n.title,file:n.file,line:n.line,...n.failingLine===void 0?{}:{failingLine:n.failingLine},...n.locator===void 0?{}:{locator:n.locator}};if(n.failingLine===void 0)return{...r,candidates:[],issues:["The report does not say which line failed."]};let i=No(t.env,{PLAYWRIGHT_HTML_OPEN:"never"}),s=Ku(t.playwright.executable,[...t.playwright.nodeArguments,"test",`${n.file}:${n.line}`,...n.project===void 0?[]:[`--project=${n.project}`],...t.configPath===void 0?[]:[`--config=${t.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:t.workspaceRoot,env:i}),a=(c,l=CN)=>Oo(process.execPath,[t.cli.entryPath,...c],{cwd:t.scratchDirectory,env:i,timeoutMs:l}),o,d=[];try{if(o=(await rb(s,/playwright-cli attach ([\w-]+)/,EN))?.[1],o===void 0)return e.push("The test did not stop in the debugger."),{...r,candidates:d,issues:e};if((await a(["attach",o])).exitCode!==0)return e.push("Playwright CLI could not attach to the paused test."),{...r,candidates:d,issues:e};let u=PN(n.file)?n.file:Un(t.workspaceRoot,n.file),p=await a([`-s=${o}`,"pause-at",`${u}:${n.failingLine}`],NN);if(p.exitCode!==0||!/### Paused/.test(p.output))return e.push(`The test did not reach line ${n.failingLine}.`),{...r,candidates:d,issues:e};let f=db((await a([`-s=${o}`,"snapshot"])).output);if(f===void 0)return e.push("Playwright CLI returned no page snapshot."),{...r,candidates:d,issues:e};for(let h of ub(f,n.locator)){let m=cb((await a([`-s=${o}`,"generate-locator",h.ref])).output);m!==void 0&&d.push({element:h.element,locator:m})}return d.length===0&&e.push("No locator could be generated for any candidate."),{...r,candidates:d,issues:e}}catch(c){return e.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...r,candidates:d,issues:e}}finally{o!==void 0&&await a([`-s=${o}`,"detach"],1e4).catch(()=>{}),await s.stop()}}import{mkdir as bb,rm as wb}from"node:fs/promises";import{dirname as WN,join as qr,relative as JN,resolve as YN}from"node:path";import{basename as GN,dirname as yb,join as Ur,relative as np,resolve as zt,sep as KN}from"node:path";import{createHash as LN}from"node:crypto";import{lstat as MN,mkdir as _N,readFile as fb,realpath as Xu,rename as jN,writeFile as FN}from"node:fs/promises";import{isAbsolute as BN,join as hb,relative as Qu,sep as mb}from"node:path";import{fileURLToPath as HN}from"node:url";var zN=".kwikqa/runtime",VN=["cypress-reporter.cjs","cypress-capture.js","wdio-reporter.mjs","wdio-capture.mjs"];async function UN(t){return fb(HN(new URL(`./${t}`,import.meta.url)),"utf8")}function qN(t,n){let e=Qu(t,n);return e===""||!BN(e)&&e!==".."&&!e.startsWith(`..${mb}`)}async function $o(t,n){let e=await Xu(t),r=e;for(let i of n.split("/").filter(s=>s!=="")){if(i==="."||i==="..")throw new Error("Unsafe KwikQA directory.");r=hb(r,i);let s=await MN(r).catch(()=>{});if(s===void 0)await _N(r);else if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`${Qu(e,r)} must be a real directory inside the workspace.`)}if(!qN(e,await Xu(r)))throw new Error("KwikQA directory escapes workspace.");return r}async function Zu(t,n){let e=`${t}.${process.pid}.tmp`;await FN(e,n,{mode:420}),await jN(e,t)}function ep(t){return LN("sha256").update(t,"utf8").digest("hex")}async function Do(t){let n=await Xu(t),e=await $o(n,zN),r={};for(let i of VN){let s=await UN(i),a=hb(e,i);await fb(a,"utf8").catch(()=>{})!==s&&await Zu(a,s),r[i]={path:a,relativePath:Qu(n,a).split(mb).join("/"),sha256:ep(s)}}return r}function rp(t){return t.split(KN).join("/")}function xs(t,n){let e=rp(np(t,n));return e.startsWith(".")?e:`./${e}`}async function tp(t,n,e){return await Zu(n,e),{path:n,relativePath:rp(np(t,n)),sha256:ep(e)}}async function Lo(t){let n=t.workspaceRoot,e=t.configFile===void 0?n:yb(zt(n,t.configFile)),r=["video=false","screenshotOnRunFailure=true",`screenshotsFolder=${zt(n,t.screenshotsDirectory)}`,...t.noRetries?["retries=0"]:[]],i=[];if(t.capture!==void 0){let a=await $o(n,t.capture.directory),o=await tp(n,Ur(a,"kwikqa-settings.js"),`// Generated by KwikQA for one run.
183
+ `).slice(0,3e3)}`)]}]}]}}function Vw(t){let n=(e,r={})=>({type:"RichTextBlock",inlines:[{type:"TextRun",text:e,...r}]});return{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",msteams:{width:"Full"},body:[n(t.headline,{weight:"Bolder",size:"Medium"}),...t.source===void 0?[]:[n(t.source,{isSubtle:!0})],...t.lines.map(e=>n(e))],actions:t.links.map(e=>({type:"Action.OpenUrl",title:e.label,url:e.url}))}}]}}function iN(t){if(!(t===void 0||t.trim()===""))try{let n=new URL(t.trim());return n.protocol==="https:"&&n.username===""&&n.password===""?n:void 0}catch{return}}function sN(t){let n=Number(t?.headers.get("retry-after"));return Number.isFinite(n)&&n>0?Math.min(n*1e3,rN):nN}async function aN(t,n,e,r,i,s){let a="";for(let o=1;o<=2;o+=1){let d;try{d=await n(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),redirect:"error",signal:AbortSignal.timeout(tN)})}catch(c){a=`the webhook couldn't be reached (${c instanceof Error?c.message:String(c)})`}if(d?.ok===!0){t.print(`${r}: posted.`);return}if(d!==void 0&&(a=`the webhook answered ${d.status}`,d.status!==429&&d.status<500))break;o===1&&await e(sN(d))}t.error(`${r}: not posted; ${a}.`)}async function Lu(t,n,e,r,i,s){let a=[{name:"Slack",variable:"KWIKQA_SLACK_WEBHOOK_URL",message:zw},{name:"Teams",variable:"KWIKQA_TEAMS_WEBHOOK_URL",message:Vw}];for(let o of a){let d=r[o.variable];if(d===void 0||d.trim()==="")continue;let c=iN(d);if(c===void 0){t.error(`${o.name}: not posted; ${o.variable} isn't an https URL.`);continue}if(s.when==="on-failure"&&!s.failures){t.print(`${o.name}: nothing failed, so nothing was posted (--notify always posts).`);continue}await aN(t,n,e,o.name,c,o.message(i))}}var oN=30,Uw=100,dN=3e4,cN=/^[\w.-]+(?:\/[\w.-]+)+$/;function Hr(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function lN(t,n){let e=(t??"").split(",").filter(i=>i.trim()!=="");if(e.length!==1)return;let r=/^(.+)!(\d+)$/.exec(e[0]?.trim()??"");return r?.[1]===n?Hr(r[2]):void 0}function ko(t){if(t.GITLAB_CI!=="true")return;let n=st(t.CI_API_V4_URL),e=cN.test(t.CI_PROJECT_PATH??"")?t.CI_PROJECT_PATH:void 0,r=st(t.CI_PROJECT_URL),i=Hr(t.CI_PROJECT_ID),s=Hr(t.CI_MERGE_REQUEST_IID),a=s??(e===void 0?void 0:lN(t.CI_OPEN_MERGE_REQUESTS,e)),o=s===void 0?i:Hr(t.CI_MERGE_REQUEST_PROJECT_ID),d=s===void 0?i:Hr(t.CI_MERGE_REQUEST_SOURCE_PROJECT_ID),c=s===void 0?r:st(t.CI_MERGE_REQUEST_PROJECT_URL),l=/^[0-9a-f]{40}$/.test(t.CI_COMMIT_SHA??"")?t.CI_COMMIT_SHA:void 0,u=t.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME||t.CI_COMMIT_BRANCH||t.CI_COMMIT_TAG||t.CI_COMMIT_REF_NAME||void 0,p=st(t.CI_JOB_URL),f=(t.GITLAB_TOKEN??"").trim(),h=Hr(t.CI_JOB_ID),m=t.CI_MERGE_REQUEST_EVENT_TYPE==="merged_result"||t.CI_MERGE_REQUEST_EVENT_TYPE==="merge_train",g=/^[0-9a-f]{40}$/.test(t.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA??"")?t.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA:m?void 0:l,y=t.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME||void 0,w=s!==void 0&&d!==o;return{...n===void 0?{}:{apiUrl:n},...e===void 0?{}:{repository:e},...p===void 0?{}:{runUrl:p},...o===void 0?{}:{projectId:o},job:t.CI_JOB_NAME??"",...u===void 0?{}:{branch:u},...l===void 0?{}:{commit:{sha:l,...r===void 0?{}:{url:`${r}/-/commit/${l}`}}},...f===""?{}:{token:f},...h===void 0?{}:{jobId:String(h)},...t.CI_COMMIT_BRANCH?{commitBranch:t.CI_COMMIT_BRANCH}:{},...s!==void 0&&!w&&y!==void 0&&g!==void 0?{pullRequestHead:{ref:y,sha:g}}:{},...w?{sourceInOtherProject:!0}:{},...a===void 0?{}:{pullRequest:{number:a,name:`Merge request !${a}`,...c===void 0?{}:{url:`${c}/-/merge_requests/${a}`},fork:d!==o&&i!==o}}}}function qw(t){return`<!-- kwikqa-ci gitlab job=${encodeURIComponent(t.job)} -->`}async function Mu(t){if(t.status===429)return"GitLab's rate limit was reached";if(t.status===401)return"GitLab refused GITLAB_TOKEN";if(t.status===403)return"GITLAB_TOKEN can't comment on this merge request; it needs at least the Reporter role, and Work Item read, create, and update on this project if it's a fine-grained token, or else the `api` scope";if(t.status===404)return"GitLab found no such merge request with GITLAB_TOKEN";let n=await t.json().catch(()=>{}),e=typeof n?.message=="string"?`: ${n.message.replace(/\s+/g," ").slice(0,200)}`:"";return`GitLab answered ${t.status}${e}`}var Vr=class{constructor(n,e,r){this.send=n;this.apiUrl=e;this.token=r}send;apiUrl;token;call(n,e,r){return this.send(`${this.apiUrl}${e}`,{method:n,headers:{Accept:"application/json","PRIVATE-TOKEN":this.token,...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error",signal:AbortSignal.timeout(dN)})}},zr=class extends Error{};async function uN(t,n,e){for(let r=1;r<=oN;r+=1){let i=await t.call("GET",`${n}?sort=asc&order_by=created_at&per_page=${Uw}&page=${r}`);if(!i.ok)throw new zr(await Mu(i));let s=await i.json(),a=s.find(o=>o.system!==!0&&typeof o.body=="string"&&o.body.startsWith(e));if(typeof a?.id=="number")return a.id;if(s.length<Uw)return}}async function ws(t,n,e,r,i){let s=new Vr(n,e.apiUrl,e.token),o=`/projects/${encodeURIComponent(String(e.project))}/merge_requests/${e.number}/notes`,{marker:d}=e,c={body:`${d}
184
+ ${r}`},l=e.noun??"merge-request note",u=`${l.charAt(0).toUpperCase()}${l.slice(1)}`;try{let p=await uN(s,o,d);if(p!==void 0){let h=await s.call("PUT",`${o}/${p}`,c);if(h.ok)return t.print(`${u}: updated.`);if(h.status!==403&&h.status!==404)throw new zr(await Mu(h))}if(p===void 0&&!i)return t.print(`No ${l}: nothing failed, and there is no earlier note to update.`);let f=await s.call("POST",o,c);if(!f.ok)throw new zr(await Mu(f));t.print(`${u}: posted.`)}catch(p){let f=p instanceof zr?p.message:`GitLab couldn't be reached (${p instanceof Error?p.message:String(p)})`;t.error(`No ${l}: ${f}.`)}}async function pN(t,n,e,r,i){let s=o=>t.print(`No merge-request note: ${o}.`),a=e.pullRequest;if(a===void 0)return s("this pipeline isn't for a merge request, or its branch has more than one");if(a.fork)return s("the merge request comes from a fork, whose pipeline gets none of this project's variables");if(e.token===void 0)return s("GITLAB_TOKEN isn't set; CI_JOB_TOKEN can't write notes, so add a token that can as a masked CI/CD variable: a fine-grained token with Work Item read, create, and update, or one with the `api` scope");if(e.apiUrl===void 0||e.projectId===void 0)return s("CI_API_V4_URL or the merge request's project isn't what GitLab sets");await ws(t,n,{apiUrl:e.apiUrl,project:e.projectId,number:a.number,token:e.token,marker:qw(e)},r,i)}async function _u(t,n,e,r,i){t.print("");for(let s of r.trimEnd().split(`
185
+ `))t.print(s);t.print(""),await pN(t,n,e,r,i.failures)}var Vn=class extends Error{};async function bs(t,n){if(t.status===429)return"GitLab's rate limit was reached";if(t.status===401)return"GitLab refused GITLAB_TOKEN";if(t.status===403)return n;if(t.status===404)return"GitLab found no such project or commit with GITLAB_TOKEN";let e=await t.json().catch(()=>{}),r=typeof e?.message=="string"?e.message:e?.message===void 0?"":JSON.stringify(e.message),i=r===""?"":`: ${r.replace(/\s+/g," ").slice(0,200)}`;return`GitLab answered ${t.status}${i}`}function Un(t,n){return`/projects/${t}${n}`}function ju(t){return`/repository/branches/${encodeURIComponent(t)}`}async function Fu(t,n,e){let r=new Vr(t,n.apiUrl,n.token),i=ft(e);try{let s=await r.call("GET",Un(n.project,`/merge_requests?state=opened&source_branch=${encodeURIComponent(i)}&per_page=100`));if(!s.ok)return{kind:"unknown",reason:await bs(s,"GITLAB_TOKEN can't read merge requests")};let a=(await s.json()).find(d=>typeof d.iid=="number"&&typeof d.description=="string"&&d.description.startsWith(Bn(e)));if(typeof a?.iid=="number")return{kind:"open",number:a.iid,...typeof a.web_url=="string"?{url:a.web_url}:{}};let o=await r.call("GET",Un(n.project,ju(i)));return o.status===404?{kind:"none"}:o.ok?{kind:"branch"}:{kind:"unknown",reason:await bs(o,"GITLAB_TOKEN can't read branches")}}catch(s){return{kind:"unknown",reason:`GitLab couldn't be reached (${s instanceof Error?s.message:String(s)})`}}}async function Bu(t,n,e,r,i){let s=i.runUrl===void 0?"a later pipeline":`[a later pipeline](${i.runUrl})`;await ws(t,n,{apiUrl:e.apiUrl,project:e.project,number:r.number,token:e.token,marker:`<!-- kwikqa-fix-seen group=${r.fingerprint} -->`,noun:"note on the fix merge request"},`This failure group failed again in ${s}, at commit ${ge(i.commit.slice(0,12))}. KwikQA asks for no other repair while this merge request is open.
186
+ `,!0)}async function Hu(t,n,e){let r=new Vr(n,e.apiUrl,e.token),i=ft(e.fingerprint),s=!1;try{let a=await ms(e);if("failure"in a)return{kind:"failed",reason:a.failure};let{files:o}=a;for(let p of o){let f=await r.call("GET",Un(e.project,`/repository/files/${encodeURIComponent(p.path)}?ref=${e.base.commit}`));if(f.status===404)return{kind:"skipped",reason:zn(p,e.base.branch)};if(!f.ok)throw new Vn(await bs(f,"GITLAB_TOKEN can't read the repository"));let h=await f.json(),m=typeof h.content=="string"&&h.encoding==="base64"?Buffer.from(h.content,"base64"):void 0;if(m===void 0||!ys(m,p))return{kind:"skipped",reason:zn(p,e.base.branch)}}if((await r.call("GET",Un(e.project,ju(i)))).ok)return{kind:"skipped",reason:`${i} already exists, from an earlier pipeline; KwikQA never pushes to a branch it didn't create`};let c=await r.call("POST",Un(e.project,"/repository/commits"),{branch:i,start_sha:e.base.commit,commit_message:e.commitMessage,actions:o.map(p=>({action:"update",file_path:p.path,content:Buffer.from(p.bytes).toString("base64"),encoding:"base64"}))});if(!c.ok)throw new Vn(await bs(c,"GITLAB_TOKEN can't push a branch; it needs the `api` scope and at least the Developer role"));s=!0;let l=await r.call("POST",Un(e.project,"/merge_requests"),{source_branch:i,target_branch:e.base.branch,title:`Draft: ${e.title}`,description:e.description,labels:an,remove_source_branch:!0});if(!l.ok)throw new Vn(await bs(l,"GITLAB_TOKEN can't open a merge request; it needs the `api` scope and at least the Developer role"));let u=await l.json();if(typeof u.iid!="number")throw new Vn("GitLab returned no merge request");return s=!1,{kind:"opened",number:u.iid,...typeof u.web_url=="string"&&u.web_url.startsWith("https://")?{url:u.web_url}:{}}}catch(a){let o=a instanceof Vn?a.message:`GitLab couldn't be reached (${a instanceof Error?a.message:String(a)})`;return s&&await r.call("DELETE",Un(e.project,ju(i))).catch(()=>{}),{kind:"failed",reason:o}}}var fN=/^[\w.-]+(?:\/[\w.-]+)+$/,hN=/^\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/,mN=/^\/([\w.-]+(?:\/[\w.-]+)+)\/-\/merge_requests\/(\d+)$/;function Gw(t){let n=Number(t);return/^\d+$/.test(t??"")&&Number.isSafeInteger(n)&&n>0?n:void 0}function yN(t,n){if(t===void 0||!t.startsWith("https:"))return;let e=new URL(t),r=hN.exec(e.pathname);if(r?.[1]!==void 0&&Number(r[2])===n)return{kind:"github",apiUrl:e.host==="github.com"?"https://api.github.com":e.host.endsWith(".ghe.com")?`https://api.${e.host}`:`${e.origin}/api/v3`,repository:r[1]};let i=mN.exec(e.pathname);if(i?.[1]!==void 0&&Number(i[2])===n)return{kind:"gitlab",apiUrl:`${e.origin}/api/v4`,project:i[1]}}function gN(t){let n=t??"",r=/^[\w.-]+@[\w.-]+:(?!\/)(.+)$/.exec(n)?.[1];if(r===void 0)try{r=new URL(n).pathname}catch{return}let i=r.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/,"");return fN.test(i)?i:void 0}function Ro(t){if(!t.JENKINS_URL&&!t.JENKINS_HOME||Gw(t.BUILD_NUMBER)===void 0)return;let n=Gw(t.CHANGE_ID),e=Ed(t.CHANGE_URL),r=n===void 0?void 0:yN(e,n),i=r?.kind==="github"?r.repository:r?.kind==="gitlab"?r.project:gN(t.GIT_URL),s=Ed(t.BUILD_URL),a=t.CHANGE_BRANCH||t.BRANCH_NAME||t.GIT_LOCAL_BRANCH||t.GIT_BRANCH?.replace(/^origin\//,"")||void 0,o=/^[0-9a-f]{40}$/.test(t.GIT_COMMIT??"")?t.GIT_COMMIT:void 0,d=(t.GITHUB_TOKEN??"").trim(),c=(t.GITLAB_TOKEN??"").trim();return{...i===void 0?{}:{repository:i},...s===void 0?{}:{runUrl:s},job:t.JOB_NAME??"",...t.STAGE_NAME?{stage:t.STAGE_NAME}:{},...a===void 0?{}:{branch:a},...o===void 0?{}:{commit:{sha:o}},...r===void 0?{}:{host:r},...d===""?{}:{githubToken:d},...c===""?{}:{gitlabToken:c},...n===void 0?{}:{pullRequest:{number:n,...r?.kind==="gitlab"?{name:`Merge request !${n}`}:{},...e===void 0?{}:{url:e},fork:!1}}}}function Kw(t){let n=t.stage===void 0?"":` stage=${encodeURIComponent(t.stage)}`;return`<!-- kwikqa-ci jenkins job=${encodeURIComponent(t.job)}${n} -->`}async function wN(t,n,e,r,i){let s=e.pullRequest,a=e.host;if(s===void 0)return t.print("No pull-request comment: this build isn't for a pull request.");if(a===void 0)return t.print(s.url?.startsWith("http:")===!0?"No pull-request comment: the pull request's page isn't https, and KwikQA sends tokens only over https.":"No pull-request comment: the pull request isn't on GitHub or GitLab, the hosts KwikQA comments on from Jenkins so far.");let o=Kw(e);return a.kind==="github"?e.githubToken===void 0?t.print("No pull-request comment: GITHUB_TOKEN isn't set; bind a token that can comment on pull requests with withCredentials."):cs(t,n,{apiUrl:a.apiUrl,repository:a.repository,number:s.number,token:e.githubToken,marker:o,forbidden:"GITHUB_TOKEN can't comment on this pull request; it needs Pull requests read and write, or a classic token's `repo` scope"},r,i):e.gitlabToken===void 0?t.print("No merge-request note: GITLAB_TOKEN isn't set; bind a token that can write notes with withCredentials: a fine-grained token with Work Item read, create, and update, or one with the `api` scope."):ws(t,n,{apiUrl:a.apiUrl,project:a.project,number:s.number,token:e.gitlabToken,marker:o},r,i)}async function zu(t,n,e,r,i){t.print("");for(let s of r.trimEnd().split(`
187
+ `))t.print(s);t.print(""),await wN(t,n,e,r,i.failures)}import{createHash as gv}from"node:crypto";import{access as bD,appendFile as xD,mkdir as vD,readdir as kD,readFile as kd,realpath as Ut,stat as wv,writeFile as vv}from"node:fs/promises";import{isAbsolute as Rd,join as He,relative as ei,resolve as Id,sep as lf}from"node:path";import{mkdir as iO,writeFile as sO}from"node:fs/promises";import{join as Ib}from"node:path";import{lstat as bN,readFile as Ww,realpath as Gu}from"node:fs/promises";import{dirname as Vu,isAbsolute as xN,join as Ao,relative as To,resolve as Io,sep as Jw}from"node:path";var Yw=["ts","mts","cts","js","mjs","cjs"],Xw={playwright:"playwright.config",cypress:"cypress.config",webdriverio:"wdio.conf"},vN={playwright:["@playwright/test"],cypress:["cypress"],webdriverio:["@wdio/cli","webdriverio"]},So={playwright:"Playwright",cypress:"Cypress",webdriverio:"WebdriverIO"};function Uu(t,n){let e=To(t,n);return e===""||!xN(e)&&e!==".."&&!e.startsWith(`..${Jw}`)}async function Po(t){return(await bN(t).catch(()=>{}))?.isFile()===!0}function qu(t){return t.split(Jw).join("/")}async function Qw(t){let n=await Gu(t),e={};try{let i=JSON.parse(await Ww(Ao(n,"package.json"),"utf8"));e={...i.dependencies,...i.devDependencies}}catch{e={}}let r=[];for(let i of["playwright","cypress","webdriverio"]){let s=vN[i].find(o=>o in e),a;for(let o of Yw){let d=`${Xw[i]}.${o}`;if(await Po(Ao(n,d))){a=d;break}}(s!==void 0||a!==void 0)&&r.push({framework:i,...a===void 0?{}:{configFile:a},...s===void 0?{}:{packageName:s}})}return r}async function Eo(t,n,e){let r=await Gu(t),i=Vu(Io(r,e));for(Uu(r,i)||(i=r);;){for(let a of Yw){let o=Ao(i,`${Xw[n]}.${a}`);if(await Po(o))return qu(To(r,o))}if(i===r)return;let s=Vu(i);if(!Uu(r,s))return;i=s}}async function Co(t,n){let e=await Gu(t),r=n===void 0?e:Vu(Io(e,n));if(n!==void 0){let i=await Ww(Io(e,n),"utf8").catch(()=>"");if(/\bsupportFile\s*:\s*false\b/.test(i))return null;let s=/\bsupportFile\s*:\s*["'`]([^"'`]+)["'`]/.exec(i)?.[1];if(s!==void 0){let a=Io(r,s);return Uu(e,a)&&await Po(a)?qu(To(e,a)):void 0}}for(let i of["ts","js","tsx","jsx"]){let s=Ao(r,"cypress","support",`e2e.${i}`);if(await Po(s))return qu(To(e,s))}}import{readFile as AN,realpath as TN}from"node:fs/promises";import{createRequire as PN}from"node:module";import{delimiter as SN,dirname as ib,isAbsolute as EN,join as qn}from"node:path";import{spawn as nb}from"node:child_process";var kN=["KWIKQA_TOKEN","KWIKQA_API_URL","OPENROUTER_API_KEY"],Zw=256*1024,RN=8e3;function No(t,n={}){let e={...t,...n};for(let r of kN)delete e[r];return e}function eb(t){return t.pid===void 0||t.exitCode!==null||t.signalCode!==null}function tb(t,n){if(t.pid!==void 0)try{process.kill(-t.pid,n)}catch{t.kill(n)}}async function IN(t,n){if(!eb(t)){if(process.platform==="win32"){await new Promise(e=>{let r=nb("taskkill",["/pid",String(t.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});r.on("exit",()=>e()),r.on("error",()=>e())});return}tb(t,"SIGINT"),await Promise.race([n,new Promise(e=>setTimeout(e,RN))]),eb(t)||tb(t,"SIGKILL")}}function Ku(t,n,e){let r=nb(t,[...n],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),i="",s=o=>{i+=o.toString("utf8"),i.length>Zw&&(i=i.slice(-Zw))};r.stdout?.on("data",s),r.stderr?.on("data",s);let a=new Promise(o=>{r.on("exit",d=>o(d??void 0)),r.on("error",()=>o(void 0))});return{child:r,output:()=>i,exited:a,stop:async()=>{await IN(r,a),await Promise.race([a,new Promise(o=>setTimeout(o,2e3))])}}}async function Oo(t,n,e){let r=Ku(t,n,e),i=!1,s=setTimeout(()=>{i=!0,r.stop()},e.timeoutMs),a=await r.exited;return clearTimeout(s),{...a===void 0?{}:{exitCode:a},timedOut:i,output:r.output()}}async function rb(t,n,e){let r=Date.now()+e,i=!1;for(t.exited.then(()=>{i=!0});Date.now()<r;){let s=n.exec(t.output());if(s!==null)return s;if(i)return n.exec(t.output())??void 0;await new Promise(a=>setTimeout(a,100))}}var ab="1.0",Wu=[1,59],CN=5,NN=6e4,ON=3e4,$N=12e4,DN=new Set(["generic","text","list","group","none","presentation"]),LN=new Set(["banner","navigation","main","contentinfo","complementary","region","form","search"]);function Ju(t){let[n=0,e=0]=t.split(".").map(r=>Number.parseInt(r,10));return n>Wu[0]||n===Wu[0]&&e>=Wu[1]}async function sb(t){try{let n=JSON.parse(await AN(qn(t,"package.json"),"utf8"));return n.name==="@playwright/cli"&&typeof n.version=="string"?n.version:void 0}catch{return}}async function ob(t,n){try{let r=PN(qn(t,"package.json")).resolve("@playwright/cli/package.json"),i=ib(r),s=await sb(i);if(s!==void 0)return{entryPath:qn(i,"playwright-cli.js"),version:s,source:"project"}}catch{}let e=process.platform==="win32"?["playwright-cli.cmd"]:["playwright-cli"];for(let r of(n.PATH??"").split(SN).filter(Boolean))for(let i of e){let s=qn(r,i);try{let a=process.platform==="win32"?qn(r,"node_modules","@playwright","cli"):ib(await TN(s)),o=await sb(a);if(o!==void 0)return{entryPath:qn(a,"playwright-cli.js"),version:o,source:"path"}}catch{}}}function Yu(t){return t.split(/\r?\n/).filter(n=>!/[║╔╚═]/.test(n)).join(`
188
+ `)}function db(t){return/```yaml\r?\n([\s\S]*?)\r?\n```/.exec(Yu(t))?.[1]?.split(/\r?\n/)}function cb(t){let n=Yu(t).split(/\r?\n/),e=n.findIndex(r=>r.trim()==="### Result");if(!(e<0))return n.slice(e+1).map(r=>r.trim()).find(r=>r!==""&&!r.startsWith("###"))}function MN(t){return/getByRole\(\s*['"]([\w-]+)['"]/.exec(t??"")?.[1]?.toLowerCase()}function lb(t){return t.trim().replace(/^-\s+/,"").replace(/\s\[(?:ref|cursor)=[^\]]+\]/g,"").replace(/:$/,"").trim()}function ub(t,n,e=CN){let r=Ar(n??""),i=MN(n);return t.map((a,o)=>{let d=/\[ref=(e\d+)\]/.exec(a)?.[1],c=lb(a),l=/^([\w-]+)/.exec(c)?.[1]?.toLowerCase()??"";if(d===void 0||DN.has(l))return;let u=c.toLowerCase(),p=r.filter(f=>u.includes(f)).length*3+(i!==void 0&&l===i?2:0);if(!(LN.has(l)&&p===0))return{ref:d,element:c,score:p,order:o}}).filter(a=>a!==void 0).sort((a,o)=>o.score-a.score||a.order-o.order).slice(0,e).map(({ref:a,element:o})=>({ref:a,element:o}))}async function pb(t){let{target:n}=t,e=[],r={logicalTestId:n.logicalTestId,title:n.title,file:n.file,line:n.line,...n.failingLine===void 0?{}:{failingLine:n.failingLine},...n.locator===void 0?{}:{locator:n.locator}};if(n.failingLine===void 0)return{...r,candidates:[],issues:["The report does not say which line failed."]};let i=No(t.env,{PLAYWRIGHT_HTML_OPEN:"never"}),s=Ku(t.playwright.executable,[...t.playwright.nodeArguments,"test",`${n.file}:${n.line}`,...n.project===void 0?[]:[`--project=${n.project}`],...t.configPath===void 0?[]:[`--config=${t.configPath}`],"--debug=cli","--timeout=0","--retries=0","--workers=1","--reporter=line"],{cwd:t.workspaceRoot,env:i}),a=(c,l=ON)=>Oo(process.execPath,[t.cli.entryPath,...c],{cwd:t.scratchDirectory,env:i,timeoutMs:l}),o,d=[];try{if(o=(await rb(s,/playwright-cli attach ([\w-]+)/,NN))?.[1],o===void 0)return e.push("The test did not stop in the debugger."),{...r,candidates:d,issues:e};if((await a(["attach",o])).exitCode!==0)return e.push("Playwright CLI could not attach to the paused test."),{...r,candidates:d,issues:e};let u=EN(n.file)?n.file:qn(t.workspaceRoot,n.file),p=await a([`-s=${o}`,"pause-at",`${u}:${n.failingLine}`],$N);if(p.exitCode!==0||!/### Paused/.test(p.output))return e.push(`The test did not reach line ${n.failingLine}.`),{...r,candidates:d,issues:e};let f=db((await a([`-s=${o}`,"snapshot"])).output);if(f===void 0)return e.push("Playwright CLI returned no page snapshot."),{...r,candidates:d,issues:e};for(let h of ub(f,n.locator)){let m=cb((await a([`-s=${o}`,"generate-locator",h.ref])).output);m!==void 0&&d.push({element:h.element,locator:m})}return d.length===0&&e.push("No locator could be generated for any candidate."),{...r,candidates:d,issues:e}}catch(c){return e.push(`The probe stopped: ${c instanceof Error?c.message:String(c)}`),{...r,candidates:d,issues:e}}finally{o!==void 0&&await a([`-s=${o}`,"detach"],1e4).catch(()=>{}),await s.stop()}}import{mkdir as bb,rm as wb}from"node:fs/promises";import{dirname as YN,join as qr,relative as XN,resolve as QN}from"node:path";import{basename as WN,dirname as yb,join as Ur,relative as np,resolve as zt,sep as JN}from"node:path";import{createHash as _N}from"node:crypto";import{lstat as jN,mkdir as FN,readFile as fb,realpath as Xu,rename as BN,writeFile as HN}from"node:fs/promises";import{isAbsolute as zN,join as hb,relative as Qu,sep as mb}from"node:path";import{fileURLToPath as VN}from"node:url";var UN=".kwikqa/runtime",qN=["cypress-reporter.cjs","cypress-capture.js","wdio-reporter.mjs","wdio-capture.mjs"];async function GN(t){return fb(VN(new URL(`./${t}`,import.meta.url)),"utf8")}function KN(t,n){let e=Qu(t,n);return e===""||!zN(e)&&e!==".."&&!e.startsWith(`..${mb}`)}async function $o(t,n){let e=await Xu(t),r=e;for(let i of n.split("/").filter(s=>s!=="")){if(i==="."||i==="..")throw new Error("Unsafe KwikQA directory.");r=hb(r,i);let s=await jN(r).catch(()=>{});if(s===void 0)await FN(r);else if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`${Qu(e,r)} must be a real directory inside the workspace.`)}if(!KN(e,await Xu(r)))throw new Error("KwikQA directory escapes workspace.");return r}async function Zu(t,n){let e=`${t}.${process.pid}.tmp`;await HN(e,n,{mode:420}),await BN(e,t)}function ep(t){return _N("sha256").update(t,"utf8").digest("hex")}async function Do(t){let n=await Xu(t),e=await $o(n,UN),r={};for(let i of qN){let s=await GN(i),a=hb(e,i);await fb(a,"utf8").catch(()=>{})!==s&&await Zu(a,s),r[i]={path:a,relativePath:Qu(n,a).split(mb).join("/"),sha256:ep(s)}}return r}function rp(t){return t.split(JN).join("/")}function xs(t,n){let e=rp(np(t,n));return e.startsWith(".")?e:`./${e}`}async function tp(t,n,e){return await Zu(n,e),{path:n,relativePath:rp(np(t,n)),sha256:ep(e)}}async function Lo(t){let n=t.workspaceRoot,e=t.configFile===void 0?n:yb(zt(n,t.configFile)),r=["video=false","screenshotOnRunFailure=true",`screenshotsFolder=${zt(n,t.screenshotsDirectory)}`,...t.noRetries?["retries=0"]:[]],i=[];if(t.capture!==void 0){let a=await $o(n,t.capture.directory),o=await tp(n,Ur(a,"kwikqa-settings.js"),`// Generated by KwikQA for one run.
189
189
  globalThis.__kwikqaCapture = ${JSON.stringify({directory:rp(np(e,Ur(a,"pages"))),...t.capture.only===void 0?{}:{only:[...t.capture.only].sort()}})};
190
190
  `),d=[`import ${JSON.stringify(xs(a,o.path))};`,`import ${JSON.stringify(xs(a,t.runtime["cypress-capture.js"].path))};`,...t.capture.supportFile===null||t.capture.supportFile===void 0?[]:[`import ${JSON.stringify(xs(a,zt(n,t.capture.supportFile)))};`]],c=await tp(n,Ur(a,"kwikqa-support.js"),`// Generated by KwikQA: its failure capture, then the project's support file.
191
191
  ${d.join(`
192
192
  `)}
193
- `);i.push(o,c),r.push(`supportFile=${c.path}`)}return{args:["run","--project",e,...t.configFile===void 0?[]:["--config-file",GN(t.configFile)],...t.specs.length===0?[]:["--spec",t.specs.map(a=>zt(n,a)).join(",")],"--reporter",t.runtime["cypress-reporter.cjs"].path,"--reporter-options",[`screenshotsFolder=${zt(n,t.screenshotsDirectory)}`,...t.capture===void 0?[]:[`captureDir=${Ur(zt(n,t.capture.directory),"pages")}`]].join(","),"--config",r.join(",")],generated:i}}function gb(t){return t.filter(n=>n!=="").slice(-2).join(" ")}async function Mo(t){let n=t.workspaceRoot,e=await $o(n,t.directory),r=zt(n,t.configFile),i=/\.([cm]?ts)$/.exec(t.configFile)?.[1]??"mjs",s={rootDir:yb(r),noRetries:t.noRetries,...t.grep===void 0?{}:{grep:t.grep},...t.reportDirectory===void 0?{}:{reportDir:zt(n,t.reportDirectory)},...t.capture?{captureDir:Ur(e,"pages")}:{}},a=["// Generated by KwikQA: the project's WebdriverIO config, with KwikQA's reporter added.",`import { config as base } from ${JSON.stringify(xs(e,r))};`,`import { withKwikqa } from ${JSON.stringify(xs(e,t.runtime["wdio-capture.mjs"].path))};`,"",`export const config = withKwikqa(base, ${JSON.stringify(s,null,2)});`,""].join(`
194
- `),o=await tp(n,Ur(e,`wdio.kwikqa.conf.${i}`),a);return{args:["run",o.path,...t.specs.flatMap(c=>["--spec",zt(n,c)])],generated:[o]}}var xb=".kwikqa/capture",XN=10*6e4,QN={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function ip(t){let n=JN(t.workspaceRoot,t.tool.entryPath).replaceAll("\\","/"),e=t.workspaceRoot,r=t.args.map(i=>{let s=i===e?".":i.split(`${e}/`).join("").split(`${e}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(s)?JSON.stringify(s):s});return`node ${n} ${r.join(" ")}`}async function vb(t){let n=t.targets[0];if(n===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let e=Ze(t.run);if(e===void 0)return{kind:"unavailable",message:lt(t.run)};let r=QN[e],i=await _i({workspaceRoot:t.workspaceRoot,...t.repositoryRoot===void 0?{}:{repositoryRoot:t.repositoryRoot},ownerPath:qr(t.workspaceRoot,n.file),packageName:r});if(i.kind!=="resolved")return{kind:"unavailable",message:i.reasons[0]?.message??`The project's ${r} could not be resolved; nothing was installed.`};let s=`${xb}/${t.captureId}`,a={framework:e,tool:i.tool,workspaceRoot:t.workspaceRoot,directory:s,targets:t.targets};if(e==="playwright"){let f=[...new Set(t.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(t.targets.map(y=>y.project).filter(y=>y!==void 0))],m=qr(t.workspaceRoot,s,"report.json"),g=["test",...f,...h.map(y=>`--project=${y}`),...t.run.configFile===void 0?[]:[`--config=${t.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${s}/results`];return{kind:"ready",plan:{...a,args:g,workingDirectory:t.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:m,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:m,...t.run.configFile===void 0?{}:{configPath:t.run.configFile}}}}let o=[...new Set(t.targets.map(f=>f.file))],d=t.run.configFile??await Eo(t.workspaceRoot,e,n.file),c=qr(t.workspaceRoot,s,"reports"),l=await Do(t.workspaceRoot);await bb(qr(t.workspaceRoot,s),{recursive:!0});let u=d===void 0?t.workspaceRoot:WN(YN(t.workspaceRoot,d));if(e==="cypress"){let f=await Lo({workspaceRoot:t.workspaceRoot,runtime:l,...d===void 0?{}:{configFile:d},specs:o,screenshotsDirectory:`${s}/screenshots`,noRetries:!0,capture:{directory:s,supportFile:await Co(t.workspaceRoot,d)}});return{kind:"ready",plan:{...a,args:f.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,...d===void 0?{}:{configPath:d}}}}if(d===void 0)return{kind:"unavailable",message:`No wdio.conf was found for ${n.file}; nothing was run.`};let p=await Mo({workspaceRoot:t.workspaceRoot,runtime:l,configFile:d,specs:o,directory:s,noRetries:!0,reportDirectory:`${s}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:p.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:d}}}async function kb(t,n){let e=qr(t.workspaceRoot,t.directory);if(t.framework==="playwright")await wb(e,{recursive:!0,force:!0}),await bb(e,{recursive:!0});else for(let u of["reports","pages","screenshots"])await wb(qr(e,u),{recursive:!0,force:!0});let r=await Oo(t.tool.executable,[...t.tool.nodeArguments,...t.args],{cwd:t.workingDirectory,env:No(n.env,t.environment),timeoutMs:n.timeoutMs??XN}),i=await ct(t.reportPath,{workspaceRoot:t.workspaceRoot}),s=So[t.framework];if(i.kind!=="parsed"){let u=r.output.trim().split(`
193
+ `);i.push(o,c),r.push(`supportFile=${c.path}`)}return{args:["run","--project",e,...t.configFile===void 0?[]:["--config-file",WN(t.configFile)],...t.specs.length===0?[]:["--spec",t.specs.map(a=>zt(n,a)).join(",")],"--reporter",t.runtime["cypress-reporter.cjs"].path,"--reporter-options",[`screenshotsFolder=${zt(n,t.screenshotsDirectory)}`,...t.capture===void 0?[]:[`captureDir=${Ur(zt(n,t.capture.directory),"pages")}`]].join(","),"--config",r.join(",")],generated:i}}function gb(t){return t.filter(n=>n!=="").slice(-2).join(" ")}async function Mo(t){let n=t.workspaceRoot,e=await $o(n,t.directory),r=zt(n,t.configFile),i=/\.([cm]?ts)$/.exec(t.configFile)?.[1]??"mjs",s={rootDir:yb(r),noRetries:t.noRetries,...t.grep===void 0?{}:{grep:t.grep},...t.reportDirectory===void 0?{}:{reportDir:zt(n,t.reportDirectory)},...t.capture?{captureDir:Ur(e,"pages")}:{}},a=["// Generated by KwikQA: the project's WebdriverIO config, with KwikQA's reporter added.",`import { config as base } from ${JSON.stringify(xs(e,r))};`,`import { withKwikqa } from ${JSON.stringify(xs(e,t.runtime["wdio-capture.mjs"].path))};`,"",`export const config = withKwikqa(base, ${JSON.stringify(s,null,2)});`,""].join(`
194
+ `),o=await tp(n,Ur(e,`wdio.kwikqa.conf.${i}`),a);return{args:["run",o.path,...t.specs.flatMap(c=>["--spec",zt(n,c)])],generated:[o]}}var xb=".kwikqa/capture",ZN=10*6e4,eO={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};function ip(t){let n=XN(t.workspaceRoot,t.tool.entryPath).replaceAll("\\","/"),e=t.workspaceRoot,r=t.args.map(i=>{let s=i===e?".":i.split(`${e}/`).join("").split(`${e}\\`).join("").replaceAll("\\","/");return/[\s"']/.test(s)?JSON.stringify(s):s});return`node ${n} ${r.join(" ")}`}async function vb(t){let n=t.targets[0];if(n===void 0)return{kind:"unavailable",message:"No failing tests to capture."};let e=Ze(t.run);if(e===void 0)return{kind:"unavailable",message:lt(t.run)};let r=eO[e],i=await _i({workspaceRoot:t.workspaceRoot,...t.repositoryRoot===void 0?{}:{repositoryRoot:t.repositoryRoot},ownerPath:qr(t.workspaceRoot,n.file),packageName:r});if(i.kind!=="resolved")return{kind:"unavailable",message:i.reasons[0]?.message??`The project's ${r} could not be resolved; nothing was installed.`};let s=`${xb}/${t.captureId}`,a={framework:e,tool:i.tool,workspaceRoot:t.workspaceRoot,directory:s,targets:t.targets};if(e==="playwright"){let f=[...new Set(t.targets.map(y=>`${y.file}:${y.line}`))],h=[...new Set(t.targets.map(y=>y.project).filter(y=>y!==void 0))],m=qr(t.workspaceRoot,s,"report.json"),g=["test",...f,...h.map(y=>`--project=${y}`),...t.run.configFile===void 0?[]:[`--config=${t.run.configFile}`],"--trace=retain-on-failure","--retries=0","--reporter=json",`--output=${s}/results`];return{kind:"ready",plan:{...a,args:g,workingDirectory:t.workspaceRoot,environment:{PLAYWRIGHT_JSON_OUTPUT_NAME:m,PLAYWRIGHT_HTML_OPEN:"never"},reportPath:m,...t.run.configFile===void 0?{}:{configPath:t.run.configFile}}}}let o=[...new Set(t.targets.map(f=>f.file))],d=t.run.configFile??await Eo(t.workspaceRoot,e,n.file),c=qr(t.workspaceRoot,s,"reports"),l=await Do(t.workspaceRoot);await bb(qr(t.workspaceRoot,s),{recursive:!0});let u=d===void 0?t.workspaceRoot:YN(QN(t.workspaceRoot,d));if(e==="cypress"){let f=await Lo({workspaceRoot:t.workspaceRoot,runtime:l,...d===void 0?{}:{configFile:d},specs:o,screenshotsDirectory:`${s}/screenshots`,noRetries:!0,capture:{directory:s,supportFile:await Co(t.workspaceRoot,d)}});return{kind:"ready",plan:{...a,args:f.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,...d===void 0?{}:{configPath:d}}}}if(d===void 0)return{kind:"unavailable",message:`No wdio.conf was found for ${n.file}; nothing was run.`};let p=await Mo({workspaceRoot:t.workspaceRoot,runtime:l,configFile:d,specs:o,directory:s,noRetries:!0,reportDirectory:`${s}/reports`,capture:!0});return{kind:"ready",plan:{...a,args:p.args,workingDirectory:u,environment:{KWIKQA_REPORT_DIR:c},reportPath:c,configPath:d}}}async function kb(t,n){let e=qr(t.workspaceRoot,t.directory);if(t.framework==="playwright")await wb(e,{recursive:!0,force:!0}),await bb(e,{recursive:!0});else for(let u of["reports","pages","screenshots"])await wb(qr(e,u),{recursive:!0,force:!0});let r=await Oo(t.tool.executable,[...t.tool.nodeArguments,...t.args],{cwd:t.workingDirectory,env:No(n.env,t.environment),timeoutMs:n.timeoutMs??ZN}),i=await ct(t.reportPath,{workspaceRoot:t.workspaceRoot}),s=So[t.framework];if(i.kind!=="parsed"){let u=r.output.trim().split(`
195
195
  `).slice(-5).join(`
196
196
  `);return{kind:"failed",message:r.timedOut?`The capture run timed out before ${s} wrote its report.`:`${s} wrote no report.${u===""?"":`
197
- ${u}`}`,reproduced:0,passed:0}}let a=new Set(t.targets.map(u=>u.logicalTestId)),o=i.run.logicalTests.filter(u=>a.has(u.logicalTestId)),d=o.filter(u=>u.status==="unexpected"||u.status==="flaky").map(u=>u.logicalTestId),c=d.length,l=o.filter(u=>u.status==="expected").length;return{kind:"captured",reportPath:t.reportPath,reproduced:c,passed:l,failedAgain:d,message:c===0?`None of the ${t.targets.length} failing tests failed again, so the failure may be flaky or depend on state the re-run did not have.`:`Captured full evidence for ${c} failing test${c===1?"":"s"}${l>0?`; ${l} passed this time, which suggests flakiness`:""}.`}}var ZN=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function eO(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tO(t,n){if(t===void 0)return;let r=new RegExp(`${eO(n)}:(\\d+):\\d+`).exec(t.replaceAll("\\","/"));return r?.[1]===void 0?void 0:Number(r[1])}function Rb(t,n){if(t===void 0)return!1;let e=t.replaceAll("\\","/");return e===n||e.endsWith(`/${n}`)}function _o(t){let n=new Map(t.projects.map(r=>[r.projectId,r.name])),e=[];for(let r of t.logicalTests){let i=Nr(r),s=i.at(-1);if(s===void 0)continue;let a=r.location.file,o=s.errors.map(u=>`${u.message??""}
198
- ${u.stack??""}`),d=(Rb(s.errorLocation?.file,a)?s.errorLocation?.line:void 0)??s.errors.map(u=>Rb(u.location?.file,a)?u.location?.line:tO(u.stack,a)).find(u=>u!==void 0),c=o.map(u=>ZN.exec(u)?.[0]).find(u=>u!==void 0),l=n.get(r.projectId);e.push({logicalTestId:r.logicalTestId,title:r.title,file:a,line:r.location.line??1,...l===void 0||l===""?{}:{project:l},...d===void 0?{}:{failingLine:d},...c===void 0?{}:{locator:c},hasTrace:i.some(u=>u.attachments.some(p=>p.name==="trace")),hasPageSnapshot:i.some(u=>u.attachments.some(p=>p.name==="error-context"))})}return e}var Ab=3;async function sp(t){let n=_o(t.run),e=await vb({run:t.run,workspaceRoot:t.workspaceRoot,...t.repositoryRoot===void 0?{}:{repositoryRoot:t.repositoryRoot},targets:n,captureId:t.captureId});if(e.kind!=="ready")return e;let{plan:r}=e,i,s,a=r.framework;t.probe&&a==="playwright"&&(Ju(r.tool.packageVersion)?(i=await ob(t.workspaceRoot,t.env),i===void 0&&(s="Live probing needs Playwright CLI: add `@playwright/cli` to the project's dev dependencies (nothing was installed).")):s=`Live probing needs Playwright 1.59 or later; this project has ${r.tool.packageVersion}.`);let o=So[a],d=`${n.length} failing test${n.length===1?"":"s"}`,c=new Set(n.map(u=>u.file)).size,l=a==="playwright"?[`Re-run ${d} with full tracing, using this project's Playwright ${r.tool.packageVersion}:`,` ${ip(r)}`,...i===void 0?[]:[`Then pause up to ${Ab} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${i.version} (${i.source==="project"?"project dependency":i.entryPath}).`],`Everything is written under ${r.directory}/. Your tests run on this machine, as they do in \`npx playwright test\`.`]:[`Re-run the ${c} spec file${c===1?"":"s"} with ${d}, using this project's ${o} ${r.tool.packageVersion} and its own config:`,` ${ip(r)}`,a==="cypress"?"KwikQA adds its reporter and a support file that loads its failure capture and then yours, and records each failed attempt's page: DOM, Cypress command log, console errors, and network.":"KwikQA adds its reporter and hooks after yours that record each failed attempt's page: DOM, screenshot, WebdriverIO commands, console, and network.",`Everything is written under ${r.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:r,...i===void 0?{}:{cli:i},...s===void 0?{}:{probeUnavailable:s},description:l}}}async function ap(t,n){let e=await kb(t.plan,{env:n});if(t.cli===void 0||e.reportPath===void 0||e.reproduced===0)return{outcome:e};let r=await ct(e.reportPath,{workspaceRoot:t.plan.workspaceRoot}),s=(r.kind==="parsed"?_o(r.run):[]).filter(l=>l.locator!==void 0).slice(0,Ab);if(s.length===0)return{outcome:e};let a=Ib(t.plan.workspaceRoot,t.plan.directory,"probe");await nO(a,{recursive:!0});let o=[];for(let l of s)o.push(await pb({workspaceRoot:t.plan.workspaceRoot,playwright:t.plan.tool,cli:t.cli,target:l,...t.plan.configPath===void 0?{}:{configPath:t.plan.configPath},scratchDirectory:a,env:n}));let d={schemaVersion:ab,tool:{name:"@playwright/cli",version:t.cli.version,source:t.cli.source},playwrightVersion:t.plan.tool.packageVersion,results:o},c=Ib(t.plan.workspaceRoot,t.plan.directory,"probe.json");return await rO(c,`${JSON.stringify(d,null,2)}
199
- `),{outcome:e,probePath:c,probe:d}}var qn=class{#e=new Set;consume(n,e){return this.#e.has(n)?!1:(this.#e.add(n),!0)}};function jo(t){return L({runId:t.manifest.runId,packetHash:t.manifest.packetHash,payloadHash:t.manifest.payloadHash,manifestHash:t.manifestHash,model:t.manifest.model,promptVersion:t.manifest.promptVersion,outputSchemaVersion:t.manifest.outputSchemaVersion,endpoint:t.endpoint,estimate:t.estimate,caps:t.caps})}function op(t,n){return{runId:t.manifest.runId,packetHash:t.manifest.packetHash,payloadManifestHash:t.manifestHash,authorizationBindingHash:n,model:t.manifest.model,estimate:t.estimate,caps:t.caps,evidence:t.manifest.evidence,artifactIds:t.manifest.artifactIds,channels:t.manifest.channels,omissionIds:t.manifest.omissionIds,redactionIds:t.manifest.redactionIds}}function dp(t,n){return t.bindingHash===n&&t.authorizationId.trim().length>0&&t.authorizedAt.trim().length>0}var iO={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function cp(t){return{...t.extra,schemaVersion:"1.1",runId:t.runId,createdAt:t.createdAt,workspace:t.workspace,sourceHashes:t.sourceHashes,packetHash:t.packetHash,...t.request??iO,model:t.model,caps:t.caps,outcome:t.outcome,recordedAt:t.recordedAt}}function We(t,n,e){return{kind:t,...n===void 0?{}:{reasonCode:n},...e===void 0?{}:{message:e}}}function lp(t){if(t===void 0||t.trim().length===0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function sO(t){let n=[t.prompt,...t.overrides.map(i=>i.prompt)].map(lp).filter(i=>i!==void 0),e=[t.completion,...t.overrides.map(i=>i.completion)].map(lp).filter(i=>i!==void 0),r=[t.request??"0",...t.overrides.map(i=>i.request)].map(lp).filter(i=>i!==void 0);if(!(n.length!==t.overrides.filter(i=>i.prompt!==void 0).length+1||e.length!==t.overrides.filter(i=>i.completion!==void 0).length+1||r.length!==t.overrides.filter(i=>i.request!==void 0).length+1))return{prompt:Math.max(...n),completion:Math.max(...e),request:Math.max(...r)}}function Fo(t,n,e){if(!Number.isInteger(n)||n<=0)return;let r=sO(e);if(r===void 0)return;let i=Buffer.byteLength(t,"utf8"),s=i+64,a=s*r.prompt+n*r.completion+r.request;if(Number.isFinite(a))return{method:"utf8-byte-upper-bound-v1",requestBytes:i,estimatedInputTokens:s,estimatedOutputTokens:n,estimatedDollars:a,promptDollarsPerToken:r.prompt,completionDollarsPerToken:r.completion,fixedRequestDollars:r.request}}function up(t){for(let[n,e]of[["request",t.request],["run",t.run]]){if(!Number.isInteger(e.maxInputTokens)||e.maxInputTokens<=0)return`${n} maxInputTokens must be a positive integer.`;if(!Number.isInteger(e.maxOutputTokens)||e.maxOutputTokens<=0)return`${n} maxOutputTokens must be a positive integer.`;if(!Number.isFinite(e.maxDollars)||e.maxDollars<=0)return`${n} maxDollars must be a positive finite number.`}}function pp(t,n){return t.estimatedInputTokens>n.request.maxInputTokens||t.estimatedOutputTokens>n.request.maxOutputTokens?{kind:"blocked",reasonCode:"request-token-budget-exceeded",message:"The conservative request token estimate exceeds the request cap."}:t.estimatedDollars>n.request.maxDollars?{kind:"blocked",reasonCode:"request-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the request cap."}:t.estimatedInputTokens>n.run.maxInputTokens||t.estimatedOutputTokens>n.run.maxOutputTokens?{kind:"blocked",reasonCode:"run-token-budget-exceeded",message:"The conservative request token estimate exceeds the remaining run cap."}:t.estimatedDollars>n.run.maxDollars?{kind:"blocked",reasonCode:"run-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the remaining run cap."}:{kind:"within-budget"}}function vs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Ho(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function zo(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0?t:void 0}function Pb(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Sb(t){if(t!=null)return zo(t)??null}function Gr(t){if(typeof t!="string"||t.trim().length===0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?t:void 0}function aO(t){let n=vs(t);if(n===void 0)return;let e=n.prompt===void 0?void 0:Gr(n.prompt),r=n.completion===void 0?void 0:Gr(n.completion),i=n.request===void 0?void 0:Gr(n.request),s=n.min_prompt_tokens===void 0?void 0:zo(n.min_prompt_tokens),a=n.utc_start===void 0?void 0:Pb(n.utc_start),o=n.utc_end===void 0?void 0:Pb(n.utc_end),d=n.utc_days===void 0?void 0:Array.isArray(n.utc_days)?n.utc_days.map(zo):void 0;if(!(n.prompt!==void 0&&e===void 0||n.completion!==void 0&&r===void 0||n.request!==void 0&&i===void 0||n.min_prompt_tokens!==void 0&&s===void 0||n.utc_start!==void 0&&a===void 0||n.utc_end!==void 0&&o===void 0||n.utc_days!==void 0&&(d===void 0||d.includes(void 0))))return{...e===void 0?{}:{prompt:e},...r===void 0?{}:{completion:r},...i===void 0?{}:{request:i},...s===void 0?{}:{minPromptTokens:s},...a===void 0?{}:{utcStart:a},...o===void 0?{}:{utcEnd:o},...d===void 0?{}:{utcDays:d}}}function oO(t){let n=vs(t);if(n===void 0)return;let e=Gr(n.prompt),r=Gr(n.completion),i=n.request===void 0?void 0:Gr(n.request);if(e===void 0||r===void 0||n.request!==void 0&&i===void 0)return;let s=n.overrides;if(s!==void 0&&!Array.isArray(s))return;let a=(s??[]).map(aO);if(!a.includes(void 0))return{prompt:e,completion:r,...i===void 0?{}:{request:i},overrides:a}}function Eb(t){return t.trim().toLocaleLowerCase("en-US")}function Cb(t){return Ho(t.tag)}function Bo(t,n){return{kind:"unsupported",code:t,message:n}}function fp(t,n){let e=vs(t),i=vs(e?.data)?.endpoints;if(!Array.isArray(i))return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let s=Eb(n.providerSlug),a=i.map(vs).filter(g=>g!==void 0).filter(g=>{let y=Cb(g);return y!==void 0&&Eb(y)===s});if(a.length===0)return Bo("provider-unavailable",`The exact provider ${n.providerSlug} does not serve ${n.modelId}.`);if(a.length!==1)return Bo("provider-ambiguous",`The provider route ${n.providerSlug} did not identify one endpoint.`);let o=a[0];if(o===void 0)return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let d=Ho(o.model_id);if(d!==n.modelId)return Bo("model-mismatch","OpenRouter metadata did not preserve the configured exact model identifier.");let c=Array.isArray(o.supported_parameters)?o.supported_parameters.map(Ho):[];if(c.includes(void 0))return{kind:"failed",code:"invalid-metadata",message:"Supported parameters were malformed."};if(!c.includes("structured_outputs"))return Bo("structured-output-unsupported","The exact endpoint does not advertise structured output support.");let l=zo(o.context_length),u=Sb(o.max_prompt_tokens),p=Sb(o.max_completion_tokens),f=oO(o.pricing),h=typeof o.status=="number"?o.status:void 0;return l===void 0||u===null||p===null||f===void 0||h===void 0||!Number.isFinite(h)?{kind:"failed",code:"invalid-metadata",message:"Endpoint limits or pricing were malformed."}:h!==0?{kind:"unavailable",code:"endpoint-unavailable",message:"The exact endpoint is not currently marked available."}:{kind:"available",endpoint:{providerName:Ho(o.provider_name)??n.providerSlug,providerSlug:Cb(o)??n.providerSlug,modelId:d,contextLength:l,...u===void 0?{}:{maxPromptTokens:u},...p===void 0?{}:{maxCompletionTokens:p},supportedParameters:c,pricing:f,status:h}}}function dO(t){return{...t.prompt===void 0?{}:{prompt:t.prompt},...t.completion===void 0?{}:{completion:t.completion},...t.request===void 0?{}:{request:t.request},...t.minPromptTokens===void 0?{}:{minPromptTokens:t.minPromptTokens},...t.utcStart===void 0?{}:{utcStart:String(t.utcStart)},...t.utcEnd===void 0?{}:{utcEnd:String(t.utcEnd)},...t.utcDays===void 0?{}:{utcDays:t.utcDays}}}function hp(t){let n={prompt:t.pricing.prompt,completion:t.pricing.completion,...t.pricing.request===void 0?{}:{request:t.pricing.request},overrides:t.pricing.overrides.map(dO)};return{modelId:t.modelId,providerId:t.providerSlug,providerName:t.providerName,contextLength:t.contextLength,...t.maxPromptTokens===void 0?{}:{maxPromptTokens:t.maxPromptTokens},...t.maxCompletionTokens===void 0?{}:{maxCompletionTokens:t.maxCompletionTokens},supportedParameters:t.supportedParameters,status:t.status,pricing:n}}var cO="https://openrouter.ai",lO=`${cO}/api/v1`,uO=3e4,pO=4*1024*1024;function Vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ks(t){if(t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError"))return"timed out";let n=t?.cause;return typeof n?.code=="string"?n.code:typeof n?.message=="string"?n.message:t instanceof Error?t.message:"unknown error"}function mp(t,n){return t!==void 0&&Number.isInteger(t)&&t>0?t:n}function fO(t){let n=t.split("/");if(!(n.length!==2||n.some(e=>e.length===0)))return n.map(encodeURIComponent).join("/")}function Nb(t){let n=t();return n===void 0||n.trim().length===0?void 0:n.trim()}async function Ob(t,n){let e=t.headers.get("content-length");if(e!==null){let d=Number(e);if(Number.isFinite(d)&&d>n)return{kind:"too-large"}}if(t.body===null)return{kind:"invalid-json"};let r=t.body.getReader(),i=[],s=0;try{for(;;){let d=await r.read();if(d.done)break;if(s+=d.value.byteLength,s>n)return await r.cancel(),{kind:"too-large"};i.push(d.value)}}finally{r.releaseLock()}let a=new Uint8Array(s),o=0;for(let d of i)a.set(d,o),o+=d.byteLength;try{return{kind:"parsed",value:JSON.parse(new TextDecoder().decode(a))}}catch{return{kind:"invalid-json"}}}function Vo(t){if(!Vt(t)||!Vt(t.error))return;let n=t.error.code;return typeof n=="number"&&Number.isFinite(n)?n:void 0}function yp(t,n){let e=Vt(n)&&Vt(n.error)?n.error:void 0,r=Vt(e?.metadata)?e.metadata:void 0,i=[e?.message,r?.raw].filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.replace(/\s+/g," ").trim()).join(": "),s=i.length>300?`${i.slice(0,299)}\u2026`:i;return`OpenRouter completion request failed (HTTP ${t})${s===""?".":`: ${s}`}`}function gp(t){return Vt(t)&&Vt(t.error)&&t.choices===void 0}function $b(t){return{Accept:"application/json",Authorization:`Bearer ${t}`}}function wp(t){if(t.body.model!==t.route.modelId)return"The completion body does not preserve the configured exact model.";if("models"in t.body)return"Model fallback arrays are forbidden.";if("tools"in t.body||"tool_choice"in t.body)return"Model tools are forbidden for bounded diagnosis.";if(t.body.stream===!0)return"Streaming is not supported by bounded diagnosis.";let n=Vt(t.body.provider)?t.body.provider:void 0,e=Array.isArray(n?.only)?n.only:void 0;if(e?.length!==1||e[0]!==t.route.providerSlug||n?.allow_fallbacks!==!1||n.require_parameters!==!0)return"The completion body does not preserve the exact no-fallback provider route.";if((Vt(t.body.response_format)?t.body.response_format:void 0)?.type!=="json_schema")return"The completion body does not require JSON Schema output."}var Wn=class{#e;#n;#t;#r;#i;#s;#a;#o;constructor(n={}){this.#e=n.fetch??fetch,this.#n=mp(n.timeoutMs,uO),this.#t=mp(n.maxResponseBytes,pO),this.#r=n.apiRoot??lO,this.#i=n.readApiKey??(()=>process.env.OPENROUTER_API_KEY),this.#s=n.credentialName??"OPENROUTER_API_KEY",this.#a=n.extraHeaders??(()=>({})),this.#o=n.onCompletionBody??(()=>{})}async preflight(n){let e=await this.#d(n);return e.kind==="failed"&&(e.code==="network-error"||e.code==="timeout")?this.#d(n):e}async#d(n){let e=fO(n.modelId);if(e===void 0||n.providerSlug.trim().length===0)return{kind:"failed",code:"invalid-request",message:"An exact model and provider route are required."};let r=Nb(this.#i);if(r===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`};let i=new AbortController,s=setTimeout(()=>i.abort(),this.#n);try{let a=await this.#e(`${this.#r}/models/${e}/endpoints`,{method:"GET",headers:{...this.#a(),...$b(r)},redirect:"error",signal:i.signal}),o=await Ob(a,this.#t);return o.kind!=="parsed"?{kind:"failed",code:o.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter endpoint metadata could not be read safely.",httpStatus:a.status}:a.ok?fp(o.value,n):{kind:"failed",code:"http-error",message:"OpenRouter endpoint metadata request failed.",httpStatus:a.status}}catch(a){return{kind:"failed",code:a instanceof DOMException&&a.name==="AbortError"?"timeout":"network-error",message:`OpenRouter endpoint metadata request did not complete (${ks(a)}).`}}finally{clearTimeout(s)}}async complete(n){let e=performance.now(),r=wp(n);if(r!==void 0)return{kind:"failed",code:"invalid-request",message:r,elapsedMs:0};let i=Nb(this.#i);if(i===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`,elapsedMs:performance.now()-e};let s=mp(n.timeoutMs,this.#n),a=new AbortController,o=setTimeout(()=>a.abort(),s);try{let d=await this.#e(`${this.#r}/chat/completions`,{method:"POST",headers:{...this.#a(n.body),...$b(i),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(n.body),redirect:"error",signal:a.signal}),c=await Ob(d,this.#t),l=performance.now()-e;if(c.kind!=="parsed")return{kind:"failed",code:c.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter completion response could not be read safely.",httpStatus:d.status,elapsedMs:l};if(!d.ok||gp(c.value)){let u=Vo(c.value),p=d.ok?u??502:d.status;return{kind:"failed",code:"http-error",message:yp(p,c.value),httpStatus:p,...u===void 0?{}:{providerCode:u},elapsedMs:l}}return this.#o(c.value),{kind:"response",httpStatus:d.status,body:c.value,elapsedMs:l}}catch(d){return{kind:"failed",code:d instanceof DOMException&&d.name==="AbortError"?"timeout":"network-error",message:"OpenRouter completion request did not complete.",elapsedMs:performance.now()-e}}finally{clearTimeout(o)}}};var Jn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},hO={type:"object",additionalProperties:!1,required:["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],properties:{hypothesisId:{type:"string",minLength:1},rank:{type:"integer",minimum:1,maximum:3},causalCategory:{type:"string",minLength:1},probableOwner:{type:"string",enum:["test-support","application","environment","undetermined"]},evidenceGrade:{type:"string",enum:["strong","moderate","weak","insufficient"]},supportingEvidenceIds:Jn,contradictingEvidenceIds:Jn,missingEvidence:Jn,unresolvedAssumptions:Jn,nextAction:{type:"string",minLength:1},statement:{type:"string",minLength:1}}},bp={type:"object",additionalProperties:!1,required:["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],properties:{status:{type:"string",enum:["conclusive","probable","inconclusive"]},hypotheses:{type:"array",items:hO,maxItems:3},symptomIds:Jn,missingEvidence:Jn,recommendedNextAction:{type:"string",minLength:1},repairEligibility:{type:"string",enum:["eligible","ineligible","undetermined"]},ownershipEvidenceIds:Jn,packetHash:{type:"string",minLength:1}}},mO=["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],yO=["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],gO=new Set(["conclusive","probable","inconclusive"]),wO=new Set(["strong","moderate","weak","insufficient"]),bO=new Set(["test-support","application","environment","undetermined"]),xO=new Set(["eligible","ineligible","undetermined"]);function Wr(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}function de(t,n,e,r){t.push({path:n,code:e,message:r})}function Jr(t,n,e,r){let i=new Set(n);for(let s of n)Object.hasOwn(t,s)||de(r,`${e}.${s}`,"missing-field","field is required");for(let s of Object.keys(t))i.has(s)||de(r,`${e}.${s}`,"unknown-field","field is not allowed")}function Be(t,n,e){if(typeof t!="string"){de(e,n,"expected-string","expected a string");return}if(t.trim()===""){de(e,n,"empty-string","string must not be empty");return}return t}function Kr(t,n,e,r){let i=Be(t,e,r);if(i!==void 0){if(!n.has(i)){de(r,e,"invalid-enum",`unsupported value ${JSON.stringify(i)}`);return}return i}}function rt(t,n,e){if(!Array.isArray(t)){de(e,n,"expected-array","expected an array");return}let r=[],i=new Set;return t.forEach((s,a)=>{let o=Be(s,`${n}[${a}]`,e);if(o!==void 0){if(i.has(o)){de(e,`${n}[${a}]`,"duplicate-item",`duplicate value ${JSON.stringify(o)}`);return}i.add(o),r.push(o)}}),r}function vO(t,n,e){let r=`$.hypotheses[${n}]`;if(!Wr(t)){de(e,r,"expected-object","expected an object");return}Jr(t,yO,r,e);let i=Be(t.hypothesisId,`${r}.hypothesisId`,e),s=t.rank;!Number.isInteger(s)||typeof s!="number"?de(e,`${r}.rank`,"expected-integer","rank must be an integer"):(s<1||s>3)&&de(e,`${r}.rank`,"invalid-rank","rank must be between 1 and 3");let a=Be(t.causalCategory,`${r}.causalCategory`,e),o=Kr(t.probableOwner,bO,`${r}.probableOwner`,e),d=Kr(t.evidenceGrade,wO,`${r}.evidenceGrade`,e),c=rt(t.supportingEvidenceIds,`${r}.supportingEvidenceIds`,e),l=rt(t.contradictingEvidenceIds,`${r}.contradictingEvidenceIds`,e),u=rt(t.missingEvidence,`${r}.missingEvidence`,e),p=rt(t.unresolvedAssumptions,`${r}.unresolvedAssumptions`,e),f=Be(t.nextAction,`${r}.nextAction`,e),h=Be(t.statement,`${r}.statement`,e);if(c!==void 0&&l!==void 0){let m=new Set(l);for(let g of c)m.has(g)&&de(e,`${r}.contradictingEvidenceIds`,"citation-overlap",`${g} cannot both support and contradict a hypothesis`)}if(d!==void 0&&d!=="insufficient"&&c?.length===0&&de(e,`${r}.supportingEvidenceIds`,"support-required",`${d} evidence requires at least one supporting citation`),!(i===void 0||typeof s!="number"||!Number.isInteger(s)||s<1||s>3||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0||p===void 0||f===void 0||h===void 0))return{hypothesisId:i,rank:s,causalCategory:a,probableOwner:o,evidenceGrade:d,supportingEvidenceIds:c,contradictingEvidenceIds:l,missingEvidence:u,unresolvedAssumptions:p,nextAction:f,statement:h}}function Uo(t){let n=[];if(!Wr(t))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"diagnosis must be an object"}]};Jr(t,mO,"$",n);let e=Kr(t.status,gO,"$.status",n),r=[];Array.isArray(t.hypotheses)?(t.hypotheses.length>3&&de(n,"$.hypotheses","too-many-items","at most three hypotheses are allowed"),t.hypotheses.forEach((p,f)=>{let h=vO(p,f,n);h!==void 0&&r.push(h)})):de(n,"$.hypotheses","expected-array","expected an array");let i=new Set;for(let p of r)i.has(p.hypothesisId)&&de(n,"$.hypotheses","duplicate-id",`duplicate hypothesis id ${JSON.stringify(p.hypothesisId)}`),i.add(p.hypothesisId);[...r].map(p=>p.rank).sort((p,f)=>p-f).forEach((p,f)=>{p!==f+1&&de(n,"$.hypotheses","invalid-rank","hypothesis ranks must be contiguous from 1")});let a=rt(t.symptomIds,"$.symptomIds",n),o=rt(t.missingEvidence,"$.missingEvidence",n),d=Be(t.recommendedNextAction,"$.recommendedNextAction",n),c=Kr(t.repairEligibility,xO,"$.repairEligibility",n),l=rt(t.ownershipEvidenceIds,"$.ownershipEvidenceIds",n),u=Be(t.packetHash,"$.packetHash",n);return n.length>0||e===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0?{kind:"invalid",issues:n}:{kind:"valid",diagnosis:{status:e,hypotheses:r,symptomIds:a,missingEvidence:o,recommendedNextAction:d,repairEligibility:c,ownershipEvidenceIds:l,packetHash:u}}}function At(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function qo(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function Yn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function kO(t){if(t===void 0)return{valid:!0};let n=At(t);if(n===void 0)return{valid:!1};let e=Yn(n.prompt_tokens),r=Yn(n.completion_tokens),i=Yn(n.total_tokens);if(e===void 0||r===void 0||i===void 0)return{valid:!1};let s=At(n.completion_tokens_details),a=At(n.prompt_tokens_details),o=At(n.cost_details),d=Yn(s?.reasoning_tokens),c=Yn(a?.cached_tokens),l=Yn(n.cost),u=Yn(o?.upstream_inference_cost);return i!==e+r||d!==void 0&&d>r||c!==void 0&&c>e||n.completion_tokens_details!==void 0&&s===void 0||n.prompt_tokens_details!==void 0&&a===void 0||n.cost_details!==void 0&&o===void 0||s?.reasoning_tokens!==void 0&&d===void 0||a?.cached_tokens!==void 0&&c===void 0||n.cost!==void 0&&l===void 0||o?.upstream_inference_cost!==void 0&&u===void 0?{valid:!1}:{valid:!0,usage:{promptTokens:e,completionTokens:r,totalTokens:i,...d===void 0?{}:{reasoningTokens:d},...c===void 0?{}:{cachedTokens:c},...l===void 0?{}:{cost:l},...u===void 0?{}:{upstreamInferenceCost:u}}}}function RO(t){let e=At(t?.endpoints)?.available;if(!Array.isArray(e))return;let r=e.map(At).filter(i=>i!==void 0&&i.selected===!0);return r.length!==1?null:qo(r[0]?.provider)??null}function Db(t,n,e){let r=At(t),i=qo(r?.model),s=r?.choices;if(r===void 0||i===void 0||!Array.isArray(s))return{kind:"malformed-response",message:"Completion response fields were malformed."};if(s.length!==1)return{kind:"malformed-response",message:"Completion response must contain exactly one choice."};let a=At(s[0]),o=At(a?.message),d=qo(a?.finish_reason);if(o===void 0||d===void 0)return{kind:"malformed-response",message:"Completion choice was malformed."};if("tool_calls"in o||"function_call"in o)return{kind:"malformed-response",message:`Tool calls are forbidden in ${n} output.`};if(o.refusal!==void 0&&o.refusal!==null)return{kind:"provider-refusal",message:`The provider refused the ${n} request.`};if(d!=="stop")return{kind:"provider-refusal",message:`The provider did not complete the structured response (${d}).`};let c=qo(o.content);if(c===void 0)return{kind:"malformed-response",message:`Structured ${n} content was missing.`};let l;try{l=JSON.parse(c)}catch{return{kind:"malformed-response",message:`Structured ${n} was not valid JSON.`}}let u=e(l);if(u.kind!=="valid")return{kind:"schema-invalid",message:u.message};let p=At(r.openrouter_metadata),f=RO(p);if(f===null)return{kind:"malformed-response",message:"Router metadata did not identify exactly one selected provider."};let h=kO(r.usage);return h.valid?{kind:"parsed",value:{output:u.output,reportedModel:i,...f===void 0?{}:{reportedProvider:f},...h.usage===void 0?{}:{usage:h.usage},finishReason:d}}:{kind:"malformed-response",message:"Completion usage metadata was malformed."}}var IO=new Set(["$defs","$ref","additionalProperties","anyOf","const","definitions","description","enum","exclusiveMaximum","exclusiveMinimum","format","items","maxItems","maximum","minItems","minimum","multipleOf","pattern","properties","required","title","type"]),AO=new Set(["$defs","definitions","properties"]);function Lb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Go(t){return Array.isArray(t)?t.map(Go):Lb(t)?Object.fromEntries(Object.entries(t).filter(([n])=>IO.has(n)).map(([n,e])=>[n,AO.has(n)&&Lb(e)?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,Go(i)])):n==="enum"||n==="const"||n==="required"?e:Go(e)])):t}function Mb(t,n){return n.startsWith("openai/")?Go(t):t}var TO=`You diagnose test failures from one bounded, redacted evidence packet. The packet's framework field names the framework that ran the tests: an end-to-end framework (Playwright, Cypress, or WebdriverIO) or a test runner whose report KwikQA reads (Vitest, Jest, Mocha, pytest, JUnit, TestNG, Cucumber, or unknown); read errors, commands, and locators in that framework's terms.
197
+ ${u}`}`,reproduced:0,passed:0}}let a=new Set(t.targets.map(u=>u.logicalTestId)),o=i.run.logicalTests.filter(u=>a.has(u.logicalTestId)),d=o.filter(u=>u.status==="unexpected"||u.status==="flaky").map(u=>u.logicalTestId),c=d.length,l=o.filter(u=>u.status==="expected").length;return{kind:"captured",reportPath:t.reportPath,reproduced:c,passed:l,failedAgain:d,message:c===0?`None of the ${t.targets.length} failing tests failed again, so the failure may be flaky or depend on state the re-run did not have.`:`Captured full evidence for ${c} failing test${c===1?"":"s"}${l>0?`; ${l} passed this time, which suggests flakiness`:""}.`}}var tO=/\b(?:getBy\w+|locator|frameLocator)\((?:[^()]|\([^()]*\))*\)/;function nO(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rO(t,n){if(t===void 0)return;let r=new RegExp(`${nO(n)}:(\\d+):\\d+`).exec(t.replaceAll("\\","/"));return r?.[1]===void 0?void 0:Number(r[1])}function Rb(t,n){if(t===void 0)return!1;let e=t.replaceAll("\\","/");return e===n||e.endsWith(`/${n}`)}function _o(t){let n=new Map(t.projects.map(r=>[r.projectId,r.name])),e=[];for(let r of t.logicalTests){let i=Or(r),s=i.at(-1);if(s===void 0)continue;let a=r.location.file,o=s.errors.map(u=>`${u.message??""}
198
+ ${u.stack??""}`),d=(Rb(s.errorLocation?.file,a)?s.errorLocation?.line:void 0)??s.errors.map(u=>Rb(u.location?.file,a)?u.location?.line:rO(u.stack,a)).find(u=>u!==void 0),c=o.map(u=>tO.exec(u)?.[0]).find(u=>u!==void 0),l=n.get(r.projectId);e.push({logicalTestId:r.logicalTestId,title:r.title,file:a,line:r.location.line??1,...l===void 0||l===""?{}:{project:l},...d===void 0?{}:{failingLine:d},...c===void 0?{}:{locator:c},hasTrace:i.some(u=>u.attachments.some(p=>p.name==="trace")),hasPageSnapshot:i.some(u=>u.attachments.some(p=>p.name==="error-context"))})}return e}var Ab=3;async function sp(t){let n=_o(t.run),e=await vb({run:t.run,workspaceRoot:t.workspaceRoot,...t.repositoryRoot===void 0?{}:{repositoryRoot:t.repositoryRoot},targets:n,captureId:t.captureId});if(e.kind!=="ready")return e;let{plan:r}=e,i,s,a=r.framework;t.probe&&a==="playwright"&&(Ju(r.tool.packageVersion)?(i=await ob(t.workspaceRoot,t.env),i===void 0&&(s="Live probing needs Playwright CLI: add `@playwright/cli` to the project's dev dependencies (nothing was installed).")):s=`Live probing needs Playwright 1.59 or later; this project has ${r.tool.packageVersion}.`);let o=So[a],d=`${n.length} failing test${n.length===1?"":"s"}`,c=new Set(n.map(u=>u.file)).size,l=a==="playwright"?[`Re-run ${d} with full tracing, using this project's Playwright ${r.tool.packageVersion}:`,` ${ip(r)}`,...i===void 0?[]:[`Then pause up to ${Ab} locator failures at their failing line and ask Playwright for locators, using Playwright CLI ${i.version} (${i.source==="project"?"project dependency":i.entryPath}).`],`Everything is written under ${r.directory}/. Your tests run on this machine, as they do in \`npx playwright test\`.`]:[`Re-run the ${c} spec file${c===1?"":"s"} with ${d}, using this project's ${o} ${r.tool.packageVersion} and its own config:`,` ${ip(r)}`,a==="cypress"?"KwikQA adds its reporter and a support file that loads its failure capture and then yours, and records each failed attempt's page: DOM, Cypress command log, console errors, and network.":"KwikQA adds its reporter and hooks after yours that record each failed attempt's page: DOM, screenshot, WebdriverIO commands, console, and network.",`Everything is written under ${r.directory}/. Your tests run on this machine, as they do in \`npx ${a==="cypress"?"cypress run":"wdio run"}\`.`];return{kind:"ready",prepared:{plan:r,...i===void 0?{}:{cli:i},...s===void 0?{}:{probeUnavailable:s},description:l}}}async function ap(t,n){let e=await kb(t.plan,{env:n});if(t.cli===void 0||e.reportPath===void 0||e.reproduced===0)return{outcome:e};let r=await ct(e.reportPath,{workspaceRoot:t.plan.workspaceRoot}),s=(r.kind==="parsed"?_o(r.run):[]).filter(l=>l.locator!==void 0).slice(0,Ab);if(s.length===0)return{outcome:e};let a=Ib(t.plan.workspaceRoot,t.plan.directory,"probe");await iO(a,{recursive:!0});let o=[];for(let l of s)o.push(await pb({workspaceRoot:t.plan.workspaceRoot,playwright:t.plan.tool,cli:t.cli,target:l,...t.plan.configPath===void 0?{}:{configPath:t.plan.configPath},scratchDirectory:a,env:n}));let d={schemaVersion:ab,tool:{name:"@playwright/cli",version:t.cli.version,source:t.cli.source},playwrightVersion:t.plan.tool.packageVersion,results:o},c=Ib(t.plan.workspaceRoot,t.plan.directory,"probe.json");return await sO(c,`${JSON.stringify(d,null,2)}
199
+ `),{outcome:e,probePath:c,probe:d}}var Gn=class{#e=new Set;consume(n,e){return this.#e.has(n)?!1:(this.#e.add(n),!0)}};function jo(t){return L({runId:t.manifest.runId,packetHash:t.manifest.packetHash,payloadHash:t.manifest.payloadHash,manifestHash:t.manifestHash,model:t.manifest.model,promptVersion:t.manifest.promptVersion,outputSchemaVersion:t.manifest.outputSchemaVersion,endpoint:t.endpoint,estimate:t.estimate,caps:t.caps})}function op(t,n){return{runId:t.manifest.runId,packetHash:t.manifest.packetHash,payloadManifestHash:t.manifestHash,authorizationBindingHash:n,model:t.manifest.model,estimate:t.estimate,caps:t.caps,evidence:t.manifest.evidence,artifactIds:t.manifest.artifactIds,channels:t.manifest.channels,omissionIds:t.manifest.omissionIds,redactionIds:t.manifest.redactionIds}}function dp(t,n){return t.bindingHash===n&&t.authorizationId.trim().length>0&&t.authorizedAt.trim().length>0}var aO={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function cp(t){return{...t.extra,schemaVersion:"1.1",runId:t.runId,createdAt:t.createdAt,workspace:t.workspace,sourceHashes:t.sourceHashes,packetHash:t.packetHash,...t.request??aO,model:t.model,caps:t.caps,outcome:t.outcome,recordedAt:t.recordedAt}}function We(t,n,e){return{kind:t,...n===void 0?{}:{reasonCode:n},...e===void 0?{}:{message:e}}}function lp(t){if(t===void 0||t.trim().length===0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function oO(t){let n=[t.prompt,...t.overrides.map(i=>i.prompt)].map(lp).filter(i=>i!==void 0),e=[t.completion,...t.overrides.map(i=>i.completion)].map(lp).filter(i=>i!==void 0),r=[t.request??"0",...t.overrides.map(i=>i.request)].map(lp).filter(i=>i!==void 0);if(!(n.length!==t.overrides.filter(i=>i.prompt!==void 0).length+1||e.length!==t.overrides.filter(i=>i.completion!==void 0).length+1||r.length!==t.overrides.filter(i=>i.request!==void 0).length+1))return{prompt:Math.max(...n),completion:Math.max(...e),request:Math.max(...r)}}function Fo(t,n,e){if(!Number.isInteger(n)||n<=0)return;let r=oO(e);if(r===void 0)return;let i=Buffer.byteLength(t,"utf8"),s=i+64,a=s*r.prompt+n*r.completion+r.request;if(Number.isFinite(a))return{method:"utf8-byte-upper-bound-v1",requestBytes:i,estimatedInputTokens:s,estimatedOutputTokens:n,estimatedDollars:a,promptDollarsPerToken:r.prompt,completionDollarsPerToken:r.completion,fixedRequestDollars:r.request}}function up(t){for(let[n,e]of[["request",t.request],["run",t.run]]){if(!Number.isInteger(e.maxInputTokens)||e.maxInputTokens<=0)return`${n} maxInputTokens must be a positive integer.`;if(!Number.isInteger(e.maxOutputTokens)||e.maxOutputTokens<=0)return`${n} maxOutputTokens must be a positive integer.`;if(!Number.isFinite(e.maxDollars)||e.maxDollars<=0)return`${n} maxDollars must be a positive finite number.`}}function pp(t,n){return t.estimatedInputTokens>n.request.maxInputTokens||t.estimatedOutputTokens>n.request.maxOutputTokens?{kind:"blocked",reasonCode:"request-token-budget-exceeded",message:"The conservative request token estimate exceeds the request cap."}:t.estimatedDollars>n.request.maxDollars?{kind:"blocked",reasonCode:"request-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the request cap."}:t.estimatedInputTokens>n.run.maxInputTokens||t.estimatedOutputTokens>n.run.maxOutputTokens?{kind:"blocked",reasonCode:"run-token-budget-exceeded",message:"The conservative request token estimate exceeds the remaining run cap."}:t.estimatedDollars>n.run.maxDollars?{kind:"blocked",reasonCode:"run-dollar-budget-exceeded",message:"The conservative request cost estimate exceeds the remaining run cap."}:{kind:"within-budget"}}function vs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Ho(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function zo(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0?t:void 0}function Pb(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Sb(t){if(t!=null)return zo(t)??null}function Gr(t){if(typeof t!="string"||t.trim().length===0)return;let n=Number(t);return Number.isFinite(n)&&n>=0?t:void 0}function dO(t){let n=vs(t);if(n===void 0)return;let e=n.prompt===void 0?void 0:Gr(n.prompt),r=n.completion===void 0?void 0:Gr(n.completion),i=n.request===void 0?void 0:Gr(n.request),s=n.min_prompt_tokens===void 0?void 0:zo(n.min_prompt_tokens),a=n.utc_start===void 0?void 0:Pb(n.utc_start),o=n.utc_end===void 0?void 0:Pb(n.utc_end),d=n.utc_days===void 0?void 0:Array.isArray(n.utc_days)?n.utc_days.map(zo):void 0;if(!(n.prompt!==void 0&&e===void 0||n.completion!==void 0&&r===void 0||n.request!==void 0&&i===void 0||n.min_prompt_tokens!==void 0&&s===void 0||n.utc_start!==void 0&&a===void 0||n.utc_end!==void 0&&o===void 0||n.utc_days!==void 0&&(d===void 0||d.includes(void 0))))return{...e===void 0?{}:{prompt:e},...r===void 0?{}:{completion:r},...i===void 0?{}:{request:i},...s===void 0?{}:{minPromptTokens:s},...a===void 0?{}:{utcStart:a},...o===void 0?{}:{utcEnd:o},...d===void 0?{}:{utcDays:d}}}function cO(t){let n=vs(t);if(n===void 0)return;let e=Gr(n.prompt),r=Gr(n.completion),i=n.request===void 0?void 0:Gr(n.request);if(e===void 0||r===void 0||n.request!==void 0&&i===void 0)return;let s=n.overrides;if(s!==void 0&&!Array.isArray(s))return;let a=(s??[]).map(dO);if(!a.includes(void 0))return{prompt:e,completion:r,...i===void 0?{}:{request:i},overrides:a}}function Eb(t){return t.trim().toLocaleLowerCase("en-US")}function Cb(t){return Ho(t.tag)}function Bo(t,n){return{kind:"unsupported",code:t,message:n}}function fp(t,n){let e=vs(t),i=vs(e?.data)?.endpoints;if(!Array.isArray(i))return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let s=Eb(n.providerSlug),a=i.map(vs).filter(g=>g!==void 0).filter(g=>{let y=Cb(g);return y!==void 0&&Eb(y)===s});if(a.length===0)return Bo("provider-unavailable",`The exact provider ${n.providerSlug} does not serve ${n.modelId}.`);if(a.length!==1)return Bo("provider-ambiguous",`The provider route ${n.providerSlug} did not identify one endpoint.`);let o=a[0];if(o===void 0)return{kind:"failed",code:"invalid-metadata",message:"Endpoint metadata was malformed."};let d=Ho(o.model_id);if(d!==n.modelId)return Bo("model-mismatch","OpenRouter metadata did not preserve the configured exact model identifier.");let c=Array.isArray(o.supported_parameters)?o.supported_parameters.map(Ho):[];if(c.includes(void 0))return{kind:"failed",code:"invalid-metadata",message:"Supported parameters were malformed."};if(!c.includes("structured_outputs"))return Bo("structured-output-unsupported","The exact endpoint does not advertise structured output support.");let l=zo(o.context_length),u=Sb(o.max_prompt_tokens),p=Sb(o.max_completion_tokens),f=cO(o.pricing),h=typeof o.status=="number"?o.status:void 0;return l===void 0||u===null||p===null||f===void 0||h===void 0||!Number.isFinite(h)?{kind:"failed",code:"invalid-metadata",message:"Endpoint limits or pricing were malformed."}:h!==0?{kind:"unavailable",code:"endpoint-unavailable",message:"The exact endpoint is not currently marked available."}:{kind:"available",endpoint:{providerName:Ho(o.provider_name)??n.providerSlug,providerSlug:Cb(o)??n.providerSlug,modelId:d,contextLength:l,...u===void 0?{}:{maxPromptTokens:u},...p===void 0?{}:{maxCompletionTokens:p},supportedParameters:c,pricing:f,status:h}}}function lO(t){return{...t.prompt===void 0?{}:{prompt:t.prompt},...t.completion===void 0?{}:{completion:t.completion},...t.request===void 0?{}:{request:t.request},...t.minPromptTokens===void 0?{}:{minPromptTokens:t.minPromptTokens},...t.utcStart===void 0?{}:{utcStart:String(t.utcStart)},...t.utcEnd===void 0?{}:{utcEnd:String(t.utcEnd)},...t.utcDays===void 0?{}:{utcDays:t.utcDays}}}function hp(t){let n={prompt:t.pricing.prompt,completion:t.pricing.completion,...t.pricing.request===void 0?{}:{request:t.pricing.request},overrides:t.pricing.overrides.map(lO)};return{modelId:t.modelId,providerId:t.providerSlug,providerName:t.providerName,contextLength:t.contextLength,...t.maxPromptTokens===void 0?{}:{maxPromptTokens:t.maxPromptTokens},...t.maxCompletionTokens===void 0?{}:{maxCompletionTokens:t.maxCompletionTokens},supportedParameters:t.supportedParameters,status:t.status,pricing:n}}var uO="https://openrouter.ai",pO=`${uO}/api/v1`,fO=3e4,hO=4*1024*1024;function Vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ks(t){if(t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError"))return"timed out";let n=t?.cause;return typeof n?.code=="string"?n.code:typeof n?.message=="string"?n.message:t instanceof Error?t.message:"unknown error"}function mp(t,n){return t!==void 0&&Number.isInteger(t)&&t>0?t:n}function mO(t){let n=t.split("/");if(!(n.length!==2||n.some(e=>e.length===0)))return n.map(encodeURIComponent).join("/")}function Nb(t){let n=t();return n===void 0||n.trim().length===0?void 0:n.trim()}async function Ob(t,n){let e=t.headers.get("content-length");if(e!==null){let d=Number(e);if(Number.isFinite(d)&&d>n)return{kind:"too-large"}}if(t.body===null)return{kind:"invalid-json"};let r=t.body.getReader(),i=[],s=0;try{for(;;){let d=await r.read();if(d.done)break;if(s+=d.value.byteLength,s>n)return await r.cancel(),{kind:"too-large"};i.push(d.value)}}finally{r.releaseLock()}let a=new Uint8Array(s),o=0;for(let d of i)a.set(d,o),o+=d.byteLength;try{return{kind:"parsed",value:JSON.parse(new TextDecoder().decode(a))}}catch{return{kind:"invalid-json"}}}function Vo(t){if(!Vt(t)||!Vt(t.error))return;let n=t.error.code;return typeof n=="number"&&Number.isFinite(n)?n:void 0}function yp(t,n){let e=Vt(n)&&Vt(n.error)?n.error:void 0,r=Vt(e?.metadata)?e.metadata:void 0,i=[e?.message,r?.raw].filter(a=>typeof a=="string"&&a.trim()!=="").map(a=>a.replace(/\s+/g," ").trim()).join(": "),s=i.length>300?`${i.slice(0,299)}\u2026`:i;return`OpenRouter completion request failed (HTTP ${t})${s===""?".":`: ${s}`}`}function gp(t){return Vt(t)&&Vt(t.error)&&t.choices===void 0}function $b(t){return{Accept:"application/json",Authorization:`Bearer ${t}`}}function wp(t){if(t.body.model!==t.route.modelId)return"The completion body does not preserve the configured exact model.";if("models"in t.body)return"Model fallback arrays are forbidden.";if("tools"in t.body||"tool_choice"in t.body)return"Model tools are forbidden for bounded diagnosis.";if(t.body.stream===!0)return"Streaming is not supported by bounded diagnosis.";let n=Vt(t.body.provider)?t.body.provider:void 0,e=Array.isArray(n?.only)?n.only:void 0;if(e?.length!==1||e[0]!==t.route.providerSlug||n?.allow_fallbacks!==!1||n.require_parameters!==!0)return"The completion body does not preserve the exact no-fallback provider route.";if((Vt(t.body.response_format)?t.body.response_format:void 0)?.type!=="json_schema")return"The completion body does not require JSON Schema output."}var Jn=class{#e;#n;#t;#r;#i;#s;#a;#o;constructor(n={}){this.#e=n.fetch??fetch,this.#n=mp(n.timeoutMs,fO),this.#t=mp(n.maxResponseBytes,hO),this.#r=n.apiRoot??pO,this.#i=n.readApiKey??(()=>process.env.OPENROUTER_API_KEY),this.#s=n.credentialName??"OPENROUTER_API_KEY",this.#a=n.extraHeaders??(()=>({})),this.#o=n.onCompletionBody??(()=>{})}async preflight(n){let e=await this.#d(n);return e.kind==="failed"&&(e.code==="network-error"||e.code==="timeout")?this.#d(n):e}async#d(n){let e=mO(n.modelId);if(e===void 0||n.providerSlug.trim().length===0)return{kind:"failed",code:"invalid-request",message:"An exact model and provider route are required."};let r=Nb(this.#i);if(r===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`};let i=new AbortController,s=setTimeout(()=>i.abort(),this.#n);try{let a=await this.#e(`${this.#r}/models/${e}/endpoints`,{method:"GET",headers:{...this.#a(),...$b(r)},redirect:"error",signal:i.signal}),o=await Ob(a,this.#t);return o.kind!=="parsed"?{kind:"failed",code:o.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter endpoint metadata could not be read safely.",httpStatus:a.status}:a.ok?fp(o.value,n):{kind:"failed",code:"http-error",message:"OpenRouter endpoint metadata request failed.",httpStatus:a.status}}catch(a){return{kind:"failed",code:a instanceof DOMException&&a.name==="AbortError"?"timeout":"network-error",message:`OpenRouter endpoint metadata request did not complete (${ks(a)}).`}}finally{clearTimeout(s)}}async complete(n){let e=performance.now(),r=wp(n);if(r!==void 0)return{kind:"failed",code:"invalid-request",message:r,elapsedMs:0};let i=Nb(this.#i);if(i===void 0)return{kind:"failed",code:"credential-unavailable",message:`${this.#s} is not configured.`,elapsedMs:performance.now()-e};let s=mp(n.timeoutMs,this.#n),a=new AbortController,o=setTimeout(()=>a.abort(),s);try{let d=await this.#e(`${this.#r}/chat/completions`,{method:"POST",headers:{...this.#a(n.body),...$b(i),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(n.body),redirect:"error",signal:a.signal}),c=await Ob(d,this.#t),l=performance.now()-e;if(c.kind!=="parsed")return{kind:"failed",code:c.kind==="too-large"?"response-too-large":"invalid-json",message:"OpenRouter completion response could not be read safely.",httpStatus:d.status,elapsedMs:l};if(!d.ok||gp(c.value)){let u=Vo(c.value),p=d.ok?u??502:d.status;return{kind:"failed",code:"http-error",message:yp(p,c.value),httpStatus:p,...u===void 0?{}:{providerCode:u},elapsedMs:l}}return this.#o(c.value),{kind:"response",httpStatus:d.status,body:c.value,elapsedMs:l}}catch(d){return{kind:"failed",code:d instanceof DOMException&&d.name==="AbortError"?"timeout":"network-error",message:"OpenRouter completion request did not complete.",elapsedMs:performance.now()-e}}finally{clearTimeout(o)}}};var Yn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yO={type:"object",additionalProperties:!1,required:["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],properties:{hypothesisId:{type:"string",minLength:1},rank:{type:"integer",minimum:1,maximum:3},causalCategory:{type:"string",minLength:1},probableOwner:{type:"string",enum:["test-support","application","environment","undetermined"]},evidenceGrade:{type:"string",enum:["strong","moderate","weak","insufficient"]},supportingEvidenceIds:Yn,contradictingEvidenceIds:Yn,missingEvidence:Yn,unresolvedAssumptions:Yn,nextAction:{type:"string",minLength:1},statement:{type:"string",minLength:1}}},bp={type:"object",additionalProperties:!1,required:["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],properties:{status:{type:"string",enum:["conclusive","probable","inconclusive"]},hypotheses:{type:"array",items:yO,maxItems:3},symptomIds:Yn,missingEvidence:Yn,recommendedNextAction:{type:"string",minLength:1},repairEligibility:{type:"string",enum:["eligible","ineligible","undetermined"]},ownershipEvidenceIds:Yn,packetHash:{type:"string",minLength:1}}},gO=["status","hypotheses","symptomIds","missingEvidence","recommendedNextAction","repairEligibility","ownershipEvidenceIds","packetHash"],wO=["hypothesisId","rank","causalCategory","probableOwner","evidenceGrade","supportingEvidenceIds","contradictingEvidenceIds","missingEvidence","unresolvedAssumptions","nextAction","statement"],bO=new Set(["conclusive","probable","inconclusive"]),xO=new Set(["strong","moderate","weak","insufficient"]),vO=new Set(["test-support","application","environment","undetermined"]),kO=new Set(["eligible","ineligible","undetermined"]);function Wr(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=Object.getPrototypeOf(t);return n===Object.prototype||n===null}function de(t,n,e,r){t.push({path:n,code:e,message:r})}function Jr(t,n,e,r){let i=new Set(n);for(let s of n)Object.hasOwn(t,s)||de(r,`${e}.${s}`,"missing-field","field is required");for(let s of Object.keys(t))i.has(s)||de(r,`${e}.${s}`,"unknown-field","field is not allowed")}function Be(t,n,e){if(typeof t!="string"){de(e,n,"expected-string","expected a string");return}if(t.trim()===""){de(e,n,"empty-string","string must not be empty");return}return t}function Kr(t,n,e,r){let i=Be(t,e,r);if(i!==void 0){if(!n.has(i)){de(r,e,"invalid-enum",`unsupported value ${JSON.stringify(i)}`);return}return i}}function rt(t,n,e){if(!Array.isArray(t)){de(e,n,"expected-array","expected an array");return}let r=[],i=new Set;return t.forEach((s,a)=>{let o=Be(s,`${n}[${a}]`,e);if(o!==void 0){if(i.has(o)){de(e,`${n}[${a}]`,"duplicate-item",`duplicate value ${JSON.stringify(o)}`);return}i.add(o),r.push(o)}}),r}function RO(t,n,e){let r=`$.hypotheses[${n}]`;if(!Wr(t)){de(e,r,"expected-object","expected an object");return}Jr(t,wO,r,e);let i=Be(t.hypothesisId,`${r}.hypothesisId`,e),s=t.rank;!Number.isInteger(s)||typeof s!="number"?de(e,`${r}.rank`,"expected-integer","rank must be an integer"):(s<1||s>3)&&de(e,`${r}.rank`,"invalid-rank","rank must be between 1 and 3");let a=Be(t.causalCategory,`${r}.causalCategory`,e),o=Kr(t.probableOwner,vO,`${r}.probableOwner`,e),d=Kr(t.evidenceGrade,xO,`${r}.evidenceGrade`,e),c=rt(t.supportingEvidenceIds,`${r}.supportingEvidenceIds`,e),l=rt(t.contradictingEvidenceIds,`${r}.contradictingEvidenceIds`,e),u=rt(t.missingEvidence,`${r}.missingEvidence`,e),p=rt(t.unresolvedAssumptions,`${r}.unresolvedAssumptions`,e),f=Be(t.nextAction,`${r}.nextAction`,e),h=Be(t.statement,`${r}.statement`,e);if(c!==void 0&&l!==void 0){let m=new Set(l);for(let g of c)m.has(g)&&de(e,`${r}.contradictingEvidenceIds`,"citation-overlap",`${g} cannot both support and contradict a hypothesis`)}if(d!==void 0&&d!=="insufficient"&&c?.length===0&&de(e,`${r}.supportingEvidenceIds`,"support-required",`${d} evidence requires at least one supporting citation`),!(i===void 0||typeof s!="number"||!Number.isInteger(s)||s<1||s>3||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0||p===void 0||f===void 0||h===void 0))return{hypothesisId:i,rank:s,causalCategory:a,probableOwner:o,evidenceGrade:d,supportingEvidenceIds:c,contradictingEvidenceIds:l,missingEvidence:u,unresolvedAssumptions:p,nextAction:f,statement:h}}function Uo(t){let n=[];if(!Wr(t))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"diagnosis must be an object"}]};Jr(t,gO,"$",n);let e=Kr(t.status,bO,"$.status",n),r=[];Array.isArray(t.hypotheses)?(t.hypotheses.length>3&&de(n,"$.hypotheses","too-many-items","at most three hypotheses are allowed"),t.hypotheses.forEach((p,f)=>{let h=RO(p,f,n);h!==void 0&&r.push(h)})):de(n,"$.hypotheses","expected-array","expected an array");let i=new Set;for(let p of r)i.has(p.hypothesisId)&&de(n,"$.hypotheses","duplicate-id",`duplicate hypothesis id ${JSON.stringify(p.hypothesisId)}`),i.add(p.hypothesisId);[...r].map(p=>p.rank).sort((p,f)=>p-f).forEach((p,f)=>{p!==f+1&&de(n,"$.hypotheses","invalid-rank","hypothesis ranks must be contiguous from 1")});let a=rt(t.symptomIds,"$.symptomIds",n),o=rt(t.missingEvidence,"$.missingEvidence",n),d=Be(t.recommendedNextAction,"$.recommendedNextAction",n),c=Kr(t.repairEligibility,kO,"$.repairEligibility",n),l=rt(t.ownershipEvidenceIds,"$.ownershipEvidenceIds",n),u=Be(t.packetHash,"$.packetHash",n);return n.length>0||e===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0?{kind:"invalid",issues:n}:{kind:"valid",diagnosis:{status:e,hypotheses:r,symptomIds:a,missingEvidence:o,recommendedNextAction:d,repairEligibility:c,ownershipEvidenceIds:l,packetHash:u}}}function At(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function qo(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function Xn(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function IO(t){if(t===void 0)return{valid:!0};let n=At(t);if(n===void 0)return{valid:!1};let e=Xn(n.prompt_tokens),r=Xn(n.completion_tokens),i=Xn(n.total_tokens);if(e===void 0||r===void 0||i===void 0)return{valid:!1};let s=At(n.completion_tokens_details),a=At(n.prompt_tokens_details),o=At(n.cost_details),d=Xn(s?.reasoning_tokens),c=Xn(a?.cached_tokens),l=Xn(n.cost),u=Xn(o?.upstream_inference_cost);return i!==e+r||d!==void 0&&d>r||c!==void 0&&c>e||n.completion_tokens_details!==void 0&&s===void 0||n.prompt_tokens_details!==void 0&&a===void 0||n.cost_details!==void 0&&o===void 0||s?.reasoning_tokens!==void 0&&d===void 0||a?.cached_tokens!==void 0&&c===void 0||n.cost!==void 0&&l===void 0||o?.upstream_inference_cost!==void 0&&u===void 0?{valid:!1}:{valid:!0,usage:{promptTokens:e,completionTokens:r,totalTokens:i,...d===void 0?{}:{reasoningTokens:d},...c===void 0?{}:{cachedTokens:c},...l===void 0?{}:{cost:l},...u===void 0?{}:{upstreamInferenceCost:u}}}}function AO(t){let e=At(t?.endpoints)?.available;if(!Array.isArray(e))return;let r=e.map(At).filter(i=>i!==void 0&&i.selected===!0);return r.length!==1?null:qo(r[0]?.provider)??null}function Db(t,n,e){let r=At(t),i=qo(r?.model),s=r?.choices;if(r===void 0||i===void 0||!Array.isArray(s))return{kind:"malformed-response",message:"Completion response fields were malformed."};if(s.length!==1)return{kind:"malformed-response",message:"Completion response must contain exactly one choice."};let a=At(s[0]),o=At(a?.message),d=qo(a?.finish_reason);if(o===void 0||d===void 0)return{kind:"malformed-response",message:"Completion choice was malformed."};if("tool_calls"in o||"function_call"in o)return{kind:"malformed-response",message:`Tool calls are forbidden in ${n} output.`};if(o.refusal!==void 0&&o.refusal!==null)return{kind:"provider-refusal",message:`The provider refused the ${n} request.`};if(d!=="stop")return{kind:"provider-refusal",message:`The provider did not complete the structured response (${d}).`};let c=qo(o.content);if(c===void 0)return{kind:"malformed-response",message:`Structured ${n} content was missing.`};let l;try{l=JSON.parse(c)}catch{return{kind:"malformed-response",message:`Structured ${n} was not valid JSON.`}}let u=e(l);if(u.kind!=="valid")return{kind:"schema-invalid",message:u.message};let p=At(r.openrouter_metadata),f=AO(p);if(f===null)return{kind:"malformed-response",message:"Router metadata did not identify exactly one selected provider."};let h=IO(r.usage);return h.valid?{kind:"parsed",value:{output:u.output,reportedModel:i,...f===void 0?{}:{reportedProvider:f},...h.usage===void 0?{}:{usage:h.usage},finishReason:d}}:{kind:"malformed-response",message:"Completion usage metadata was malformed."}}var TO=new Set(["$defs","$ref","additionalProperties","anyOf","const","definitions","description","enum","exclusiveMaximum","exclusiveMinimum","format","items","maxItems","maximum","minItems","minimum","multipleOf","pattern","properties","required","title","type"]),PO=new Set(["$defs","definitions","properties"]);function Lb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Go(t){return Array.isArray(t)?t.map(Go):Lb(t)?Object.fromEntries(Object.entries(t).filter(([n])=>TO.has(n)).map(([n,e])=>[n,PO.has(n)&&Lb(e)?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,Go(i)])):n==="enum"||n==="const"||n==="required"?e:Go(e)])):t}function Mb(t,n){return n.startsWith("openai/")?Go(t):t}var SO=`You diagnose test failures from one bounded, redacted evidence packet. The packet's framework field names the framework that ran the tests: an end-to-end framework (Playwright, Cypress, or WebdriverIO) or a test runner whose report KwikQA reads (Vitest, Jest, Mocha, pytest, JUnit, TestNG, Cucumber, or unknown); read errors, commands, and locators in that framework's terms.
200
200
  Deterministic observations are authoritative; your output contains causal hypotheses, not new facts.
201
201
  Cite only supplied evidence, artifact, and symptom IDs. State contradictions, missing evidence, and assumptions.
202
202
  Return no more than three ranked hypotheses and abstain with an inconclusive diagnosis when evidence cannot rank a cause.
203
203
  Owner and repair eligibility require positive cited evidence; absence of application evidence proves nothing.
204
204
  Diff evidence holds recent commits and uncommitted changes whose changed lines mention this failure, each with its commit subject, and a change-search item says what was searched and lists the searched commits' subjects. A deliberate application change that produces the new behaviour (a renamed, moved, or removed element, or new copy or data, in a commit that describes that change) is positive evidence that the test is out of date. A change that breaks what the test checks without describing an intended change points to the application. Recency alone, or finding no related change, is never ownership proof.
205
- You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Xn(t,n){return[...t].sort((e,r)=>n(e).localeCompare(n(r)))}function PO(t){return{gitRootAvailable:t.workspace.gitRoot!==void 0,sourceHashes:t.sourceHashes}}function xp(t){return t.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??"<path>"}function jb(t){return t.type==="source-range"||t.type==="diff-hunk"?{...t,path:xp(t.path)}:t.type==="report-field"?{...t,path:t.path.startsWith("/")?xp(t.path):t.path}:t}function vp(t){return Xn(t,n=>n.artifactId).map(n=>({artifactId:n.artifactId,channel:n.channel,availability:n.availability,...n.sha256===void 0?{}:{sha256:n.sha256},...n.format===void 0?{}:{format:n.format},...n.producerVersion===void 0?{}:{producerVersion:n.producerVersion},...n.attemptId===void 0?{}:{attemptId:n.attemptId},warnings:n.warnings}))}function kp(t){return Xn(t,n=>n.evidenceId).map(n=>({...n,locator:jb(n.locator)}))}function SO(t){return Xn(t.omissions,n=>n.omissionId).map(n=>({omissionId:n.omissionId,channel:n.channel,reason:n.reason,message:n.message,...n.locator===void 0?{}:{locator:xp(n.locator)},...n.cap===void 0?{}:{cap:n.cap}}))}function EO(t,n,e){return{requestSchemaVersion:"1.0",promptVersion:"1.3",outputSchemaVersion:"1.0",runId:t.runId,packetHash:t.packetHash,framework:t.framework??"playwright",workspace:PO(t),artifacts:vp(t.artifacts),evidence:kp(t.evidence),omissions:SO(t),accounting:Xn(t.accounting,r=>r.channel),symptoms:Xn(n.symptoms,r=>r.symptomId),unclassifiedAttemptIds:[...n.unclassifiedAttemptIds].sort(),clusters:Xn(e.clusters,r=>r.clusterId)}}function CO(t,n,e,r,i){let s=new Map(t.artifacts.map(o=>[o.artifactId,o.channel])),a=new Set(n.artifactIds);return{schemaVersion:"1.1",runId:t.runId,packetHash:t.packetHash,payloadHash:r,purpose:n.purpose,model:e,promptVersion:n.promptVersion,outputSchemaVersion:n.outputSchemaVersion,evidence:Xn(n.evidence,o=>o.evidenceId).map(o=>({evidenceId:o.evidenceId,artifactId:o.artifactId,channel:s.get(o.artifactId)??"report",locator:jb(o.locator),...o.logicalTestId===void 0?{}:{logicalTestId:o.logicalTestId},...o.attemptId===void 0?{}:{attemptId:o.attemptId},redactionIds:[...o.redactionIds].sort()})),artifactIds:[...n.artifactIds].sort(),symptomIds:[...n.symptomIds].sort(),clusterIds:[...n.clusterIds].sort(),omissionIds:[...n.omissionIds].sort(),redactionIds:[...n.redactionIds].sort(),channels:[...new Set(t.artifacts.filter(o=>a.has(o.artifactId)).map(o=>o.channel))].sort(),serializedBytes:i}}function Rp(t,n,e,r){let i={model:e.modelId,messages:[{role:"system",content:n.systemPrompt},{role:"user",content:ue(n.userContent)}],max_completion_tokens:r,...e.reasoningEffort===void 0?{}:{reasoning:{effort:e.reasoningEffort,exclude:!0}},response_format:{type:"json_schema",json_schema:{name:n.schemaName,strict:!0,schema:Mb(n.schema,e.modelId)}},provider:{only:[e.providerId],allow_fallbacks:!1,require_parameters:!0,...e.zeroDataRetention===!0?{zdr:!0}:{},max_price:{prompt:0,completion:0,request:0}}},s=ue(i),a=L(i);return{body:i,canonicalBody:s,payloadHash:a,manifest:CO(t,n,e,a,Buffer.byteLength(s,"utf8")),manifestHash:""}}function Ip(t,n,e,r,i){return Rp(t,{purpose:"diagnosis",schemaName:"kwikqa_diagnosis",schema:bp,systemPrompt:TO,promptVersion:"1.3",outputSchemaVersion:"1.0",userContent:EO(t,n,e),evidence:t.evidence,artifactIds:t.artifacts.map(s=>s.artifactId),symptomIds:n.symptoms.map(s=>s.symptomId),clusterIds:e.clusters.map(s=>s.clusterId),omissionIds:t.omissions.map(s=>s.omissionId),redactionIds:t.redactions.map(s=>s.redactionId)},r,i)}function Ap(t,n){let e={...t.body,provider:{...t.body.provider,max_price:{prompt:n.promptDollarsPerToken*1e6,completion:n.completionDollarsPerToken*1e6,request:n.fixedRequestDollars}}},r=ue(e),i=L(e),s={...t.manifest,payloadHash:i,serializedBytes:Buffer.byteLength(r,"utf8")};return{body:e,canonicalBody:r,payloadHash:i,manifest:s,manifestHash:L(s)}}function NO(t){let{packetHash:n,...e}=t;return Rr(e)===n}function OO(t){if(!/^[^/\s]+\/[^/\s]+$/.test(t.modelId))return"An exact non-empty author/model identifier is required.";if(t.providerId.trim().length===0)return"An exact provider route is required."}function mt(t,n,e,r={}){return cp({runId:t.packet.runId,createdAt:t.packet.createdAt,workspace:t.packet.workspace,sourceHashes:t.packet.sourceHashes,packetHash:t.packet.packetHash,model:t.model,caps:t.caps,recordedAt:n,outcome:e,request:t.request,extra:r})}function ht(t,n,e,r,i,s={}){return{kind:e,reasonCode:r,message:i,audit:mt(t,n,We(e,r,i),s)}}function $O(t,n){if(t.kind==="available")return{kind:"supported",endpoint:hp(t.endpoint),checkedAt:n};let e=t.code==="structured-output-unsupported"?"schema-capability-unsupported":t.code==="provider-unavailable"||t.code==="model-mismatch"?"model-or-provider-mismatch":t.code==="credential-unavailable"?"credential-unavailable":"preflight-failed";return{kind:t.kind==="failed"?"failed":t.kind,reasonCode:e,message:t.message,checkedAt:n}}async function Ko(t){let{identity:n,recordedAt:e}=t,r=OO(n.model)??up(n.caps);if(r!==void 0)return ht(n,e,"blocked","invalid-configuration",r);if(!NO(n.packet))return ht(n,e,"blocked","invalid-provenance","The evidence packet contents do not match its packet hash.");if(t.provenanceError!==void 0)return ht(n,e,"blocked","invalid-provenance",t.provenanceError);let i=await t.transport.preflight({modelId:n.model.modelId,providerSlug:n.model.providerId}),s=$O(i,e);if(s.kind!=="supported")return ht(n,e,s.kind==="failed"?"failed":"blocked",s.reasonCode,s.message,{preflight:s});if(s.endpoint.maxCompletionTokens!==void 0&&n.caps.request.maxOutputTokens>s.endpoint.maxCompletionTokens)return ht(n,e,"blocked","context-limit-exceeded","Requested output cap exceeds the exact endpoint limit.",{preflight:s});if(n.model.reasoningEffort!==void 0&&n.model.reasoningEffort!=="none"&&!s.endpoint.supportedParameters.includes("reasoning"))return ht(n,e,"blocked","schema-capability-unsupported","The exact endpoint does not support the requested reasoning effort.",{preflight:s});let a=t.buildPayload(n.caps.request.maxOutputTokens),o=Fo(a.canonicalBody,n.caps.request.maxOutputTokens,s.endpoint.pricing);if(o===void 0)return ht(n,e,"blocked","pricing-unavailable","A conservative dollar estimate could not be derived from endpoint pricing.",{preflight:s});let d=Ap(a,o),c=Fo(d.canonicalBody,n.caps.request.maxOutputTokens,s.endpoint.pricing);if(c===void 0)return ht(n,e,"blocked","estimate-unavailable","A conservative final request estimate could not be computed.",{preflight:s});if(c.estimatedInputTokens+c.estimatedOutputTokens>s.endpoint.contextLength||s.endpoint.maxPromptTokens!==void 0&&c.estimatedInputTokens>s.endpoint.maxPromptTokens)return ht(n,e,"blocked","context-limit-exceeded","The conservative request estimate exceeds the exact endpoint context limit.",{preflight:s,estimate:c});let l=pp(c,n.caps);if(l.kind==="blocked")return ht(n,e,"blocked",l.reasonCode,l.message,{preflight:s,estimate:c});let u={manifest:d.manifest,manifestHash:d.manifestHash,endpoint:s.endpoint,estimate:c,caps:n.caps},p=jo(u);return{kind:"ready",prepared:{preflight:s,preparedAt:e,payload:d,estimate:c,preview:op(u,p),authorizationBindingHash:p}}}function DO(t){return t.code==="credential-unavailable"?"credential-unavailable":"transport-failed"}async function Wo(t){let{identity:n,prepared:e,recordedAt:r}=t,i={payloadHash:e.payload.payloadHash,payloadManifestHash:e.payload.manifestHash,authorizationBindingHash:e.authorizationBindingHash,preflight:e.preflight,estimate:e.estimate},s=(f,h,m,g={})=>ht(n,r,f,h,m,{...i,...g}),a=jo({manifest:e.payload.manifest,manifestHash:e.payload.manifestHash,endpoint:e.preflight.endpoint,estimate:e.estimate,caps:n.caps});if(ue(e.payload.body)!==e.payload.canonicalBody||L(e.payload.body)!==e.payload.payloadHash||e.payload.manifest.payloadHash!==e.payload.payloadHash||L(e.payload.manifest)!==e.payload.manifestHash||!t.inputsIntact||a!==e.authorizationBindingHash||!dp(t.authorization,a))return s("blocked","authorization-mismatch","Authorization does not match the exact prepared request.");if(!t.authorizationStore.consume(t.authorization.authorizationId,e.authorizationBindingHash))return s("blocked","authorization-replayed","Authorization has already been consumed for this prepared request.");let d=await t.transport.complete({route:{modelId:n.model.modelId,providerSlug:n.model.providerId},body:e.payload.body}),c={mode:t.authorization.mode,authorizationId:t.authorization.authorizationId,authorizedAt:t.authorization.authorizedAt};if(d.kind==="failed")return s("failed",DO(d),d.message,{authorization:c,latencyMs:d.elapsedMs});let l=Db(d.body,t.label,t.validate);if(l.kind!=="parsed")return s("rejected",l.kind,l.message,{authorization:c,latencyMs:d.elapsedMs});let u=l.value.usage===void 0?{}:{usage:l.value.usage};if(l.value.reportedModel!==n.model.modelId)return s("rejected","routed-model-mismatch","Reported model differs from the authorized model.",{authorization:c,reportedModel:l.value.reportedModel,...l.value.reportedProvider===void 0?{}:{reportedProvider:l.value.reportedProvider},latencyMs:d.elapsedMs,...u});if(l.value.reportedProvider===void 0)return s("rejected","routed-provider-mismatch","The completion response did not report the selected provider route.",{authorization:c,reportedModel:l.value.reportedModel,providerProvenance:"unavailable",latencyMs:d.elapsedMs,...u});let p=l.value.reportedProvider.toLocaleLowerCase("en-US");return p!==n.model.providerId.toLocaleLowerCase("en-US")&&p!==e.preflight.endpoint.providerName?.toLocaleLowerCase("en-US")?s("rejected","routed-provider-mismatch","Reported provider differs from the authorized provider.",{authorization:c,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",latencyMs:d.elapsedMs,...u}):{kind:"parsed",output:l.value.output,audit:{...i,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",...u,latencyMs:d.elapsedMs,authorization:c}}}var LO={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function Fb(t){return t??new Date().toISOString()}function Bb(t,n){return L({packet:t,symptoms:n})}function Hb(t){return{packet:t.packet,model:t.model,caps:t.caps,request:LO}}async function Jo(t){let n=Fb(t.now),e=t.symptoms.runId===t.packet.runId&&t.clusters.runId===t.packet.runId&&t.symptoms.packetHash===t.packet.packetHash,r=await Ko({identity:Hb(t),transport:t.transport,recordedAt:n,...e?{}:{provenanceError:"M2 and M3 inputs do not identify the same run and packet."},buildPayload:i=>Ip(t.packet,t.symptoms,t.clusters,t.model,i)});return r.kind!=="ready"?{...r,kind:r.kind==="failed"?"failed":"blocked"}:{kind:"preview-ready",prepared:{packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,model:t.model,caps:t.caps,...r.prepared,gradingInputHash:Bb(t.packet,t.symptoms)}}}async function Tp(t){let n=Fb(t.now),e=t.prepared,r=Hb(e),i=await Wo({identity:r,prepared:e,inputsIntact:Bb(e.packet,e.symptoms)===e.gradingInputHash,authorization:t.authorization,authorizationStore:t.authorizationStore,transport:t.transport,recordedAt:n,label:"diagnosis",validate:d=>{let c=Uo(d);return c.kind==="valid"?{kind:"valid",output:c.diagnosis}:{kind:"invalid",message:`Diagnosis failed strict schema validation: ${c.issues.map(l=>`${l.path}:${l.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=i.output,a=ds(s,e.packet,e.symptoms),o={...i.audit,grading:a};if(!a.passed){let d="Diagnosis failed deterministic local grading.";return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:d,audit:mt(r,n,We("rejected","citation-or-grading-invalid",d),o)}}return s.status==="inconclusive"?{kind:"abstained",reasonCode:"insufficient-evidence",diagnosis:s,grading:a,audit:mt(r,n,We("abstained","insufficient-evidence"),o)}:{kind:"diagnosed",diagnosis:s,grading:a,audit:mt(r,n,We("diagnosed"),o)}}var Pp=20,Yo={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},zb=["targetEvidenceId","oldText","newText","rationale","evidenceIds","expectedEffect","latencyContractEvidenceIds","brittleLocatorEvidenceIds"],Vb=["statement","preservedBehavior","evidenceIds"],Ub=["status","acceptedHypothesisId","declineReason","intent","replacements","packetHash"],Sp={type:"object",additionalProperties:!1,required:Ub,properties:{status:{type:"string",enum:["proposed","declined"]},acceptedHypothesisId:{type:"string",minLength:1},declineReason:{type:"string"},intent:{type:"object",additionalProperties:!1,required:Vb,properties:{statement:{type:"string"},preservedBehavior:{type:"string"},evidenceIds:Yo}},replacements:{type:"array",maxItems:Pp,items:{type:"object",additionalProperties:!1,required:zb,properties:{targetEvidenceId:{type:"string",minLength:1},oldText:{type:"string",minLength:1},newText:{type:"string"},rationale:{type:"string",minLength:1},evidenceIds:Yo,expectedEffect:{type:"string",minLength:1},latencyContractEvidenceIds:Yo,brittleLocatorEvidenceIds:Yo}}},packetHash:{type:"string",minLength:1}}},MO=new Set(["proposed","declined"]);function Xo(t,n,e){if(typeof t=="string")return t;de(e,n,"expected-string","expected a string")}function _O(t,n,e){let r=`$.replacements[${n}]`;if(!Wr(t)){de(e,r,"expected-object","replacement must be an object");return}Jr(t,zb,r,e);let i=Be(t.targetEvidenceId,`${r}.targetEvidenceId`,e),s=Be(t.oldText,`${r}.oldText`,e),a=Xo(t.newText,`${r}.newText`,e),o=Be(t.rationale,`${r}.rationale`,e),d=rt(t.evidenceIds,`${r}.evidenceIds`,e),c=Be(t.expectedEffect,`${r}.expectedEffect`,e),l=rt(t.latencyContractEvidenceIds,`${r}.latencyContractEvidenceIds`,e),u=rt(t.brittleLocatorEvidenceIds,`${r}.brittleLocatorEvidenceIds`,e);if(d!==void 0&&d.length===0&&de(e,`${r}.evidenceIds`,"support-required","a replacement must cite evidence"),!(i===void 0||s===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0))return{targetEvidenceId:i,oldText:s,newText:a,rationale:o,evidenceIds:d,expectedEffect:c,latencyContractEvidenceIds:l,brittleLocatorEvidenceIds:u}}function Ep(t){let n=[];if(!Wr(t))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"proposal must be an object"}]};Jr(t,Ub,"$",n);let e=Kr(t.status,MO,"$.status",n),r=Be(t.acceptedHypothesisId,"$.acceptedHypothesisId",n),i=Xo(t.declineReason,"$.declineReason",n),s=Be(t.packetHash,"$.packetHash",n),a;if(!Wr(t.intent))de(n,"$.intent","expected-object","intent must be an object");else{Jr(t.intent,Vb,"$.intent",n);let d=Xo(t.intent.statement,"$.intent.statement",n),c=Xo(t.intent.preservedBehavior,"$.intent.preservedBehavior",n),l=rt(t.intent.evidenceIds,"$.intent.evidenceIds",n);d!==void 0&&c!==void 0&&l!==void 0&&(a={statement:d,preservedBehavior:c,evidenceIds:l})}let o=[];return Array.isArray(t.replacements)?(t.replacements.length>Pp&&de(n,"$.replacements","too-many-items","too many replacements"),t.replacements.forEach((d,c)=>{let l=_O(d,c,n);l!==void 0&&o.push(l)})):de(n,"$.replacements","expected-array","expected an array"),e==="proposed"&&a!==void 0&&(o.length===0&&Array.isArray(t.replacements)&&de(n,"$.replacements","support-required","a proposal needs a replacement"),a.statement.trim()===""&&de(n,"$.intent.statement","empty-string","a proposal must state its intent"),a.preservedBehavior.trim()===""&&de(n,"$.intent.preservedBehavior","empty-string","a proposal must state the preserved behavior"),a.evidenceIds.length===0&&de(n,"$.intent.evidenceIds","support-required","intent must cite evidence")),e==="declined"&&(i!==void 0&&i.trim()===""&&de(n,"$.declineReason","empty-string","a decline must give its reason"),Array.isArray(t.replacements)&&t.replacements.length>0&&de(n,"$.replacements","too-many-items","a decline must not propose edits")),n.length>0||e===void 0||r===void 0||i===void 0||a===void 0||s===void 0?{kind:"invalid",issues:n}:{kind:"valid",proposal:{status:e,acceptedHypothesisId:r,declineReason:i,intent:a,replacements:o,packetHash:s}}}var qb="1.0",Qo="1.1",Zo="1.0",jO={purpose:"repair-proposal",promptVersion:Qo,outputSchemaVersion:Zo},FO=`You propose a minimal repair to end-to-end test-support code for one accepted, test-side diagnosis. The framework field says whether the code is Playwright, Cypress, or WebdriverIO; write idiomatic code for that framework and its existing style.
205
+ You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Qn(t,n){return[...t].sort((e,r)=>n(e).localeCompare(n(r)))}function EO(t){return{gitRootAvailable:t.workspace.gitRoot!==void 0,sourceHashes:t.sourceHashes}}function xp(t){return t.replaceAll("\\","/").split("/").filter(Boolean).at(-1)??"<path>"}function jb(t){return t.type==="source-range"||t.type==="diff-hunk"?{...t,path:xp(t.path)}:t.type==="report-field"?{...t,path:t.path.startsWith("/")?xp(t.path):t.path}:t}function vp(t){return Qn(t,n=>n.artifactId).map(n=>({artifactId:n.artifactId,channel:n.channel,availability:n.availability,...n.sha256===void 0?{}:{sha256:n.sha256},...n.format===void 0?{}:{format:n.format},...n.producerVersion===void 0?{}:{producerVersion:n.producerVersion},...n.attemptId===void 0?{}:{attemptId:n.attemptId},warnings:n.warnings}))}function kp(t){return Qn(t,n=>n.evidenceId).map(n=>({...n,locator:jb(n.locator)}))}function CO(t){return Qn(t.omissions,n=>n.omissionId).map(n=>({omissionId:n.omissionId,channel:n.channel,reason:n.reason,message:n.message,...n.locator===void 0?{}:{locator:xp(n.locator)},...n.cap===void 0?{}:{cap:n.cap}}))}function NO(t,n,e){return{requestSchemaVersion:"1.0",promptVersion:"1.3",outputSchemaVersion:"1.0",runId:t.runId,packetHash:t.packetHash,framework:t.framework??"playwright",workspace:EO(t),artifacts:vp(t.artifacts),evidence:kp(t.evidence),omissions:CO(t),accounting:Qn(t.accounting,r=>r.channel),symptoms:Qn(n.symptoms,r=>r.symptomId),unclassifiedAttemptIds:[...n.unclassifiedAttemptIds].sort(),clusters:Qn(e.clusters,r=>r.clusterId)}}function OO(t,n,e,r,i){let s=new Map(t.artifacts.map(o=>[o.artifactId,o.channel])),a=new Set(n.artifactIds);return{schemaVersion:"1.1",runId:t.runId,packetHash:t.packetHash,payloadHash:r,purpose:n.purpose,model:e,promptVersion:n.promptVersion,outputSchemaVersion:n.outputSchemaVersion,evidence:Qn(n.evidence,o=>o.evidenceId).map(o=>({evidenceId:o.evidenceId,artifactId:o.artifactId,channel:s.get(o.artifactId)??"report",locator:jb(o.locator),...o.logicalTestId===void 0?{}:{logicalTestId:o.logicalTestId},...o.attemptId===void 0?{}:{attemptId:o.attemptId},redactionIds:[...o.redactionIds].sort()})),artifactIds:[...n.artifactIds].sort(),symptomIds:[...n.symptomIds].sort(),clusterIds:[...n.clusterIds].sort(),omissionIds:[...n.omissionIds].sort(),redactionIds:[...n.redactionIds].sort(),channels:[...new Set(t.artifacts.filter(o=>a.has(o.artifactId)).map(o=>o.channel))].sort(),serializedBytes:i}}function Rp(t,n,e,r){let i={model:e.modelId,messages:[{role:"system",content:n.systemPrompt},{role:"user",content:ue(n.userContent)}],max_completion_tokens:r,...e.reasoningEffort===void 0?{}:{reasoning:{effort:e.reasoningEffort,exclude:!0}},response_format:{type:"json_schema",json_schema:{name:n.schemaName,strict:!0,schema:Mb(n.schema,e.modelId)}},provider:{only:[e.providerId],allow_fallbacks:!1,require_parameters:!0,...e.zeroDataRetention===!0?{zdr:!0}:{},max_price:{prompt:0,completion:0,request:0}}},s=ue(i),a=L(i);return{body:i,canonicalBody:s,payloadHash:a,manifest:OO(t,n,e,a,Buffer.byteLength(s,"utf8")),manifestHash:""}}function Ip(t,n,e,r,i){return Rp(t,{purpose:"diagnosis",schemaName:"kwikqa_diagnosis",schema:bp,systemPrompt:SO,promptVersion:"1.3",outputSchemaVersion:"1.0",userContent:NO(t,n,e),evidence:t.evidence,artifactIds:t.artifacts.map(s=>s.artifactId),symptomIds:n.symptoms.map(s=>s.symptomId),clusterIds:e.clusters.map(s=>s.clusterId),omissionIds:t.omissions.map(s=>s.omissionId),redactionIds:t.redactions.map(s=>s.redactionId)},r,i)}function Ap(t,n){let e={...t.body,provider:{...t.body.provider,max_price:{prompt:n.promptDollarsPerToken*1e6,completion:n.completionDollarsPerToken*1e6,request:n.fixedRequestDollars}}},r=ue(e),i=L(e),s={...t.manifest,payloadHash:i,serializedBytes:Buffer.byteLength(r,"utf8")};return{body:e,canonicalBody:r,payloadHash:i,manifest:s,manifestHash:L(s)}}function $O(t){let{packetHash:n,...e}=t;return Ir(e)===n}function DO(t){if(!/^[^/\s]+\/[^/\s]+$/.test(t.modelId))return"An exact non-empty author/model identifier is required.";if(t.providerId.trim().length===0)return"An exact provider route is required."}function mt(t,n,e,r={}){return cp({runId:t.packet.runId,createdAt:t.packet.createdAt,workspace:t.packet.workspace,sourceHashes:t.packet.sourceHashes,packetHash:t.packet.packetHash,model:t.model,caps:t.caps,recordedAt:n,outcome:e,request:t.request,extra:r})}function ht(t,n,e,r,i,s={}){return{kind:e,reasonCode:r,message:i,audit:mt(t,n,We(e,r,i),s)}}function LO(t,n){if(t.kind==="available")return{kind:"supported",endpoint:hp(t.endpoint),checkedAt:n};let e=t.code==="structured-output-unsupported"?"schema-capability-unsupported":t.code==="provider-unavailable"||t.code==="model-mismatch"?"model-or-provider-mismatch":t.code==="credential-unavailable"?"credential-unavailable":"preflight-failed";return{kind:t.kind==="failed"?"failed":t.kind,reasonCode:e,message:t.message,checkedAt:n}}async function Ko(t){let{identity:n,recordedAt:e}=t,r=DO(n.model)??up(n.caps);if(r!==void 0)return ht(n,e,"blocked","invalid-configuration",r);if(!$O(n.packet))return ht(n,e,"blocked","invalid-provenance","The evidence packet contents do not match its packet hash.");if(t.provenanceError!==void 0)return ht(n,e,"blocked","invalid-provenance",t.provenanceError);let i=await t.transport.preflight({modelId:n.model.modelId,providerSlug:n.model.providerId}),s=LO(i,e);if(s.kind!=="supported")return ht(n,e,s.kind==="failed"?"failed":"blocked",s.reasonCode,s.message,{preflight:s});if(s.endpoint.maxCompletionTokens!==void 0&&n.caps.request.maxOutputTokens>s.endpoint.maxCompletionTokens)return ht(n,e,"blocked","context-limit-exceeded","Requested output cap exceeds the exact endpoint limit.",{preflight:s});if(n.model.reasoningEffort!==void 0&&n.model.reasoningEffort!=="none"&&!s.endpoint.supportedParameters.includes("reasoning"))return ht(n,e,"blocked","schema-capability-unsupported","The exact endpoint does not support the requested reasoning effort.",{preflight:s});let a=t.buildPayload(n.caps.request.maxOutputTokens),o=Fo(a.canonicalBody,n.caps.request.maxOutputTokens,s.endpoint.pricing);if(o===void 0)return ht(n,e,"blocked","pricing-unavailable","A conservative dollar estimate could not be derived from endpoint pricing.",{preflight:s});let d=Ap(a,o),c=Fo(d.canonicalBody,n.caps.request.maxOutputTokens,s.endpoint.pricing);if(c===void 0)return ht(n,e,"blocked","estimate-unavailable","A conservative final request estimate could not be computed.",{preflight:s});if(c.estimatedInputTokens+c.estimatedOutputTokens>s.endpoint.contextLength||s.endpoint.maxPromptTokens!==void 0&&c.estimatedInputTokens>s.endpoint.maxPromptTokens)return ht(n,e,"blocked","context-limit-exceeded","The conservative request estimate exceeds the exact endpoint context limit.",{preflight:s,estimate:c});let l=pp(c,n.caps);if(l.kind==="blocked")return ht(n,e,"blocked",l.reasonCode,l.message,{preflight:s,estimate:c});let u={manifest:d.manifest,manifestHash:d.manifestHash,endpoint:s.endpoint,estimate:c,caps:n.caps},p=jo(u);return{kind:"ready",prepared:{preflight:s,preparedAt:e,payload:d,estimate:c,preview:op(u,p),authorizationBindingHash:p}}}function MO(t){return t.code==="credential-unavailable"?"credential-unavailable":"transport-failed"}async function Wo(t){let{identity:n,prepared:e,recordedAt:r}=t,i={payloadHash:e.payload.payloadHash,payloadManifestHash:e.payload.manifestHash,authorizationBindingHash:e.authorizationBindingHash,preflight:e.preflight,estimate:e.estimate},s=(f,h,m,g={})=>ht(n,r,f,h,m,{...i,...g}),a=jo({manifest:e.payload.manifest,manifestHash:e.payload.manifestHash,endpoint:e.preflight.endpoint,estimate:e.estimate,caps:n.caps});if(ue(e.payload.body)!==e.payload.canonicalBody||L(e.payload.body)!==e.payload.payloadHash||e.payload.manifest.payloadHash!==e.payload.payloadHash||L(e.payload.manifest)!==e.payload.manifestHash||!t.inputsIntact||a!==e.authorizationBindingHash||!dp(t.authorization,a))return s("blocked","authorization-mismatch","Authorization does not match the exact prepared request.");if(!t.authorizationStore.consume(t.authorization.authorizationId,e.authorizationBindingHash))return s("blocked","authorization-replayed","Authorization has already been consumed for this prepared request.");let d=await t.transport.complete({route:{modelId:n.model.modelId,providerSlug:n.model.providerId},body:e.payload.body}),c={mode:t.authorization.mode,authorizationId:t.authorization.authorizationId,authorizedAt:t.authorization.authorizedAt};if(d.kind==="failed")return s("failed",MO(d),d.message,{authorization:c,latencyMs:d.elapsedMs});let l=Db(d.body,t.label,t.validate);if(l.kind!=="parsed")return s("rejected",l.kind,l.message,{authorization:c,latencyMs:d.elapsedMs});let u=l.value.usage===void 0?{}:{usage:l.value.usage};if(l.value.reportedModel!==n.model.modelId)return s("rejected","routed-model-mismatch","Reported model differs from the authorized model.",{authorization:c,reportedModel:l.value.reportedModel,...l.value.reportedProvider===void 0?{}:{reportedProvider:l.value.reportedProvider},latencyMs:d.elapsedMs,...u});if(l.value.reportedProvider===void 0)return s("rejected","routed-provider-mismatch","The completion response did not report the selected provider route.",{authorization:c,reportedModel:l.value.reportedModel,providerProvenance:"unavailable",latencyMs:d.elapsedMs,...u});let p=l.value.reportedProvider.toLocaleLowerCase("en-US");return p!==n.model.providerId.toLocaleLowerCase("en-US")&&p!==e.preflight.endpoint.providerName?.toLocaleLowerCase("en-US")?s("rejected","routed-provider-mismatch","Reported provider differs from the authorized provider.",{authorization:c,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",latencyMs:d.elapsedMs,...u}):{kind:"parsed",output:l.value.output,audit:{...i,reportedModel:l.value.reportedModel,reportedProvider:l.value.reportedProvider,providerProvenance:"reported",...u,latencyMs:d.elapsedMs,authorization:c}}}var _O={purpose:"diagnosis",promptVersion:"1.3",outputSchemaVersion:"1.0"};function Fb(t){return t??new Date().toISOString()}function Bb(t,n){return L({packet:t,symptoms:n})}function Hb(t){return{packet:t.packet,model:t.model,caps:t.caps,request:_O}}async function Jo(t){let n=Fb(t.now),e=t.symptoms.runId===t.packet.runId&&t.clusters.runId===t.packet.runId&&t.symptoms.packetHash===t.packet.packetHash,r=await Ko({identity:Hb(t),transport:t.transport,recordedAt:n,...e?{}:{provenanceError:"M2 and M3 inputs do not identify the same run and packet."},buildPayload:i=>Ip(t.packet,t.symptoms,t.clusters,t.model,i)});return r.kind!=="ready"?{...r,kind:r.kind==="failed"?"failed":"blocked"}:{kind:"preview-ready",prepared:{packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,model:t.model,caps:t.caps,...r.prepared,gradingInputHash:Bb(t.packet,t.symptoms)}}}async function Tp(t){let n=Fb(t.now),e=t.prepared,r=Hb(e),i=await Wo({identity:r,prepared:e,inputsIntact:Bb(e.packet,e.symptoms)===e.gradingInputHash,authorization:t.authorization,authorizationStore:t.authorizationStore,transport:t.transport,recordedAt:n,label:"diagnosis",validate:d=>{let c=Uo(d);return c.kind==="valid"?{kind:"valid",output:c.diagnosis}:{kind:"invalid",message:`Diagnosis failed strict schema validation: ${c.issues.map(l=>`${l.path}:${l.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=i.output,a=ds(s,e.packet,e.symptoms),o={...i.audit,grading:a};if(!a.passed){let d="Diagnosis failed deterministic local grading.";return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:d,audit:mt(r,n,We("rejected","citation-or-grading-invalid",d),o)}}return s.status==="inconclusive"?{kind:"abstained",reasonCode:"insufficient-evidence",diagnosis:s,grading:a,audit:mt(r,n,We("abstained","insufficient-evidence"),o)}:{kind:"diagnosed",diagnosis:s,grading:a,audit:mt(r,n,We("diagnosed"),o)}}var Pp=20,Yo={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},zb=["targetEvidenceId","oldText","newText","rationale","evidenceIds","expectedEffect","latencyContractEvidenceIds","brittleLocatorEvidenceIds"],Vb=["statement","preservedBehavior","evidenceIds"],Ub=["status","acceptedHypothesisId","declineReason","intent","replacements","packetHash"],Sp={type:"object",additionalProperties:!1,required:Ub,properties:{status:{type:"string",enum:["proposed","declined"]},acceptedHypothesisId:{type:"string",minLength:1},declineReason:{type:"string"},intent:{type:"object",additionalProperties:!1,required:Vb,properties:{statement:{type:"string"},preservedBehavior:{type:"string"},evidenceIds:Yo}},replacements:{type:"array",maxItems:Pp,items:{type:"object",additionalProperties:!1,required:zb,properties:{targetEvidenceId:{type:"string",minLength:1},oldText:{type:"string",minLength:1},newText:{type:"string"},rationale:{type:"string",minLength:1},evidenceIds:Yo,expectedEffect:{type:"string",minLength:1},latencyContractEvidenceIds:Yo,brittleLocatorEvidenceIds:Yo}}},packetHash:{type:"string",minLength:1}}},jO=new Set(["proposed","declined"]);function Xo(t,n,e){if(typeof t=="string")return t;de(e,n,"expected-string","expected a string")}function FO(t,n,e){let r=`$.replacements[${n}]`;if(!Wr(t)){de(e,r,"expected-object","replacement must be an object");return}Jr(t,zb,r,e);let i=Be(t.targetEvidenceId,`${r}.targetEvidenceId`,e),s=Be(t.oldText,`${r}.oldText`,e),a=Xo(t.newText,`${r}.newText`,e),o=Be(t.rationale,`${r}.rationale`,e),d=rt(t.evidenceIds,`${r}.evidenceIds`,e),c=Be(t.expectedEffect,`${r}.expectedEffect`,e),l=rt(t.latencyContractEvidenceIds,`${r}.latencyContractEvidenceIds`,e),u=rt(t.brittleLocatorEvidenceIds,`${r}.brittleLocatorEvidenceIds`,e);if(d!==void 0&&d.length===0&&de(e,`${r}.evidenceIds`,"support-required","a replacement must cite evidence"),!(i===void 0||s===void 0||a===void 0||o===void 0||d===void 0||c===void 0||l===void 0||u===void 0))return{targetEvidenceId:i,oldText:s,newText:a,rationale:o,evidenceIds:d,expectedEffect:c,latencyContractEvidenceIds:l,brittleLocatorEvidenceIds:u}}function Ep(t){let n=[];if(!Wr(t))return{kind:"invalid",issues:[{path:"$",code:"expected-object",message:"proposal must be an object"}]};Jr(t,Ub,"$",n);let e=Kr(t.status,jO,"$.status",n),r=Be(t.acceptedHypothesisId,"$.acceptedHypothesisId",n),i=Xo(t.declineReason,"$.declineReason",n),s=Be(t.packetHash,"$.packetHash",n),a;if(!Wr(t.intent))de(n,"$.intent","expected-object","intent must be an object");else{Jr(t.intent,Vb,"$.intent",n);let d=Xo(t.intent.statement,"$.intent.statement",n),c=Xo(t.intent.preservedBehavior,"$.intent.preservedBehavior",n),l=rt(t.intent.evidenceIds,"$.intent.evidenceIds",n);d!==void 0&&c!==void 0&&l!==void 0&&(a={statement:d,preservedBehavior:c,evidenceIds:l})}let o=[];return Array.isArray(t.replacements)?(t.replacements.length>Pp&&de(n,"$.replacements","too-many-items","too many replacements"),t.replacements.forEach((d,c)=>{let l=FO(d,c,n);l!==void 0&&o.push(l)})):de(n,"$.replacements","expected-array","expected an array"),e==="proposed"&&a!==void 0&&(o.length===0&&Array.isArray(t.replacements)&&de(n,"$.replacements","support-required","a proposal needs a replacement"),a.statement.trim()===""&&de(n,"$.intent.statement","empty-string","a proposal must state its intent"),a.preservedBehavior.trim()===""&&de(n,"$.intent.preservedBehavior","empty-string","a proposal must state the preserved behavior"),a.evidenceIds.length===0&&de(n,"$.intent.evidenceIds","support-required","intent must cite evidence")),e==="declined"&&(i!==void 0&&i.trim()===""&&de(n,"$.declineReason","empty-string","a decline must give its reason"),Array.isArray(t.replacements)&&t.replacements.length>0&&de(n,"$.replacements","too-many-items","a decline must not propose edits")),n.length>0||e===void 0||r===void 0||i===void 0||a===void 0||s===void 0?{kind:"invalid",issues:n}:{kind:"valid",proposal:{status:e,acceptedHypothesisId:r,declineReason:i,intent:a,replacements:o,packetHash:s}}}var qb="1.0",Qo="1.1",Zo="1.0",BO={purpose:"repair-proposal",promptVersion:Qo,outputSchemaVersion:Zo},HO=`You propose a minimal repair to end-to-end test-support code for one accepted, test-side diagnosis. The framework field says whether the code is Playwright, Cypress, or WebdriverIO; write idiomatic code for that framework and its existing style.
206
206
  Edit only source excerpts listed in targetEvidenceIds. Each oldText must be copied exactly from that excerpt's text and identify one place to change.
207
207
  Cite only supplied evidence IDs. State the test's intent and the behavior every edit preserves, citing evidence for it; the intent may cite only the accepted hypothesis's supportingEvidenceIds, and a proposal whose intent cites anything else is rejected.
208
208
  Never skip, focus, or mark tests as expected to fail (test.skip, it.only, xit, describe.skip, fixme); never add fixed sleeps (waitForTimeout, cy.wait with a number, browser.pause), retries, or error swallowing, including a Cypress uncaught:exception handler that returns false; never pass force: true to bypass Cypress actionability checks; never remove or weaken an assertion (expect, should, and, assert); never regenerate snapshots to accept current output.
209
209
  Increase a timeout only with cited evidence of a legitimate latency contract, and replace a semantic locator with a brittle selector only with cited evidence that requires it.
210
210
  Stay within the file and line budget. If no edit can repair the accepted cause while preserving intent, decline and explain why.
211
- You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Gb(t){return t??new Date().toISOString()}function Kb(t){return{packet:t.packet,model:t.model,caps:t.caps,request:jO}}function BO(t){return t.locator.type==="source-range"?t.locator.path:void 0}function HO(t){let{packet:n,diagnosis:e,grading:r}=t;if(!r.passed||r.packetHash!==n.packetHash||e.packetHash!==n.packetHash)return{message:"The diagnosis did not pass local grading for this evidence packet."};if(e.status==="inconclusive"||e.repairEligibility!=="eligible")return{message:"The diagnosis does not declare a repair-eligible cause."};let i=e.hypotheses.find(s=>s.hypothesisId===t.hypothesisId);return i===void 0||i.rank!==1?{message:"Only the rank-1 hypothesis of a graded diagnosis can be repaired."}:i.probableOwner!=="test-support"?{message:"The accepted hypothesis is not owned by test support."}:i.evidenceGrade!=="strong"&&i.evidenceGrade!=="moderate"||e.ownershipEvidenceIds.length===0?{message:"Test-side ownership is not supported by cited positive evidence."}:{hypothesis:i}}function Wb(t){return L({packet:t.packet,diagnosis:t.diagnosis,hypothesisId:t.hypothesisId,targetEvidenceIds:t.targetEvidenceIds,budgets:t.budgets})}async function Cp(t){let n=Gb(t.now),e=Kb(t),r=HO(t);if("message"in r)return{kind:"blocked",reasonCode:"repair-not-eligible",message:r.message,audit:mt(e,n,We("blocked","repair-not-eligible",r.message))};let{packet:i,diagnosis:s}=t,a=new Set(t.editablePaths),o=new Set([...r.hypothesis.supportingEvidenceIds,...r.hypothesis.contradictingEvidenceIds,...s.ownershipEvidenceIds]),d=i.evidence.filter(g=>o.has(g.evidenceId)||g.kind==="source-range"),l=d.filter(g=>{let y=BO(g);return y!==void 0&&a.has(y)}).map(g=>g.evidenceId).sort();if(l.length===0){let g="No source excerpt in the evidence packet is an authorized repair target.";return{kind:"blocked",reasonCode:"repair-not-eligible",message:g,audit:mt(e,n,We("blocked","repair-not-eligible",g))}}let u=new Set(d.map(g=>g.artifactId)),p=i.artifacts.filter(g=>u.has(g.artifactId)),f=[...new Set(d.flatMap(g=>g.redactionIds))],h=await Ko({identity:e,transport:t.transport,recordedAt:n,buildPayload:g=>Rp(i,{purpose:"repair-proposal",schemaName:"kwikqa_repair_proposal",schema:Sp,systemPrompt:FO,promptVersion:Qo,outputSchemaVersion:Zo,userContent:{requestSchemaVersion:qb,promptVersion:Qo,outputSchemaVersion:Zo,runId:i.runId,packetHash:i.packetHash,framework:i.framework??"playwright",acceptedHypothesis:r.hypothesis,diagnosis:{status:s.status,symptomIds:s.symptomIds,ownershipEvidenceIds:s.ownershipEvidenceIds,recommendedNextAction:s.recommendedNextAction},budgets:t.budgets,targetEvidenceIds:l,artifacts:vp(p),evidence:kp(d)},evidence:d,artifactIds:[...u],symptomIds:s.symptomIds,clusterIds:[],omissionIds:[],redactionIds:f},t.model,g)});if(h.kind!=="ready")return{...h,kind:h.kind==="failed"?"failed":"blocked"};let m={packet:i,diagnosis:s,hypothesisId:t.hypothesisId,targetEvidenceIds:l,budgets:t.budgets};return{kind:"preview-ready",prepared:{...h.prepared,...m,includedEvidenceIds:d.map(g=>g.evidenceId).sort(),model:t.model,caps:t.caps,inputHash:Wb(m)}}}function zO(t){let n=t.observation.indexOf(`
212
- `);return n===-1?"":t.observation.slice(n+1)}function VO(t,n){let e=[],r=new Set(t.includedEvidenceIds),i=new Set(t.targetEvidenceIds),s=new Map(t.packet.evidence.map(d=>[d.evidenceId,d])),a=(d,c)=>{for(let l of d)r.has(l)||e.push(`${c} cites evidence that was not supplied: ${l}`)};n.packetHash!==t.packet.packetHash&&e.push("The proposal names a different evidence packet."),n.acceptedHypothesisId!==t.hypothesisId&&e.push("The proposal names a different hypothesis than the accepted one."),a(n.intent.evidenceIds,"intent");let o=[];return n.replacements.forEach((d,c)=>{let l=`replacement ${c+1}`;a(d.evidenceIds,l),a(d.latencyContractEvidenceIds,l),a(d.brittleLocatorEvidenceIds,l);let u=s.get(d.targetEvidenceId);if(u===void 0||!i.has(d.targetEvidenceId)||u.locator.type!=="source-range"){e.push(`${l} targets an excerpt that is not an authorized repair target.`);return}if(!zO(u).includes(d.oldText)){e.push(`${l} replaces text that does not appear in its cited excerpt.`);return}o.push({path:u.locator.path,sourceSha256:u.locator.sha256,oldText:d.oldText,newText:d.newText,rationale:d.rationale,evidenceIds:d.evidenceIds,expectedEffect:d.expectedEffect,...d.latencyContractEvidenceIds.length===0?{}:{latencyContractEvidenceIds:d.latencyContractEvidenceIds},...d.brittleLocatorEvidenceIds.length===0?{}:{brittleLocatorEvidenceIds:d.brittleLocatorEvidenceIds}})}),e.length>0?{problems:e}:{draft:{acceptedHypothesisId:n.acceptedHypothesisId,intent:n.intent,replacements:o}}}async function Np(t){let n=Gb(t.now),e=t.prepared,r=Kb(e),i=await Wo({identity:r,prepared:e,inputsIntact:Wb(e)===e.inputHash,authorization:t.authorization,authorizationStore:t.authorizationStore,transport:t.transport,recordedAt:n,label:"repair proposal",validate:a=>{let o=Ep(a);return o.kind==="valid"?{kind:"valid",output:o.proposal}:{kind:"invalid",message:`Repair proposal failed strict schema validation: ${o.issues.map(d=>`${d.path}:${d.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=VO(e,i.output);if("problems"in s){let a=`Repair proposal failed local checks: ${s.problems.join(" ")}`;return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:a,audit:mt(r,n,We("rejected","citation-or-grading-invalid",a),i.audit)}}return i.output.status==="declined"?{kind:"declined",reasonCode:"model-declined-repair",message:i.output.declineReason,audit:mt(r,n,We("declined","model-declined-repair",i.output.declineReason),i.audit)}:{kind:"proposed",draft:s.draft,audit:mt(r,n,We("proposed"),i.audit)}}var Jb=new Set(["spec","page-object","fixture","test-data","test-helper","playwright-config","framework-config"]),UO=new Set(["schemaVersion","editablePaths","generatedPaths","budgets","ci"]),qO=new Set(["pattern","class"]),GO=new Set(["maxFiles","maxChangedLines"]),KO=new Set(["fix"]),WO=new Set(["pullRequests","maxPullRequestsPerRun","retry"]);function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function ed(t,n=!1){return t.length===0||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[A-Za-z]:/.test(t)||t.split("/").some(r=>r===""||r==="."||r==="..")?!1:t!=="*"&&t!=="**"&&(n||!t.startsWith("**/"))}function JO(t){if(!(!Array.isArray(t)||t.some(n=>typeof n!="string")))return t}function Yb(t,n){return Number.isInteger(t)&&typeof t=="number"&&t>0&&t<=n}function YO(t,n){let e=Is(t);if(e===void 0){n.push("ci must be an object.");return}for(let s of Object.keys(e))KO.has(s)||n.push(`Unknown ci field: ${s}.`);let r=Is(e.fix);if(r===void 0){n.push("ci.fix must be an object.");return}for(let s of Object.keys(r))WO.has(s)||n.push(`Unknown ci.fix field: ${s}.`);let i=n.length;if(r.pullRequests!=="draft"&&n.push('ci.fix.pullRequests must be "draft": KwikQA opens only draft pull requests.'),r.maxPullRequestsPerRun!==void 0&&r.maxPullRequestsPerRun!==1&&n.push("ci.fix.maxPullRequestsPerRun must be 1, the only value so far."),r.retry!==void 0&&typeof r.retry!="boolean"&&n.push("ci.fix.retry must be true or false."),!(n.length>i))return{fix:{pullRequests:"draft",maxPullRequestsPerRun:1,retry:r.retry===!0}}}function Qn(t){let n=Is(t);if(n===void 0)return{kind:"invalid",issues:["Configuration must be an object."]};let e=[];for(let d of Object.keys(n))UO.has(d)||e.push(`Unknown configuration field: ${d}.`);n.schemaVersion!=="1.0"&&e.push(`schemaVersion must be ${"1.0"}.`);let r=n.editablePaths,i=[];if(!Array.isArray(r)||r.length===0)e.push("editablePaths must contain at least one explicit rule.");else for(let[d,c]of r.entries()){let l=Is(c);if(l===void 0){e.push(`editablePaths[${d}] must be an object.`);continue}for(let u of Object.keys(l))qO.has(u)||e.push(`Unknown editablePaths[${d}] field: ${u}.`);(typeof l.pattern!="string"||!ed(l.pattern))&&e.push(`editablePaths[${d}].pattern is unsafe or overly broad.`),(typeof l.class!="string"||!Jb.has(l.class))&&e.push(`editablePaths[${d}].class is invalid.`),typeof l.pattern=="string"&&ed(l.pattern)&&typeof l.class=="string"&&Jb.has(l.class)&&i.push({pattern:l.pattern,class:l.class})}let s=JO(n.generatedPaths);(s===void 0||s.some(d=>!ed(d,!0)))&&e.push("generatedPaths must contain only safe repository-relative patterns.");let a=Is(n.budgets);if(a===void 0)e.push("budgets must be an object.");else{for(let d of Object.keys(a))GO.has(d)||e.push(`Unknown budgets field: ${d}.`);Yb(a.maxFiles,3)||e.push(`budgets.maxFiles must be an integer from 1 to ${3}.`),Yb(a.maxChangedLines,100)||e.push(`budgets.maxChangedLines must be an integer from 1 to ${100}.`)}let o=n.ci===void 0?void 0:YO(n.ci,e);return e.length>0||a===void 0||s===void 0?{kind:"invalid",issues:e}:{kind:"valid",config:{schemaVersion:"1.0",editablePaths:i,generatedPaths:s,budgets:{maxFiles:a.maxFiles,maxChangedLines:a.maxChangedLines},...o===void 0?{}:{ci:o}}}}var Xb={schemaVersion:"1.0",editablePaths:[{pattern:"tests/**/*.ts",class:"spec"},{pattern:"tests/**/*.tsx",class:"spec"}],generatedPaths:["**/*.generated.ts","**/__snapshots__/**"],budgets:{maxFiles:3,maxChangedLines:100}};var XO=[{prefix:"tests/",rules:[{pattern:"tests/**/*.ts",class:"spec"}]},{prefix:"e2e/",rules:[{pattern:"e2e/**/*.ts",class:"spec"}]},{prefix:"cypress/e2e/",rules:[{pattern:"cypress/e2e/**/*.cy.ts",class:"spec"},{pattern:"cypress/e2e/**/*.cy.js",class:"spec"}]},{prefix:"test/specs/",rules:[{pattern:"test/specs/**/*.ts",class:"spec"},{pattern:"test/specs/**/*.js",class:"spec"}]}],QO=[{prefix:"cypress/support/",rule:{pattern:"cypress/support/**/*.ts",class:"test-helper"}},{prefix:"cypress/pages/",rule:{pattern:"cypress/pages/**/*.ts",class:"page-object"}},{prefix:"test/pageobjects/",rule:{pattern:"test/pageobjects/**/*.ts",class:"page-object"}}];function Op(t){let n=t.repositoryPaths.map(a=>a.replaceAll("\\","/")).filter(a=>ed(a)),e=a=>n.some(o=>o.startsWith(a)),r=[];(e("tests/")||e("test/")&&!e("test/specs/"))&&r.push({pattern:"tests/**/*.ts",class:"spec"});for(let a of XO.slice(1))e(a.prefix)&&r.push(...a.rules);let i=[];r.length===0&&i.push("No standard test directory was found."),i.push("Shared support modules require explicit review before authorization.");for(let a of QO)e(a.prefix)&&i.push(`${a.prefix} looks like shared ${a.rule.class==="page-object"?"page objects":"support code"}; add {"pattern": "${a.rule.pattern}", "class": "${a.rule.class}"} to let KwikQA propose fixes there.`);let s={...Xb,editablePaths:r.length===0?Xb.editablePaths:r};return{destination:"kwikqa.config.json",config:s,canonicalContents:`${ue(s)}
211
+ You have no tools, filesystem, shell, repository access, commands, or external lookup. Return only the required JSON object.`;function Gb(t){return t??new Date().toISOString()}function Kb(t){return{packet:t.packet,model:t.model,caps:t.caps,request:BO}}function zO(t){return t.locator.type==="source-range"?t.locator.path:void 0}function VO(t){let{packet:n,diagnosis:e,grading:r}=t;if(!r.passed||r.packetHash!==n.packetHash||e.packetHash!==n.packetHash)return{message:"The diagnosis did not pass local grading for this evidence packet."};if(e.status==="inconclusive"||e.repairEligibility!=="eligible")return{message:"The diagnosis does not declare a repair-eligible cause."};let i=e.hypotheses.find(s=>s.hypothesisId===t.hypothesisId);return i===void 0||i.rank!==1?{message:"Only the rank-1 hypothesis of a graded diagnosis can be repaired."}:i.probableOwner!=="test-support"?{message:"The accepted hypothesis is not owned by test support."}:i.evidenceGrade!=="strong"&&i.evidenceGrade!=="moderate"||e.ownershipEvidenceIds.length===0?{message:"Test-side ownership is not supported by cited positive evidence."}:{hypothesis:i}}function Wb(t){return L({packet:t.packet,diagnosis:t.diagnosis,hypothesisId:t.hypothesisId,targetEvidenceIds:t.targetEvidenceIds,budgets:t.budgets})}async function Cp(t){let n=Gb(t.now),e=Kb(t),r=VO(t);if("message"in r)return{kind:"blocked",reasonCode:"repair-not-eligible",message:r.message,audit:mt(e,n,We("blocked","repair-not-eligible",r.message))};let{packet:i,diagnosis:s}=t,a=new Set(t.editablePaths),o=new Set([...r.hypothesis.supportingEvidenceIds,...r.hypothesis.contradictingEvidenceIds,...s.ownershipEvidenceIds]),d=i.evidence.filter(g=>o.has(g.evidenceId)||g.kind==="source-range"),l=d.filter(g=>{let y=zO(g);return y!==void 0&&a.has(y)}).map(g=>g.evidenceId).sort();if(l.length===0){let g="No source excerpt in the evidence packet is an authorized repair target.";return{kind:"blocked",reasonCode:"repair-not-eligible",message:g,audit:mt(e,n,We("blocked","repair-not-eligible",g))}}let u=new Set(d.map(g=>g.artifactId)),p=i.artifacts.filter(g=>u.has(g.artifactId)),f=[...new Set(d.flatMap(g=>g.redactionIds))],h=await Ko({identity:e,transport:t.transport,recordedAt:n,buildPayload:g=>Rp(i,{purpose:"repair-proposal",schemaName:"kwikqa_repair_proposal",schema:Sp,systemPrompt:HO,promptVersion:Qo,outputSchemaVersion:Zo,userContent:{requestSchemaVersion:qb,promptVersion:Qo,outputSchemaVersion:Zo,runId:i.runId,packetHash:i.packetHash,framework:i.framework??"playwright",acceptedHypothesis:r.hypothesis,diagnosis:{status:s.status,symptomIds:s.symptomIds,ownershipEvidenceIds:s.ownershipEvidenceIds,recommendedNextAction:s.recommendedNextAction},budgets:t.budgets,targetEvidenceIds:l,artifacts:vp(p),evidence:kp(d)},evidence:d,artifactIds:[...u],symptomIds:s.symptomIds,clusterIds:[],omissionIds:[],redactionIds:f},t.model,g)});if(h.kind!=="ready")return{...h,kind:h.kind==="failed"?"failed":"blocked"};let m={packet:i,diagnosis:s,hypothesisId:t.hypothesisId,targetEvidenceIds:l,budgets:t.budgets};return{kind:"preview-ready",prepared:{...h.prepared,...m,includedEvidenceIds:d.map(g=>g.evidenceId).sort(),model:t.model,caps:t.caps,inputHash:Wb(m)}}}function UO(t){let n=t.observation.indexOf(`
212
+ `);return n===-1?"":t.observation.slice(n+1)}function qO(t,n){let e=[],r=new Set(t.includedEvidenceIds),i=new Set(t.targetEvidenceIds),s=new Map(t.packet.evidence.map(d=>[d.evidenceId,d])),a=(d,c)=>{for(let l of d)r.has(l)||e.push(`${c} cites evidence that was not supplied: ${l}`)};n.packetHash!==t.packet.packetHash&&e.push("The proposal names a different evidence packet."),n.acceptedHypothesisId!==t.hypothesisId&&e.push("The proposal names a different hypothesis than the accepted one."),a(n.intent.evidenceIds,"intent");let o=[];return n.replacements.forEach((d,c)=>{let l=`replacement ${c+1}`;a(d.evidenceIds,l),a(d.latencyContractEvidenceIds,l),a(d.brittleLocatorEvidenceIds,l);let u=s.get(d.targetEvidenceId);if(u===void 0||!i.has(d.targetEvidenceId)||u.locator.type!=="source-range"){e.push(`${l} targets an excerpt that is not an authorized repair target.`);return}if(!UO(u).includes(d.oldText)){e.push(`${l} replaces text that does not appear in its cited excerpt.`);return}o.push({path:u.locator.path,sourceSha256:u.locator.sha256,oldText:d.oldText,newText:d.newText,rationale:d.rationale,evidenceIds:d.evidenceIds,expectedEffect:d.expectedEffect,...d.latencyContractEvidenceIds.length===0?{}:{latencyContractEvidenceIds:d.latencyContractEvidenceIds},...d.brittleLocatorEvidenceIds.length===0?{}:{brittleLocatorEvidenceIds:d.brittleLocatorEvidenceIds}})}),e.length>0?{problems:e}:{draft:{acceptedHypothesisId:n.acceptedHypothesisId,intent:n.intent,replacements:o}}}async function Np(t){let n=Gb(t.now),e=t.prepared,r=Kb(e),i=await Wo({identity:r,prepared:e,inputsIntact:Wb(e)===e.inputHash,authorization:t.authorization,authorizationStore:t.authorizationStore,transport:t.transport,recordedAt:n,label:"repair proposal",validate:a=>{let o=Ep(a);return o.kind==="valid"?{kind:"valid",output:o.proposal}:{kind:"invalid",message:`Repair proposal failed strict schema validation: ${o.issues.map(d=>`${d.path}:${d.code}`).join(", ")}`}}});if(i.kind!=="parsed")return i;let s=qO(e,i.output);if("problems"in s){let a=`Repair proposal failed local checks: ${s.problems.join(" ")}`;return{kind:"rejected",reasonCode:"citation-or-grading-invalid",message:a,audit:mt(r,n,We("rejected","citation-or-grading-invalid",a),i.audit)}}return i.output.status==="declined"?{kind:"declined",reasonCode:"model-declined-repair",message:i.output.declineReason,audit:mt(r,n,We("declined","model-declined-repair",i.output.declineReason),i.audit)}:{kind:"proposed",draft:s.draft,audit:mt(r,n,We("proposed"),i.audit)}}var Jb=new Set(["spec","page-object","fixture","test-data","test-helper","playwright-config","framework-config"]),GO=new Set(["schemaVersion","editablePaths","generatedPaths","budgets","ci"]),KO=new Set(["pattern","class"]),WO=new Set(["maxFiles","maxChangedLines"]),JO=new Set(["fix"]),YO=new Set(["pullRequests","maxPullRequestsPerRun","retry"]);function Is(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function ed(t,n=!1){return t.length===0||t.includes("\0")||t.includes("\\")||t.startsWith("/")||/^[A-Za-z]:/.test(t)||t.split("/").some(r=>r===""||r==="."||r==="..")?!1:t!=="*"&&t!=="**"&&(n||!t.startsWith("**/"))}function XO(t){if(!(!Array.isArray(t)||t.some(n=>typeof n!="string")))return t}function Yb(t,n){return Number.isInteger(t)&&typeof t=="number"&&t>0&&t<=n}function QO(t,n){let e=Is(t);if(e===void 0){n.push("ci must be an object.");return}for(let s of Object.keys(e))JO.has(s)||n.push(`Unknown ci field: ${s}.`);let r=Is(e.fix);if(r===void 0){n.push("ci.fix must be an object.");return}for(let s of Object.keys(r))YO.has(s)||n.push(`Unknown ci.fix field: ${s}.`);let i=n.length;if(r.pullRequests!=="draft"&&n.push('ci.fix.pullRequests must be "draft": KwikQA opens only draft pull requests.'),r.maxPullRequestsPerRun!==void 0&&r.maxPullRequestsPerRun!==1&&n.push("ci.fix.maxPullRequestsPerRun must be 1, the only value so far."),r.retry!==void 0&&typeof r.retry!="boolean"&&n.push("ci.fix.retry must be true or false."),!(n.length>i))return{fix:{pullRequests:"draft",maxPullRequestsPerRun:1,retry:r.retry===!0}}}function Zn(t){let n=Is(t);if(n===void 0)return{kind:"invalid",issues:["Configuration must be an object."]};let e=[];for(let d of Object.keys(n))GO.has(d)||e.push(`Unknown configuration field: ${d}.`);n.schemaVersion!=="1.0"&&e.push(`schemaVersion must be ${"1.0"}.`);let r=n.editablePaths,i=[];if(!Array.isArray(r)||r.length===0)e.push("editablePaths must contain at least one explicit rule.");else for(let[d,c]of r.entries()){let l=Is(c);if(l===void 0){e.push(`editablePaths[${d}] must be an object.`);continue}for(let u of Object.keys(l))KO.has(u)||e.push(`Unknown editablePaths[${d}] field: ${u}.`);(typeof l.pattern!="string"||!ed(l.pattern))&&e.push(`editablePaths[${d}].pattern is unsafe or overly broad.`),(typeof l.class!="string"||!Jb.has(l.class))&&e.push(`editablePaths[${d}].class is invalid.`),typeof l.pattern=="string"&&ed(l.pattern)&&typeof l.class=="string"&&Jb.has(l.class)&&i.push({pattern:l.pattern,class:l.class})}let s=XO(n.generatedPaths);(s===void 0||s.some(d=>!ed(d,!0)))&&e.push("generatedPaths must contain only safe repository-relative patterns.");let a=Is(n.budgets);if(a===void 0)e.push("budgets must be an object.");else{for(let d of Object.keys(a))WO.has(d)||e.push(`Unknown budgets field: ${d}.`);Yb(a.maxFiles,3)||e.push(`budgets.maxFiles must be an integer from 1 to ${3}.`),Yb(a.maxChangedLines,100)||e.push(`budgets.maxChangedLines must be an integer from 1 to ${100}.`)}let o=n.ci===void 0?void 0:QO(n.ci,e);return e.length>0||a===void 0||s===void 0?{kind:"invalid",issues:e}:{kind:"valid",config:{schemaVersion:"1.0",editablePaths:i,generatedPaths:s,budgets:{maxFiles:a.maxFiles,maxChangedLines:a.maxChangedLines},...o===void 0?{}:{ci:o}}}}var Xb={schemaVersion:"1.0",editablePaths:[{pattern:"tests/**/*.ts",class:"spec"},{pattern:"tests/**/*.tsx",class:"spec"}],generatedPaths:["**/*.generated.ts","**/__snapshots__/**"],budgets:{maxFiles:3,maxChangedLines:100}};var ZO=[{prefix:"tests/",rules:[{pattern:"tests/**/*.ts",class:"spec"}]},{prefix:"e2e/",rules:[{pattern:"e2e/**/*.ts",class:"spec"}]},{prefix:"cypress/e2e/",rules:[{pattern:"cypress/e2e/**/*.cy.ts",class:"spec"},{pattern:"cypress/e2e/**/*.cy.js",class:"spec"}]},{prefix:"test/specs/",rules:[{pattern:"test/specs/**/*.ts",class:"spec"},{pattern:"test/specs/**/*.js",class:"spec"}]}],e$=[{prefix:"cypress/support/",rule:{pattern:"cypress/support/**/*.ts",class:"test-helper"}},{prefix:"cypress/pages/",rule:{pattern:"cypress/pages/**/*.ts",class:"page-object"}},{prefix:"test/pageobjects/",rule:{pattern:"test/pageobjects/**/*.ts",class:"page-object"}}];function Op(t){let n=t.repositoryPaths.map(a=>a.replaceAll("\\","/")).filter(a=>ed(a)),e=a=>n.some(o=>o.startsWith(a)),r=[];(e("tests/")||e("test/")&&!e("test/specs/"))&&r.push({pattern:"tests/**/*.ts",class:"spec"});for(let a of ZO.slice(1))e(a.prefix)&&r.push(...a.rules);let i=[];r.length===0&&i.push("No standard test directory was found."),i.push("Shared support modules require explicit review before authorization.");for(let a of e$)e(a.prefix)&&i.push(`${a.prefix} looks like shared ${a.rule.class==="page-object"?"page objects":"support code"}; add {"pattern": "${a.rule.pattern}", "class": "${a.rule.class}"} to let KwikQA propose fixes there.`);let s={...Xb,editablePaths:r.length===0?Xb.editablePaths:r};return{destination:"kwikqa.config.json",config:s,canonicalContents:`${ue(s)}
213
213
  `,reasons:r.map(a=>`Observed repository paths matching ${a.pattern}.`),ambiguities:i}}function Qb(t){let e=t.replaceAll(`\r
214
214
  `,`
215
215
  `).split(`
216
- `);return e.at(-1)===""?e.slice(0,-1):e}function ZO(t,n){let e=Array.from({length:t.length+1},()=>Array(n.length+1).fill(0));for(let a=t.length-1;a>=0;a-=1)for(let o=n.length-1;o>=0;o-=1){let d=e[a],c=e[a+1];d===void 0||c===void 0||(d[o]=t[a]===n[o]?(c[o+1]??0)+1:Math.max(c[o]??0,d[o+1]??0))}let r=[],i=0,s=0;for(;i<t.length||s<n.length;)i<t.length&&s<n.length&&t[i]===n[s]?(r.push({kind:"context",text:t[i]??""}),i+=1,s+=1):s<n.length&&(i>=t.length||(e[i]?.[s+1]??0)>(e[i+1]?.[s]??0))?(r.push({kind:"add",text:n[s]??""}),s+=1):(r.push({kind:"delete",text:t[i]??""}),i+=1);return r}function e$(t){let n=Qb(t.source),e=Qb(t.result),r=ZO(n,e),i=r.filter(a=>a.kind!=="context").length;return{text:`${[`diff --git a/${t.path} b/${t.path}`,`--- a/${t.path}`,`+++ b/${t.path}`,`@@ -1,${n.length} +1,${e.length} @@`,...r.map(a=>`${a.kind==="add"?"+":a.kind==="delete"?"-":" "}${a.text}`)].join(`
216
+ `);return e.at(-1)===""?e.slice(0,-1):e}function t$(t,n){let e=Array.from({length:t.length+1},()=>Array(n.length+1).fill(0));for(let a=t.length-1;a>=0;a-=1)for(let o=n.length-1;o>=0;o-=1){let d=e[a],c=e[a+1];d===void 0||c===void 0||(d[o]=t[a]===n[o]?(c[o+1]??0)+1:Math.max(c[o]??0,d[o+1]??0))}let r=[],i=0,s=0;for(;i<t.length||s<n.length;)i<t.length&&s<n.length&&t[i]===n[s]?(r.push({kind:"context",text:t[i]??""}),i+=1,s+=1):s<n.length&&(i>=t.length||(e[i]?.[s+1]??0)>(e[i+1]?.[s]??0))?(r.push({kind:"add",text:n[s]??""}),s+=1):(r.push({kind:"delete",text:t[i]??""}),i+=1);return r}function n$(t){let n=Qb(t.source),e=Qb(t.result),r=t$(n,e),i=r.filter(a=>a.kind!=="context").length;return{text:`${[`diff --git a/${t.path} b/${t.path}`,`--- a/${t.path}`,`+++ b/${t.path}`,`@@ -1,${n.length} +1,${e.length} @@`,...r.map(a=>`${a.kind==="add"?"+":a.kind==="delete"?"-":" "}${a.text}`)].join(`
217
217
  `)}
218
- `,changed:i}}function $p(t){let n=[],e={},r=0;for(let i of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=e$(i);n.push(s.text),e[i.path]=s.changed,r+=s.changed}return{text:n.join(""),changedFiles:t.length,changedLines:r,perFileChangedLines:e}}function Zb(t,n){return t.changedFiles<=n.maxFiles&&t.changedLines<=n.maxChangedLines?[]:[{code:"budget-exceeded",message:`Proposal changes ${t.changedFiles} files and ${t.changedLines} lines; configured limits are ${n.maxFiles} files and ${n.maxChangedLines} lines.`,manualRepairRecommended:!0}]}function ex(t,n,e,r){let i=[];(n.packetHash!==t.packetHash||e.packetHash!==t.packetHash||!e.passed)&&i.push({code:"invalid-provenance",message:"Diagnosis and passing deterministic grading must match the evidence packet."});let s=[...n.hypotheses].sort((d,c)=>d.rank-c.rank)[0],a=new Set(t.evidence.map(d=>d.evidenceId)),o=new Set(n.ownershipEvidenceIds);return(n.repairEligibility!=="eligible"||s===void 0||s.probableOwner!=="test-support"||!new Set(["strong","moderate"]).has(s.evidenceGrade)||o.size===0||[...o].some(d=>!a.has(d)||!s.supportingEvidenceIds.includes(d)))&&i.push({code:"insufficient-ownership-evidence",message:"Repair requires a sufficiently graded test-support hypothesis with positive evidence."}),(r.statement.trim().length===0||r.preservedBehavior.trim().length===0||r.evidenceIds.length===0||r.evidenceIds.some(d=>!a.has(d)||!s?.supportingEvidenceIds.includes(d)))&&i.push({code:"intent-ambiguous",message:"Test intent and preserved behavior require valid positive evidence citations."}),i.length>0||s===void 0?{kind:"rejected",reasons:i}:{kind:"eligible",hypothesis:s}}var tx=Bs(vi(),1),t$=/\.([cm]?[jt]sx?)$/i;function Dp(t,n){let e=t.match(t$)?.[1]?.toLowerCase();if(e===void 0)return!1;let r=[];e.includes("t")&&r.push("typescript"),e.endsWith("x")&&r.push("jsx");try{return(0,tx.parse)(n,{sourceType:"unambiguous",errorRecovery:!1,plugins:r}),!0}catch{return!1}}var n$=[{pattern:/\b(?:test|describe|it|context|specify)\.(?:skip|only|fixme)\s*\(|\bx(?:it|test|describe|context|specify)\s*\(|\bf(?:it|describe)\s*\(/g,message:"skip, focus, and expected-failure controls are forbidden",exception:"never"},{pattern:/\bwaitForTimeout\s*\(|\bcy\.wait\(\s*\d|\.pause\s*\(/g,message:"arbitrary fixed waits are forbidden",exception:"never"},{pattern:/\bforce\s*:\s*true\b/g,message:"forcing actions past actionability checks is forbidden",exception:"never"},{pattern:/uncaught:exception/g,message:"suppressing application errors is forbidden",exception:"never"},{pattern:/\bthis\.retries\s*\(|\bretries\s*\(\s*\d/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\bsetTimeout\s*\(/g,message:"timeout increases require a demonstrated latency contract",exception:"latency"},{pattern:/\bretries\s*:/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\btoMatchSnapshot\s*\(/g,message:"broad snapshot acceptance is forbidden",exception:"never"},{pattern:/catch\s*\([^)]*\)\s*\{\s*\}/g,message:"empty catches swallow errors",exception:"never"},{pattern:/\.locator\(\s*["'`](?:#|\.|\/\/|css=)/g,message:"brittle locator regressions require positive evidence",exception:"locator"},{pattern:/(?:\bcy\.get|\.find|(?<![\w$])\$\$?)\(\s*["'`](?:#|\.[A-Za-z_-]|\/\/|\.\/\/)/g,message:"brittle locator regressions require positive evidence",exception:"locator"}];function As(t,n){return[...t.matchAll(n)].length}function nx(t){return As(t,/\bexpect\s*\(/g)+As(t,/\bassert(?:\.|\s*\()/g)+As(t,/\.(?:should|and)\s*\(/g)}function rx(t){let n=new Map;for(let e of t.matchAll(/\.((?:(?:not|resolves|rejects)\.)*)(to[A-Z]\w*)\s*\(/g)){let r=`${e[1]??""}${e[2]??""}`;n.set(r,(n.get(r)??0)+1)}for(let e of t.matchAll(/\.(?:should|and)\s*\(\s*["'`]([\w.]+)["'`]/g)){let r=`should:${e[1]??""}`;n.set(r,(n.get(r)??0)+1)}return n}function r$(t,n){let e=rx(n);return[...rx(t)].filter(([r,i])=>(e.get(r)??0)<i).map(([r])=>r).sort()}function ix(t){let n=[];for(let e of t){if(!Dp(e.path,e.source)||!Dp(e.path,e.result)){n.push({code:"parse-failed",message:"Original and resulting source must parse as supported JavaScript or TypeScript.",path:e.path});continue}let r=r$(e.source,e.result);r.length>0&&n.push({code:"forbidden-edit",message:`The proposal removes, negates, or swaps assertion matchers: ${r.join(", ")}.`,path:e.path});for(let i of e.replacements){nx(i.newText)<nx(i.oldText)&&n.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let s of n$){if(As(i.newText,s.pattern)<=As(i.oldText,s.pattern))continue;let a=s.exception==="latency"?i.latencyContractEvidenceIds??[]:s.exception==="locator"?i.brittleLocatorEvidenceIds??[]:[];s.exception!=="never"&&a.length>0||n.push({code:"forbidden-edit",message:s.message,path:e.path})}}}return n}var i$=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,s$=/^[A-Z][A-Z0-9_]*$/,a$=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,o$=new Set(["focused","affected","static"]);function sx(t){return t.length>0&&!t.includes("\0")&&!t.includes("\\")&&!t.startsWith("/")&&!/^[A-Za-z]:/.test(t)&&!t.split("/").some(n=>n===".."||n==="")}var d$=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function c$(t){let n=Object.entries(t.environment);return t.id.trim().length>0&&i$.test(t.executable)&&sx(t.executable.replace(/^\.\//,""))&&!t.args.some(e=>e.includes("\0"))&&(t.workingDirectory==="."||sx(t.workingDirectory))&&o$.has(t.scope)&&n.every(([e,r])=>s$.test(e)&&!a$.test(e)&&!r.includes("\0"))&&Number.isInteger(t.timeoutMs)&&t.timeoutMs>0&&t.reason.trim().length>0}function ax(t,n){let e=n.some(s=>d$.has(s)),r=[...t.validation].sort((s,a)=>s.id.localeCompare(a.id));if(r.some(s=>!c$(s)))return{plan:{status:"unresolved",steps:[],unresolvedReasons:["Validation discovery supplied an unsafe or malformed structured step."]},reasons:[{code:"invalid-provenance",message:"Validation plan inputs must be safe structured executable/argument records."}]};let i=[];return r.length===0&&i.push("No deterministic validation steps were discovered."),e&&!r.some(s=>s.scope==="affected")&&i.push("Shared test-support edits require affected-test validation."),{plan:{status:i.length===0?"planned":"unresolved",steps:r,unresolvedReasons:i},reasons:[]}}var Lp=1e6,Mp=1e3;function it(t){return{kind:"rejected",reasons:t}}function l$(t){let{packetHash:n,...e}=t;return Rr(e)===n}function u$(t,n){let e=[];for(let r of t)[...r.evidenceIds,...r.latencyContractEvidenceIds??[],...r.brittleLocatorEvidenceIds??[]].some(s=>!n.has(s))&&e.push({code:"invalid-replacement",message:"Every replacement and policy exception must cite accepted supporting evidence.",path:r.path});return e}async function _p(t){let n=Qn(t.config);if(n.kind!=="valid")return it(n.issues.map(p=>({code:"invalid-config",message:p})));if(!l$(t.packet)||t.snapshot.workspaceRoot!==t.packet.workspace.root||t.packet.workspace.gitRoot!==void 0&&t.snapshot.gitRoot!==t.packet.workspace.gitRoot)return it([{code:"invalid-provenance",message:"Packet integrity and repository snapshot identity must match."}]);let e=ex(t.packet,t.diagnosis,t.grading,t.intent);if(e.kind!=="eligible")return it(e.reasons);let r=t.maxSourceBytes??Lp;if(!Number.isInteger(r)||r<=0||r>Lp)return it([{code:"invalid-provenance",message:`maxSourceBytes must be an integer from 1 to ${Lp}.`}]);if(t.replacements.length===0)return it([{code:"invalid-replacement",message:"Proposal has no replacements."}]);let i=u$(t.replacements,new Set(e.hypothesis.supportingEvidenceIds));if(i.length>0)return it(i);let s=await by(n.config,t.snapshot,t.replacements,r);if(s.kind!=="authorized")return it(s.reasons);if(s.targets.some(p=>p.source.split(/\r?\n/u).length>Mp||p.replacements.some(f=>f.newText.split(/\r?\n/u).length>Mp)))return it([{code:"budget-exceeded",message:`M5 safely derives diffs only for targets and replacement text up to ${Mp} lines.`,manualRepairRecommended:!0}]);let a=gy(s.targets);if(a.kind!=="applied")return it(a.reasons);let o=ix(a.targets);if(o.length>0)return it(o);let d=$p(a.targets),c=Zb(d,n.config.budgets);if(c.length>0)return it(c);let l=ax(t.snapshot,a.targets.map(p=>p.class));if(l.reasons.length>0)return it(l.reasons);let u={schemaVersion:"1.0",policyVersion:"1.0",runId:t.packet.runId,packetHash:t.packet.packetHash,acceptedHypothesisId:e.hypothesis.hypothesisId,intent:t.intent,budgets:n.config.budgets,changedFiles:d.changedFiles,changedLines:d.changedLines,replacements:t.replacements,targets:a.targets.map(p=>({path:p.path,class:p.class,sourceSha256:p.sourceSha256,resultSha256:p.resultSha256,changedLines:d.perFileChangedLines[p.path]??0})),diff:d.text,diffHash:L(d.text),validationPlan:l.plan};return{kind:"proposal-ready",proposal:{...u,proposalHash:L(u)}}}import{readFile as R$,realpath as bx}from"node:fs/promises";import{join as I$,relative as A$,sep as T$}from"node:path";var p$=new Set(["failed","timedOut","interrupted"]);function f$(t){return t.status==="unexpected"||t.status==="flaky"}function cx(t){return[...t.clusters].sort((n,e)=>e.logicalTestIds.length-n.logicalTestIds.length||n.clusterId.localeCompare(e.clusterId)).slice(0,6)}function h$(t){return t.attachments.reduce((n,e)=>n+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function lx(t,n){let e=new Set(n.logicalTestIds);return t.logicalTests.filter(i=>e.has(i.logicalTestId)).map(i=>{let s=i.attempts.filter(a=>p$.has(a.status));return{test:i,score:Math.max(0,...s.map(h$)),startedAt:s.map(a=>a.startTime).sort()[0]??""}}).sort((i,s)=>s.score-i.score||i.startedAt.localeCompare(s.startedAt)||i.test.logicalTestId.localeCompare(s.test.logicalTestId))[0]?.test}function ux(t,n,e){let r=new Set(n.logicalTestIds);return{...t,logicalTests:t.logicalTests.map(i=>r.has(i.logicalTestId)?i.logicalTestId===e?i:{...i,attempts:i.attempts.map(s=>({...s,attachments:[]}))}:f$(i)?{...i,attempts:[]}:i)}}function px(t,n,e){return{...e,runId:n.runId,clusters:[{...t,symptomIds:n.symptoms.filter(r=>r.logicalTestId!==void 0&&t.logicalTestIds.includes(r.logicalTestId)).map(r=>r.symptomId).sort()}]}}async function fx(t,n,e){let r=new Array(t.length),i=0,s=Array.from({length:Math.min(n,t.length)},async()=>{for(;i<t.length;){let a=i;i+=1,r[a]=await e(t[a])}});return await Promise.all(s),r}import{randomUUID as hx}from"node:crypto";import{readdir as mx,readFile as m$,realpath as y$}from"node:fs/promises";import{join as Yr,relative as g$,sep as w$}from"node:path";var jp=/^run_[a-f0-9]{24}$/,Fp=/^rec_[a-f0-9]{24}$/;function rd(){return`rec_${hx().replaceAll("-","").slice(0,24)}`}function Xr(){return`auth_${hx().replaceAll("-","").slice(0,24)}`}async function Ts(t,n){if(!jp.test(n.runId)||!Fp.test(n.recordId))throw new Error("Run record identity is not path-safe.");let e=await ze(t,[".kwikqa","runs",n.runId]),r=await ze(t,[".kwikqa","runs",n.runId,"records"]),i=`${ue(n)}
219
- `,s=Yr(r,`${n.recordId}.json`);return await ye(s,i,{mode:384,replace:!1}),await ye(Yr(e,"result.json"),i,{mode:384,replace:!0}),g$(await y$(t),s).split(w$).join("/")}var b$=new Set(["analyze","fix","validate"]),x$=["analysis","proposal","application","validation"];function v$(t,n){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.schemaVersion=="string"&&e.schemaVersion.startsWith("1.")&&typeof e.recordId=="string"&&Fp.test(e.recordId)&&e.runId===n&&typeof e.command=="string"&&b$.has(e.command)&&typeof e.recordedAt=="string"&&typeof e.outcome=="string"&&typeof e.reasonCode=="string"&&typeof e.message=="string"&&x$.every(r=>typeof e[r]=="object"&&e[r]!==null)}async function yx(t,n){try{let e=JSON.parse(await m$(t,"utf8"));return v$(e,n)?e:void 0}catch{return}}async function Bp(t,n){if(!jp.test(n))return[];let e=Yr(t,".kwikqa","runs",n,"records"),r=await mx(e).catch(()=>[]);return(await Promise.all(r.filter(s=>Fp.test(s.replace(/\.json$/,""))&&s.endsWith(".json")).map(s=>yx(Yr(e,s),n)))).filter(s=>s!==void 0).sort((s,a)=>s.recordedAt.localeCompare(a.recordedAt)||s.recordId.localeCompare(a.recordId))}async function Hp(t){let n=Yr(t,".kwikqa","runs"),e=(await mx(n).catch(()=>[])).filter(i=>jp.test(i)),r;for(let i of e){let s=await yx(Yr(n,i,"result.json"),i);s!==void 0&&(r===void 0||s.recordedAt>r.recordedAt)&&(r=s)}return r?.runId}var sd=new Set(["context-limit-exceeded","request-token-budget-exceeded","request-dollar-budget-exceeded","run-token-budget-exceeded","run-dollar-budget-exceeded"]),P$={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function S$(t){return t.logicalTests.filter(n=>n.status==="unexpected"||n.status==="flaky").map(n=>n.logicalTestId).sort()}function E$(t,n){switch(t.usability){case"zero-tests":return{reasonCode:"zero-tests",message:"The report contains no tests to diagnose."};case"interrupted":return{reasonCode:"interrupted-run",message:"The run was interrupted, so its failures cannot support a diagnosis."};case"report-errors":return{reasonCode:"report-errors",message:"The report has run-level errors, so its failures cannot support a diagnosis."};case"analysis-ready":return n.length===0?{reasonCode:"no-failures",message:"The run has no failing or flaky tests."}:void 0}}async function gx(t,n){let e=await bx(n).catch(()=>n);return A$(t,e).split(T$).join("/")}async function C$(t,n){return{report:await gx(n,t.reportPath),...t.framework===void 0?{}:{framework:t.framework},...t.probePath===void 0?{}:{probe:await gx(n,t.probePath)},changeHistory:t.includeChangeHistory===!0,currentDiff:t.includeCurrentDiff===!0,maxPacketBytes:t.evidencePolicy.maxPacketBytes}}function ad(t){let n=[...t.hypotheses].sort((e,r)=>e.rank-r.rank)[0];return P$[n?.probableOwner??"undetermined"]??"owner-undetermined"}function N$(t,n){return t==="operation-failed"?"failed":n?"insufficient-evidence":"completed"}async function Ss(t,n){let e=await ct(t.reportPath,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},...t.framework===void 0?{}:{framework:t.framework}});if(e.kind==="unreadable")return{kind:"unreadable",outcome:"inconclusive",reasonCode:e.artifact.availability==="unavailable"?"report-unavailable":"report-unreadable",message:e.diagnostic.message};let r=e.run,i=S$(r),s=await C$(t,r.workspace.root),a=(v,R={})=>({kind:"analyzed",stage:{run:r,failing:i,inputs:s,...R,result:v}});if(t.repairableOnly===!0&&Ze(r)===void 0)return a({outcome:"inconclusive",reasonCode:"report-only-framework",message:lt(r),insufficient:!0});let o=await fo(r,{artifactRoot:t.artifactRoot??r.workspace.root,includeCurrentDiff:t.includeCurrentDiff===!0,includeChangeHistory:t.includeChangeHistory===!0,...t.probePath===void 0?{}:{probePath:t.probePath}},{...t.evidencePolicy,workspaceRoot:r.workspace.root});if(o.kind!=="built")return a(o.kind==="invalid-policy"?{outcome:"operation-failed",reasonCode:"invalid-evidence-policy",message:o.message}:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:o.message,insufficient:!0});let d=o.packet,c=go(r,d),l=gu(c),u={packet:d,symptoms:c,clusters:l},p={...u,triage:u},f=E$(r,i);if(f!==void 0)return a({outcome:"inconclusive",...f,insufficient:!0},p);if(t.remote===void 0)return a({outcome:"inconclusive",reasonCode:"remote-diagnosis-not-configured",message:"Local evidence analysis completed; no remote diagnosis was configured."},p);let h=await _$(t,r,l,n),m=D$(h);if(m===void 0)return a({outcome:"inconclusive",reasonCode:"no-failures",message:"No failing test produced a symptom to diagnose.",insufficient:!0},p);let g=h.filter(v=>v.result.reasonCode!=="cluster-not-requested"),y=g.filter(v=>v.result.outcome==="diagnosed").length,w=l.clusters.length-g.length,x=l.clusters.length>1?`${y} of ${l.clusters.length} failure groups diagnosed.${w>0?` ${w} not sent: ${O$(h)}`:""}`:m.result.message;return a({...m.result,message:x},{triage:u,...m.packet===void 0?p:{packet:m.packet},...m.symptoms===void 0?{}:{symptoms:m.symptoms},...m.clusters===void 0?{}:{clusters:m.clusters},clusterStages:[m,...h.filter(v=>v!==m)],representativeId:m.representativeId})}function O$(t){return t.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var $$={strong:3,moderate:2,weak:1,insufficient:0};function wx(t){let[n]=[...t.result.diagnosis?.hypotheses??[]].sort((e,r)=>e.rank-r.rank);return $$[n?.evidenceGrade??""]??0}function od(t){return t.map((n,e)=>({item:n,index:e})).filter(({item:n})=>n.result.outcome==="diagnosed"&&n.result.reasonCode==="test-support-owned").sort((n,e)=>wx(e.item)-wx(n.item)||e.item.cluster.logicalTestIds.length-n.item.cluster.logicalTestIds.length||n.index-e.index).map(({item:n})=>n)}function D$(t){let n=t.filter(e=>e.result.outcome==="diagnosed");return od(t)[0]??n[0]??t[0]}var L$=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function xx(t,n,e,r){let i=lx(n,r);if(i===void 0)return;let s=ux(n,r,i.logicalTestId),a=await fo(s,{artifactRoot:t.artifactRoot??n.workspace.root,includeCurrentDiff:t.includeCurrentDiff===!0,includeChangeHistory:t.includeChangeHistory===!0,...t.probePath===void 0?{}:{probePath:t.probePath}},{...t.evidencePolicy,workspaceRoot:n.workspace.root});if(a.kind!=="built")return{cluster:r,representativeId:i.logicalTestId,result:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:a.message,insufficient:!0}};let o=go(s,a.packet);return{cluster:r,representativeId:i.logicalTestId,packet:a.packet,symptoms:o,clusters:px(r,o,e)}}var M$={approveDiagnosis:async()=>!1};async function zp(t,n){let e=await Ss({...t,interaction:M$,persist:!1},()=>new Date().toISOString());if(e.kind==="unreadable")return{kind:"unreadable",message:e.message};let{run:r,triage:i}=e.stage;if(i===void 0)return{kind:"rebuilt",run:r};let s={};for(let a of i.clusters.clusters){if(!n.includes(a.clusterId))continue;let o=await xx(t,r,i.clusters,a);o?.packet!==void 0&&(s[a.clusterId]=o.packet)}return{kind:"rebuilt",run:r,detail:{...i,groupPackets:s}}}async function _$(t,n,e,r){let i=t.remote;if(i===void 0)return[];let s=cx(e),a=[],o=[];for(let g of s){let y=await xx(t,n,e,g);y!==void 0&&("result"in y?a.push(y):o.push(y))}let d=[];for(let g of o){let y=t.reuseDiagnosis===!0?await F$(n.workspace.root,n.runId,g.packet,g.symptoms):void 0;y===void 0?d.push(g):a.push(on(g,y))}let c=a.some(g=>g.result.reasonCode==="test-support-owned"),l=(g,y)=>{for(let w of g)a.push(on(w,{outcome:"inconclusive",reasonCode:"cluster-not-requested",message:y}))};if(t.reuseDiagnosis===!0&&c)return l(d,"A recorded diagnosis of another group already supports a repair."),Ps(a,s);let u=i.session===void 0?d.slice(0,1):d;l(d.slice(u.length),"the service counts each request separately, so only the largest group was sent.");let f=(await Promise.all(u.map(async g=>({item:g,prepared:await Jo({packet:g.packet,symptoms:g.symptoms,clusters:g.clusters,model:i.model,caps:i.caps,transport:i.transport,now:r()})})))).flatMap(({item:g,prepared:y})=>y.kind==="preview-ready"?[{item:g,prepared:y.prepared}]:(a.push(on(g,{outcome:sd.has(y.reasonCode)?"inconclusive":"operation-failed",reasonCode:y.reasonCode,message:y.message,audit:y.audit})),[]));if(f.length===0)return Ps(a,s);let h=f.map(g=>g.prepared.preview),m;if(t.interaction.approveDiagnoses!==void 0)m=await t.interaction.approveDiagnoses(h);else{m=!0;for(let g of h)await t.interaction.approveDiagnosis(g)||(m=!1)}if(!m){for(let g of f)a.push(on(g.item,{outcome:"inconclusive",reasonCode:"remote-consent-declined",message:"The developer declined the diagnosis request; no evidence was sent."}));return Ps(a,s)}if(i.session!==void 0)try{await i.session.open(f.length)}catch(g){let y=g instanceof Error?g.message:"The analysis session could not be opened.";for(let w of f)a.push(on(w.item,{outcome:"operation-failed",reasonCode:"session-unavailable",message:y}));return Ps(a,s)}try{let g=await fx(f,3,async y=>{let w=await vx(t,y.prepared,i.transport,r),x=i.escalation;if(x===void 0||!L$.has(w.reasonCode))return on(y.item,w);let v=await j$(t,y.item,x,i.transport,r);return v===void 0?on(y.item,w):{...on(y.item,v),escalated:!0}});a.push(...g)}finally{await i.session?.close().catch(()=>{})}return Ps(a,s)}function Ps(t,n){let e=new Map(n.map((r,i)=>[r.clusterId,i]));return[...t].sort((r,i)=>(e.get(r.cluster.clusterId)??0)-(e.get(i.cluster.clusterId)??0))}function on(t,n){return{cluster:t.cluster,representativeId:t.representativeId,packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,result:n}}async function vx(t,n,e,r){let i=await Tp({prepared:n,authorization:{bindingHash:n.authorizationBindingHash,mode:"interactive",authorizedAt:r(),authorizationId:Xr()},authorizationStore:t.authorizationStore??new qn,transport:e,now:r()});switch(i.kind){case"diagnosed":return{outcome:"diagnosed",reasonCode:ad(i.diagnosis),message:"The diagnosis passed schema validation and local grading.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};case"abstained":return{outcome:"inconclusive",reasonCode:i.reasonCode,message:"The evidence was insufficient for a supported diagnosis.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};default:return{outcome:sd.has(i.reasonCode)?"inconclusive":"operation-failed",reasonCode:i.reasonCode,message:i.message,audit:i.audit}}}async function j$(t,n,e,r,i){let s=await Jo({packet:n.packet,symptoms:n.symptoms,clusters:n.clusters,model:e.model,caps:e.caps,transport:r,now:i()});if(s.kind==="preview-ready"&&await t.interaction.approveDiagnosis(s.prepared.preview))return vx(t,s.prepared,r,i)}async function F$(t,n,e,r){if(/^run_[a-f0-9]{24}$/.test(n))try{let i=await bx(t),s=JSON.parse(await R$(I$(i,".kwikqa","runs",n,"result.json"),"utf8")),a=u=>u==="diagnosed"||u==="inconclusive",o=[...(s.clusters??[]).filter(u=>a(u.outcome)),...a(s.outcome)?[s]:[]].find(u=>u.diagnosis?.packetHash===e.packetHash&&u.diagnosisAudit!==void 0),d=o?.diagnosis;if(o===void 0||d===void 0||o.diagnosisAudit===void 0)return;let c=ds(d,e,r);if(!c.passed)return;let l=o.outcome==="inconclusive";return{outcome:l?"inconclusive":"diagnosed",reasonCode:l?o.reasonCode??"insufficient-evidence":ad(d),message:"Reused the graded diagnosis recorded for this exact evidence packet.",diagnosis:d,grading:c,audit:o.diagnosisAudit}}catch{return}}function B$(t){return{clusterId:t.cluster.clusterId,logicalTestIds:t.cluster.logicalTestIds,representativeId:t.representativeId,signals:t.cluster.signals,...t.packet===void 0?{}:{packetHash:t.packet.packetHash},outcome:t.result.outcome,reasonCode:t.result.reasonCode,message:t.result.message,...t.result.diagnosis===void 0?{}:{diagnosis:t.result.diagnosis},...t.result.grading===void 0?{}:{grading:t.result.grading},...t.result.audit===void 0?{}:{diagnosisAudit:t.result.audit},...t.escalated===!0?{escalated:!0}:{}}}function dd(t,n,e,r,i={}){let{run:s,packet:a,symptoms:o,clusters:d}=t,c=t.result;return{schemaVersion:"1.1",recordId:rd(),command:n,runId:s.runId,createdAt:s.createdAt,recordedAt:r(),workspace:s.workspace,sourceHashes:a?.sourceHashes??s.sourceHashes,usability:s.usability,failingLogicalTestIds:t.failing,inputs:t.inputs,analysis:{status:N$(c.outcome,c.insufficient===!0)},proposal:{status:"not-requested"},application:{status:"not-requested"},validation:{status:"not-requested"},...a===void 0?{}:{evidence:{packetHash:a.packetHash,evidence:a.totals.evidence,artifacts:a.totals.artifacts,omissions:a.totals.omissions,redactions:a.totals.redactions,serializedBytes:a.totals.serializedBytes}},...o===void 0||d===void 0?{}:{symptoms:{symptoms:o.symptoms.length,unclassifiedAttempts:o.unclassifiedAttemptIds.length,clusters:d.clusters.length}},...t.clusterStages===void 0||t.clusterStages.length===0?{}:{clusters:t.clusterStages.map(B$)},...c.diagnosis===void 0?{}:{diagnosis:c.diagnosis},...c.grading===void 0?{}:{grading:c.grading},...c.audit===void 0?{}:{diagnosisAudit:c.audit},...i,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message}}function H$(t,n){let e={};for(let r of n.clusterStages??[])r.packet!==void 0&&(e[r.cluster.clusterId]=r.packet);return{...t,groupPackets:e}}async function cd(t,n,e){let r={run:t.run,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},...t.triage===void 0?{}:{detail:H$(t.triage,t)}},i=(s,a)=>({outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,...a===void 0?{}:{recordPath:a},...r});if(!e)return i(n);try{return i(n,await Ts(t.run.workspace.root,n))}catch{return i({...n,outcome:"operation-failed",reasonCode:"record-write-failed",message:"The run record could not be written safely under .kwikqa/runs/."})}}async function ld(t){let n=t.now??(()=>new Date().toISOString()),e=await Ss(t,n);if(e.kind==="unreadable")return{outcome:e.outcome,reasonCode:e.reasonCode,message:e.message};let{stage:r}=e;return cd(r,dd(r,"analyze",r.result,n),t.persist!==!1)}import{randomUUID as a2}from"node:crypto";import{relative as o2,resolve as d2,sep as c2}from"node:path";import{createHash as kx}from"node:crypto";import{lstat as z$,readFile as V$,realpath as ud}from"node:fs/promises";import{isAbsolute as U$,join as q$,relative as G$,resolve as K$,sep as W$}from"node:path";var dn=/^[a-f0-9]{64}$/,Ix=/^vld_[a-f0-9]{24}$/,J$=Gt,Y$=4*1024*1024,X$=2*1024*1024;function Zn(t){return{code:"transaction-unavailable",message:t}}function Es(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Up(t,n){let e=Object.keys(t).sort(),r=[...n].sort();return e.length===r.length&&e.every((i,s)=>i===r[s])}function Vp(t){return Array.isArray(t)&&t.every(n=>typeof n=="string"&&n.length>0&&!n.includes("\0"))}function Q$(t,n){let e=G$(t,n);return e===""||!U$(e)&&e!==".."&&!e.startsWith(`..${W$}`)}function Z$(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function Rx(t){return Es(t)?Up(t,["path","observedBytes","storedBytes","sha256","storedSha256","truncated","redacted"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&dn.test(t.sha256)&&typeof t.storedSha256=="string"&&dn.test(t.storedSha256)&&Number.isInteger(t.observedBytes)&&t.observedBytes>=0&&Number.isInteger(t.storedBytes)&&t.storedBytes>=0&&typeof t.truncated=="boolean"&&typeof t.redacted=="boolean":!1}function Ax(t){if(!Es(t))throw new Error("Validation command record is not an object.");let n=t,{recordHash:e,...r}=n;if(!Up(t,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])||n.schemaVersion!=="1.0"||!Ix.test(n.validationRunId)||!J$.test(n.commandId)||!dn.test(n.commandHash)||!dn.test(n.planHash)||n.timing!=="post-patch"||n.required!==!0||n.executable!==process.execPath||!Vp(n.args)||typeof n.kind!="string"||n.kind.length===0||typeof n.workingDirectory!="string"||n.workingDirectory.length===0||!Es(n.environmentDelta)||!Object.entries(n.environmentDelta).every(([i,s])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&typeof s=="string"&&!s.includes("\0"))||!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0||typeof n.purpose!="string"||n.purpose.length===0||!Vp(n.logicalTestIds)||!Vp(n.projectIds)||!Z$(n.startedAt)||!Number.isInteger(n.durationMs)||n.durationMs<0||!Es(n.termination)||n.termination.kind!=="exit"||n.termination.exitCode!==0||!Rx(n.stdout)||!Rx(n.stderr)||n.stdout.truncated||n.stderr.truncated||!Array.isArray(n.artifacts)||!n.artifacts.every(i=>Es(i)&&Up(i,["path","sha256","bytes"])&&typeof i.path=="string"&&i.path.length>0&&typeof i.sha256=="string"&&dn.test(i.sha256)&&Number.isInteger(i.bytes)&&i.bytes>=0)||n.status!=="passed"||!dn.test(e)||L(r)!==e)throw new Error("Validation command record is malformed or non-passing.");return n}function e2(t){let n=Kt(JSON.parse(t));if(n.status!=="passed")throw new Error("Validation manifest is not passing.");for(let e of n.commandRecords)Ax(e);return n}async function Tx(t){let[n,e,r,i]=await Promise.all([ud(t.workspace.workspaceRoot),ud(t.snapshot.workspaceRoot),ud(t.workspace.gitRoot),ud(t.snapshot.gitRoot)]);if(n!==e||r!==i)throw new Error("Validation workspace identity changed.");return n}async function Px(t,n,e){for(let r of e.manifest.targets){let i=await X(t,r.path,n.maxTargetBytes);if(i.kind!=="read"||i.relativePath!==r.path||i.sha256!==r.resultSha256)return!1}return!0}function Sx(t){return dn.test(t.planHash)&&Ix.test(t.validationRunId)}async function pd(t,n,e){let r=K$(t,n);if(!Q$(t,r))throw new Error("Validation record path escapes its run.");let i=await z$(r);if(!i.isFile()||i.isSymbolicLink()||i.size>e)throw new Error("Validation record path is unsafe or unbounded.");return V$(r)}async function t2(t,n,e){let r=new Map(e.requiredCommands.map(i=>[i.commandId,i.commandHash]));for(let i of n.commandRecords){if(i.validationRunId!==n.validationRunId||i.planHash!==n.planHash||r.get(i.commandId)===void 0)return!1;let s=r.get(i.commandId);if(s===void 0||i.commandHash!==s)return!1;let a=await pd(t,`commands/${i.commandId}/result.json`,X$),o=Ax(JSON.parse(a.toString("utf8")));if(L(o)!==L(i))return!1;for(let d of[i.stdout,i.stderr]){let c=await pd(t,d.path,hn);if(c.byteLength!==d.storedBytes||kx("sha256").update(c).digest("hex")!==d.storedSha256)return!1}for(let d of i.artifacts){let c=await pd(t,d.path,rr);if(c.byteLength!==d.bytes||kx("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function qp(t){if(!Sx(t))return{kind:"rejected",reasons:[Zn("Validation identity is invalid.")]};let n=t.now??new Date().toISOString(),e;try{let r=await Tx(t.context);e=await Je(r,{operation:"begin-validation",transactionId:t.transactionId,validationRunId:t.validationRunId,at:n});let i=await Re(r,t.transactionId),s=i.state.history.at(-1);return i.state.phase==="validating"&&s?.type==="validation-started"&&s.planHash===t.planHash&&s.validationRunId===t.validationRunId?{kind:"validating",transaction:Te(i)}:i.state.phase!=="applied"||i.manifest.preview.authoritativeValidation.planHash!==t.planHash||!await Px(r,t.context,i)?{kind:"rejected",reasons:[Zn("Applied transaction does not match the approved validation handoff.")],transaction:Te(i)}:(i=await Ge({transaction:i,phase:"validating",type:"validation-started",planHash:t.planHash,validationRunId:t.validationRunId,now:n}),{kind:"validating",transaction:Te(i)})}catch{return{kind:"failed",reasons:[Zn("Validation transition failed closed.")]}}finally{await e?.release().catch(()=>{})}}async function Gp(t){if(!Sx(t)||!dn.test(t.validationManifestHash))return{kind:"rejected",reasons:[Zn("Validation completion identity is invalid.")]};let n=t.now??new Date().toISOString(),e;try{let r=await Tx(t.context);e=await Je(r,{operation:"complete-validation",transactionId:t.transactionId,validationRunId:t.validationRunId,at:n});let i=await Re(r,t.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history.at(-1);if(i.state.phase==="completed"&&a?.type==="validation-passed"&&a.planHash===t.planHash&&a.validationRunId===t.validationRunId&&a.validationManifestHash===t.validationManifestHash)return{kind:"completed",transaction:Te(i)};if(i.state.phase!=="validating"||s.planHash!==t.planHash||a?.type!=="validation-started"||a.validationRunId!==t.validationRunId||a.planHash!==t.planHash||!await Px(r,t.context,i))return{kind:"rejected",reasons:[Zn("Transaction is not validating this exact approved run.")],transaction:Te(i)};let o=q$(i.directory,"validation",t.validationRunId),d=await pd(o,"manifest.json",Y$),c=e2(d.toString("utf8")),l=new Set(c.requiredCommandIds),u=new Set(c.commandRecords.map(f=>f.commandId)),p=s.targetHashes;return c.manifestHash!==t.validationManifestHash||c.transactionId!==t.transactionId||c.validationRunId!==t.validationRunId||c.planHash!==t.planHash||c.repositoryFingerprint!==s.repositoryFingerprint||L(c.targetHashes)!==L(p)||l.size!==c.requiredCommandIds.length||u.size!==c.commandRecords.length||s.requiredCommandIds.some(f=>!l.has(f)||!u.has(f))||l.size!==s.requiredCommandIds.length||u.size!==s.requiredCommandIds.length||!await t2(o,c,s)?{kind:"rejected",reasons:[Zn("Validation manifest does not prove the exact approved command set.")],transaction:Te(i)}:(i=await Ge({transaction:i,phase:"completed",type:"validation-passed",planHash:t.planHash,validationRunId:t.validationRunId,validationManifestHash:c.manifestHash,now:n}),{kind:"completed",transaction:Te(i)})}catch{return{kind:"failed",reasons:[Zn("Validation completion failed closed.")]}}finally{await e?.release().catch(()=>{})}}import{join as n2}from"node:path";var Ex="1.0",r2=/^rps_[a-f0-9]{24}$/,i2=8*1024*1024;function s2(t){if(typeof t!="object"||t===null)return;let n=t;if(!(typeof n.reportPath!="string"||!Array.isArray(n.logicalTestIds)||!n.logicalTestIds.every(e=>typeof e=="string")||n.framework!==void 0&&!kt.includes(n.framework)))return{reportPath:n.reportPath,...n.framework===void 0?{}:{framework:n.framework},logicalTestIds:n.logicalTestIds}}function Cx(t){if(!r2.test(t))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",t]}async function Nx(t,n){let e=await ze(t,Cx(n.repairSessionId));await ye(n2(e,`attempt-${n.attempt}.json`),`${ue(n)}
220
- `,{mode:384,replace:!1})}async function Ox(t,n,e){let r=await ze(t,Cx(n)),i=await vn(r,`attempt-${e}.json`,i2),s=Qn(i.config);if(i.schemaVersion!==Ex||i.repairSessionId!==n||i.attempt!==e||typeof i.transactionId!="string"||i.workspace===void 0||typeof i.maxTargetBytes!="number"||i.record===void 0||s.kind!=="valid")throw new Error("Repair attempt state is malformed.");let a=s2(i.group);return{schemaVersion:Ex,repairSessionId:n,attempt:e,transactionId:i.transactionId,plan:mn(i.plan),workspace:i.workspace,config:s.config,maxTargetBytes:i.maxTargetBytes,record:i.record,...a===void 0?{}:{group:a}}}import{dirname as $x,resolve as Dx}from"node:path";function Qr(t,n){return{kind:"configuration",path:t.relativePath,sha256:t.sha256,detail:n}}async function Lx(t){let{run:n,test:e,discovery:r}=t,i=Ze(n);if(i===void 0)return{kind:"unavailable",message:lt(n)};if(i==="playwright")return{kind:"unavailable",message:"Playwright validation needs no prepared run."};let s=n.configFile??await Eo(t.workspaceRoot,i,e.location.file),a=r.scope==="focused"?[e.location.file]:r.scope==="affected"?r.testPaths:[],o=await Do(t.workspaceRoot);if(i==="cypress"){let c=await Co(t.workspaceRoot,s),l=r.scope==="focused"?n.logicalTests.filter(f=>f.location.file===e.location.file&&f.projectId===e.projectId&&f.status==="expected"):[],u=await Lo({workspaceRoot:t.workspaceRoot,runtime:o,...s===void 0?{}:{configFile:s},specs:a,screenshotsDirectory:`${t.artifactRoot}/screenshots`,noRetries:!0,capture:{directory:`${t.artifactRoot}/capture`,supportFile:c,...r.scope==="focused"?{only:[e,...l].map(f=>f.titlePath.join(" "))}:{}}}),p=l.map(f=>f.logicalTestId);return{kind:"prepared",prepared:{args:u.args,workingDirectory:s===void 0?t.workspaceRoot:$x(Dx(t.workspaceRoot,s)),evidence:[Qr(o["cypress-reporter.cjs"],"KwikQA's Cypress reporter."),Qr(o["cypress-capture.js"],"KwikQA's Cypress failure capture."),...u.generated.map(f=>Qr(f,"Support file KwikQA generated for this validation."))],companionLogicalTestIds:p}}}if(s===void 0)return{kind:"unavailable",message:"No wdio.conf was found for the failing spec, so its validation run is unknown."};let d=await Mo({workspaceRoot:t.workspaceRoot,runtime:o,configFile:s,specs:a,directory:`${t.artifactRoot}/runner`,noRetries:!0,...r.scope==="focused"?{grep:gb(e.titlePath)}:{},capture:!0});return{kind:"prepared",prepared:{args:d.args,workingDirectory:$x(Dx(t.workspaceRoot,s)),evidence:[Qr(o["wdio-reporter.mjs"],"KwikQA's WebdriverIO reporter."),Qr(o["wdio-capture.mjs"],"KwikQA's WebdriverIO run wrapper."),...d.generated.map(c=>Qr(c,"WebdriverIO config KwikQA generated for this validation."))],companionLogicalTestIds:[]}}}var l2=600*1e3,Mx=1e6,u2={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},p2={biome:"@biomejs/biome",prettier:"prettier",typescript:"typescript",eslint:"eslint"};function fd(t,n,e,r){let i=t.logicalTests.filter(l=>l.status==="unexpected"||l.status==="flaky"),s=[...n.hypotheses].sort((l,u)=>l.rank-u.rank)[0],a=new Set([...s?.supportingEvidenceIds??[],...n.ownershipEvidenceIds]),o=new Set(e.evidence.filter(l=>a.has(l.evidenceId)&&l.logicalTestId!==void 0).map(l=>l.logicalTestId)),d=i.filter(l=>o.has(l.logicalTestId));if(d.length===1)return d[0];let c=i.find(l=>l.logicalTestId===r);return c!==void 0&&(d.length===0||d.includes(c))?c:i.length===1?i[0]:void 0}function f2(t){return fd(t.run,t.diagnosis,t.packet,t.representativeId)}function _x(t){return t.payloadManifestHash===void 0||t.payloadHash===void 0?[]:[{manifestHash:t.payloadManifestHash,payloadHash:t.payloadHash,packetHash:t.packetHash,model:t.model.modelId,provider:t.model.providerId,promptVersion:t.promptVersion,outputSchemaVersion:t.outputSchemaVersion}]}function h2(t){return{maxRequestTokens:t.request.maxInputTokens+t.request.maxOutputTokens,maxRunTokens:t.run.maxInputTokens+t.run.maxOutputTokens,maxRequestDollars:t.request.maxDollars,maxRunDollars:t.run.maxDollars}}var m2={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function y2(t,n,e,r){let i=async o=>{let d=await _i({workspaceRoot:t.workspaceRoot,repositoryRoot:t.gitRoot,ownerPath:n,packageName:o});return d.kind==="resolved"?d.tool:void 0},s={},a=await i(m2[e]);a!==void 0&&(s[e]=a);for(let o of new Set(r)){if(o==="kwikqa-babel")continue;let d=await i(p2[o]);d!==void 0&&(s[o]=d)}return s}async function jx(t){let{input:n,now:e,run:r,proposal:i,repository:s}=t,a={repairProposal:i,repairAudit:t.repairAudit},o=(I,$)=>t.finish({outcome:"validation-unavailable",reasonCode:I,message:$},{...a,proposal:{status:"ready"},application:{status:"not-run"},validation:{status:"unavailable"}}),d=Ze(r);if(d===void 0)return o("report-only-framework",lt(r));let c=f2(t);if(c===void 0)return o("original-test-ambiguous","The repair cannot be validated because the original failing test is ambiguous.");let l=r.projects.find(I=>I.projectId===c.projectId),u=await Ec({workspaceRoot:s.workspaceRoot,targets:i.targets.map(I=>({path:I.path,class:I.class})),originalTestPath:c.location.file,projects:r.projects.map(I=>({id:I.name,testDirectory:I.testDir??"",...r.configFile===void 0?{}:{configPath:r.configFile}})),limits:u2}),p=u.scope==="focused"&&u.projectIds.length===0&&l!==void 0&&l.name!==""?{...u,projectIds:[l.name]}:u,f=await y2(s,c.location.file,d,p.staticChecks.map(I=>I.tool)),h=`.kwikqa/validation-artifacts/${i.proposalHash.slice(0,24)}`,m;if(d!=="playwright"&&p.status==="resolved"){let I=await Lx({workspaceRoot:s.workspaceRoot,run:r,test:c,discovery:p,artifactRoot:h});if(I.kind==="unavailable")return o("validation-scope-unavailable",I.message);m=I.prepared}let g=bl({proposal:i,advisoryPlan:i.validationPlan,discovery:p,tools:f,workspaceRoot:s.workspaceRoot,originalTest:{path:c.location.file,line:c.location.line??1,logicalTestId:c.logicalTestId,projectId:l===void 0||l.name===""?c.projectId:l.name,...r.configFile===void 0?{}:{configPath:r.configFile},environmentEquivalent:n.environmentEquivalent!==!1},artifactRoot:h,timeoutMs:n.validationTimeoutMs??l2,framework:d,...m===void 0?{}:{frameworkRun:{args:m.args,workingDirectory:m.workingDirectory,evidence:m.evidence},companionLogicalTestIds:m.companionLogicalTestIds}}),y=g.plan;if(y.status!=="resolved")return o("validation-scope-unavailable",y.unresolvedReasons.map(I=>I.message).join(" "));if(g.requiredBaselineCommands.length>0)return o("baseline-capture-unavailable","This repair changes shared test support, which needs a pre-patch baseline that cannot be captured yet.");let w=t.retry===void 0?1:2,x=t.retry?.repairSessionId??(await Ol({workspaceRoot:s.workspaceRoot,originalRunId:r.runId,originalPacketHash:t.packet.packetHash,now:e()})).repairSessionId,v={config:t.config,snapshot:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot,dirtyPaths:s.dirtyPaths,validation:[]},workspace:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot},maxTargetBytes:Mx},R=t.ciApprover??{kind:"interactive",sessionId:`kwikqa-${a2()}`},P=kl({proposal:i,context:v,payloadManifests:[...t.diagnosisAudit===void 0?[]:_x(t.diagnosisAudit),..._x(t.repairAudit)],costBounds:h2(t.caps),scopes:{baseline:[],validation:[p.scope]},authoritativeValidation:xl({plan:y,advisoryPlan:i.validationPlan,repairSessionId:x,attemptOrdinal:w}),previewedAt:e(),approver:R}),C={repairSessionId:x,attempt:w,planHash:y.planHash};if(P.kind!=="preview-ready")return t.finish({outcome:"operation-failed",reasonCode:"application-rejected",message:P.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"ready"},application:{status:"blocked"}});if(!await n.interaction.approveApplication(P.preview,y))return t.finish({outcome:"repair-declined",reasonCode:"application-declined",message:"The developer declined the patch and validation plan; nothing was changed."},{...a,proposal:{status:"declined"},application:{status:"not-run"},repair:C});let E=Xr(),M=e(),A=await Al({preview:P.preview,authorization:{authorizationId:E,bindingHash:za(P.preview,E,M,R),authorizedAt:M,approver:R},context:v,now:M});if(A.kind!=="applied")return t.finish({outcome:"operation-failed",reasonCode:A.kind==="recovery-required"?"application-recovery-required":"application-rejected",message:A.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"approved"},application:{status:A.kind==="recovery-required"?"recovery-required":"failed"},repair:C});let N=A.transaction.transactionId;await Ll(s.workspaceRoot,x,{ordinal:w,proposalHash:i.proposalHash,transactionId:N,outcome:"applied",recordedAt:e()});let T=(t.memberIds??[]).filter(I=>I!==c.logicalTestId);return await Nx(s.workspaceRoot,{schemaVersion:"1.0",repairSessionId:x,attempt:w,transactionId:N,plan:y,workspace:v.workspace,config:t.config,maxTargetBytes:Mx,...T.length===0?{}:{group:{reportPath:o2(s.workspaceRoot,d2(s.workspaceRoot,n.reportPath)).split(c2).join("/"),...n.framework===void 0?{}:{framework:n.framework},logicalTestIds:T}},record:{runId:r.runId,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:t.packet.sourceHashes,usability:r.usability,failingLogicalTestIds:r.logicalTests.filter(I=>I.status==="unexpected"||I.status==="flaky").map(I=>I.logicalTestId).sort()}}),t.finish({outcome:"awaiting-validation",reasonCode:"patch-applied",message:t.ciApprover===void 0?"The approved patch was applied. Run `kwikqa validate` to verify it.":"The patch was applied to this runner's checkout, and is validated next."},{...a,proposal:{status:"approved"},application:{status:"applied"},repair:{...C,transactionId:N}})}import{createHash as T2}from"node:crypto";import{join as P2,relative as S2,sep as E2}from"node:path";import{execFile as g2}from"node:child_process";import{createHash as w2}from"node:crypto";import{realpath as Cs}from"node:fs/promises";import{isAbsolute as b2,relative as x2,resolve as Kp,sep as Fx}from"node:path";import{promisify as v2}from"node:util";var k2=v2(g2),R2=3e4,I2=16*1024*1024;async function Ns(t,n){return(await k2("git",["-C",t,"--no-optional-locks",...n],{timeout:R2,maxBuffer:I2,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function Bx(t){let n=t.split("\0"),e=[];for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(i.length<4)continue;let s=i.slice(0,2);if(e.push(i.slice(3)),s.includes("R")||s.includes("C")){let a=n[r+1];a!==void 0&&a.length>0&&e.push(a),r+=1}}return e}function A2(t,n,e){let r=x2(t,Kp(n,e));if(!(r===""||b2(r)||r===".."||r.startsWith(`..${Fx}`)))return r.split(Fx).join("/")}async function Os(t){let n=await Cs(t);try{return await Cs(Kp((await Ns(n,["rev-parse","--show-toplevel"])).trim()))}catch{return n}}async function Hx(t,n,e){let r;try{r=(await Ns(t,["rev-parse","--verify","--quiet",`HEAD:${n}`])).trim()}catch{return!1}let i=r.length===64?"sha256":"sha1";return w2(i).update(`blob ${e.byteLength}\0`).update(e).digest("hex")===r}async function Wp(t){let n=await Cs(t);return(await Ns(n,["-c","core.quotePath=false","ls-files","-z"])).split("\0").filter(r=>r.length>0).sort()}async function er(t){let n,e,r;try{n=await Cs(t),e=await Cs(Kp((await Ns(n,["rev-parse","--show-toplevel"])).trim())),r=await Ns(e,["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all","--ignored=no"])}catch(a){let o=a,d=o.code==="ENOENT"?"git executable was not found.":(o.stderr??o.message??"").trim().split(`
221
- `)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let i=Bx(r),s=[...new Set(i.map(a=>A2(n,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:n,gitRoot:e,dirtyPaths:s,pristine:i.length===0}}}var Ux="kwikqa.config.json",C2=256*1024;async function qx(t,n){let e=await X(t,n,C2);if(e.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${n}; none was found in the workspace.`};if(e.kind!=="read")return{kind:"repair-config-invalid",message:`${n} could not be read: ${e.message}`};let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes))}catch{return{kind:"repair-config-invalid",message:`${n} is not valid UTF-8 JSON.`}}let i=Qn(r);return i.kind!=="valid"?{kind:"repair-config-invalid",message:i.issues.join(" ")}:{...i,bytes:e.bytes}}async function hd(t,n=Ux){let e=await qx(t,n);return e.kind==="valid"?e.config.ci?.fix:void 0}async function N2(t,n,e,r){if(t.ci===void 0)return{};if(n.config.ci?.fix===void 0)return{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-missing",message:`\`kwikqa fix\` needs a terminal, unless ${r} has a committed ci.fix policy, which lets it validate a repair on this runner and open a draft pull request.`}};let i=S2(e.gitRoot,P2(e.workspaceRoot,r)).split(E2).join("/");return await Hx(e.gitRoot,i,n.bytes)?{approver:{kind:"ci-policy",...t.ci,policyHash:T2("sha256").update(n.bytes).digest("hex")}}:{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-uncommitted",message:`${r} differs from its committed version, so its ci.fix policy wasn't reviewed; a fix in CI runs only under the committed policy.`}}}function O2(t,n,e){let r=new Set(e.map(s=>s.toLocaleLowerCase("en-US"))),i=new Set;for(let s of t.evidence){if(s.locator.type!=="source-range")continue;let a=s.locator.path;zi(a,n.editablePaths)!==void 0&&!Hi(a,n)&&!Bi(a)&&!r.has(a.toLocaleLowerCase("en-US"))&&i.add(a)}return[...i].sort()}async function md(t){let n=t.now??(()=>new Date().toISOString()),e=await er(t.workspaceRoot);if(e.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:e.message};let{workspaceRoot:r,gitRoot:i,dirtyPaths:s,pristine:a}=e.status,o=t.configPath??Ux,d=await qx(r,o);if(d.kind!=="valid")return{outcome:"operation-failed",reasonCode:d.kind,message:d.message};let c=d.config,l=await N2(t,d,{workspaceRoot:r,gitRoot:i},o);if("refusal"in l)return l.refusal;let{approver:u}=l;if(t.retryRepairSessionId!==void 0&&(await tn(r,t.retryRepairSessionId).catch(()=>{}))?.state!=="retry-approval-required")return{outcome:"operation-failed",reasonCode:"no-retry-available",message:"That repair session has no retry available; only one retry follows a failed validation."};let p=await Ss({...t,workspaceRoot:r,gitRoot:i,repairableOnly:!0},n);if(p.kind==="unreadable")return{outcome:p.outcome,reasonCode:p.reasonCode,message:p.message};let{stage:f}=p,h={workspaceRoot:r,gitRoot:i,dirtyPaths:s},m=(x,v=[])=>(R,P={})=>cd(x,dd(x,"fix",v.length===0?R:{...R,message:`${v.join(" ")} ${R.message}`},n,{repository:{pristine:a,dirtyPaths:s},...P}),t.persist!==!1),g=_2(f,t);if("refusal"in g)return m(f)(g.refusal);if(g.groups.length===0){let{packet:x}=f,{diagnosis:v,grading:R}=f.result;return f.result.outcome!=="diagnosed"||x===void 0||v===void 0||R===void 0?m(f)(f.result):Vx(t,f,{packet:x,diagnosis:v,grading:R},c,n,m(f),h,u)}let y=[],w=[];for(let x of g.groups){let v=await t.fixInReview?.(x.cluster.signals);v===void 0?w.push(x):y.push(`Failure group ${zx(f,x)}: ${v}.`)}if(w.length===0)return m(f)({outcome:"abstained-from-repair",reasonCode:"fix-in-review",message:y.join(" ")});await t.repairSession?.open(w.length);try{let x;for(let v of w){let R=M2(f,v),{packet:P}=R,{diagnosis:C,grading:E}=v.result;if(!(P===void 0||C===void 0||E===void 0)){if(x=await Vx(t,R,{packet:P,diagnosis:C,grading:E},c,n,m(R,y),h,u),!L2(x))return x;y.push(`Failure group ${zx(f,v)}: ${x.message}`)}}return x??m(f)(f.result)}finally{await t.repairSession?.close()}}var $2=3,D2=new Set(["model-declined-repair","repair-not-eligible","failure-not-reproduced","insufficient-ownership-evidence","intent-ambiguous","invalid-replacement","unauthorized-target","dirty-target-file","source-hash-mismatch","non-unique-match","overlapping-replacement","forbidden-edit","parse-failed","budget-exceeded","unreadable-target"]);function L2(t){return t.outcome==="abstained-from-repair"?D2.has(t.reasonCode):t.outcome==="validation-unavailable"&&t.record?.application.status==="not-run"}function zx(t,n){return(t.clusterStages??[]).indexOf(n)+1}function M2(t,n){return{...t,...n.packet===void 0?{}:{packet:n.packet},...n.symptoms===void 0?{}:{symptoms:n.symptoms},...n.clusters===void 0?{}:{clusters:n.clusters},result:n.result,clusterStages:[n,...(t.clusterStages??[]).filter(e=>e!==n)],representativeId:n.representativeId}}function _2(t,n){let e=t.clusterStages??[];if(n.group!==void 0){let s=e[n.group-1];return s===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${n.group}; this run has ${e.length}.`}}:od([s]).includes(s)?{groups:[s]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${n.group} is not diagnosed as the test's fault (${s.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=od(e),i=n.repairSession===void 0||n.retryRepairSessionId!==void 0?1:$2;return{groups:r.slice(0,i)}}async function j2(t,n){let{interaction:e}=t;if(e.confirmFailure===void 0||t.retryRepairSessionId!==void 0)return;let r=n.clusterStages?.[0]?.cluster.logicalTestIds??n.failing,i=n.representativeId??r[0];if(i===void 0)return;let s=await e.confirmFailure(n.run,r);if(s.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(s.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:s.message};let a=r.filter(d=>s.failedAgain.includes(d));if(a.includes(i))return{status:"reproduced",logicalTestIds:r,failedAgain:a};let o=n.run.logicalTests.find(d=>d.logicalTestId===i)?.title;return{status:"not-reproduced",logicalTestIds:r,failedAgain:a,message:`${o===void 0?"The failing test":`"${o}"`} passed when re-run, so the failure looks flaky or depends on state the re-run did not have. KwikQA does not patch a test that passes; no repair was requested.`}}async function Vx(t,n,e,r,i,s,a,o){let{packet:d,diagnosis:c,grading:l}=e,u=[...c.hypotheses].sort((w,x)=>w.rank-x.rank)[0],p=t.repairCaps??t.remote.caps,f=await Cp({packet:d,diagnosis:c,grading:l,hypothesisId:u?.hypothesisId??"",editablePaths:O2(d,r,a.dirtyPaths),budgets:r.budgets,model:t.repairModel??t.remote.model,caps:p,transport:t.remote.transport,now:i()});if(f.kind!=="preview-ready"){let w=f.reasonCode==="repair-not-eligible"&&u?.probableOwner!=="test-support"?ad(c):f.reasonCode,x=f.reasonCode==="repair-not-eligible"||sd.has(f.reasonCode);return s({outcome:x?"abstained-from-repair":"operation-failed",reasonCode:w,message:f.message},{proposal:{status:x?"not-eligible":"failed"},repairAudit:f.audit})}let h=await j2(t,n),m=(w,x={})=>s(w,{...h===void 0?{}:{confirmation:h},...x});if(h?.status==="not-reproduced")return m({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:h.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await t.interaction.approveRepairRequest(f.prepared.preview))return m({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let g=await Np({prepared:f.prepared,authorization:{bindingHash:f.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:i(),authorizationId:Xr()},authorizationStore:t.authorizationStore??new qn,transport:t.remote.transport,now:i()});if(g.kind==="declined")return m({outcome:"abstained-from-repair",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"not-eligible"},repairAudit:g.audit});if(g.kind!=="proposed")return m({outcome:"operation-failed",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"failed"},repairAudit:g.audit});let y=await _p({packet:d,diagnosis:c,grading:l,config:r,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:g.draft.intent,replacements:g.draft.replacements});if(y.kind==="rejected"){let[w]=y.reasons;return m({outcome:"abstained-from-repair",reasonCode:w?.code??"invalid-replacement",message:y.reasons.map(x=>x.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:g.audit,proposalRejections:y.reasons})}return t.proposeOnly===!0?m({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:g.audit,repairProposal:y.proposal}):jx({input:t,now:i,run:n.run,packet:d,diagnosis:c,...n.representativeId===void 0?{}:{representativeId:n.representativeId},...n.clusterStages?.[0]===void 0?{}:{memberIds:n.clusterStages[0].cluster.logicalTestIds},proposal:y.proposal,config:r,repository:a,diagnosisAudit:n.result.audit,repairAudit:g.audit,caps:p,...t.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:t.retryRepairSessionId}},...o===void 0?{}:{ciApprover:o},finish:m})}import{randomUUID as F2}from"node:crypto";import{realpath as B2}from"node:fs/promises";import{join as H2,relative as z2,sep as Jp}from"node:path";var V2={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},U2=32*1024*1024,q2=new Set(["applied","validating"]);function G2(){return`vld_${F2().replaceAll("-","").slice(0,24)}`}function K2(t){return{config:t.config,snapshot:{workspaceRoot:t.workspace.workspaceRoot,gitRoot:t.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:t.workspace,maxTargetBytes:t.maxTargetBytes}}function W2(t,n,e){let r=i=>z2(t,`${n}${Jp}${i.split("/").join(Jp)}`).split(Jp).join("/");for(let i of e.commandRecords){let s=i.artifacts.find(d=>d.path.endsWith("/report.json"));if(s!==void 0)return r(s.path);let o=i.artifacts.filter(d=>ja.test(d.path.split("/").at(-1)??""))[0];if(o!==void 0)return r(o.path.split("/").slice(0,-1).join("/"))}}async function J2(t,n,e){let r=n.group;if(r===void 0||r.logicalTestIds.length===0||t.checkGroup===void 0)return;let{logicalTestIds:i}=r,s=`${i.length} other test${i.length===1?"":"s"}`,a=await ct(H2(e,r.reportPath),{workspaceRoot:e,gitRoot:n.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),o=a.kind==="parsed"?new Set(a.run.logicalTests.map(u=>u.logicalTestId)):void 0;if(a.kind!=="parsed"||!i.every(u=>o?.has(u)))return{status:"unavailable",logicalTestIds:i,message:`The report fix read has changed, so the group's ${s} were not re-run.`};let d=await t.checkGroup(a.run,i);if(d.kind==="declined")return{status:"declined",logicalTestIds:i,message:`The group's ${s} were not re-run.`};if(d.kind==="unavailable")return{status:"unavailable",logicalTestIds:i,message:d.message};let c=i.filter(u=>d.failedAgain.includes(u)),l=c.map(u=>a.run.logicalTests.find(p=>p.logicalTestId===u)?.title??u).map(u=>`"${u}"`).join(", ");return{status:"rerun",logicalTestIds:i,stillFailing:c,message:c.length===0?`The group's ${s} pass now as well.`:`${c.length} of the group's ${s} still fail${c.length===1?"s":""}: ${l}. The patch stays; run \`kwikqa fix\` again for them.`}}async function yd(t){let n=t.now??(()=>new Date().toISOString()),e=()=>new Date().toISOString(),r=await B2(t.workspaceRoot),i=await Sl(r);if(i.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:i.reasons.map(P=>P.message).join(" ")};let s=i.transactions.filter(P=>q2.has(P.phase));if(s.length!==1||s[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:s.length===0?"There is no applied repair waiting for validation. Run `kwikqa fix` first.":"More than one repair is waiting for validation; recover the workspace first."};let a=await Re(r,s[0].transactionId),o=a.manifest.preview.authoritativeValidation,d=await Ox(r,o.repairSessionId,o.attemptOrdinal);if(d.transactionId!==a.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(d.plan.planHash!==o.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=K2(d),l=d.transactionId,u=d.plan,p;if(a.state.phase==="validating"){let P=a.state.history.findLast(C=>C.type==="validation-started");if(P?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");p=P.validationRunId}else{p=G2();let P=await qp({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,now:e()});if(P.kind==="rejected"||P.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:P.reasons.map(C=>C.message).join(" ")};for(let C of u.commands)if(!(!C.required||C.timing!=="post-patch")){if(t.signal?.aborted===!0)break;await _c({workspaceRoot:r,repositoryRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,commandId:C.commandId,limits:V2,...t.signal===void 0?{}:{signal:t.signal}}).catch(()=>{})}}let f=await pl({workspaceRoot:r,gitRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,reportMaxBytes:U2,completedAt:e()}),h=f.manifest,m={repairSessionId:d.repairSessionId,attempt:d.attempt,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash};if(h.status==="passed"&&(await Gp({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash,now:e()})).kind==="completed"){await Wa({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:n()});let C=await J2(t,d,r);return Yp(t,d,n,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${C?.message===void 0?"":` ${C.message}`}`,application:"applied",validation:"passed",repair:m,...C===void 0?{}:{groupCheck:C}})}await Wa({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:n()});let g=await El(c,l,e()),y=h.status==="passed"?"incomplete":h.status,w=y==="failed"?"validation-failed":y==="unavailable"?"validation-unavailable":"validation-incomplete";if(g.kind!=="rolled-back")return Yp(t,d,n,{outcome:"repair-failed",reasonCode:"rollback-conflicted",message:"Validation did not pass and the patch could not be rolled back automatically because the files changed; resolve them manually.",application:"recovery-required",validation:y==="blocked"?"incomplete":y,repair:m});let v=(await Ml({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,proof:{transactionId:l,phase:"rolled-back",transactionRevision:g.transaction.revision},now:n()})).retry!==void 0,R=v?W2(r,f.directory,h):void 0;return Yp(t,d,n,{outcome:"repair-failed",reasonCode:w,message:v?"Validation did not pass, so the patch was rolled back. One retry is available.":"Validation did not pass, so the patch was rolled back. No retry remains.",application:"rolled-back",validation:y==="blocked"?"incomplete":y,repair:{...m,retryAvailable:v,...R===void 0?{}:{retryReportPath:R}}})}async function Yp(t,n,e,r){let i={schemaVersion:"1.1",recordId:rd(),command:"validate",...n.record,recordedAt:e(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:r.application},validation:{status:r.validation},repair:r.repair,...r.groupCheck===void 0?{}:{groupCheck:r.groupCheck},outcome:r.outcome,reasonCode:r.reasonCode,message:r.message};if(t.persist===!1)return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i};try{let s=await Ts(n.workspace.workspaceRoot,i);return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i,recordPath:s}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${i.message} The run record could not be written safely under .kwikqa/runs/.`,record:i}}}var Y2=1200*1e3,X2=10,Q2=1e3,Z2=15e3,eD=3e3,tD=6e4,Gx=3e4,nD=2;function Qp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Wx(t){try{let n=await t.json();return Qp(n)?n:void 0}catch{return}}async function rD(t){return await Wx(t)??{}}function Kx(t){return typeof t=="number"&&Number.isFinite(t)?Math.min(Z2,Math.max(Q2,t)):eD}function Xp(t){let n=Qp(t.error)?t.error:void 0;return typeof n?.message=="string"?n.message:void 0}var gd=class{constructor(n){this.options=n}options;preflight(n){return this.options.preflight.preflight(n)}async complete(n){let e=performance.now(),r=()=>performance.now()-e;for(let i=0;;i+=1){let s=await this.#e(n,r);if(s!=="interrupted")return s;if(i===nD)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:r()};this.options.onRestart?.()}}async#e(n,e){let r=(u,p)=>({kind:"failed",code:u,message:p,elapsedMs:e()}),i=wp(n);if(i!==void 0)return{kind:"failed",code:"invalid-request",message:i,elapsedMs:0};let s;try{s=await this.#t("POST","/v1/jobs",tD,{headers:{...this.options.headers(n.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(n.body)})}catch(u){return r("network-error",`The model request could not reach the KwikQA service (${ks(u)}).`)}let a=await rD(s);if(s.status!==202){let u=Vo(a);return{kind:"failed",code:"http-error",message:Xp(a)??"The KwikQA service refused the model request.",httpStatus:s.status,...u===void 0?{}:{providerCode:u},elapsedMs:e()}}let o=a.jobId;if(typeof o!="string"||o==="")return r("invalid-json","The KwikQA service did not name the job it started.");let d=this.options.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=Kx(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??Y2))return await this.#n(o),r("timeout","The model did not answer in time; nothing was charged.");await d(c);let u;try{u=await this.#t("GET",`/v1/jobs/${o}`,Gx)}catch{u=new Response(null,{status:599})}let p=u.status>=500?void 0:await Wx(u);if(u.status===404)return"interrupted";if(u.status<500&&!u.ok)return{kind:"failed",code:"http-error",message:Xp(p??{})??"The KwikQA service refused to report the job.",httpStatus:u.status,elapsedMs:e()};if(p===void 0){if(l+=1,l>X2)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}if(l=0,p.status==="running"){this.options.onProgress?.(e()),c=Kx(p.pollAfterMs);continue}if(p.status==="failed")return Qp(p.error)&&p.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:Xp(p)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:e()};if(p.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#n(o);let f=typeof p.httpStatus=="number"?p.httpStatus:502,h=p.result,m=f>=200&&f<300;if(!m||gp(h)){let g=Vo(h),y=m?g??502:f;return{kind:"failed",code:"http-error",message:yp(y,h),httpStatus:y,...g===void 0?{}:{providerCode:g},elapsedMs:e()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:f,body:h,elapsedMs:e()}}}async#n(n){try{await this.#t("DELETE",`/v1/jobs/${n}`,Gx)}catch{}}#t(n,e,r,i={}){return this.options.fetch(`${this.options.baseUrl}${e}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...i.headers},...i.body===void 0?{}:{body:i.body},redirect:"error",signal:AbortSignal.timeout(r)})}};var iD="https://api.kwikqa.com",Zr="https://kwikqa.com/dashboard/";function Jx(t){return t.hosted??!(t.plan==="byo"||t.plan==="byo-team")}function sD(t){return t?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var yt=class extends Error{constructor(e,r,i){super(i);this.status=e;this.code=r}status;code};function cn(t,n){return(t.KWIKQA_API_URL??(n===void 0||n===""?iD:n)).replace(/\/+$/,"")}function Yx(t){let n=t?.messages;if(!Array.isArray(n))return;let e=n.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(e!==void 0)try{let r=JSON.parse(e.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var Tt=class{constructor(n,e,r=fetch){this.baseUrl=n;this.token=e;this.fetchImpl=r}baseUrl;token;fetchImpl;async#e(n,e,r,i,s){let a=()=>this.fetchImpl(`${this.baseUrl}${e}`,{method:n,headers:{Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...i===void 0?{}:{"X-KwikQA-Retry-Ticket":i},...s===void 0?{}:{"X-KwikQA-Session":s}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),o;try{o=await a().catch(c=>{if(n==="GET")return a();throw c})}catch(c){throw new yt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${ks(c)}).`)}let d;try{d=await o.json()}catch{d=void 0}if(!o.ok){let c=d?.error;throw new yt(o.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${o.status}.`)}return d}startDeviceLogin(){return this.#e("POST","/v1/auth/device")}pollDeviceLogin(n){return this.#e("POST","/v1/auth/token",{deviceCode:n})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(n,e){return this.#e("POST","/v1/billing/checkout",{plan:n,...e})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(n,e,r){return this.#e("POST","/v1/usage/reserve",n,e,r)}openSession(n,e="diagnosis"){return this.#e("POST","/v1/usage/session",e==="diagnosis"?{requests:n}:{requests:n,kind:e})}async closeSession(n){let r=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,n))?.retryTicket;return typeof r=="string"&&r!==""?{retryTicket:r}:{}}reportInsights(n){return this.#e("POST","/v1/insights",{events:n})}releaseUsage(n,e){return this.#e("POST","/v1/usage/release",{id:n,status:e})}logout(){return this.#e("POST","/v1/auth/logout")}transport(n){let e=s=>{let a=Yx(s),o=sD(s)?n.session?.():n.repairSession?.();return{...n.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":n.retryTicket},...o===void 0?{}:{"X-KwikQA-Session":o},...a===void 0?{}:{"X-KwikQA-Framework":a}}},r=s=>{let a=s?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&n.onRetryTicket?.(a)},i=new Wn({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:e,onCompletionBody:r});return n.jobs!==!0||this.token===void 0?i:new gd({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:i,headers:e,onCompletionBody:r,...n.onProgress===void 0?{}:{onProgress:n.onProgress},...n.onRestart===void 0?{}:{onRestart:n.onRestart},...n.sleep===void 0?{}:{sleep:n.sleep}})}},wd=class{constructor(n,e,r={}){this.inner=n;this.client=e;this.options=r}inner;client;options;preflight(n){return this.inner.preflight(n)}async complete(n){let r=n.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",i;try{let a=Yx(n.body);i=await this.client.reserveUsage({kind:r,model:n.route.modelId,provider:n.route.providerSlug,...a===void 0?{}:{framework:a}},this.options.retryTicket,r==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(a){if(!(a instanceof yt))throw a;return{kind:"failed",code:"http-error",message:a.message,elapsedMs:0,...a.status===0?{}:{httpStatus:a.status}}}i.retryTicket!==void 0&&this.options.onRetryTicket?.(i.retryTicket);let s=await this.inner.complete(n);return s.kind!=="response"&&await this.client.releaseUsage(i.id,s.httpStatus??599).catch(()=>{}),s}};import{mkdir as aD,readFile as oD,rm as dD,writeFile as cD}from"node:fs/promises";import{homedir as Xx}from"node:os";import{join as $s}from"node:path";function Qx(t){return t.KWIKQA_CONFIG_DIR!==void 0&&t.KWIKQA_CONFIG_DIR!==""?t.KWIKQA_CONFIG_DIR:process.platform==="win32"?$s(t.APPDATA??$s(Xx(),"AppData","Roaming"),"kwikqa"):$s(t.XDG_CONFIG_HOME??$s(Xx(),".config"),"kwikqa")}function Zp(t){return $s(Qx(t),"credentials.json")}async function ln(t){if(t.KWIKQA_TOKEN!==void 0&&t.KWIKQA_TOKEN.trim()!=="")return{token:t.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let n=JSON.parse(await oD(Zp(t),"utf8"));return typeof n.token!="string"||n.token===""||typeof n.login!="string"||typeof n.apiUrl!="string"?void 0:{token:n.token,login:n.login,apiUrl:n.apiUrl}}catch{return}}async function Zx(t,n){await aD(Qx(t),{recursive:!0,mode:448}),await cD(Zp(t),`${JSON.stringify(n)}
222
- `,{mode:384})}async function ev(t){await dD(Zp(t),{force:!0})}import{appendFile as tv}from"node:fs/promises";function Le(t,n=!0){return{reason:t,misconfigured:n}}var rv={noun:"pull request",sigil:"#"},nv={noun:"merge request",sigil:"!"};async function ef(t,n,e,r,i=rv){if(n.kind==="open")return await r(n.number),`fix ${i.noun} ${i.sigil}${n.number} is already open for it, so no repair was requested; this run is noted there`;if(n.kind==="branch")return`its fix branch ${ft(e)} is left from an earlier fix, without an open ${i.noun}, so no repair was requested; delete the branch to let KwikQA open a new fix`;n.kind==="unknown"&&t.io.print(`Couldn't check for an open fix ${i.noun}: ${n.reason}.`)}function tf(t,n,e,r=rv){let i=`Fix ${r.noun}`;n.kind==="opened"?t.io.print(`${i}: opened ${r.sigil}${n.number}, a draft into ${e}${n.url===void 0?"":`: ${n.url}`}.`):n.kind==="skipped"?t.io.print(`No fix ${r.noun}: ${n.reason}.`):t.io.error(`No fix ${r.noun}: ${n.reason}.`)}function nf(t){return(t.fix.repairProposal?.targets??[]).map(n=>({path:n.path,sourceSha256:n.sourceSha256,resultSha256:n.resultSha256}))}function iv(t,n){let{repository:e,runId:r,runAttempt:i,commit:s}=n;if(e===void 0||r===void 0||i===void 0||s===void 0)return"`kwikqa fix` in CI needs GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, and GITHUB_SHA as GitHub Actions sets them.";let a={system:"GitHub Actions",ci:{system:"github-actions",repository:e,runId:r,runAttempt:i,commit:s.sha},checkout:{variable:"GITHUB_WORKSPACE",path:t.env.GITHUB_WORKSPACE||void 0}},o=n.pullRequest;if(o?.fork===!0)return{...a,host:{reason:`the pull request comes from a fork, and GitHub gives its workflows a read-only token, so no fix pull request can be opened. A maintainer can check out the pull request (\`gh pr checkout ${o.number}\`) and run \`npx kwikqa fix\``,misconfigured:!1,note:async()=>{n.summaryPath!==void 0&&await tv(n.summaryPath,`
218
+ `,changed:i}}function $p(t){let n=[],e={},r=0;for(let i of[...t].sort((s,a)=>s.path.localeCompare(a.path))){let s=n$(i);n.push(s.text),e[i.path]=s.changed,r+=s.changed}return{text:n.join(""),changedFiles:t.length,changedLines:r,perFileChangedLines:e}}function Zb(t,n){return t.changedFiles<=n.maxFiles&&t.changedLines<=n.maxChangedLines?[]:[{code:"budget-exceeded",message:`Proposal changes ${t.changedFiles} files and ${t.changedLines} lines; configured limits are ${n.maxFiles} files and ${n.maxChangedLines} lines.`,manualRepairRecommended:!0}]}function ex(t,n,e,r){let i=[];(n.packetHash!==t.packetHash||e.packetHash!==t.packetHash||!e.passed)&&i.push({code:"invalid-provenance",message:"Diagnosis and passing deterministic grading must match the evidence packet."});let s=[...n.hypotheses].sort((d,c)=>d.rank-c.rank)[0],a=new Set(t.evidence.map(d=>d.evidenceId)),o=new Set(n.ownershipEvidenceIds);return(n.repairEligibility!=="eligible"||s===void 0||s.probableOwner!=="test-support"||!new Set(["strong","moderate"]).has(s.evidenceGrade)||o.size===0||[...o].some(d=>!a.has(d)||!s.supportingEvidenceIds.includes(d)))&&i.push({code:"insufficient-ownership-evidence",message:"Repair requires a sufficiently graded test-support hypothesis with positive evidence."}),(r.statement.trim().length===0||r.preservedBehavior.trim().length===0||r.evidenceIds.length===0||r.evidenceIds.some(d=>!a.has(d)||!s?.supportingEvidenceIds.includes(d)))&&i.push({code:"intent-ambiguous",message:"Test intent and preserved behavior require valid positive evidence citations."}),i.length>0||s===void 0?{kind:"rejected",reasons:i}:{kind:"eligible",hypothesis:s}}var tx=Bs(vi(),1),r$=/\.([cm]?[jt]sx?)$/i;function Dp(t,n){let e=t.match(r$)?.[1]?.toLowerCase();if(e===void 0)return!1;let r=[];e.includes("t")&&r.push("typescript"),e.endsWith("x")&&r.push("jsx");try{return(0,tx.parse)(n,{sourceType:"unambiguous",errorRecovery:!1,plugins:r}),!0}catch{return!1}}var i$=[{pattern:/\b(?:test|describe|it|context|specify)\.(?:skip|only|fixme)\s*\(|\bx(?:it|test|describe|context|specify)\s*\(|\bf(?:it|describe)\s*\(/g,message:"skip, focus, and expected-failure controls are forbidden",exception:"never"},{pattern:/\bwaitForTimeout\s*\(|\bcy\.wait\(\s*\d|\.pause\s*\(/g,message:"arbitrary fixed waits are forbidden",exception:"never"},{pattern:/\bforce\s*:\s*true\b/g,message:"forcing actions past actionability checks is forbidden",exception:"never"},{pattern:/uncaught:exception/g,message:"suppressing application errors is forbidden",exception:"never"},{pattern:/\bthis\.retries\s*\(|\bretries\s*\(\s*\d/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\bsetTimeout\s*\(/g,message:"timeout increases require a demonstrated latency contract",exception:"latency"},{pattern:/\bretries\s*:/g,message:"retry additions are forbidden",exception:"never"},{pattern:/\btoMatchSnapshot\s*\(/g,message:"broad snapshot acceptance is forbidden",exception:"never"},{pattern:/catch\s*\([^)]*\)\s*\{\s*\}/g,message:"empty catches swallow errors",exception:"never"},{pattern:/\.locator\(\s*["'`](?:#|\.|\/\/|css=)/g,message:"brittle locator regressions require positive evidence",exception:"locator"},{pattern:/(?:\bcy\.get|\.find|(?<![\w$])\$\$?)\(\s*["'`](?:#|\.[A-Za-z_-]|\/\/|\.\/\/)/g,message:"brittle locator regressions require positive evidence",exception:"locator"}];function As(t,n){return[...t.matchAll(n)].length}function nx(t){return As(t,/\bexpect\s*\(/g)+As(t,/\bassert(?:\.|\s*\()/g)+As(t,/\.(?:should|and)\s*\(/g)}function rx(t){let n=new Map;for(let e of t.matchAll(/\.((?:(?:not|resolves|rejects)\.)*)(to[A-Z]\w*)\s*\(/g)){let r=`${e[1]??""}${e[2]??""}`;n.set(r,(n.get(r)??0)+1)}for(let e of t.matchAll(/\.(?:should|and)\s*\(\s*["'`]([\w.]+)["'`]/g)){let r=`should:${e[1]??""}`;n.set(r,(n.get(r)??0)+1)}return n}function s$(t,n){let e=rx(n);return[...rx(t)].filter(([r,i])=>(e.get(r)??0)<i).map(([r])=>r).sort()}function ix(t){let n=[];for(let e of t){if(!Dp(e.path,e.source)||!Dp(e.path,e.result)){n.push({code:"parse-failed",message:"Original and resulting source must parse as supported JavaScript or TypeScript.",path:e.path});continue}let r=s$(e.source,e.result);r.length>0&&n.push({code:"forbidden-edit",message:`The proposal removes, negates, or swaps assertion matchers: ${r.join(", ")}.`,path:e.path});for(let i of e.replacements){nx(i.newText)<nx(i.oldText)&&n.push({code:"forbidden-edit",message:"The proposal removes or weakens assertion coverage.",path:e.path});for(let s of i$){if(As(i.newText,s.pattern)<=As(i.oldText,s.pattern))continue;let a=s.exception==="latency"?i.latencyContractEvidenceIds??[]:s.exception==="locator"?i.brittleLocatorEvidenceIds??[]:[];s.exception!=="never"&&a.length>0||n.push({code:"forbidden-edit",message:s.message,path:e.path})}}}return n}var a$=/^(?:\.\/)?[A-Za-z0-9_./-]+$/,o$=/^[A-Z][A-Z0-9_]*$/,d$=/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTH)/i,c$=new Set(["focused","affected","static"]);function sx(t){return t.length>0&&!t.includes("\0")&&!t.includes("\\")&&!t.startsWith("/")&&!/^[A-Za-z]:/.test(t)&&!t.split("/").some(n=>n===".."||n==="")}var l$=new Set(["page-object","fixture","test-data","test-helper","playwright-config","framework-config"]);function u$(t){let n=Object.entries(t.environment);return t.id.trim().length>0&&a$.test(t.executable)&&sx(t.executable.replace(/^\.\//,""))&&!t.args.some(e=>e.includes("\0"))&&(t.workingDirectory==="."||sx(t.workingDirectory))&&c$.has(t.scope)&&n.every(([e,r])=>o$.test(e)&&!d$.test(e)&&!r.includes("\0"))&&Number.isInteger(t.timeoutMs)&&t.timeoutMs>0&&t.reason.trim().length>0}function ax(t,n){let e=n.some(s=>l$.has(s)),r=[...t.validation].sort((s,a)=>s.id.localeCompare(a.id));if(r.some(s=>!u$(s)))return{plan:{status:"unresolved",steps:[],unresolvedReasons:["Validation discovery supplied an unsafe or malformed structured step."]},reasons:[{code:"invalid-provenance",message:"Validation plan inputs must be safe structured executable/argument records."}]};let i=[];return r.length===0&&i.push("No deterministic validation steps were discovered."),e&&!r.some(s=>s.scope==="affected")&&i.push("Shared test-support edits require affected-test validation."),{plan:{status:i.length===0?"planned":"unresolved",steps:r,unresolvedReasons:i},reasons:[]}}var Lp=1e6,Mp=1e3;function it(t){return{kind:"rejected",reasons:t}}function p$(t){let{packetHash:n,...e}=t;return Ir(e)===n}function f$(t,n){let e=[];for(let r of t)[...r.evidenceIds,...r.latencyContractEvidenceIds??[],...r.brittleLocatorEvidenceIds??[]].some(s=>!n.has(s))&&e.push({code:"invalid-replacement",message:"Every replacement and policy exception must cite accepted supporting evidence.",path:r.path});return e}async function _p(t){let n=Zn(t.config);if(n.kind!=="valid")return it(n.issues.map(p=>({code:"invalid-config",message:p})));if(!p$(t.packet)||t.snapshot.workspaceRoot!==t.packet.workspace.root||t.packet.workspace.gitRoot!==void 0&&t.snapshot.gitRoot!==t.packet.workspace.gitRoot)return it([{code:"invalid-provenance",message:"Packet integrity and repository snapshot identity must match."}]);let e=ex(t.packet,t.diagnosis,t.grading,t.intent);if(e.kind!=="eligible")return it(e.reasons);let r=t.maxSourceBytes??Lp;if(!Number.isInteger(r)||r<=0||r>Lp)return it([{code:"invalid-provenance",message:`maxSourceBytes must be an integer from 1 to ${Lp}.`}]);if(t.replacements.length===0)return it([{code:"invalid-replacement",message:"Proposal has no replacements."}]);let i=f$(t.replacements,new Set(e.hypothesis.supportingEvidenceIds));if(i.length>0)return it(i);let s=await by(n.config,t.snapshot,t.replacements,r);if(s.kind!=="authorized")return it(s.reasons);if(s.targets.some(p=>p.source.split(/\r?\n/u).length>Mp||p.replacements.some(f=>f.newText.split(/\r?\n/u).length>Mp)))return it([{code:"budget-exceeded",message:`M5 safely derives diffs only for targets and replacement text up to ${Mp} lines.`,manualRepairRecommended:!0}]);let a=gy(s.targets);if(a.kind!=="applied")return it(a.reasons);let o=ix(a.targets);if(o.length>0)return it(o);let d=$p(a.targets),c=Zb(d,n.config.budgets);if(c.length>0)return it(c);let l=ax(t.snapshot,a.targets.map(p=>p.class));if(l.reasons.length>0)return it(l.reasons);let u={schemaVersion:"1.0",policyVersion:"1.0",runId:t.packet.runId,packetHash:t.packet.packetHash,acceptedHypothesisId:e.hypothesis.hypothesisId,intent:t.intent,budgets:n.config.budgets,changedFiles:d.changedFiles,changedLines:d.changedLines,replacements:t.replacements,targets:a.targets.map(p=>({path:p.path,class:p.class,sourceSha256:p.sourceSha256,resultSha256:p.resultSha256,changedLines:d.perFileChangedLines[p.path]??0})),diff:d.text,diffHash:L(d.text),validationPlan:l.plan};return{kind:"proposal-ready",proposal:{...u,proposalHash:L(u)}}}import{readFile as A$,realpath as bx}from"node:fs/promises";import{join as T$,relative as P$,sep as S$}from"node:path";var h$=new Set(["failed","timedOut","interrupted"]);function m$(t){return t.status==="unexpected"||t.status==="flaky"}function cx(t){return[...t.clusters].sort((n,e)=>e.logicalTestIds.length-n.logicalTestIds.length||n.clusterId.localeCompare(e.clusterId)).slice(0,6)}function y$(t){return t.attachments.reduce((n,e)=>n+(e.name==="trace"||e.contentType==="application/zip"?10:e.path===void 0?0:1),0)}function lx(t,n){let e=new Set(n.logicalTestIds);return t.logicalTests.filter(i=>e.has(i.logicalTestId)).map(i=>{let s=i.attempts.filter(a=>h$.has(a.status));return{test:i,score:Math.max(0,...s.map(y$)),startedAt:s.map(a=>a.startTime).sort()[0]??""}}).sort((i,s)=>s.score-i.score||i.startedAt.localeCompare(s.startedAt)||i.test.logicalTestId.localeCompare(s.test.logicalTestId))[0]?.test}function ux(t,n,e){let r=new Set(n.logicalTestIds);return{...t,logicalTests:t.logicalTests.map(i=>r.has(i.logicalTestId)?i.logicalTestId===e?i:{...i,attempts:i.attempts.map(s=>({...s,attachments:[]}))}:m$(i)?{...i,attempts:[]}:i)}}function px(t,n,e){return{...e,runId:n.runId,clusters:[{...t,symptomIds:n.symptoms.filter(r=>r.logicalTestId!==void 0&&t.logicalTestIds.includes(r.logicalTestId)).map(r=>r.symptomId).sort()}]}}async function fx(t,n,e){let r=new Array(t.length),i=0,s=Array.from({length:Math.min(n,t.length)},async()=>{for(;i<t.length;){let a=i;i+=1,r[a]=await e(t[a])}});return await Promise.all(s),r}import{randomUUID as hx}from"node:crypto";import{readdir as mx,readFile as g$,realpath as w$}from"node:fs/promises";import{join as Yr,relative as b$,sep as x$}from"node:path";var jp=/^run_[a-f0-9]{24}$/,Fp=/^rec_[a-f0-9]{24}$/;function rd(){return`rec_${hx().replaceAll("-","").slice(0,24)}`}function Xr(){return`auth_${hx().replaceAll("-","").slice(0,24)}`}async function Ts(t,n){if(!jp.test(n.runId)||!Fp.test(n.recordId))throw new Error("Run record identity is not path-safe.");let e=await ze(t,[".kwikqa","runs",n.runId]),r=await ze(t,[".kwikqa","runs",n.runId,"records"]),i=`${ue(n)}
219
+ `,s=Yr(r,`${n.recordId}.json`);return await ye(s,i,{mode:384,replace:!1}),await ye(Yr(e,"result.json"),i,{mode:384,replace:!0}),b$(await w$(t),s).split(x$).join("/")}var v$=new Set(["analyze","fix","validate"]),k$=["analysis","proposal","application","validation"];function R$(t,n){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.schemaVersion=="string"&&e.schemaVersion.startsWith("1.")&&typeof e.recordId=="string"&&Fp.test(e.recordId)&&e.runId===n&&typeof e.command=="string"&&v$.has(e.command)&&typeof e.recordedAt=="string"&&typeof e.outcome=="string"&&typeof e.reasonCode=="string"&&typeof e.message=="string"&&k$.every(r=>typeof e[r]=="object"&&e[r]!==null)}async function yx(t,n){try{let e=JSON.parse(await g$(t,"utf8"));return R$(e,n)?e:void 0}catch{return}}async function Bp(t,n){if(!jp.test(n))return[];let e=Yr(t,".kwikqa","runs",n,"records"),r=await mx(e).catch(()=>[]);return(await Promise.all(r.filter(s=>Fp.test(s.replace(/\.json$/,""))&&s.endsWith(".json")).map(s=>yx(Yr(e,s),n)))).filter(s=>s!==void 0).sort((s,a)=>s.recordedAt.localeCompare(a.recordedAt)||s.recordId.localeCompare(a.recordId))}async function Hp(t){let n=Yr(t,".kwikqa","runs"),e=(await mx(n).catch(()=>[])).filter(i=>jp.test(i)),r;for(let i of e){let s=await yx(Yr(n,i,"result.json"),i);s!==void 0&&(r===void 0||s.recordedAt>r.recordedAt)&&(r=s)}return r?.runId}var sd=new Set(["context-limit-exceeded","request-token-budget-exceeded","request-dollar-budget-exceeded","run-token-budget-exceeded","run-dollar-budget-exceeded"]),E$={"test-support":"test-support-owned",application:"application-owned",environment:"environment-owned",undetermined:"owner-undetermined"};function C$(t){return t.logicalTests.filter(n=>n.status==="unexpected"||n.status==="flaky").map(n=>n.logicalTestId).sort()}function N$(t,n){switch(t.usability){case"zero-tests":return{reasonCode:"zero-tests",message:"The report contains no tests to diagnose."};case"interrupted":return{reasonCode:"interrupted-run",message:"The run was interrupted, so its failures cannot support a diagnosis."};case"report-errors":return{reasonCode:"report-errors",message:"The report has run-level errors, so its failures cannot support a diagnosis."};case"analysis-ready":return n.length===0?{reasonCode:"no-failures",message:"The run has no failing or flaky tests."}:void 0}}async function gx(t,n){let e=await bx(n).catch(()=>n);return P$(t,e).split(S$).join("/")}async function O$(t,n){return{report:await gx(n,t.reportPath),...t.framework===void 0?{}:{framework:t.framework},...t.probePath===void 0?{}:{probe:await gx(n,t.probePath)},changeHistory:t.includeChangeHistory===!0,currentDiff:t.includeCurrentDiff===!0,maxPacketBytes:t.evidencePolicy.maxPacketBytes}}function ad(t){let n=[...t.hypotheses].sort((e,r)=>e.rank-r.rank)[0];return E$[n?.probableOwner??"undetermined"]??"owner-undetermined"}function $$(t,n){return t==="operation-failed"?"failed":n?"insufficient-evidence":"completed"}async function Ss(t,n){let e=await ct(t.reportPath,{workspaceRoot:t.workspaceRoot,...t.gitRoot===void 0?{}:{gitRoot:t.gitRoot},...t.framework===void 0?{}:{framework:t.framework}});if(e.kind==="unreadable")return{kind:"unreadable",outcome:"inconclusive",reasonCode:e.artifact.availability==="unavailable"?"report-unavailable":"report-unreadable",message:e.diagnostic.message};let r=e.run,i=C$(r),s=await O$(t,r.workspace.root),a=(v,R={})=>({kind:"analyzed",stage:{run:r,failing:i,inputs:s,...R,result:v}});if(t.repairableOnly===!0&&Ze(r)===void 0)return a({outcome:"inconclusive",reasonCode:"report-only-framework",message:lt(r),insufficient:!0});let o=await fo(r,{artifactRoot:t.artifactRoot??r.workspace.root,includeCurrentDiff:t.includeCurrentDiff===!0,includeChangeHistory:t.includeChangeHistory===!0,...t.probePath===void 0?{}:{probePath:t.probePath}},{...t.evidencePolicy,workspaceRoot:r.workspace.root});if(o.kind!=="built")return a(o.kind==="invalid-policy"?{outcome:"operation-failed",reasonCode:"invalid-evidence-policy",message:o.message}:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:o.message,insufficient:!0});let d=o.packet,c=go(r,d),l=gu(c),u={packet:d,symptoms:c,clusters:l},p={...u,triage:u},f=N$(r,i);if(f!==void 0)return a({outcome:"inconclusive",...f,insufficient:!0},p);if(t.remote===void 0)return a({outcome:"inconclusive",reasonCode:"remote-diagnosis-not-configured",message:"Local evidence analysis completed; no remote diagnosis was configured."},p);let h=await F$(t,r,l,n),m=M$(h);if(m===void 0)return a({outcome:"inconclusive",reasonCode:"no-failures",message:"No failing test produced a symptom to diagnose.",insufficient:!0},p);let g=h.filter(v=>v.result.reasonCode!=="cluster-not-requested"),y=g.filter(v=>v.result.outcome==="diagnosed").length,w=l.clusters.length-g.length,x=l.clusters.length>1?`${y} of ${l.clusters.length} failure groups diagnosed.${w>0?` ${w} not sent: ${D$(h)}`:""}`:m.result.message;return a({...m.result,message:x},{triage:u,...m.packet===void 0?p:{packet:m.packet},...m.symptoms===void 0?{}:{symptoms:m.symptoms},...m.clusters===void 0?{}:{clusters:m.clusters},clusterStages:[m,...h.filter(v=>v!==m)],representativeId:m.representativeId})}function D$(t){return t.find(e=>e.result.reasonCode==="cluster-not-requested")?.result.message??"at most 6 groups are sent per analysis."}var L$={strong:3,moderate:2,weak:1,insufficient:0};function wx(t){let[n]=[...t.result.diagnosis?.hypotheses??[]].sort((e,r)=>e.rank-r.rank);return L$[n?.evidenceGrade??""]??0}function od(t){return t.map((n,e)=>({item:n,index:e})).filter(({item:n})=>n.result.outcome==="diagnosed"&&n.result.reasonCode==="test-support-owned").sort((n,e)=>wx(e.item)-wx(n.item)||e.item.cluster.logicalTestIds.length-n.item.cluster.logicalTestIds.length||n.index-e.index).map(({item:n})=>n)}function M$(t){let n=t.filter(e=>e.result.outcome==="diagnosed");return od(t)[0]??n[0]??t[0]}var _$=new Set(["provider-refusal","malformed-response","schema-invalid","citation-or-grading-invalid"]);async function xx(t,n,e,r){let i=lx(n,r);if(i===void 0)return;let s=ux(n,r,i.logicalTestId),a=await fo(s,{artifactRoot:t.artifactRoot??n.workspace.root,includeCurrentDiff:t.includeCurrentDiff===!0,includeChangeHistory:t.includeChangeHistory===!0,...t.probePath===void 0?{}:{probePath:t.probePath}},{...t.evidencePolicy,workspaceRoot:n.workspace.root});if(a.kind!=="built")return{cluster:r,representativeId:i.logicalTestId,result:{outcome:"inconclusive",reasonCode:"evidence-budget-exceeded",message:a.message,insufficient:!0}};let o=go(s,a.packet);return{cluster:r,representativeId:i.logicalTestId,packet:a.packet,symptoms:o,clusters:px(r,o,e)}}var j$={approveDiagnosis:async()=>!1};async function zp(t,n){let e=await Ss({...t,interaction:j$,persist:!1},()=>new Date().toISOString());if(e.kind==="unreadable")return{kind:"unreadable",message:e.message};let{run:r,triage:i}=e.stage;if(i===void 0)return{kind:"rebuilt",run:r};let s={};for(let a of i.clusters.clusters){if(!n.includes(a.clusterId))continue;let o=await xx(t,r,i.clusters,a);o?.packet!==void 0&&(s[a.clusterId]=o.packet)}return{kind:"rebuilt",run:r,detail:{...i,groupPackets:s}}}async function F$(t,n,e,r){let i=t.remote;if(i===void 0)return[];let s=cx(e),a=[],o=[];for(let g of s){let y=await xx(t,n,e,g);y!==void 0&&("result"in y?a.push(y):o.push(y))}let d=[];for(let g of o){let y=t.reuseDiagnosis===!0?await H$(n.workspace.root,n.runId,g.packet,g.symptoms):void 0;y===void 0?d.push(g):a.push(on(g,y))}let c=a.some(g=>g.result.reasonCode==="test-support-owned"),l=(g,y)=>{for(let w of g)a.push(on(w,{outcome:"inconclusive",reasonCode:"cluster-not-requested",message:y}))};if(t.reuseDiagnosis===!0&&c)return l(d,"A recorded diagnosis of another group already supports a repair."),Ps(a,s);let u=i.session===void 0?d.slice(0,1):d;l(d.slice(u.length),"the service counts each request separately, so only the largest group was sent.");let f=(await Promise.all(u.map(async g=>({item:g,prepared:await Jo({packet:g.packet,symptoms:g.symptoms,clusters:g.clusters,model:i.model,caps:i.caps,transport:i.transport,now:r()})})))).flatMap(({item:g,prepared:y})=>y.kind==="preview-ready"?[{item:g,prepared:y.prepared}]:(a.push(on(g,{outcome:sd.has(y.reasonCode)?"inconclusive":"operation-failed",reasonCode:y.reasonCode,message:y.message,audit:y.audit})),[]));if(f.length===0)return Ps(a,s);let h=f.map(g=>g.prepared.preview),m;if(t.interaction.approveDiagnoses!==void 0)m=await t.interaction.approveDiagnoses(h);else{m=!0;for(let g of h)await t.interaction.approveDiagnosis(g)||(m=!1)}if(!m){for(let g of f)a.push(on(g.item,{outcome:"inconclusive",reasonCode:"remote-consent-declined",message:"The developer declined the diagnosis request; no evidence was sent."}));return Ps(a,s)}if(i.session!==void 0)try{await i.session.open(f.length)}catch(g){let y=g instanceof Error?g.message:"The analysis session could not be opened.";for(let w of f)a.push(on(w.item,{outcome:"operation-failed",reasonCode:"session-unavailable",message:y}));return Ps(a,s)}try{let g=await fx(f,3,async y=>{let w=await vx(t,y.prepared,i.transport,r),x=i.escalation;if(x===void 0||!_$.has(w.reasonCode))return on(y.item,w);let v=await B$(t,y.item,x,i.transport,r);return v===void 0?on(y.item,w):{...on(y.item,v),escalated:!0}});a.push(...g)}finally{await i.session?.close().catch(()=>{})}return Ps(a,s)}function Ps(t,n){let e=new Map(n.map((r,i)=>[r.clusterId,i]));return[...t].sort((r,i)=>(e.get(r.cluster.clusterId)??0)-(e.get(i.cluster.clusterId)??0))}function on(t,n){return{cluster:t.cluster,representativeId:t.representativeId,packet:t.packet,symptoms:t.symptoms,clusters:t.clusters,result:n}}async function vx(t,n,e,r){let i=await Tp({prepared:n,authorization:{bindingHash:n.authorizationBindingHash,mode:"interactive",authorizedAt:r(),authorizationId:Xr()},authorizationStore:t.authorizationStore??new Gn,transport:e,now:r()});switch(i.kind){case"diagnosed":return{outcome:"diagnosed",reasonCode:ad(i.diagnosis),message:"The diagnosis passed schema validation and local grading.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};case"abstained":return{outcome:"inconclusive",reasonCode:i.reasonCode,message:"The evidence was insufficient for a supported diagnosis.",diagnosis:i.diagnosis,grading:i.grading,audit:i.audit};default:return{outcome:sd.has(i.reasonCode)?"inconclusive":"operation-failed",reasonCode:i.reasonCode,message:i.message,audit:i.audit}}}async function B$(t,n,e,r,i){let s=await Jo({packet:n.packet,symptoms:n.symptoms,clusters:n.clusters,model:e.model,caps:e.caps,transport:r,now:i()});if(s.kind==="preview-ready"&&await t.interaction.approveDiagnosis(s.prepared.preview))return vx(t,s.prepared,r,i)}async function H$(t,n,e,r){if(/^run_[a-f0-9]{24}$/.test(n))try{let i=await bx(t),s=JSON.parse(await A$(T$(i,".kwikqa","runs",n,"result.json"),"utf8")),a=u=>u==="diagnosed"||u==="inconclusive",o=[...(s.clusters??[]).filter(u=>a(u.outcome)),...a(s.outcome)?[s]:[]].find(u=>u.diagnosis?.packetHash===e.packetHash&&u.diagnosisAudit!==void 0),d=o?.diagnosis;if(o===void 0||d===void 0||o.diagnosisAudit===void 0)return;let c=ds(d,e,r);if(!c.passed)return;let l=o.outcome==="inconclusive";return{outcome:l?"inconclusive":"diagnosed",reasonCode:l?o.reasonCode??"insufficient-evidence":ad(d),message:"Reused the graded diagnosis recorded for this exact evidence packet.",diagnosis:d,grading:c,audit:o.diagnosisAudit}}catch{return}}function z$(t){return{clusterId:t.cluster.clusterId,logicalTestIds:t.cluster.logicalTestIds,representativeId:t.representativeId,signals:t.cluster.signals,...t.packet===void 0?{}:{packetHash:t.packet.packetHash},outcome:t.result.outcome,reasonCode:t.result.reasonCode,message:t.result.message,...t.result.diagnosis===void 0?{}:{diagnosis:t.result.diagnosis},...t.result.grading===void 0?{}:{grading:t.result.grading},...t.result.audit===void 0?{}:{diagnosisAudit:t.result.audit},...t.escalated===!0?{escalated:!0}:{}}}function dd(t,n,e,r,i={}){let{run:s,packet:a,symptoms:o,clusters:d}=t,c=t.result;return{schemaVersion:"1.1",recordId:rd(),command:n,runId:s.runId,createdAt:s.createdAt,recordedAt:r(),workspace:s.workspace,sourceHashes:a?.sourceHashes??s.sourceHashes,usability:s.usability,failingLogicalTestIds:t.failing,inputs:t.inputs,analysis:{status:$$(c.outcome,c.insufficient===!0)},proposal:{status:"not-requested"},application:{status:"not-requested"},validation:{status:"not-requested"},...a===void 0?{}:{evidence:{packetHash:a.packetHash,evidence:a.totals.evidence,artifacts:a.totals.artifacts,omissions:a.totals.omissions,redactions:a.totals.redactions,serializedBytes:a.totals.serializedBytes}},...o===void 0||d===void 0?{}:{symptoms:{symptoms:o.symptoms.length,unclassifiedAttempts:o.unclassifiedAttemptIds.length,clusters:d.clusters.length}},...t.clusterStages===void 0||t.clusterStages.length===0?{}:{clusters:t.clusterStages.map(z$)},...c.diagnosis===void 0?{}:{diagnosis:c.diagnosis},...c.grading===void 0?{}:{grading:c.grading},...c.audit===void 0?{}:{diagnosisAudit:c.audit},...i,outcome:e.outcome,reasonCode:e.reasonCode,message:e.message}}function V$(t,n){let e={};for(let r of n.clusterStages??[])r.packet!==void 0&&(e[r.cluster.clusterId]=r.packet);return{...t,groupPackets:e}}async function cd(t,n,e){let r={run:t.run,...t.packet===void 0?{}:{packet:t.packet},...t.symptoms===void 0?{}:{symptoms:t.symptoms},...t.clusters===void 0?{}:{clusters:t.clusters},...t.triage===void 0?{}:{detail:V$(t.triage,t)}},i=(s,a)=>({outcome:s.outcome,reasonCode:s.reasonCode,message:s.message,record:s,...a===void 0?{}:{recordPath:a},...r});if(!e)return i(n);try{return i(n,await Ts(t.run.workspace.root,n))}catch{return i({...n,outcome:"operation-failed",reasonCode:"record-write-failed",message:"The run record could not be written safely under .kwikqa/runs/."})}}async function ld(t){let n=t.now??(()=>new Date().toISOString()),e=await Ss(t,n);if(e.kind==="unreadable")return{outcome:e.outcome,reasonCode:e.reasonCode,message:e.message};let{stage:r}=e;return cd(r,dd(r,"analyze",r.result,n),t.persist!==!1)}import{randomUUID as d2}from"node:crypto";import{relative as c2,resolve as l2,sep as u2}from"node:path";import{createHash as kx}from"node:crypto";import{lstat as U$,readFile as q$,realpath as ud}from"node:fs/promises";import{isAbsolute as G$,join as K$,relative as W$,resolve as J$,sep as Y$}from"node:path";var dn=/^[a-f0-9]{64}$/,Ix=/^vld_[a-f0-9]{24}$/,X$=Gt,Q$=4*1024*1024,Z$=2*1024*1024;function er(t){return{code:"transaction-unavailable",message:t}}function Es(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Up(t,n){let e=Object.keys(t).sort(),r=[...n].sort();return e.length===r.length&&e.every((i,s)=>i===r[s])}function Vp(t){return Array.isArray(t)&&t.every(n=>typeof n=="string"&&n.length>0&&!n.includes("\0"))}function e2(t,n){let e=W$(t,n);return e===""||!G$(e)&&e!==".."&&!e.startsWith(`..${Y$}`)}function t2(t){return typeof t=="string"&&t.length>0&&Number.isFinite(Date.parse(t))}function Rx(t){return Es(t)?Up(t,["path","observedBytes","storedBytes","sha256","storedSha256","truncated","redacted"])&&typeof t.path=="string"&&t.path.length>0&&typeof t.sha256=="string"&&dn.test(t.sha256)&&typeof t.storedSha256=="string"&&dn.test(t.storedSha256)&&Number.isInteger(t.observedBytes)&&t.observedBytes>=0&&Number.isInteger(t.storedBytes)&&t.storedBytes>=0&&typeof t.truncated=="boolean"&&typeof t.redacted=="boolean":!1}function Ax(t){if(!Es(t))throw new Error("Validation command record is not an object.");let n=t,{recordHash:e,...r}=n;if(!Up(t,["schemaVersion","validationRunId","commandId","commandHash","planHash","kind","timing","required","executable","args","workingDirectory","environmentDelta","timeoutMs","purpose","logicalTestIds","projectIds","startedAt","durationMs","termination","stdout","stderr","artifacts","status","recordHash"])||n.schemaVersion!=="1.0"||!Ix.test(n.validationRunId)||!X$.test(n.commandId)||!dn.test(n.commandHash)||!dn.test(n.planHash)||n.timing!=="post-patch"||n.required!==!0||n.executable!==process.execPath||!Vp(n.args)||typeof n.kind!="string"||n.kind.length===0||typeof n.workingDirectory!="string"||n.workingDirectory.length===0||!Es(n.environmentDelta)||!Object.entries(n.environmentDelta).every(([i,s])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&typeof s=="string"&&!s.includes("\0"))||!Number.isInteger(n.timeoutMs)||n.timeoutMs<=0||typeof n.purpose!="string"||n.purpose.length===0||!Vp(n.logicalTestIds)||!Vp(n.projectIds)||!t2(n.startedAt)||!Number.isInteger(n.durationMs)||n.durationMs<0||!Es(n.termination)||n.termination.kind!=="exit"||n.termination.exitCode!==0||!Rx(n.stdout)||!Rx(n.stderr)||n.stdout.truncated||n.stderr.truncated||!Array.isArray(n.artifacts)||!n.artifacts.every(i=>Es(i)&&Up(i,["path","sha256","bytes"])&&typeof i.path=="string"&&i.path.length>0&&typeof i.sha256=="string"&&dn.test(i.sha256)&&Number.isInteger(i.bytes)&&i.bytes>=0)||n.status!=="passed"||!dn.test(e)||L(r)!==e)throw new Error("Validation command record is malformed or non-passing.");return n}function n2(t){let n=Kt(JSON.parse(t));if(n.status!=="passed")throw new Error("Validation manifest is not passing.");for(let e of n.commandRecords)Ax(e);return n}async function Tx(t){let[n,e,r,i]=await Promise.all([ud(t.workspace.workspaceRoot),ud(t.snapshot.workspaceRoot),ud(t.workspace.gitRoot),ud(t.snapshot.gitRoot)]);if(n!==e||r!==i)throw new Error("Validation workspace identity changed.");return n}async function Px(t,n,e){for(let r of e.manifest.targets){let i=await X(t,r.path,n.maxTargetBytes);if(i.kind!=="read"||i.relativePath!==r.path||i.sha256!==r.resultSha256)return!1}return!0}function Sx(t){return dn.test(t.planHash)&&Ix.test(t.validationRunId)}async function pd(t,n,e){let r=J$(t,n);if(!e2(t,r))throw new Error("Validation record path escapes its run.");let i=await U$(r);if(!i.isFile()||i.isSymbolicLink()||i.size>e)throw new Error("Validation record path is unsafe or unbounded.");return q$(r)}async function r2(t,n,e){let r=new Map(e.requiredCommands.map(i=>[i.commandId,i.commandHash]));for(let i of n.commandRecords){if(i.validationRunId!==n.validationRunId||i.planHash!==n.planHash||r.get(i.commandId)===void 0)return!1;let s=r.get(i.commandId);if(s===void 0||i.commandHash!==s)return!1;let a=await pd(t,`commands/${i.commandId}/result.json`,Z$),o=Ax(JSON.parse(a.toString("utf8")));if(L(o)!==L(i))return!1;for(let d of[i.stdout,i.stderr]){let c=await pd(t,d.path,hn);if(c.byteLength!==d.storedBytes||kx("sha256").update(c).digest("hex")!==d.storedSha256)return!1}for(let d of i.artifacts){let c=await pd(t,d.path,ir);if(c.byteLength!==d.bytes||kx("sha256").update(c).digest("hex")!==d.sha256)return!1}}return!0}async function qp(t){if(!Sx(t))return{kind:"rejected",reasons:[er("Validation identity is invalid.")]};let n=t.now??new Date().toISOString(),e;try{let r=await Tx(t.context);e=await Je(r,{operation:"begin-validation",transactionId:t.transactionId,validationRunId:t.validationRunId,at:n});let i=await Re(r,t.transactionId),s=i.state.history.at(-1);return i.state.phase==="validating"&&s?.type==="validation-started"&&s.planHash===t.planHash&&s.validationRunId===t.validationRunId?{kind:"validating",transaction:Te(i)}:i.state.phase!=="applied"||i.manifest.preview.authoritativeValidation.planHash!==t.planHash||!await Px(r,t.context,i)?{kind:"rejected",reasons:[er("Applied transaction does not match the approved validation handoff.")],transaction:Te(i)}:(i=await Ge({transaction:i,phase:"validating",type:"validation-started",planHash:t.planHash,validationRunId:t.validationRunId,now:n}),{kind:"validating",transaction:Te(i)})}catch{return{kind:"failed",reasons:[er("Validation transition failed closed.")]}}finally{await e?.release().catch(()=>{})}}async function Gp(t){if(!Sx(t)||!dn.test(t.validationManifestHash))return{kind:"rejected",reasons:[er("Validation completion identity is invalid.")]};let n=t.now??new Date().toISOString(),e;try{let r=await Tx(t.context);e=await Je(r,{operation:"complete-validation",transactionId:t.transactionId,validationRunId:t.validationRunId,at:n});let i=await Re(r,t.transactionId),s=i.manifest.preview.authoritativeValidation,a=i.state.history.at(-1);if(i.state.phase==="completed"&&a?.type==="validation-passed"&&a.planHash===t.planHash&&a.validationRunId===t.validationRunId&&a.validationManifestHash===t.validationManifestHash)return{kind:"completed",transaction:Te(i)};if(i.state.phase!=="validating"||s.planHash!==t.planHash||a?.type!=="validation-started"||a.validationRunId!==t.validationRunId||a.planHash!==t.planHash||!await Px(r,t.context,i))return{kind:"rejected",reasons:[er("Transaction is not validating this exact approved run.")],transaction:Te(i)};let o=K$(i.directory,"validation",t.validationRunId),d=await pd(o,"manifest.json",Q$),c=n2(d.toString("utf8")),l=new Set(c.requiredCommandIds),u=new Set(c.commandRecords.map(f=>f.commandId)),p=s.targetHashes;return c.manifestHash!==t.validationManifestHash||c.transactionId!==t.transactionId||c.validationRunId!==t.validationRunId||c.planHash!==t.planHash||c.repositoryFingerprint!==s.repositoryFingerprint||L(c.targetHashes)!==L(p)||l.size!==c.requiredCommandIds.length||u.size!==c.commandRecords.length||s.requiredCommandIds.some(f=>!l.has(f)||!u.has(f))||l.size!==s.requiredCommandIds.length||u.size!==s.requiredCommandIds.length||!await r2(o,c,s)?{kind:"rejected",reasons:[er("Validation manifest does not prove the exact approved command set.")],transaction:Te(i)}:(i=await Ge({transaction:i,phase:"completed",type:"validation-passed",planHash:t.planHash,validationRunId:t.validationRunId,validationManifestHash:c.manifestHash,now:n}),{kind:"completed",transaction:Te(i)})}catch{return{kind:"failed",reasons:[er("Validation completion failed closed.")]}}finally{await e?.release().catch(()=>{})}}import{join as i2}from"node:path";var Ex="1.0",s2=/^rps_[a-f0-9]{24}$/,a2=8*1024*1024;function o2(t){if(typeof t!="object"||t===null)return;let n=t;if(!(typeof n.reportPath!="string"||!Array.isArray(n.logicalTestIds)||!n.logicalTestIds.every(e=>typeof e=="string")||n.framework!==void 0&&!kt.includes(n.framework)))return{reportPath:n.reportPath,...n.framework===void 0?{}:{framework:n.framework},logicalTestIds:n.logicalTestIds}}function Cx(t){if(!s2.test(t))throw new Error("Repair session id is invalid.");return[".kwikqa","repairs",t]}async function Nx(t,n){let e=await ze(t,Cx(n.repairSessionId));await ye(i2(e,`attempt-${n.attempt}.json`),`${ue(n)}
220
+ `,{mode:384,replace:!1})}async function Ox(t,n,e){let r=await ze(t,Cx(n)),i=await vn(r,`attempt-${e}.json`,a2),s=Zn(i.config);if(i.schemaVersion!==Ex||i.repairSessionId!==n||i.attempt!==e||typeof i.transactionId!="string"||i.workspace===void 0||typeof i.maxTargetBytes!="number"||i.record===void 0||s.kind!=="valid")throw new Error("Repair attempt state is malformed.");let a=o2(i.group);return{schemaVersion:Ex,repairSessionId:n,attempt:e,transactionId:i.transactionId,plan:mn(i.plan),workspace:i.workspace,config:s.config,maxTargetBytes:i.maxTargetBytes,record:i.record,...a===void 0?{}:{group:a}}}import{dirname as $x,resolve as Dx}from"node:path";function Qr(t,n){return{kind:"configuration",path:t.relativePath,sha256:t.sha256,detail:n}}async function Lx(t){let{run:n,test:e,discovery:r}=t,i=Ze(n);if(i===void 0)return{kind:"unavailable",message:lt(n)};if(i==="playwright")return{kind:"unavailable",message:"Playwright validation needs no prepared run."};let s=n.configFile??await Eo(t.workspaceRoot,i,e.location.file),a=r.scope==="focused"?[e.location.file]:r.scope==="affected"?r.testPaths:[],o=await Do(t.workspaceRoot);if(i==="cypress"){let c=await Co(t.workspaceRoot,s),l=r.scope==="focused"?n.logicalTests.filter(f=>f.location.file===e.location.file&&f.projectId===e.projectId&&f.status==="expected"):[],u=await Lo({workspaceRoot:t.workspaceRoot,runtime:o,...s===void 0?{}:{configFile:s},specs:a,screenshotsDirectory:`${t.artifactRoot}/screenshots`,noRetries:!0,capture:{directory:`${t.artifactRoot}/capture`,supportFile:c,...r.scope==="focused"?{only:[e,...l].map(f=>f.titlePath.join(" "))}:{}}}),p=l.map(f=>f.logicalTestId);return{kind:"prepared",prepared:{args:u.args,workingDirectory:s===void 0?t.workspaceRoot:$x(Dx(t.workspaceRoot,s)),evidence:[Qr(o["cypress-reporter.cjs"],"KwikQA's Cypress reporter."),Qr(o["cypress-capture.js"],"KwikQA's Cypress failure capture."),...u.generated.map(f=>Qr(f,"Support file KwikQA generated for this validation."))],companionLogicalTestIds:p}}}if(s===void 0)return{kind:"unavailable",message:"No wdio.conf was found for the failing spec, so its validation run is unknown."};let d=await Mo({workspaceRoot:t.workspaceRoot,runtime:o,configFile:s,specs:a,directory:`${t.artifactRoot}/runner`,noRetries:!0,...r.scope==="focused"?{grep:gb(e.titlePath)}:{},capture:!0});return{kind:"prepared",prepared:{args:d.args,workingDirectory:$x(Dx(t.workspaceRoot,s)),evidence:[Qr(o["wdio-reporter.mjs"],"KwikQA's WebdriverIO reporter."),Qr(o["wdio-capture.mjs"],"KwikQA's WebdriverIO run wrapper."),...d.generated.map(c=>Qr(c,"WebdriverIO config KwikQA generated for this validation."))],companionLogicalTestIds:[]}}}var p2=600*1e3,Mx=1e6,f2={maxFiles:5e3,maxFileBytes:1024*1024,maxTotalBytes:64*1024*1024,maxImportEdges:5e4,maxImportDepth:20},h2={biome:"@biomejs/biome",prettier:"prettier",typescript:"typescript",eslint:"eslint"};function fd(t,n,e,r){let i=t.logicalTests.filter(l=>l.status==="unexpected"||l.status==="flaky"),s=[...n.hypotheses].sort((l,u)=>l.rank-u.rank)[0],a=new Set([...s?.supportingEvidenceIds??[],...n.ownershipEvidenceIds]),o=new Set(e.evidence.filter(l=>a.has(l.evidenceId)&&l.logicalTestId!==void 0).map(l=>l.logicalTestId)),d=i.filter(l=>o.has(l.logicalTestId));if(d.length===1)return d[0];let c=i.find(l=>l.logicalTestId===r);return c!==void 0&&(d.length===0||d.includes(c))?c:i.length===1?i[0]:void 0}function m2(t){return fd(t.run,t.diagnosis,t.packet,t.representativeId)}function _x(t){return t.payloadManifestHash===void 0||t.payloadHash===void 0?[]:[{manifestHash:t.payloadManifestHash,payloadHash:t.payloadHash,packetHash:t.packetHash,model:t.model.modelId,provider:t.model.providerId,promptVersion:t.promptVersion,outputSchemaVersion:t.outputSchemaVersion}]}function y2(t){return{maxRequestTokens:t.request.maxInputTokens+t.request.maxOutputTokens,maxRunTokens:t.run.maxInputTokens+t.run.maxOutputTokens,maxRequestDollars:t.request.maxDollars,maxRunDollars:t.run.maxDollars}}var g2={playwright:"@playwright/test",cypress:"cypress",webdriverio:"@wdio/cli"};async function w2(t,n,e,r){let i=async o=>{let d=await _i({workspaceRoot:t.workspaceRoot,repositoryRoot:t.gitRoot,ownerPath:n,packageName:o});return d.kind==="resolved"?d.tool:void 0},s={},a=await i(g2[e]);a!==void 0&&(s[e]=a);for(let o of new Set(r)){if(o==="kwikqa-babel")continue;let d=await i(h2[o]);d!==void 0&&(s[o]=d)}return s}async function jx(t){let{input:n,now:e,run:r,proposal:i,repository:s}=t,a={repairProposal:i,repairAudit:t.repairAudit},o=(I,$)=>t.finish({outcome:"validation-unavailable",reasonCode:I,message:$},{...a,proposal:{status:"ready"},application:{status:"not-run"},validation:{status:"unavailable"}}),d=Ze(r);if(d===void 0)return o("report-only-framework",lt(r));let c=m2(t);if(c===void 0)return o("original-test-ambiguous","The repair cannot be validated because the original failing test is ambiguous.");let l=r.projects.find(I=>I.projectId===c.projectId),u=await Ec({workspaceRoot:s.workspaceRoot,targets:i.targets.map(I=>({path:I.path,class:I.class})),originalTestPath:c.location.file,projects:r.projects.map(I=>({id:I.name,testDirectory:I.testDir??"",...r.configFile===void 0?{}:{configPath:r.configFile}})),limits:f2}),p=u.scope==="focused"&&u.projectIds.length===0&&l!==void 0&&l.name!==""?{...u,projectIds:[l.name]}:u,f=await w2(s,c.location.file,d,p.staticChecks.map(I=>I.tool)),h=`.kwikqa/validation-artifacts/${i.proposalHash.slice(0,24)}`,m;if(d!=="playwright"&&p.status==="resolved"){let I=await Lx({workspaceRoot:s.workspaceRoot,run:r,test:c,discovery:p,artifactRoot:h});if(I.kind==="unavailable")return o("validation-scope-unavailable",I.message);m=I.prepared}let g=bl({proposal:i,advisoryPlan:i.validationPlan,discovery:p,tools:f,workspaceRoot:s.workspaceRoot,originalTest:{path:c.location.file,line:c.location.line??1,logicalTestId:c.logicalTestId,projectId:l===void 0||l.name===""?c.projectId:l.name,...r.configFile===void 0?{}:{configPath:r.configFile},environmentEquivalent:n.environmentEquivalent!==!1},artifactRoot:h,timeoutMs:n.validationTimeoutMs??p2,framework:d,...m===void 0?{}:{frameworkRun:{args:m.args,workingDirectory:m.workingDirectory,evidence:m.evidence},companionLogicalTestIds:m.companionLogicalTestIds}}),y=g.plan;if(y.status!=="resolved")return o("validation-scope-unavailable",y.unresolvedReasons.map(I=>I.message).join(" "));if(g.requiredBaselineCommands.length>0)return o("baseline-capture-unavailable","This repair changes shared test support, which needs a pre-patch baseline that cannot be captured yet.");let w=t.retry===void 0?1:2,x=t.retry?.repairSessionId??(await Ol({workspaceRoot:s.workspaceRoot,originalRunId:r.runId,originalPacketHash:t.packet.packetHash,now:e()})).repairSessionId,v={config:t.config,snapshot:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot,dirtyPaths:s.dirtyPaths,validation:[]},workspace:{workspaceRoot:s.workspaceRoot,gitRoot:s.gitRoot},maxTargetBytes:Mx},R=t.ciApprover??{kind:"interactive",sessionId:`kwikqa-${d2()}`},P=kl({proposal:i,context:v,payloadManifests:[...t.diagnosisAudit===void 0?[]:_x(t.diagnosisAudit),..._x(t.repairAudit)],costBounds:y2(t.caps),scopes:{baseline:[],validation:[p.scope]},authoritativeValidation:xl({plan:y,advisoryPlan:i.validationPlan,repairSessionId:x,attemptOrdinal:w}),previewedAt:e(),approver:R}),C={repairSessionId:x,attempt:w,planHash:y.planHash};if(P.kind!=="preview-ready")return t.finish({outcome:"operation-failed",reasonCode:"application-rejected",message:P.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"ready"},application:{status:"blocked"}});if(!await n.interaction.approveApplication(P.preview,y))return t.finish({outcome:"repair-declined",reasonCode:"application-declined",message:"The developer declined the patch and validation plan; nothing was changed."},{...a,proposal:{status:"declined"},application:{status:"not-run"},repair:C});let E=Xr(),M=e(),A=await Al({preview:P.preview,authorization:{authorizationId:E,bindingHash:za(P.preview,E,M,R),authorizedAt:M,approver:R},context:v,now:M});if(A.kind!=="applied")return t.finish({outcome:"operation-failed",reasonCode:A.kind==="recovery-required"?"application-recovery-required":"application-rejected",message:A.reasons.map(I=>I.message).join(" ")},{...a,proposal:{status:"approved"},application:{status:A.kind==="recovery-required"?"recovery-required":"failed"},repair:C});let N=A.transaction.transactionId;await Ll(s.workspaceRoot,x,{ordinal:w,proposalHash:i.proposalHash,transactionId:N,outcome:"applied",recordedAt:e()});let T=(t.memberIds??[]).filter(I=>I!==c.logicalTestId);return await Nx(s.workspaceRoot,{schemaVersion:"1.0",repairSessionId:x,attempt:w,transactionId:N,plan:y,workspace:v.workspace,config:t.config,maxTargetBytes:Mx,...T.length===0?{}:{group:{reportPath:c2(s.workspaceRoot,l2(s.workspaceRoot,n.reportPath)).split(u2).join("/"),...n.framework===void 0?{}:{framework:n.framework},logicalTestIds:T}},record:{runId:r.runId,createdAt:r.createdAt,workspace:r.workspace,sourceHashes:t.packet.sourceHashes,usability:r.usability,failingLogicalTestIds:r.logicalTests.filter(I=>I.status==="unexpected"||I.status==="flaky").map(I=>I.logicalTestId).sort()}}),t.finish({outcome:"awaiting-validation",reasonCode:"patch-applied",message:t.ciApprover===void 0?"The approved patch was applied. Run `kwikqa validate` to verify it.":"The patch was applied to this runner's checkout, and is validated next."},{...a,proposal:{status:"approved"},application:{status:"applied"},repair:{...C,transactionId:N}})}import{createHash as S2}from"node:crypto";import{join as E2,relative as C2,sep as N2}from"node:path";import{execFile as b2}from"node:child_process";import{createHash as x2}from"node:crypto";import{realpath as Cs}from"node:fs/promises";import{isAbsolute as v2,relative as k2,resolve as Kp,sep as Fx}from"node:path";import{promisify as R2}from"node:util";var I2=R2(b2),A2=3e4,T2=16*1024*1024;async function Ns(t,n){return(await I2("git",["-C",t,"--no-optional-locks",...n],{timeout:A2,maxBuffer:T2,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1"}})).stdout}function Bx(t){let n=t.split("\0"),e=[];for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(i.length<4)continue;let s=i.slice(0,2);if(e.push(i.slice(3)),s.includes("R")||s.includes("C")){let a=n[r+1];a!==void 0&&a.length>0&&e.push(a),r+=1}}return e}function P2(t,n,e){let r=k2(t,Kp(n,e));if(!(r===""||v2(r)||r===".."||r.startsWith(`..${Fx}`)))return r.split(Fx).join("/")}async function Os(t){let n=await Cs(t);try{return await Cs(Kp((await Ns(n,["rev-parse","--show-toplevel"])).trim()))}catch{return n}}async function Hx(t,n,e){let r;try{r=(await Ns(t,["rev-parse","--verify","--quiet",`HEAD:${n}`])).trim()}catch{return!1}let i=r.length===64?"sha256":"sha1";return x2(i).update(`blob ${e.byteLength}\0`).update(e).digest("hex")===r}async function Wp(t){let n=await Cs(t);return(await Ns(n,["-c","core.quotePath=false","ls-files","-z"])).split("\0").filter(r=>r.length>0).sort()}async function tr(t){let n,e,r;try{n=await Cs(t),e=await Cs(Kp((await Ns(n,["rev-parse","--show-toplevel"])).trim())),r=await Ns(e,["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all","--ignored=no"])}catch(a){let o=a,d=o.code==="ENOENT"?"git executable was not found.":(o.stderr??o.message??"").trim().split(`
221
+ `)[0]??"";return{kind:"unavailable",message:`Repository status could not be read: ${d===""?"git failed.":d}`}}let i=Bx(r),s=[...new Set(i.map(a=>P2(n,e,a)).filter(a=>a!==void 0))].sort();return{kind:"read",status:{workspaceRoot:n,gitRoot:e,dirtyPaths:s,pristine:i.length===0}}}var Ux="kwikqa.config.json",O2=256*1024;async function qx(t,n){let e=await X(t,n,O2);if(e.kind==="unavailable")return{kind:"repair-config-missing",message:`Repair requires a reviewed ${n}; none was found in the workspace.`};if(e.kind!=="read")return{kind:"repair-config-invalid",message:`${n} could not be read: ${e.message}`};let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes))}catch{return{kind:"repair-config-invalid",message:`${n} is not valid UTF-8 JSON.`}}let i=Zn(r);return i.kind!=="valid"?{kind:"repair-config-invalid",message:i.issues.join(" ")}:{...i,bytes:e.bytes}}async function hd(t,n=Ux){let e=await qx(t,n);return e.kind==="valid"?e.config.ci?.fix:void 0}async function $2(t,n,e,r){if(t.ci===void 0)return{};if(n.config.ci?.fix===void 0)return{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-missing",message:`\`kwikqa fix\` needs a terminal, unless ${r} has a committed ci.fix policy, which lets it validate a repair on this runner and open a draft pull request.`}};let i=C2(e.gitRoot,E2(e.workspaceRoot,r)).split(N2).join("/");return await Hx(e.gitRoot,i,n.bytes)?{approver:{kind:"ci-policy",...t.ci,policyHash:S2("sha256").update(n.bytes).digest("hex")}}:{refusal:{outcome:"operation-failed",reasonCode:"ci-fix-policy-uncommitted",message:`${r} differs from its committed version, so its ci.fix policy wasn't reviewed; a fix in CI runs only under the committed policy.`}}}function D2(t,n,e){let r=new Set(e.map(s=>s.toLocaleLowerCase("en-US"))),i=new Set;for(let s of t.evidence){if(s.locator.type!=="source-range")continue;let a=s.locator.path;zi(a,n.editablePaths)!==void 0&&!Hi(a,n)&&!Bi(a)&&!r.has(a.toLocaleLowerCase("en-US"))&&i.add(a)}return[...i].sort()}async function md(t){let n=t.now??(()=>new Date().toISOString()),e=await tr(t.workspaceRoot);if(e.kind==="unavailable")return{outcome:"operation-failed",reasonCode:"repository-status-unavailable",message:e.message};let{workspaceRoot:r,gitRoot:i,dirtyPaths:s,pristine:a}=e.status,o=t.configPath??Ux,d=await qx(r,o);if(d.kind!=="valid")return{outcome:"operation-failed",reasonCode:d.kind,message:d.message};let c=d.config,l=await $2(t,d,{workspaceRoot:r,gitRoot:i},o);if("refusal"in l)return l.refusal;let{approver:u}=l;if(t.retryRepairSessionId!==void 0&&(await tn(r,t.retryRepairSessionId).catch(()=>{}))?.state!=="retry-approval-required")return{outcome:"operation-failed",reasonCode:"no-retry-available",message:"That repair session has no retry available; only one retry follows a failed validation."};let p=await Ss({...t,workspaceRoot:r,gitRoot:i,repairableOnly:!0},n);if(p.kind==="unreadable")return{outcome:p.outcome,reasonCode:p.reasonCode,message:p.message};let{stage:f}=p,h={workspaceRoot:r,gitRoot:i,dirtyPaths:s},m=(x,v=[])=>(R,P={})=>cd(x,dd(x,"fix",v.length===0?R:{...R,message:`${v.join(" ")} ${R.message}`},n,{repository:{pristine:a,dirtyPaths:s},...P}),t.persist!==!1),g=F2(f,t);if("refusal"in g)return m(f)(g.refusal);if(g.groups.length===0){let{packet:x}=f,{diagnosis:v,grading:R}=f.result;return f.result.outcome!=="diagnosed"||x===void 0||v===void 0||R===void 0?m(f)(f.result):Vx(t,f,{packet:x,diagnosis:v,grading:R},c,n,m(f),h,u)}let y=[],w=[];for(let x of g.groups){let v=await t.fixInReview?.(x.cluster.signals);v===void 0?w.push(x):y.push(`Failure group ${zx(f,x)}: ${v}.`)}if(w.length===0)return m(f)({outcome:"abstained-from-repair",reasonCode:"fix-in-review",message:y.join(" ")});await t.repairSession?.open(w.length);try{let x;for(let v of w){let R=j2(f,v),{packet:P}=R,{diagnosis:C,grading:E}=v.result;if(!(P===void 0||C===void 0||E===void 0)){if(x=await Vx(t,R,{packet:P,diagnosis:C,grading:E},c,n,m(R,y),h,u),!_2(x))return x;y.push(`Failure group ${zx(f,v)}: ${x.message}`)}}return x??m(f)(f.result)}finally{await t.repairSession?.close()}}var L2=3,M2=new Set(["model-declined-repair","repair-not-eligible","failure-not-reproduced","insufficient-ownership-evidence","intent-ambiguous","invalid-replacement","unauthorized-target","dirty-target-file","source-hash-mismatch","non-unique-match","overlapping-replacement","forbidden-edit","parse-failed","budget-exceeded","unreadable-target"]);function _2(t){return t.outcome==="abstained-from-repair"?M2.has(t.reasonCode):t.outcome==="validation-unavailable"&&t.record?.application.status==="not-run"}function zx(t,n){return(t.clusterStages??[]).indexOf(n)+1}function j2(t,n){return{...t,...n.packet===void 0?{}:{packet:n.packet},...n.symptoms===void 0?{}:{symptoms:n.symptoms},...n.clusters===void 0?{}:{clusters:n.clusters},result:n.result,clusterStages:[n,...(t.clusterStages??[]).filter(e=>e!==n)],representativeId:n.representativeId}}function F2(t,n){let e=t.clusterStages??[];if(n.group!==void 0){let s=e[n.group-1];return s===void 0?{refusal:{outcome:"operation-failed",reasonCode:"group-not-found",message:`There is no failure group ${n.group}; this run has ${e.length}.`}}:od([s]).includes(s)?{groups:[s]}:{refusal:{outcome:"abstained-from-repair",reasonCode:"group-not-repairable",message:`Failure group ${n.group} is not diagnosed as the test's fault (${s.result.reasonCode}); KwikQA repairs only test-side causes.`}}}let r=od(e),i=n.repairSession===void 0||n.retryRepairSessionId!==void 0?1:L2;return{groups:r.slice(0,i)}}async function B2(t,n){let{interaction:e}=t;if(e.confirmFailure===void 0||t.retryRepairSessionId!==void 0)return;let r=n.clusterStages?.[0]?.cluster.logicalTestIds??n.failing,i=n.representativeId??r[0];if(i===void 0)return;let s=await e.confirmFailure(n.run,r);if(s.kind==="declined")return{status:"declined",logicalTestIds:r,message:"The developer chose not to re-run the failing tests first."};if(s.kind==="unavailable")return{status:"unavailable",logicalTestIds:r,message:s.message};let a=r.filter(d=>s.failedAgain.includes(d));if(a.includes(i))return{status:"reproduced",logicalTestIds:r,failedAgain:a};let o=n.run.logicalTests.find(d=>d.logicalTestId===i)?.title;return{status:"not-reproduced",logicalTestIds:r,failedAgain:a,message:`${o===void 0?"The failing test":`"${o}"`} passed when re-run, so the failure looks flaky or depends on state the re-run did not have. KwikQA does not patch a test that passes; no repair was requested.`}}async function Vx(t,n,e,r,i,s,a,o){let{packet:d,diagnosis:c,grading:l}=e,u=[...c.hypotheses].sort((w,x)=>w.rank-x.rank)[0],p=t.repairCaps??t.remote.caps,f=await Cp({packet:d,diagnosis:c,grading:l,hypothesisId:u?.hypothesisId??"",editablePaths:D2(d,r,a.dirtyPaths),budgets:r.budgets,model:t.repairModel??t.remote.model,caps:p,transport:t.remote.transport,now:i()});if(f.kind!=="preview-ready"){let w=f.reasonCode==="repair-not-eligible"&&u?.probableOwner!=="test-support"?ad(c):f.reasonCode,x=f.reasonCode==="repair-not-eligible"||sd.has(f.reasonCode);return s({outcome:x?"abstained-from-repair":"operation-failed",reasonCode:w,message:f.message},{proposal:{status:x?"not-eligible":"failed"},repairAudit:f.audit})}let h=await B2(t,n),m=(w,x={})=>s(w,{...h===void 0?{}:{confirmation:h},...x});if(h?.status==="not-reproduced")return m({outcome:"abstained-from-repair",reasonCode:"failure-not-reproduced",message:h.message??"The failing test passed when re-run."},{proposal:{status:"not-eligible"}});if(!await t.interaction.approveRepairRequest(f.prepared.preview))return m({outcome:"repair-declined",reasonCode:"remote-consent-declined",message:"The developer declined the repair-proposal request; no evidence was sent."},{proposal:{status:"declined"}});let g=await Np({prepared:f.prepared,authorization:{bindingHash:f.prepared.authorizationBindingHash,mode:"interactive",authorizedAt:i(),authorizationId:Xr()},authorizationStore:t.authorizationStore??new Gn,transport:t.remote.transport,now:i()});if(g.kind==="declined")return m({outcome:"abstained-from-repair",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"not-eligible"},repairAudit:g.audit});if(g.kind!=="proposed")return m({outcome:"operation-failed",reasonCode:g.reasonCode,message:g.message},{proposal:{status:"failed"},repairAudit:g.audit});let y=await _p({packet:d,diagnosis:c,grading:l,config:r,snapshot:{workspaceRoot:a.workspaceRoot,gitRoot:a.gitRoot,dirtyPaths:a.dirtyPaths,validation:[]},intent:g.draft.intent,replacements:g.draft.replacements});if(y.kind==="rejected"){let[w]=y.reasons;return m({outcome:"abstained-from-repair",reasonCode:w?.code??"invalid-replacement",message:y.reasons.map(x=>x.message).join(" ")},{proposal:{status:"not-eligible"},repairAudit:g.audit,proposalRejections:y.reasons})}return t.proposeOnly===!0?m({outcome:"proposal-ready",reasonCode:"test-support-owned",message:"A policy-checked proposal is ready for review; nothing was applied."},{proposal:{status:"ready"},repairAudit:g.audit,repairProposal:y.proposal}):jx({input:t,now:i,run:n.run,packet:d,diagnosis:c,...n.representativeId===void 0?{}:{representativeId:n.representativeId},...n.clusterStages?.[0]===void 0?{}:{memberIds:n.clusterStages[0].cluster.logicalTestIds},proposal:y.proposal,config:r,repository:a,diagnosisAudit:n.result.audit,repairAudit:g.audit,caps:p,...t.retryRepairSessionId===void 0?{}:{retry:{repairSessionId:t.retryRepairSessionId}},...o===void 0?{}:{ciApprover:o},finish:m})}import{randomUUID as H2}from"node:crypto";import{realpath as z2}from"node:fs/promises";import{join as V2,relative as U2,sep as Jp}from"node:path";var q2={maxStreamBytes:4*1024*1024,maxTotalStreamBytes:16*1024*1024,terminationGraceMs:5e3},G2=32*1024*1024,K2=new Set(["applied","validating"]);function W2(){return`vld_${H2().replaceAll("-","").slice(0,24)}`}function J2(t){return{config:t.config,snapshot:{workspaceRoot:t.workspace.workspaceRoot,gitRoot:t.workspace.gitRoot,dirtyPaths:[],validation:[]},workspace:t.workspace,maxTargetBytes:t.maxTargetBytes}}function Y2(t,n,e){let r=i=>U2(t,`${n}${Jp}${i.split("/").join(Jp)}`).split(Jp).join("/");for(let i of e.commandRecords){let s=i.artifacts.find(d=>d.path.endsWith("/report.json"));if(s!==void 0)return r(s.path);let o=i.artifacts.filter(d=>ja.test(d.path.split("/").at(-1)??""))[0];if(o!==void 0)return r(o.path.split("/").slice(0,-1).join("/"))}}async function X2(t,n,e){let r=n.group;if(r===void 0||r.logicalTestIds.length===0||t.checkGroup===void 0)return;let{logicalTestIds:i}=r,s=`${i.length} other test${i.length===1?"":"s"}`,a=await ct(V2(e,r.reportPath),{workspaceRoot:e,gitRoot:n.workspace.gitRoot,...r.framework===void 0?{}:{framework:r.framework}}),o=a.kind==="parsed"?new Set(a.run.logicalTests.map(u=>u.logicalTestId)):void 0;if(a.kind!=="parsed"||!i.every(u=>o?.has(u)))return{status:"unavailable",logicalTestIds:i,message:`The report fix read has changed, so the group's ${s} were not re-run.`};let d=await t.checkGroup(a.run,i);if(d.kind==="declined")return{status:"declined",logicalTestIds:i,message:`The group's ${s} were not re-run.`};if(d.kind==="unavailable")return{status:"unavailable",logicalTestIds:i,message:d.message};let c=i.filter(u=>d.failedAgain.includes(u)),l=c.map(u=>a.run.logicalTests.find(p=>p.logicalTestId===u)?.title??u).map(u=>`"${u}"`).join(", ");return{status:"rerun",logicalTestIds:i,stillFailing:c,message:c.length===0?`The group's ${s} pass now as well.`:`${c.length} of the group's ${s} still fail${c.length===1?"s":""}: ${l}. The patch stays; run \`kwikqa fix\` again for them.`}}async function yd(t){let n=t.now??(()=>new Date().toISOString()),e=()=>new Date().toISOString(),r=await z2(t.workspaceRoot),i=await Sl(r);if(i.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-recovery-required",message:i.reasons.map(P=>P.message).join(" ")};let s=i.transactions.filter(P=>K2.has(P.phase));if(s.length!==1||s[0]===void 0)return{outcome:"operation-failed",reasonCode:"no-pending-repair",message:s.length===0?"There is no applied repair waiting for validation. Run `kwikqa fix` first.":"More than one repair is waiting for validation; recover the workspace first."};let a=await Re(r,s[0].transactionId),o=a.manifest.preview.authoritativeValidation,d=await Ox(r,o.repairSessionId,o.attemptOrdinal);if(d.transactionId!==a.manifest.transactionId)throw new Error("Repair attempt state does not belong to the pending transaction.");if(d.plan.planHash!==o.planHash)throw new Error("Saved validation plan does not match the approved plan.");let c=J2(d),l=d.transactionId,u=d.plan,p;if(a.state.phase==="validating"){let P=a.state.history.findLast(C=>C.type==="validation-started");if(P?.validationRunId===void 0)throw new Error("Validating transaction has no started validation run.");p=P.validationRunId}else{p=W2();let P=await qp({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,now:e()});if(P.kind==="rejected"||P.kind==="failed")return{outcome:"operation-failed",reasonCode:"application-rejected",message:P.reasons.map(C=>C.message).join(" ")};for(let C of u.commands)if(!(!C.required||C.timing!=="post-patch")){if(t.signal?.aborted===!0)break;await _c({workspaceRoot:r,repositoryRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,commandId:C.commandId,limits:q2,...t.signal===void 0?{}:{signal:t.signal}}).catch(()=>{})}}let f=await pl({workspaceRoot:r,gitRoot:d.workspace.gitRoot,transactionId:l,validationRunId:p,plan:u,reportMaxBytes:G2,completedAt:e()}),h=f.manifest,m={repairSessionId:d.repairSessionId,attempt:d.attempt,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash};if(h.status==="passed"&&(await Gp({context:c,transactionId:l,planHash:u.planHash,validationRunId:p,validationManifestHash:h.manifestHash,now:e()})).kind==="completed"){await Wa({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:n()});let C=await X2(t,d,r);return Yp(t,d,n,{outcome:"repaired",reasonCode:"validation-passed",message:`Every required validation check passed; the repair is complete.${C?.message===void 0?"":` ${C.message}`}`,application:"applied",validation:"passed",repair:m,...C===void 0?{}:{groupCheck:C}})}await Wa({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,validationRunId:p,now:n()});let g=await El(c,l,e()),y=h.status==="passed"?"incomplete":h.status,w=y==="failed"?"validation-failed":y==="unavailable"?"validation-unavailable":"validation-incomplete";if(g.kind!=="rolled-back")return Yp(t,d,n,{outcome:"repair-failed",reasonCode:"rollback-conflicted",message:"Validation did not pass and the patch could not be rolled back automatically because the files changed; resolve them manually.",application:"recovery-required",validation:y==="blocked"?"incomplete":y,repair:m});let v=(await Ml({workspaceRoot:r,repairSessionId:d.repairSessionId,ordinal:d.attempt,proof:{transactionId:l,phase:"rolled-back",transactionRevision:g.transaction.revision},now:n()})).retry!==void 0,R=v?Y2(r,f.directory,h):void 0;return Yp(t,d,n,{outcome:"repair-failed",reasonCode:w,message:v?"Validation did not pass, so the patch was rolled back. One retry is available.":"Validation did not pass, so the patch was rolled back. No retry remains.",application:"rolled-back",validation:y==="blocked"?"incomplete":y,repair:{...m,retryAvailable:v,...R===void 0?{}:{retryReportPath:R}}})}async function Yp(t,n,e,r){let i={schemaVersion:"1.1",recordId:rd(),command:"validate",...n.record,recordedAt:e(),analysis:{status:"completed"},proposal:{status:"approved"},application:{status:r.application},validation:{status:r.validation},repair:r.repair,...r.groupCheck===void 0?{}:{groupCheck:r.groupCheck},outcome:r.outcome,reasonCode:r.reasonCode,message:r.message};if(t.persist===!1)return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i};try{let s=await Ts(n.workspace.workspaceRoot,i);return{outcome:i.outcome,reasonCode:i.reasonCode,message:i.message,record:i,recordPath:s}}catch{return{outcome:"operation-failed",reasonCode:"record-write-failed",message:`${i.message} The run record could not be written safely under .kwikqa/runs/.`,record:i}}}var Q2=1200*1e3,Z2=10,eD=1e3,tD=15e3,nD=3e3,rD=6e4,Gx=3e4,iD=2;function Qp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Wx(t){try{let n=await t.json();return Qp(n)?n:void 0}catch{return}}async function sD(t){return await Wx(t)??{}}function Kx(t){return typeof t=="number"&&Number.isFinite(t)?Math.min(tD,Math.max(eD,t)):nD}function Xp(t){let n=Qp(t.error)?t.error:void 0;return typeof n?.message=="string"?n.message:void 0}var gd=class{constructor(n){this.options=n}options;preflight(n){return this.options.preflight.preflight(n)}async complete(n){let e=performance.now(),r=()=>performance.now()-e;for(let i=0;;i+=1){let s=await this.#e(n,r);if(s!=="interrupted")return s;if(i===iD)return{kind:"failed",code:"http-error",message:"The model request was interrupted on our side; nothing was charged. Try again.",httpStatus:503,elapsedMs:r()};this.options.onRestart?.()}}async#e(n,e){let r=(u,p)=>({kind:"failed",code:u,message:p,elapsedMs:e()}),i=wp(n);if(i!==void 0)return{kind:"failed",code:"invalid-request",message:i,elapsedMs:0};let s;try{s=await this.#t("POST","/v1/jobs",rD,{headers:{...this.options.headers(n.body),"Content-Type":"application/json","X-OpenRouter-Metadata":"enabled"},body:JSON.stringify(n.body)})}catch(u){return r("network-error",`The model request could not reach the KwikQA service (${ks(u)}).`)}let a=await sD(s);if(s.status!==202){let u=Vo(a);return{kind:"failed",code:"http-error",message:Xp(a)??"The KwikQA service refused the model request.",httpStatus:s.status,...u===void 0?{}:{providerCode:u},elapsedMs:e()}}let o=a.jobId;if(typeof o!="string"||o==="")return r("invalid-json","The KwikQA service did not name the job it started.");let d=this.options.sleep??(u=>new Promise(p=>setTimeout(p,u))),c=Kx(a.pollAfterMs),l=0;for(;;){if(e()>(this.options.maxWaitMs??Q2))return await this.#n(o),r("timeout","The model did not answer in time; nothing was charged.");await d(c);let u;try{u=await this.#t("GET",`/v1/jobs/${o}`,Gx)}catch{u=new Response(null,{status:599})}let p=u.status>=500?void 0:await Wx(u);if(u.status===404)return"interrupted";if(u.status<500&&!u.ok)return{kind:"failed",code:"http-error",message:Xp(p??{})??"The KwikQA service refused to report the job.",httpStatus:u.status,elapsedMs:e()};if(p===void 0){if(l+=1,l>Z2)return r("network-error","Lost contact with the KwikQA service while the model was working. If it answered, it is given back unused.");continue}if(l=0,p.status==="running"){this.options.onProgress?.(e()),c=Kx(p.pollAfterMs);continue}if(p.status==="failed")return Qp(p.error)&&p.error.code==="job-interrupted"?"interrupted":{kind:"failed",code:"http-error",message:Xp(p)??"The model request was interrupted; nothing was charged.",httpStatus:503,elapsedMs:e()};if(p.status!=="answered")return r("invalid-json","The KwikQA service reported a job state the CLI does not know.");await this.#n(o);let f=typeof p.httpStatus=="number"?p.httpStatus:502,h=p.result,m=f>=200&&f<300;if(!m||gp(h)){let g=Vo(h),y=m?g??502:f;return{kind:"failed",code:"http-error",message:yp(y,h),httpStatus:y,...g===void 0?{}:{providerCode:g},elapsedMs:e()}}return this.options.onCompletionBody?.(h),{kind:"response",httpStatus:f,body:h,elapsedMs:e()}}}async#n(n){try{await this.#t("DELETE",`/v1/jobs/${n}`,Gx)}catch{}}#t(n,e,r,i={}){return this.options.fetch(`${this.options.baseUrl}${e}`,{method:n,headers:{Accept:"application/json",Authorization:`Bearer ${this.options.token}`,...i.headers},...i.body===void 0?{}:{body:i.body},redirect:"error",signal:AbortSignal.timeout(r)})}};var aD="https://api.kwikqa.com",Zr="https://kwikqa.com/dashboard/";function Jx(t){return t.hosted??!(t.plan==="byo"||t.plan==="byo-team")}function oD(t){return t?.response_format?.json_schema?.name==="kwikqa_diagnosis"}var yt=class extends Error{constructor(e,r,i){super(i);this.status=e;this.code=r}status;code};function cn(t,n){return(t.KWIKQA_API_URL??(n===void 0||n===""?aD:n)).replace(/\/+$/,"")}function Yx(t){let n=t?.messages;if(!Array.isArray(n))return;let e=n.find(r=>typeof r=="object"&&r!==null&&r.role==="user"&&typeof r.content=="string");if(e!==void 0)try{let r=JSON.parse(e.content).framework;return r==="playwright"||r==="cypress"||r==="webdriverio"?r:void 0}catch{return}}var Tt=class{constructor(n,e,r=fetch){this.baseUrl=n;this.token=e;this.fetchImpl=r}baseUrl;token;fetchImpl;async#e(n,e,r,i,s){let a=()=>this.fetchImpl(`${this.baseUrl}${e}`,{method:n,headers:{Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"},...this.token===void 0?{}:{Authorization:`Bearer ${this.token}`},...i===void 0?{}:{"X-KwikQA-Retry-Ticket":i},...s===void 0?{}:{"X-KwikQA-Session":s}},...r===void 0?{}:{body:JSON.stringify(r)},redirect:"error"}),o;try{o=await a().catch(c=>{if(n==="GET")return a();throw c})}catch(c){throw new yt(0,"network-error",`Could not reach the KwikQA service at ${this.baseUrl} (${ks(c)}).`)}let d;try{d=await o.json()}catch{d=void 0}if(!o.ok){let c=d?.error;throw new yt(o.status,c?.code??"http-error",c?.message??`The KwikQA service returned HTTP ${o.status}.`)}return d}startDeviceLogin(){return this.#e("POST","/v1/auth/device")}pollDeviceLogin(n){return this.#e("POST","/v1/auth/token",{deviceCode:n})}status(){return this.#e("GET","/v1/me")}hostedConfig(){return this.#e("GET","/v1/config")}plans(){return this.#e("GET","/v1/plans")}checkout(n,e){return this.#e("POST","/v1/billing/checkout",{plan:n,...e})}billingPortal(){return this.#e("POST","/v1/billing/portal")}reserveUsage(n,e,r){return this.#e("POST","/v1/usage/reserve",n,e,r)}openSession(n,e="diagnosis"){return this.#e("POST","/v1/usage/session",e==="diagnosis"?{requests:n}:{requests:n,kind:e})}async closeSession(n){let r=(await this.#e("DELETE","/v1/usage/session",void 0,void 0,n))?.retryTicket;return typeof r=="string"&&r!==""?{retryTicket:r}:{}}reportInsights(n){return this.#e("POST","/v1/insights",{events:n})}releaseUsage(n,e){return this.#e("POST","/v1/usage/release",{id:n,status:e})}logout(){return this.#e("POST","/v1/auth/logout")}transport(n){let e=s=>{let a=Yx(s),o=oD(s)?n.session?.():n.repairSession?.();return{...n.retryTicket===void 0?{}:{"X-KwikQA-Retry-Ticket":n.retryTicket},...o===void 0?{}:{"X-KwikQA-Session":o},...a===void 0?{}:{"X-KwikQA-Framework":a}}},r=s=>{let a=s?.kwikqa?.retryTicket;typeof a=="string"&&a!==""&&n.onRetryTicket?.(a)},i=new Jn({apiRoot:`${this.baseUrl}/v1/openrouter`,credentialName:"A KwikQA login (run `npx kwikqa login`)",readApiKey:()=>this.token,fetch:this.fetchImpl,timeoutMs:6e5,extraHeaders:e,onCompletionBody:r});return n.jobs!==!0||this.token===void 0?i:new gd({baseUrl:this.baseUrl,token:this.token,fetch:this.fetchImpl,preflight:i,headers:e,onCompletionBody:r,...n.onProgress===void 0?{}:{onProgress:n.onProgress},...n.onRestart===void 0?{}:{onRestart:n.onRestart},...n.sleep===void 0?{}:{sleep:n.sleep}})}},wd=class{constructor(n,e,r={}){this.inner=n;this.client=e;this.options=r}inner;client;options;preflight(n){return this.inner.preflight(n)}async complete(n){let r=n.body.response_format?.json_schema?.name==="kwikqa_repair_proposal"?"repair":"diagnosis",i;try{let a=Yx(n.body);i=await this.client.reserveUsage({kind:r,model:n.route.modelId,provider:n.route.providerSlug,...a===void 0?{}:{framework:a}},this.options.retryTicket,r==="diagnosis"?this.options.session?.():this.options.repairSession?.())}catch(a){if(!(a instanceof yt))throw a;return{kind:"failed",code:"http-error",message:a.message,elapsedMs:0,...a.status===0?{}:{httpStatus:a.status}}}i.retryTicket!==void 0&&this.options.onRetryTicket?.(i.retryTicket);let s=await this.inner.complete(n);return s.kind!=="response"&&await this.client.releaseUsage(i.id,s.httpStatus??599).catch(()=>{}),s}};import{mkdir as dD,readFile as cD,rm as lD,writeFile as uD}from"node:fs/promises";import{homedir as Xx}from"node:os";import{join as $s}from"node:path";function Qx(t){return t.KWIKQA_CONFIG_DIR!==void 0&&t.KWIKQA_CONFIG_DIR!==""?t.KWIKQA_CONFIG_DIR:process.platform==="win32"?$s(t.APPDATA??$s(Xx(),"AppData","Roaming"),"kwikqa"):$s(t.XDG_CONFIG_HOME??$s(Xx(),".config"),"kwikqa")}function Zp(t){return $s(Qx(t),"credentials.json")}async function ln(t){if(t.KWIKQA_TOKEN!==void 0&&t.KWIKQA_TOKEN.trim()!=="")return{token:t.KWIKQA_TOKEN.trim(),login:"(KWIKQA_TOKEN)",apiUrl:""};try{let n=JSON.parse(await cD(Zp(t),"utf8"));return typeof n.token!="string"||n.token===""||typeof n.login!="string"||typeof n.apiUrl!="string"?void 0:{token:n.token,login:n.login,apiUrl:n.apiUrl}}catch{return}}async function Zx(t,n){await dD(Qx(t),{recursive:!0,mode:448}),await uD(Zp(t),`${JSON.stringify(n)}
222
+ `,{mode:384})}async function ev(t){await lD(Zp(t),{force:!0})}import{appendFile as tv}from"node:fs/promises";function Le(t,n=!0){return{reason:t,misconfigured:n}}var rv={noun:"pull request",sigil:"#"},nv={noun:"merge request",sigil:"!"};async function ef(t,n,e,r,i=rv){if(n.kind==="open")return await r(n.number),`fix ${i.noun} ${i.sigil}${n.number} is already open for it, so no repair was requested; this run is noted there`;if(n.kind==="branch")return`its fix branch ${ft(e)} is left from an earlier fix, without an open ${i.noun}, so no repair was requested; delete the branch to let KwikQA open a new fix`;n.kind==="unknown"&&t.io.print(`Couldn't check for an open fix ${i.noun}: ${n.reason}.`)}function tf(t,n,e,r=rv){let i=`Fix ${r.noun}`;n.kind==="opened"?t.io.print(`${i}: opened ${r.sigil}${n.number}, a draft into ${e}${n.url===void 0?"":`: ${n.url}`}.`):n.kind==="skipped"?t.io.print(`No fix ${r.noun}: ${n.reason}.`):t.io.error(`No fix ${r.noun}: ${n.reason}.`)}function nf(t){return(t.fix.repairProposal?.targets??[]).map(n=>({path:n.path,sourceSha256:n.sourceSha256,resultSha256:n.resultSha256}))}function iv(t,n){let{repository:e,runId:r,runAttempt:i,commit:s}=n;if(e===void 0||r===void 0||i===void 0||s===void 0)return"`kwikqa fix` in CI needs GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT, and GITHUB_SHA as GitHub Actions sets them.";let a={system:"GitHub Actions",ci:{system:"github-actions",repository:e,runId:r,runAttempt:i,commit:s.sha},checkout:{variable:"GITHUB_WORKSPACE",path:t.env.GITHUB_WORKSPACE||void 0}},o=n.pullRequest;if(o?.fork===!0)return{...a,host:{reason:`the pull request comes from a fork, and GitHub gives its workflows a read-only token, so no fix pull request can be opened. A maintainer can check out the pull request (\`gh pr checkout ${o.number}\`) and run \`npx kwikqa fix\``,misconfigured:!1,note:async()=>{n.summaryPath!==void 0&&await tv(n.summaryPath,`
223
223
  ### KwikQA: no fix pull request for a fork
224
224
 
225
225
  GitHub gives a fork's workflows a read-only token, so KwikQA can't open a fix pull request here. A maintainer can check out this pull request (\`gh pr checkout ${o.number}\`) and run \`npx kwikqa fix\` on their machine.
226
- `).catch(()=>{})}}};let d=o!==void 0?n.pullRequestHead===void 0?void 0:{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.ref?.startsWith("refs/heads/")===!0?{branch:n.ref.slice(11),commit:s.sha}:void 0;if(d===void 0)return{...a,host:o===void 0?Le("this run isn't on a branch, so there's no branch for a fix pull request",!1):Le("the event doesn't name the pull request's head")};if(n.token===void 0)return{...a,host:Le("GITHUB_TOKEN isn't set; add `GITHUB_TOKEN: ${{ github.token }}` to the step's env, with `contents: write` and `pull-requests: write`")};if(n.apiUrl===void 0)return{...a,host:Le("GITHUB_API_URL isn't what GitHub Actions sets")};let c={apiUrl:n.apiUrl,repository:e,token:n.token},l=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...a,host:{fixInReview:async u=>{let p=jr(u);return ef(t,await Pu(t.fetch,c,p),p,f=>Su(t.io,t.fetch,c,{number:f,fingerprint:p},{...l,commit:s.sha}))},publish:async(u,p)=>{let f=nf(u);if(f.length===0)return t.io.print("No fix pull request: the fix's record names no repaired file.");let h=ps(u.fix),m=await Eu(t.io,t.fetch,{...c,base:d,workspaceRoot:p.root,gitRoot:p.gitRoot,targets:f,fingerprint:h,title:Bn(u.fix),body:hs({fix:u.fix,...u.validation===void 0?{}:{validation:u.validation},...u.plan===void 0?{}:{plan:u.plan},fingerprint:h,...l,commit:s.sha,host:"github"}),commitMessage:fs(u.fix,h)});if(tf(t,m,d.branch),m.kind==="opened"&&n.summaryPath!==void 0){let g=m.url===void 0?`#${m.number}`:`[#${m.number}](${m.url})`;await tv(n.summaryPath,`
226
+ `).catch(()=>{})}}};let d=o!==void 0?n.pullRequestHead===void 0?void 0:{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.ref?.startsWith("refs/heads/")===!0?{branch:n.ref.slice(11),commit:s.sha}:void 0;if(d===void 0)return{...a,host:o===void 0?Le("this run isn't on a branch, so there's no branch for a fix pull request",!1):Le("the event doesn't name the pull request's head")};if(n.token===void 0)return{...a,host:Le("GITHUB_TOKEN isn't set; add `GITHUB_TOKEN: ${{ github.token }}` to the step's env, with `contents: write` and `pull-requests: write`")};if(n.apiUrl===void 0)return{...a,host:Le("GITHUB_API_URL isn't what GitHub Actions sets")};let c={apiUrl:n.apiUrl,repository:e,token:n.token},l=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...a,host:{fixInReview:async u=>{let p=jr(u);return ef(t,await Pu(t.fetch,c,p),p,f=>Su(t.io,t.fetch,c,{number:f,fingerprint:p},{...l,commit:s.sha}))},publish:async(u,p)=>{let f=nf(u);if(f.length===0)return t.io.print("No fix pull request: the fix's record names no repaired file.");let h=ps(u.fix),m=await Eu(t.io,t.fetch,{...c,base:d,workspaceRoot:p.root,gitRoot:p.gitRoot,targets:f,fingerprint:h,title:Hn(u.fix),body:hs({fix:u.fix,...u.validation===void 0?{}:{validation:u.validation},...u.plan===void 0?{}:{plan:u.plan},fingerprint:h,...l,commit:s.sha,host:"github"}),commitMessage:fs(u.fix,h)});if(tf(t,m,d.branch),m.kind==="opened"&&n.summaryPath!==void 0){let g=m.url===void 0?`#${m.number}`:`[#${m.number}](${m.url})`;await tv(n.summaryPath,`
227
227
  ### KwikQA opened a fix
228
228
 
229
229
  Draft pull request ${g}, into ${ge(d.branch)}, with a repair validated on this runner.
230
- `).catch(()=>{})}}}}}function sv(t,n){let{projectId:e,repositoryId:r,buildId:i,jobAttempt:s,commit:a}=n;if(e===void 0||r===void 0||i===void 0||s===void 0||a===void 0)return"`kwikqa fix` in CI needs System.TeamProjectId, Build.Repository.ID, Build.BuildId, System.JobAttempt, and Build.SourceVersion as Azure Pipelines sets them.";let o={system:"Azure Pipelines",ci:{system:"azure-pipelines",repository:`${e}/${r}`,runId:i,runAttempt:s,commit:a.sha.toLowerCase()},checkout:{variable:"BUILD_SOURCESDIRECTORY",path:t.env.BUILD_SOURCESDIRECTORY||void 0}};if(n.provider!=="TfsGit")return{...o,host:Le(`the repository is on ${n.provider||"another host"}, and from Azure Pipelines KwikQA opens fix pull requests only on Azure Repos`)};let d=n.pullRequest;if(d?.fork===!0)return{...o,host:Le("the pull request comes from a fork, whose build gets no secrets by default, so no fix pull request is opened. A maintainer can check out its branch and run `npx kwikqa fix`",!1)};let c=d!==void 0?n.pullRequestHead===void 0?void 0:{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.ref?.startsWith("refs/heads/")===!0?{branch:n.ref.slice(11),commit:a.sha.toLowerCase()}:void 0;if(c===void 0)return{...o,host:d===void 0?Le("this build isn't on a branch, so there's no branch for a fix pull request",!1):Le("the build doesn't name the pull request's source branch and commit (System.PullRequest.SourceBranch, System.PullRequest.SourceCommitId)")};if(n.token===void 0)return{...o,host:Le("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env")};if(n.collectionUrl===void 0)return{...o,host:Le("System.CollectionUri isn't what Azure Pipelines sets")};let l={collectionUrl:n.collectionUrl,projectId:e,repositoryId:r,token:n.token},u=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...o,host:{fixInReview:async p=>{let f=jr(p);return ef(t,await Nu(t.fetch,l,f),f,h=>Ou(t.io,t.fetch,l,{number:h,fingerprint:f},{...u,commit:a.sha}))},publish:async(p,f)=>{let h=nf(p);if(h.length===0)return t.io.print("No fix pull request: the fix's record names no repaired file.");let m=ps(p.fix),g=await $u(t.io,t.fetch,{...l,base:c,workspaceRoot:f.root,gitRoot:f.gitRoot,targets:h,fingerprint:m,title:Bn(p.fix),description:hs({fix:p.fix,...p.validation===void 0?{}:{validation:p.validation},...p.plan===void 0?{}:{plan:p.plan},fingerprint:m,...u,commit:a.sha,host:"azure-repos"}),commitMessage:fs(p.fix,m)});tf(t,g,c.branch)}}}}function av(t,n){let{repository:e,jobId:r,commit:i}=n;if(e===void 0||r===void 0||i===void 0)return"`kwikqa fix` in CI needs CI_PROJECT_PATH, CI_JOB_ID, and CI_COMMIT_SHA as GitLab CI/CD sets them.";let s={system:"GitLab CI/CD",ci:{system:"gitlab-ci",repository:e,runId:r,runAttempt:1,commit:i.sha},checkout:{variable:"CI_PROJECT_DIR",path:t.env.CI_PROJECT_DIR||void 0}},a="A maintainer can check out its branch and run `npx kwikqa fix` on their machine";if(n.pullRequest?.fork===!0)return{...s,host:Le(`the merge request comes from a fork, whose pipeline gets none of this project's variables, so no fix merge request is opened. ${a}`,!1)};if(n.sourceInOtherProject===!0)return{...s,host:Le(`the merge request's branch is in another project, such as a fork, which this project's token can't push to. ${a}`,!1)};let o=n.pullRequestHead!==void 0?{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.commitBranch!==void 0?{branch:n.commitBranch,commit:i.sha}:void 0;if(o===void 0)return{...s,host:t.env.CI_MERGE_REQUEST_IID===void 0||t.env.CI_MERGE_REQUEST_IID===""?Le("this pipeline isn't on a branch, so there's no branch for a fix merge request",!1):Le("the pipeline doesn't name the merge request's source commit (CI_MERGE_REQUEST_SOURCE_BRANCH_SHA)")};if(n.token===void 0)return{...s,host:Le("GITLAB_TOKEN isn't set; add a token with the `api` scope and at least the Developer role as a masked CI/CD variable")};if(n.apiUrl===void 0||n.projectId===void 0)return{...s,host:Le("CI_API_V4_URL or the project isn't what GitLab sets")};let d={apiUrl:n.apiUrl,project:n.projectId,token:n.token},c=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...s,host:{fixInReview:async l=>{let u=jr(l);return ef(t,await Fu(t.fetch,d,u),u,p=>Bu(t.io,t.fetch,d,{number:p,fingerprint:u},{...c,commit:i.sha}),nv)},publish:async(l,u)=>{let p=nf(l);if(p.length===0)return t.io.print("No fix merge request: the fix's record names no repaired file.");let f=ps(l.fix),h=await Hu(t.io,t.fetch,{...d,base:o,workspaceRoot:u.root,gitRoot:u.gitRoot,targets:p,fingerprint:f,title:Bn(l.fix),description:hs({fix:l.fix,...l.validation===void 0?{}:{validation:l.validation},...l.plan===void 0?{}:{plan:l.plan},fingerprint:f,...c,commit:i.sha,host:"gitlab"}),commitMessage:fs(l.fix,f)});tf(t,h,o.branch,nv)}}}}import{createHash as lD}from"node:crypto";import{basename as uD}from"node:path";var pD=100;function ov(t){return lD("sha256").update(t).digest("hex")}function dv(t,n){let e=t.projects.find(s=>s.projectId===n.projectId)?.name??"",r=n.location.file,i=n.titlePath.filter(s=>s!==""&&s!==r&&s!==uD(r));return{key:ov([e,r,...n.titlePath].join("\0")).slice(0,32),title:(i.length===0?[n.title]:i).join(" \u203A ").slice(0,300),file:r.slice(0,300),project:e.slice(0,100)}}function cv(t){return t===void 0?void 0:ov(t).slice(0,32)}function rf(t){if(t.run===void 0)return;let n=t.run,e=n.logicalTests.filter(r=>r.status==="unexpected"||r.status==="flaky").slice(0,pD).map(r=>({...dv(n,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:t.outcome,reasonCode:t.reasonCode,framework:n.framework,tests:e}}function bd(t){let n=t.record,e=t.run===void 0||t.packet===void 0||n?.diagnosis===void 0?void 0:fd(t.run,n.diagnosis,t.packet,n.clusters?.[0]?.representativeId),r=cv(n?.repair?.repairSessionId);return{kind:"fix",outcome:t.outcome,reasonCode:t.reasonCode,...t.run===void 0?{}:{framework:t.run.framework},...r===void 0?{}:{session:r},...n?.repair?.attempt===void 0?{}:{attempt:n.repair.attempt},...e===void 0||t.run===void 0?{}:{test:dv(t.run,e)},...n?.repairProposal===void 0?{}:{changedFiles:n.repairProposal.changedFiles,changedLines:n.repairProposal.changedLines}}}function lv(t){let n=t.record?.repair,e=cv(n?.repairSessionId);if(!(e===void 0||n===void 0))return{kind:"validation",outcome:t.outcome,reasonCode:t.reasonCode,session:e,attempt:n.attempt}}async function tr(t,n,e,r){if(r===void 0||e.team?.insights!==!0)return;try{await n.reportInsights([r])}catch{t.print("Team insights: couldn't share this result; nothing else changed.");return}let i=r.kind==="analysis"?`${r.tests.length} failing or flaky test name${r.tests.length===1?"":"s"} and the result`:r.kind==="fix"?"this fix's test and outcome":"the validation result";t.print(`Team insights: shared ${i} with ${e.team.owner}'s team.`)}var fD={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},hD={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function uv(t){let n=(t.npm_config_user_agent??"").split("/")[0];return n==="pnpm"||n==="yarn"||n==="bun"?n:"npm"}function Pt(t){return`${fD[uv(t)]} kwikqa`}function sf(t,n){return`${hD[uv(t)]} ${n}`}import{basename as mD}from"node:path";function un(t,n){return`${t} ${n}${t===1?"":"s"}`}function pv(t){return`$${t.toFixed(t<.1?4:2)}`}function yD(t){let n=t.evidence.flatMap(i=>i.locator.type==="diff-hunk"?[i.locator]:[]);if(n.length===0)return[];let e=new Set(n.flatMap(i=>i.commit===void 0?[]:[i.commit])),r=[...e.size===0?[]:[un(e.size,"commit")],...n.some(i=>i.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${un(n.length,"changed hunk")} from ${r} that mention the failures (--no-changes leaves them out)`]}function Ds(t,n,e){let r=n.model.reasoningEffort===void 0?"":`, effort ${n.model.reasoningEffort}`,i=n.model.zeroDataRetention===!0?", zero data retention":"";return[`${t==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${n.model.modelId} via ${n.model.providerId}${r}${i}`,` Evidence: ${un(n.evidence.length,"redacted item")} from ${n.channels.join(", ")||"the report"}`,` ${un(n.redactionIds.length,"redaction")} applied, ${un(n.omissionIds.length,"item")} withheld by policy`,...yD(n),` Estimate: at most ${n.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${n.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${pv(n.estimate.estimatedDollars)}`,` Caps: ${pv(n.caps.request.maxDollars)} per request`,` Payload: ${n.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function af(t,n,e={}){let r=t.proposal,i=["Proposed repair",` Intent: ${r.intent.statement}`,` Preserves: ${r.intent.preservedBehavior}`,` Changes: ${un(r.changedFiles,"file")}, ${un(r.changedLines,"line")}`,"",...r.diff.trimEnd().split(`
231
- `),"",e.validatedNow===!0?"Validation commands (run next, on this runner):":"Validation commands (run later by `kwikqa validate`):"],s=new Map;for(let a of n.commands.filter(o=>o.timing==="post-patch")){let o=a.args.map(c=>/\s/.test(c)?JSON.stringify(c):c),d=` ${mD(a.executable)} ${o.join(" ")}`;s.set(d,(s.get(d)??0)+1)}for(let[a,o]of s)i.push(o===1?a:`${a} (${o} runs)`);return t.checkoutPristine||i.push("","Note: this checkout has other uncommitted changes; they are not touched."),i}function fv(t,n){let e=r=>n?.logicalTests.find(i=>i.logicalTestId===r)?.title;return t.flatMap((r,i)=>{let s=r.logicalTestIds.map(d=>e(d)??d),a=s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`,o=`${s.length} test${s.length===1?"":"s"}`;return[`Failure group ${i+1} of ${t.length}: ${o} (${a})${r.escalated===!0?", answered by the stronger model":""}`,...r.diagnosis!==void 0&&r.diagnosis.hypotheses.length>0?of(r.diagnosis):[` ${r.outcome} (${r.reasonCode}): ${r.message}`],""]})}function of(t){if(t.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${t.recommendedNextAction}`];let n=[];for(let e of[...t.hypotheses].sort((r,i)=>r.rank-i.rank))n.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return n.push(` Next: ${t.recommendedNextAction}`),n}function hv(t,n,e,r,i={}){if(i.ciFix!=="running")switch(n){case"diagnosed":return r!==void 0&&Ze(r)===void 0?lt(r):t?.diagnosis?.repairEligibility!=="eligible"?void 0:i.ci===!0&&i.ciFix==="policy"?`The committed ci.fix policy lets \`${e} fix\` repair it in this job and open a draft pull request.`:i.ci===!0?`To repair it, run \`${e} analyze\` and then \`${e} fix\` on your machine.`:`Run \`${e} fix\` to propose a repair.`;case"proposal-ready":return`Run \`${e} fix\` without --propose-only to review and apply it.`;case"awaiting-validation":return`Run \`${e} validate\` to verify the patch.`;case"repair-failed":return t?.repair?.retryAvailable===!0?`Run \`${e} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}function mv(t){if(t===void 0)return;let n=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`,e=t.artifact.format===void 0?void 0:Zt[t.artifact.format],r=t.logicalTests.filter(a=>a.status==="unexpected").length,i=t.logicalTests.filter(a=>a.status==="flaky").length;return`Read a ${t.framework==="unknown"?"run from an unidentified framework":`${Rt[t.framework]}${n} run`}${e===void 0?"":` (${e})`}: ${un(t.logicalTests.length,"test")}, ${r} failing${i===0?"":`, ${i} flaky`}.`}function yv(t,n){if(t===void 0||Ze(t)===void 0)return;let e=t.framework==="playwright",r=e?"trace":"kwikqa-capture",i=0,s=0;for(let c of t.logicalTests)for(let l of Nr(c))i+=1,l.attachments.some(u=>u.name===r)&&(s+=1);if(i===0||s===i)return;let a=i-s;return[`Note: ${a===i?i===1?`The failing attempt has no ${e?"Playwright trace":"KwikQA failure capture"}`:`None of the ${i} failing attempts has ${e?"a Playwright trace":"a KwikQA failure capture"}`:`${a} of ${i} failing attempts have no ${e?"Playwright trace":"KwikQA failure capture"}`}, so browser actions, network, console, and DOM were not available to the diagnosis.`,e?` Run \`${n} analyze --capture\` to re-run them with full tracing, or set`:` Run \`${n} analyze --capture\` to re-run the failing specs and record each failure's page.`,...e?[' `use: { trace: "retain-on-failure" }` in playwright.config to keep traces of failures.']:[]].join(`
232
- `)}var Ls="0.3.0";var U={ok:0,failed:1,usage:2,account:3},Ms=(()=>{let{workspaceRoot:t,...n}=Bl;return{...n,maxPacketBytes:6e5}})(),vD=.85;function Td(t){if(t===void 0)return Ms;let n=Math.min(t.diagnosis.caps.request.maxInputTokens,t.repairCaps.request.maxInputTokens);return{...Ms,maxPacketBytes:Math.min(Ms.maxPacketBytes,Math.floor(n*vD))}}var bv=["test-results/kwikqa-report.json","test-results/kwikqa","playwright-report/results.json","test-results/results.json","mochawesome-report","cypress/reports","cypress/results","results.json","report.json"],kv=He(".kwikqa","cli-state.json");function uf(t){return`Not signed in. Run \`${Pt(t.env)} login\` first.`}async function ti(t){return gD(t).then(()=>!0,()=>!1)}async function pf(t){try{return JSON.parse(await kd(He(t,kv),"utf8"))}catch{return{}}}async function ff(t,n){await bD(He(t,".kwikqa"),{recursive:!0,mode:448}),await vv(He(t,kv),`${JSON.stringify(n)}
233
- `,{mode:384})}async function js(t,n,e){if(e!==void 0)return Rd(e)?e:Id(t.cwd,e);for(let r of[t.env.PLAYWRIGHT_JSON_OUTPUT_NAME,t.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let i=Rd(r)?r:Id(n,r);if(await ti(i))return i}for(let r of bv)if(await ti(He(n,r)))return He(n,r);return He(n,bv[0]??"report.json")}async function Rv(t){try{if((await wv(t)).isDirectory()){let n=gv("sha256");for(let e of(await xD(t)).sort()){let r=He(t,e);(await wv(r)).isFile()&&n.update(`${e}\0`).update(await kd(r))}return n.digest("hex")}return gv("sha256").update(await kd(t)).digest("hex")}catch{return}}async function kD(t,n,e){let r=n.capture;if(r===void 0)return;let i=He(t,r.reportPath);if(await Rv(e)!==r.sourceSha256||!await ti(i))return;let s=r.probePath===void 0?void 0:He(t,r.probePath);return{reportPath:i,...s!==void 0&&await ti(s)?{probePath:s}:{}}}async function RD(t,n,e,r){let i=await ct(e,{workspaceRoot:n,...r.framework===void 0?{}:{framework:r.framework}});if(i.kind!=="parsed"){t.io.error(`Capture skipped: ${i.diagnostic.message}`);return}let s=i.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await sp({run:i.run,workspaceRoot:n,repositoryRoot:await Os(n),captureId:s,env:t.env,probe:r.probe});if(a.kind!=="ready"){t.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)t.io.print(c);if(a.prepared.probeUnavailable!==void 0&&t.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)t.io.print("Run these tests? yes (--yes)");else if(!await t.io.confirm("Run these tests?")){t.io.print("Capture declined; analyzing the existing report.");return}let o=await ap(a.prepared,t.env);if(t.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);t.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${o.probe.results.length} failing test${o.probe.results.length===1?"":"s"}.`)}if(o.outcome.reportPath===void 0||o.outcome.reproduced===0)return;let d=await Rv(e);if(d!==void 0){let c=await pf(n);await ff(n,{...c,capture:{sourceSha256:d,reportPath:ei(n,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:ei(n,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function xv(t,n){if(t===void 0||t==="")return{...n,evaluationStatus:"unverified-model"};let[e,r]=t.split("@");if(e===void 0||r===void 0||r==="")throw new yt(0,"invalid-model",`Model routes look like author/model@provider, not ${t}.`);return{modelId:e,providerId:r,evaluationStatus:"unverified-model"}}async function _s(t,n,e){let r=await ln(t.env);if(r===void 0)return{exit:U.account,messages:[uf(t)]};let i=new Tt(cn(t.env,r.apiUrl),r.token,t.fetch),s=await i.status(),a=await i.hostedConfig(),o=Jx(s);if(!o&&(t.env.OPENROUTER_API_KEY??"").trim()==="")return{exit:U.account,messages:["The BYOK plans need OPENROUTER_API_KEY in the environment."]};let d=n==="analysis"?s.usage.analyses:s.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let v=n==="analysis"?"analyses":"fixes";return{exit:U.account,messages:[`You have used all ${d.limit} ${v} on the ${s.plan} plan until ${s.periodEnd.slice(0,10)}.`,s.team?.role==="member"?`Ask ${s.team.owner}, who manages your team's plan, to add seats.`:`Run \`${Pt(t.env)} upgrade\` to see plans with more.`]}}let c,l,u=a.sessions===!0&&e===void 0?{open:async v=>{l=(await i.openSession(v)).sessionTicket},close:async()=>{let v=l;l=void 0,v!==void 0&&await i.closeSession(v)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async v=>{p=(await i.openSession(v,"repair")).sessionTicket},close:async()=>{let v=p;if(p=void 0,v===void 0)return;let R=await i.closeSession(v);R.retryTicket!==void 0&&(c=R.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:v=>{c=v},session:()=>l,repairSession:()=>p};if(!o){let v=new wd(new Wn({readApiKey:()=>t.env.OPENROUTER_API_KEY,fetch:t.fetch}),i,h);return{diagnosis:{model:xv(t.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:v,...u===void 0?{}:{session:u}},repairModel:xv(t.env.KWIKQA_REPAIR_MODEL,a.models.repair),repairCaps:a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"OpenRouter, with your own API key (KwikQA counts the request)",ticket:()=>c,client:i,status:s}}let m=i.transport({...h,jobs:a.jobs===!0,onProgress:TD(t),onRestart:()=>t.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...t.sleep===void 0?{}:{sleep:t.sleep}}),g=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=g?a.models.escalation:void 0,w=g?a.caps.escalation:void 0,x=!g&&u!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0?{model:a.models.escalation,caps:a.caps.escalation}:void 0;return{diagnosis:{model:y??a.models.diagnosis,caps:w??a.caps.diagnosis,transport:m,...u===void 0?{}:{session:u},...x===void 0?{}:{escalation:x}},repairModel:y??a.models.repair,repairCaps:w??a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>c,client:i,status:s}}function Ad(t,n){for(let e of n.messages)t.io.error(e);return n.exit}var ID=3e4;function AD(t){let n=Math.floor(t/1e3),e=Math.floor(n/60);return e===0?`${n}s`:`${e}m ${String(n%60).padStart(2,"0")}s`}function TD(t){let n=0;return e=>{let r=Math.floor(e/ID);r<=n||(n=r,t.io.print(` The model is still working (${AD(e)})\u2026`))}}function Pd(t,n,e){let r=async(i,s)=>{for(let a of i)t.io.print(a);return e!==!1?(t.io.print(`${s} yes (${e===!0?"--yes":e})`),!0):t.io.confirm(s)};return{approveDiagnosis:i=>r(Ds("diagnosis",i,n),"Send this request?"),approveDiagnoses:i=>{let[s]=i;return i.length===1&&s!==void 0?r(Ds("diagnosis",s,n),"Send this request?"):r([`${i.length} diagnosis requests, one for each group of failures with a shared cause:`,...i.flatMap((a,o)=>["",`Request ${o+1} of ${i.length}`,...Ds("diagnosis",a,n)])],`Send these ${i.length} requests?`)},approveRepairRequest:i=>r(Ds("repair proposal",i,n),"Send this request?"),approveApplication:async(i,s)=>{for(let a of af(i,s))t.io.print(a);return t.io.confirm("Apply this patch?")}}}async function Sd(t,n,e,r,i){let s=new Set(r),a=await sp({run:{...e,logicalTests:e.logicalTests.filter(d=>s.has(d.logicalTestId))},workspaceRoot:n,repositoryRoot:await Os(n),captureId:`${i.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:t.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};t.io.print(""),t.io.print(i.intro);for(let d of a.prepared.description)t.io.print(d);if(i.approvedBy!==void 0)t.io.print(`${i.question} yes (${i.approvedBy})`);else if(!await t.io.confirm(i.question))return{kind:"declined"};let o=await ap(a.prepared,t.env);return t.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function PD(t){return t==="repair-failed"||t==="validation-unavailable"||t==="operation-failed"?U.failed:U.ok}function pn(t,n,e={}){t.io.print("");let r=mv("run"in n?n.run:void 0);r!==void 0&&n.record?.command!=="validate"&&t.io.print(r);let i=n.record?.clusters??[];if(i.length>1&&n.record?.command!=="validate")for(let d of fv(i,"run"in n?n.run:void 0))t.io.print(d);else if(n.record?.diagnosis!==void 0&&n.record.command!=="validate"){for(let d of of(n.record.diagnosis))t.io.print(d);t.io.print("")}t.io.print(`Result: ${n.outcome} (${n.reasonCode})`),t.io.print(n.message);let s=Pt(t.env),a=yv("run"in n?n.run:void 0,s);a!==void 0&&t.io.print(a);let o=hv(n.record,n.outcome,s,"run"in n?n.run:void 0,e);return o!==void 0&&t.io.print(o),n.recordPath!==void 0&&t.io.print(`Record: ${n.recordPath}`),PD(n.outcome)}async function fn(t,n){try{return await n()}catch(e){if(e instanceof yt)return t.io.error(e.message),[401,402,403,409].includes(e.status)?U.account:U.failed;throw e}}function Iv(t){return t.sleep??(n=>new Promise(e=>setTimeout(e,n)))}async function Av(t){return fn(t,async()=>{let n=new Tt(cn(t.env),void 0,t.fetch),e=await n.startDeviceLogin();t.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let r=Iv(t),i=Math.max(1,e.interval),s=Date.now()+e.expiresIn*1e3;for(;Date.now()<s;){await r(i*1e3);let a=await n.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await Zx(t.env,{token:a.token,login:a.login,apiUrl:n.baseUrl}),t.io.print(`Signed in as ${a.login}.`),U.ok;if(a.status==="slow_down"&&(i+=5),a.status==="expired"||a.status==="denied")return t.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),U.account}return t.io.error("The code expired before sign-in finished."),U.account})}async function Tv(t){let n=(t.env.KWIKQA_TOKEN??"").trim()!=="",e=n?void 0:await ln(t.env);if(e!==void 0)try{await new Tt(cn(t.env,e.apiUrl),e.token,t.fetch).logout()}catch{t.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Zr}account/.`)}return await ev(t.env),t.io.print("Signed out."),n&&t.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),U.ok}function SD(t){let n=[...t.seats!==void 0&&t.seats>1?[`${t.seats} seats`]:[],...t.interval===void 0?[]:[t.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${t.plan} plan${n.length===0?"":` (${n.join(", ")})`}`}async function Pv(t){return fn(t,async()=>{let n=await ln(t.env);if(n===void 0)return t.io.print(uf(t)),U.account;let r=await new Tt(cn(t.env,n.apiUrl),n.token,t.fetch).status(),i=(s,a)=>a===void 0?`${s} (unlimited)`:`${s} of ${a}`;return t.io.print(`Signed in as ${r.login} ${SD(r)}.`),r.team!==void 0&&(t.io.print(r.team.role==="member"?`Team: ${r.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${r.team.members} member${r.team.members===1?"":"s"}; usage below is the shared pool.`),t.io.print(r.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),t.io.print(`Analyses this period: ${i(r.usage.analyses.used,r.usage.analyses.limit)}`),t.io.print(`Fixes this period: ${i(r.usage.repairs.used,r.usage.repairs.limit)}`),t.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`),t.io.print(`Manage your account, team, and tokens: ${Zr}`),U.ok})}async function Sv(t){let n=await ln(t.env);if(n===void 0){t.io.error(uf(t));return}return new Tt(cn(t.env,n.apiUrl),n.token,t.fetch)}function ED(t){let n=t.perSeat?"/seat":"",e=t.monthlyUsd===0?"$0":`$${t.monthlyUsd}${n}/mo or $${t.annualUsd}${n}/yr`,r=t.analyses===void 0?"unlimited analyses and fixes":`${t.analyses} analyses and ${t.repairs} fixes a month${t.perSeat?" per seat, shared":""}`,i=[...t.hosted?[]:["your OpenRouter key"],...t.perSeat?[`${t.minSeats}+ seats`]:[]];return{price:e,limits:i.length===0?r:`${r} (${i.join(", ")})`}}async function Ev(t,n,e={annual:!1}){return fn(t,async()=>{let r=await ln(t.env),i=await new Tt(cn(t.env,r?.apiUrl),void 0,t.fetch).plans(),s=i.paidPlansOpen!==!1,o=i.plans.filter(m=>m.id!=="free").find(m=>m.id===n);if(o===void 0||!s){n!==void 0&&o===void 0&&t.io.error(`Unknown plan: ${n}`),t.io.print(`Plans (monthly, or yearly with ${12-i.annualMonthsCharged} months free):`);let m=Math.max(...i.plans.map(g=>g.id.length));for(let g of i.plans){let{price:y,limits:w}=ED(g);t.io.print(` ${g.id.padEnd(m)} ${y}: ${w}`)}if(s)t.io.print(`Run \`${Pt(t.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else if(t.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return U.account;return n===void 0?U.ok:U.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=i.maxSeats:d===1)))return t.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${i.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),U.usage;let c=await Sv(t);if(c===void 0)return U.account;let l=await c.status();if(l.team?.role==="member")return t.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),U.ok;if(l.plan!=="free")return t.io.print(`You're on the ${l.plan} plan. Change plans, seats, or billing period in Billing, where you see the charge before you confirm:`),t.io.print(`${Zr}billing/`),U.ok;let u=e.annual?"year":"month",p=await c.checkout(o.id,{interval:u,...d===void 0?{}:{seats:d}}),f=o.perSeat?d??o.minSeats:1,h=(e.annual?o.annualUsd:o.monthlyUsd)*f;return t.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),t.io.print(p.url),U.ok})}async function Cv(t){return fn(t,async()=>{let n=await Sv(t);if(n===void 0)return U.account;try{let{url:e}=await n.billingPortal();return t.io.print("Open this link to update your payment method or download invoices:"),t.io.print(e),t.io.print(`To change or cancel your plan: ${Zr}billing/`),U.ok}catch(e){if(e instanceof yt&&e.code==="no-billing-account")return t.io.print("You don't have a paid subscription yet."),t.io.print(`Run \`${Pt(t.env)} upgrade <plan>\` to choose one.`),U.ok;if(e instanceof yt&&e.code==="team-member")return t.io.print(e.message),U.ok;throw e}})}async function Nv(t){let n=await Ut(t.cwd),e=He(n,"kwikqa.config.json");if(await ti(e))t.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let p=Op({repositoryPaths:await Wp(n)});t.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let f of p.canonicalContents.trimEnd().split(`
234
- `))t.io.print(` ${f}`);for(let f of[...p.reasons,...p.ambiguities])t.io.print(` - ${f}`);await t.io.confirm("Write kwikqa.config.json?")&&(await vv(e,p.canonicalContents,{flag:"wx"}),t.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let r=He(n,".gitignore"),i=await ti(r)?await kd(r,"utf8"):"",s=p=>p.trim().replace(/^\//,"").replace(/\/$/,""),a=new Set(i.split(/\r?\n/).map(s)),o=[{entry:".kwikqa/",what:"local run records"},{entry:Ya,what:"the failure report"}].filter(p=>!a.has(s(p.entry))),d=o.map(p=>`${p.entry} (${p.what})`).join(" and ");o.length>0&&await t.io.confirm(`Add ${d} to .gitignore?`)&&await wD(r,`
230
+ `).catch(()=>{})}}}}}function sv(t,n){let{projectId:e,repositoryId:r,buildId:i,jobAttempt:s,commit:a}=n;if(e===void 0||r===void 0||i===void 0||s===void 0||a===void 0)return"`kwikqa fix` in CI needs System.TeamProjectId, Build.Repository.ID, Build.BuildId, System.JobAttempt, and Build.SourceVersion as Azure Pipelines sets them.";let o={system:"Azure Pipelines",ci:{system:"azure-pipelines",repository:`${e}/${r}`,runId:i,runAttempt:s,commit:a.sha.toLowerCase()},checkout:{variable:"BUILD_SOURCESDIRECTORY",path:t.env.BUILD_SOURCESDIRECTORY||void 0}};if(n.provider!=="TfsGit")return{...o,host:Le(`the repository is on ${n.provider||"another host"}, and from Azure Pipelines KwikQA opens fix pull requests only on Azure Repos`)};let d=n.pullRequest;if(d?.fork===!0)return{...o,host:Le("the pull request comes from a fork, whose build gets no secrets by default, so no fix pull request is opened. A maintainer can check out its branch and run `npx kwikqa fix`",!1)};let c=d!==void 0?n.pullRequestHead===void 0?void 0:{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.ref?.startsWith("refs/heads/")===!0?{branch:n.ref.slice(11),commit:a.sha.toLowerCase()}:void 0;if(c===void 0)return{...o,host:d===void 0?Le("this build isn't on a branch, so there's no branch for a fix pull request",!1):Le("the build doesn't name the pull request's source branch and commit (System.PullRequest.SourceBranch, System.PullRequest.SourceCommitId)")};if(n.token===void 0)return{...o,host:Le("SYSTEM_ACCESSTOKEN isn't set; add `SYSTEM_ACCESSTOKEN: $(System.AccessToken)` to the step's env")};if(n.collectionUrl===void 0)return{...o,host:Le("System.CollectionUri isn't what Azure Pipelines sets")};let l={collectionUrl:n.collectionUrl,projectId:e,repositoryId:r,token:n.token},u=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...o,host:{fixInReview:async p=>{let f=jr(p);return ef(t,await Nu(t.fetch,l,f),f,h=>Ou(t.io,t.fetch,l,{number:h,fingerprint:f},{...u,commit:a.sha}))},publish:async(p,f)=>{let h=nf(p);if(h.length===0)return t.io.print("No fix pull request: the fix's record names no repaired file.");let m=ps(p.fix),g=await $u(t.io,t.fetch,{...l,base:c,workspaceRoot:f.root,gitRoot:f.gitRoot,targets:h,fingerprint:m,title:Hn(p.fix),description:hs({fix:p.fix,...p.validation===void 0?{}:{validation:p.validation},...p.plan===void 0?{}:{plan:p.plan},fingerprint:m,...u,commit:a.sha,host:"azure-repos"}),commitMessage:fs(p.fix,m)});tf(t,g,c.branch)}}}}function av(t,n){let{repository:e,jobId:r,commit:i}=n;if(e===void 0||r===void 0||i===void 0)return"`kwikqa fix` in CI needs CI_PROJECT_PATH, CI_JOB_ID, and CI_COMMIT_SHA as GitLab CI/CD sets them.";let s={system:"GitLab CI/CD",ci:{system:"gitlab-ci",repository:e,runId:r,runAttempt:1,commit:i.sha},checkout:{variable:"CI_PROJECT_DIR",path:t.env.CI_PROJECT_DIR||void 0}},a="A maintainer can check out its branch and run `npx kwikqa fix` on their machine";if(n.pullRequest?.fork===!0)return{...s,host:Le(`the merge request comes from a fork, whose pipeline gets none of this project's variables, so no fix merge request is opened. ${a}`,!1)};if(n.sourceInOtherProject===!0)return{...s,host:Le(`the merge request's branch is in another project, such as a fork, which this project's token can't push to. ${a}`,!1)};let o=n.pullRequestHead!==void 0?{branch:n.pullRequestHead.ref,commit:n.pullRequestHead.sha}:n.commitBranch!==void 0?{branch:n.commitBranch,commit:i.sha}:void 0;if(o===void 0)return{...s,host:t.env.CI_MERGE_REQUEST_IID===void 0||t.env.CI_MERGE_REQUEST_IID===""?Le("this pipeline isn't on a branch, so there's no branch for a fix merge request",!1):Le("the pipeline doesn't name the merge request's source commit (CI_MERGE_REQUEST_SOURCE_BRANCH_SHA)")};if(n.token===void 0)return{...s,host:Le("GITLAB_TOKEN isn't set; add a token with the `api` scope and at least the Developer role as a masked CI/CD variable")};if(n.apiUrl===void 0||n.projectId===void 0)return{...s,host:Le("CI_API_V4_URL or the project isn't what GitLab sets")};let d={apiUrl:n.apiUrl,project:n.projectId,token:n.token},c=n.runUrl===void 0?{}:{runUrl:n.runUrl};return{...s,host:{fixInReview:async l=>{let u=jr(l);return ef(t,await Fu(t.fetch,d,u),u,p=>Bu(t.io,t.fetch,d,{number:p,fingerprint:u},{...c,commit:i.sha}),nv)},publish:async(l,u)=>{let p=nf(l);if(p.length===0)return t.io.print("No fix merge request: the fix's record names no repaired file.");let f=ps(l.fix),h=await Hu(t.io,t.fetch,{...d,base:o,workspaceRoot:u.root,gitRoot:u.gitRoot,targets:p,fingerprint:f,title:Hn(l.fix),description:hs({fix:l.fix,...l.validation===void 0?{}:{validation:l.validation},...l.plan===void 0?{}:{plan:l.plan},fingerprint:f,...c,commit:i.sha,host:"gitlab"}),commitMessage:fs(l.fix,f)});tf(t,h,o.branch,nv)}}}}import{createHash as pD}from"node:crypto";import{basename as fD}from"node:path";var hD=100;function ov(t){return pD("sha256").update(t).digest("hex")}function dv(t,n){let e=t.projects.find(s=>s.projectId===n.projectId)?.name??"",r=n.location.file,i=n.titlePath.filter(s=>s!==""&&s!==r&&s!==fD(r));return{key:ov([e,r,...n.titlePath].join("\0")).slice(0,32),title:(i.length===0?[n.title]:i).join(" \u203A ").slice(0,300),file:r.slice(0,300),project:e.slice(0,100)}}function cv(t){return t===void 0?void 0:ov(t).slice(0,32)}function rf(t){if(t.run===void 0)return;let n=t.run,e=n.logicalTests.filter(r=>r.status==="unexpected"||r.status==="flaky").slice(0,hD).map(r=>({...dv(n,r),status:r.status==="flaky"?"flaky":"failed"}));return{kind:"analysis",outcome:t.outcome,reasonCode:t.reasonCode,framework:n.framework,tests:e}}function bd(t){let n=t.record,e=t.run===void 0||t.packet===void 0||n?.diagnosis===void 0?void 0:fd(t.run,n.diagnosis,t.packet,n.clusters?.[0]?.representativeId),r=cv(n?.repair?.repairSessionId);return{kind:"fix",outcome:t.outcome,reasonCode:t.reasonCode,...t.run===void 0?{}:{framework:t.run.framework},...r===void 0?{}:{session:r},...n?.repair?.attempt===void 0?{}:{attempt:n.repair.attempt},...e===void 0||t.run===void 0?{}:{test:dv(t.run,e)},...n?.repairProposal===void 0?{}:{changedFiles:n.repairProposal.changedFiles,changedLines:n.repairProposal.changedLines}}}function lv(t){let n=t.record?.repair,e=cv(n?.repairSessionId);if(!(e===void 0||n===void 0))return{kind:"validation",outcome:t.outcome,reasonCode:t.reasonCode,session:e,attempt:n.attempt}}async function nr(t,n,e,r){if(r===void 0||e.team?.insights!==!0)return;try{await n.reportInsights([r])}catch{t.print("Team insights: couldn't share this result; nothing else changed.");return}let i=r.kind==="analysis"?`${r.tests.length} failing or flaky test name${r.tests.length===1?"":"s"} and the result`:r.kind==="fix"?"this fix's test and outcome":"the validation result";t.print(`Team insights: shared ${i} with ${e.team.owner}'s team.`)}var mD={npm:"npx",pnpm:"pnpm exec",yarn:"yarn",bun:"bunx"},yD={npm:"npm i -D",pnpm:"pnpm add -D",yarn:"yarn add -D",bun:"bun add -d"};function uv(t){let n=(t.npm_config_user_agent??"").split("/")[0];return n==="pnpm"||n==="yarn"||n==="bun"?n:"npm"}function Pt(t){return`${mD[uv(t)]} kwikqa`}function sf(t,n){return`${yD[uv(t)]} ${n}`}import{basename as gD}from"node:path";function un(t,n){return`${t} ${n}${t===1?"":"s"}`}function pv(t){return`$${t.toFixed(t<.1?4:2)}`}function wD(t){let n=t.evidence.flatMap(i=>i.locator.type==="diff-hunk"?[i.locator]:[]);if(n.length===0)return[];let e=new Set(n.flatMap(i=>i.commit===void 0?[]:[i.commit])),r=[...e.size===0?[]:[un(e.size,"commit")],...n.some(i=>i.commit===void 0)?["uncommitted changes"]:[]].join(" and ");return[` Changes: ${un(n.length,"changed hunk")} from ${r} that mention the failures (--no-changes leaves them out)`]}function Ds(t,n,e){let r=n.model.reasoningEffort===void 0?"":`, effort ${n.model.reasoningEffort}`,i=n.model.zeroDataRetention===!0?", zero data retention":"";return[`${t==="diagnosis"?"Diagnosis":"Repair proposal"} request -> ${e}`,` Model: ${n.model.modelId} via ${n.model.providerId}${r}${i}`,` Evidence: ${un(n.evidence.length,"redacted item")} from ${n.channels.join(", ")||"the report"}`,` ${un(n.redactionIds.length,"redaction")} applied, ${un(n.omissionIds.length,"item")} withheld by policy`,...wD(n),` Estimate: at most ${n.estimate.estimatedInputTokens.toLocaleString("en-US")} input + ${n.estimate.estimatedOutputTokens.toLocaleString("en-US")} output tokens, at most ${pv(n.estimate.estimatedDollars)}`,` Caps: ${pv(n.caps.request.maxDollars)} per request`,` Payload: ${n.payloadManifestHash.slice(0,16)}... (exactly this redacted payload is sent)`]}function af(t,n,e={}){let r=t.proposal,i=["Proposed repair",` Intent: ${r.intent.statement}`,` Preserves: ${r.intent.preservedBehavior}`,` Changes: ${un(r.changedFiles,"file")}, ${un(r.changedLines,"line")}`,"",...r.diff.trimEnd().split(`
231
+ `),"",e.validatedNow===!0?"Validation commands (run next, on this runner):":"Validation commands (run later by `kwikqa validate`):"],s=new Map;for(let a of n.commands.filter(o=>o.timing==="post-patch")){let o=a.args.map(c=>/\s/.test(c)?JSON.stringify(c):c),d=` ${gD(a.executable)} ${o.join(" ")}`;s.set(d,(s.get(d)??0)+1)}for(let[a,o]of s)i.push(o===1?a:`${a} (${o} runs)`);return t.checkoutPristine||i.push("","Note: this checkout has other uncommitted changes; they are not touched."),i}function fv(t,n){let e=r=>n?.logicalTests.find(i=>i.logicalTestId===r)?.title;return t.flatMap((r,i)=>{let s=r.logicalTestIds.map(d=>e(d)??d),a=s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`,o=`${s.length} test${s.length===1?"":"s"}`;return[`Failure group ${i+1} of ${t.length}: ${o} (${a})${r.escalated===!0?", answered by the stronger model":""}`,...r.diagnosis!==void 0&&r.diagnosis.hypotheses.length>0?of(r.diagnosis):[` ${r.outcome} (${r.reasonCode}): ${r.message}`],""]})}function of(t){if(t.hypotheses.length===0)return["No cause is supported by the evidence.",` Next: ${t.recommendedNextAction}`];let n=[];for(let e of[...t.hypotheses].sort((r,i)=>r.rank-i.rank))n.push(`#${e.rank} ${e.statement}`,` owner: ${e.probableOwner}, evidence: ${e.evidenceGrade}, cause: ${e.causalCategory}`);return n.push(` Next: ${t.recommendedNextAction}`),n}function hv(t,n,e,r,i={}){if(i.ciFix!=="running")switch(n){case"diagnosed":return r!==void 0&&Ze(r)===void 0?lt(r):t?.diagnosis?.repairEligibility!=="eligible"?void 0:i.ci===!0&&i.ciFix==="policy"?`The committed ci.fix policy lets \`${e} fix\` repair it in this job and open a draft pull request.`:i.ci===!0?`To repair it, run \`${e} analyze\` and then \`${e} fix\` on your machine.`:`Run \`${e} fix\` to propose a repair.`;case"proposal-ready":return`Run \`${e} fix\` without --propose-only to review and apply it.`;case"awaiting-validation":return`Run \`${e} validate\` to verify the patch.`;case"repair-failed":return t?.repair?.retryAvailable===!0?`Run \`${e} fix --retry\` to re-diagnose from the validation evidence (one retry left).`:void 0;default:return}}function mv(t){if(t===void 0)return;let n=t.artifact.formatVersion===void 0?"":` ${t.artifact.formatVersion}`,e=t.artifact.format===void 0?void 0:Zt[t.artifact.format],r=t.logicalTests.filter(a=>a.status==="unexpected").length,i=t.logicalTests.filter(a=>a.status==="flaky").length;return`Read a ${t.framework==="unknown"?"run from an unidentified framework":`${Rt[t.framework]}${n} run`}${e===void 0?"":` (${e})`}: ${un(t.logicalTests.length,"test")}, ${r} failing${i===0?"":`, ${i} flaky`}.`}function yv(t,n){if(t===void 0||Ze(t)===void 0)return;let e=t.framework==="playwright",r=e?"trace":"kwikqa-capture",i=0,s=0;for(let c of t.logicalTests)for(let l of Or(c))i+=1,l.attachments.some(u=>u.name===r)&&(s+=1);if(i===0||s===i)return;let a=i-s;return[`Note: ${a===i?i===1?`The failing attempt has no ${e?"Playwright trace":"KwikQA failure capture"}`:`None of the ${i} failing attempts has ${e?"a Playwright trace":"a KwikQA failure capture"}`:`${a} of ${i} failing attempts have no ${e?"Playwright trace":"KwikQA failure capture"}`}, so browser actions, network, console, and DOM were not available to the diagnosis.`,e?` Run \`${n} analyze --capture\` to re-run them with full tracing, or set`:` Run \`${n} analyze --capture\` to re-run the failing specs and record each failure's page.`,...e?[' `use: { trace: "retain-on-failure" }` in playwright.config to keep traces of failures.']:[]].join(`
232
+ `)}var Ls="0.3.1";var U={ok:0,failed:1,usage:2,account:3},Ms=(()=>{let{workspaceRoot:t,...n}=Bl;return{...n,maxPacketBytes:6e5}})(),RD=.85;function Td(t){if(t===void 0)return Ms;let n=Math.min(t.diagnosis.caps.request.maxInputTokens,t.repairCaps.request.maxInputTokens);return{...Ms,maxPacketBytes:Math.min(Ms.maxPacketBytes,Math.floor(n*RD))}}var bv=["test-results/kwikqa-report.json","test-results/kwikqa","playwright-report/results.json","test-results/results.json","mochawesome-report","cypress/reports","cypress/results","results.json","report.json"],kv=He(".kwikqa","cli-state.json");function uf(t){return`Not signed in. Run \`${Pt(t.env)} login\` first.`}async function ti(t){return bD(t).then(()=>!0,()=>!1)}async function pf(t){try{return JSON.parse(await kd(He(t,kv),"utf8"))}catch{return{}}}async function ff(t,n){await vD(He(t,".kwikqa"),{recursive:!0,mode:448}),await vv(He(t,kv),`${JSON.stringify(n)}
233
+ `,{mode:384})}async function js(t,n,e){if(e!==void 0)return Rd(e)?e:Id(t.cwd,e);for(let r of[t.env.PLAYWRIGHT_JSON_OUTPUT_NAME,t.env.KWIKQA_REPORT_DIR])if(r!==void 0&&r!==""){let i=Rd(r)?r:Id(n,r);if(await ti(i))return i}for(let r of bv)if(await ti(He(n,r)))return He(n,r);return He(n,bv[0]??"report.json")}async function Rv(t){try{if((await wv(t)).isDirectory()){let n=gv("sha256");for(let e of(await kD(t)).sort()){let r=He(t,e);(await wv(r)).isFile()&&n.update(`${e}\0`).update(await kd(r))}return n.digest("hex")}return gv("sha256").update(await kd(t)).digest("hex")}catch{return}}async function ID(t,n,e){let r=n.capture;if(r===void 0)return;let i=He(t,r.reportPath);if(await Rv(e)!==r.sourceSha256||!await ti(i))return;let s=r.probePath===void 0?void 0:He(t,r.probePath);return{reportPath:i,...s!==void 0&&await ti(s)?{probePath:s}:{}}}async function AD(t,n,e,r){let i=await ct(e,{workspaceRoot:n,...r.framework===void 0?{}:{framework:r.framework}});if(i.kind!=="parsed"){t.io.error(`Capture skipped: ${i.diagnostic.message}`);return}let s=i.run.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest",a=await sp({run:i.run,workspaceRoot:n,repositoryRoot:await Os(n),captureId:s,env:t.env,probe:r.probe});if(a.kind!=="ready"){t.io.print(`Capture skipped: ${a.message}`);return}for(let c of a.prepared.description)t.io.print(c);if(a.prepared.probeUnavailable!==void 0&&t.io.print(`Note: ${a.prepared.probeUnavailable}`),r.yes)t.io.print("Run these tests? yes (--yes)");else if(!await t.io.confirm("Run these tests?")){t.io.print("Capture declined; analyzing the existing report.");return}let o=await ap(a.prepared,t.env);if(t.io.print(o.outcome.message),o.probe!==void 0){let c=o.probe.results.reduce((l,u)=>l+u.candidates.length,0);t.io.print(`Live probe: ${c} Playwright-generated locator${c===1?"":"s"} for ${o.probe.results.length} failing test${o.probe.results.length===1?"":"s"}.`)}if(o.outcome.reportPath===void 0||o.outcome.reproduced===0)return;let d=await Rv(e);if(d!==void 0){let c=await pf(n);await ff(n,{...c,capture:{sourceSha256:d,reportPath:ei(n,o.outcome.reportPath),...o.probePath===void 0?{}:{probePath:ei(n,o.probePath)}}})}return{reportPath:o.outcome.reportPath,...o.probePath===void 0?{}:{probePath:o.probePath}}}function xv(t,n){if(t===void 0||t==="")return{...n,evaluationStatus:"unverified-model"};let[e,r]=t.split("@");if(e===void 0||r===void 0||r==="")throw new yt(0,"invalid-model",`Model routes look like author/model@provider, not ${t}.`);return{modelId:e,providerId:r,evaluationStatus:"unverified-model"}}async function _s(t,n,e){let r=await ln(t.env);if(r===void 0)return{exit:U.account,messages:[uf(t)]};let i=new Tt(cn(t.env,r.apiUrl),r.token,t.fetch),s=await i.status(),a=await i.hostedConfig(),o=Jx(s);if(!o&&(t.env.OPENROUTER_API_KEY??"").trim()==="")return{exit:U.account,messages:["The BYOK plans need OPENROUTER_API_KEY in the environment."]};let d=n==="analysis"?s.usage.analyses:s.usage.repairs;if(e===void 0&&d.limit!==void 0&&d.used>=d.limit){let v=n==="analysis"?"analyses":"fixes";return{exit:U.account,messages:[`You have used all ${d.limit} ${v} on the ${s.plan} plan until ${s.periodEnd.slice(0,10)}.`,s.team?.role==="member"?`Ask ${s.team.owner}, who manages your team's plan, to add seats.`:`Run \`${Pt(t.env)} upgrade\` to see plans with more.`]}}let c,l,u=a.sessions===!0&&e===void 0?{open:async v=>{l=(await i.openSession(v)).sessionTicket},close:async()=>{let v=l;l=void 0,v!==void 0&&await i.closeSession(v)}}:void 0,p,f=a.repairSessions===!0&&e===void 0?{open:async v=>{p=(await i.openSession(v,"repair")).sessionTicket},close:async()=>{let v=p;if(p=void 0,v===void 0)return;let R=await i.closeSession(v);R.retryTicket!==void 0&&(c=R.retryTicket)}}:void 0,h={...e===void 0?{}:{retryTicket:e},onRetryTicket:v=>{c=v},session:()=>l,repairSession:()=>p};if(!o){let v=new wd(new Jn({readApiKey:()=>t.env.OPENROUTER_API_KEY,fetch:t.fetch}),i,h);return{diagnosis:{model:xv(t.env.KWIKQA_DIAGNOSIS_MODEL,a.models.diagnosis),caps:a.caps.diagnosis,transport:v,...u===void 0?{}:{session:u}},repairModel:xv(t.env.KWIKQA_REPAIR_MODEL,a.models.repair),repairCaps:a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"OpenRouter, with your own API key (KwikQA counts the request)",ticket:()=>c,client:i,status:s}}let m=i.transport({...h,jobs:a.jobs===!0,onProgress:SD(t),onRestart:()=>t.io.print(" The KwikQA service restarted while the model was working; sending the request again (nothing was charged)."),...t.sleep===void 0?{}:{sleep:t.sleep}}),g=e!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0,y=g?a.models.escalation:void 0,w=g?a.caps.escalation:void 0,x=!g&&u!==void 0&&a.models.escalation!==void 0&&a.caps.escalation!==void 0?{model:a.models.escalation,caps:a.caps.escalation}:void 0;return{diagnosis:{model:y??a.models.diagnosis,caps:w??a.caps.diagnosis,transport:m,...u===void 0?{}:{session:u},...x===void 0?{}:{escalation:x}},repairModel:y??a.models.repair,repairCaps:w??a.caps.repair,...f===void 0?{}:{repairSession:f},destination:"the KwikQA service, which forwards it to OpenRouter",ticket:()=>c,client:i,status:s}}function Ad(t,n){for(let e of n.messages)t.io.error(e);return n.exit}var TD=3e4;function PD(t){let n=Math.floor(t/1e3),e=Math.floor(n/60);return e===0?`${n}s`:`${e}m ${String(n%60).padStart(2,"0")}s`}function SD(t){let n=0;return e=>{let r=Math.floor(e/TD);r<=n||(n=r,t.io.print(` The model is still working (${PD(e)})\u2026`))}}function Pd(t,n,e){let r=async(i,s)=>{for(let a of i)t.io.print(a);return e!==!1?(t.io.print(`${s} yes (${e===!0?"--yes":e})`),!0):t.io.confirm(s)};return{approveDiagnosis:i=>r(Ds("diagnosis",i,n),"Send this request?"),approveDiagnoses:i=>{let[s]=i;return i.length===1&&s!==void 0?r(Ds("diagnosis",s,n),"Send this request?"):r([`${i.length} diagnosis requests, one for each group of failures with a shared cause:`,...i.flatMap((a,o)=>["",`Request ${o+1} of ${i.length}`,...Ds("diagnosis",a,n)])],`Send these ${i.length} requests?`)},approveRepairRequest:i=>r(Ds("repair proposal",i,n),"Send this request?"),approveApplication:async(i,s)=>{for(let a of af(i,s))t.io.print(a);return t.io.confirm("Apply this patch?")}}}async function Sd(t,n,e,r,i){let s=new Set(r),a=await sp({run:{...e,logicalTests:e.logicalTests.filter(d=>s.has(d.logicalTestId))},workspaceRoot:n,repositoryRoot:await Os(n),captureId:`${i.purpose}-${e.runId.replace(/[^A-Za-z0-9]/g,"").slice(-16)||"latest"}`,env:t.env,probe:!1});if(a.kind!=="ready")return{kind:"unavailable",message:a.message};t.io.print(""),t.io.print(i.intro);for(let d of a.prepared.description)t.io.print(d);if(i.approvedBy!==void 0)t.io.print(`${i.question} yes (${i.approvedBy})`);else if(!await t.io.confirm(i.question))return{kind:"declined"};let o=await ap(a.prepared,t.env);return t.io.print(o.outcome.message),o.outcome.kind==="failed"?{kind:"unavailable",message:o.outcome.message}:{kind:"rerun",failedAgain:o.outcome.failedAgain??[]}}function ED(t){return t==="repair-failed"||t==="validation-unavailable"||t==="operation-failed"?U.failed:U.ok}function pn(t,n,e={}){t.io.print("");let r=mv("run"in n?n.run:void 0);r!==void 0&&n.record?.command!=="validate"&&t.io.print(r);let i=n.record?.clusters??[];if(i.length>1&&n.record?.command!=="validate")for(let d of fv(i,"run"in n?n.run:void 0))t.io.print(d);else if(n.record?.diagnosis!==void 0&&n.record.command!=="validate"){for(let d of of(n.record.diagnosis))t.io.print(d);t.io.print("")}t.io.print(`Result: ${n.outcome} (${n.reasonCode})`),t.io.print(n.message);let s=Pt(t.env),a=yv("run"in n?n.run:void 0,s);a!==void 0&&t.io.print(a);let o=hv(n.record,n.outcome,s,"run"in n?n.run:void 0,e);return o!==void 0&&t.io.print(o),n.recordPath!==void 0&&t.io.print(`Record: ${n.recordPath}`),ED(n.outcome)}async function fn(t,n){try{return await n()}catch(e){if(e instanceof yt)return t.io.error(e.message),[401,402,403,409].includes(e.status)?U.account:U.failed;throw e}}function Iv(t){return t.sleep??(n=>new Promise(e=>setTimeout(e,n)))}async function Av(t){return fn(t,async()=>{let n=new Tt(cn(t.env),void 0,t.fetch),e=await n.startDeviceLogin();t.io.print(`Open ${e.verificationUri} and enter the code: ${e.userCode}`);let r=Iv(t),i=Math.max(1,e.interval),s=Date.now()+e.expiresIn*1e3;for(;Date.now()<s;){await r(i*1e3);let a=await n.pollDeviceLogin(e.deviceCode);if(a.status==="complete")return await Zx(t.env,{token:a.token,login:a.login,apiUrl:n.baseUrl}),t.io.print(`Signed in as ${a.login}.`),U.ok;if(a.status==="slow_down"&&(i+=5),a.status==="expired"||a.status==="denied")return t.io.error(a.status==="denied"?"Sign-in was denied.":"The code expired."),U.account}return t.io.error("The code expired before sign-in finished."),U.account})}async function Tv(t){let n=(t.env.KWIKQA_TOKEN??"").trim()!=="",e=n?void 0:await ln(t.env);if(e!==void 0)try{await new Tt(cn(t.env,e.apiUrl),e.token,t.fetch).logout()}catch{t.io.error(`Could not reach the KwikQA service to revoke this token; revoke it at ${Zr}account/.`)}return await ev(t.env),t.io.print("Signed out."),n&&t.io.print("KWIKQA_TOKEN is still set in this environment; unset it to stop using it."),U.ok}function CD(t){let n=[...t.seats!==void 0&&t.seats>1?[`${t.seats} seats`]:[],...t.interval===void 0?[]:[t.interval==="year"?"billed yearly":"billed monthly"]];return`on the ${t.plan} plan${n.length===0?"":` (${n.join(", ")})`}`}async function Pv(t){return fn(t,async()=>{let n=await ln(t.env);if(n===void 0)return t.io.print(uf(t)),U.account;let r=await new Tt(cn(t.env,n.apiUrl),n.token,t.fetch).status(),i=(s,a)=>a===void 0?`${s} (unlimited)`:`${s} of ${a}`;return t.io.print(`Signed in as ${r.login} ${CD(r)}.`),r.team!==void 0&&(t.io.print(r.team.role==="member"?`Team: ${r.team.owner}'s team; usage below is the team's shared pool.`:`Team: yours, with ${r.team.members} member${r.team.members===1?"":"s"}; usage below is the shared pool.`),t.io.print(r.team.insights===!0?"Team insights: on. Test names and fix outcomes from your runs are shared with your team.":"Team insights: off.")),t.io.print(`Analyses this period: ${i(r.usage.analyses.used,r.usage.analyses.limit)}`),t.io.print(`Fixes this period: ${i(r.usage.repairs.used,r.usage.repairs.limit)}`),t.io.print(`Period ends: ${r.periodEnd.slice(0,10)}`),t.io.print(`Manage your account, team, and tokens: ${Zr}`),U.ok})}async function Sv(t){let n=await ln(t.env);if(n===void 0){t.io.error(uf(t));return}return new Tt(cn(t.env,n.apiUrl),n.token,t.fetch)}function ND(t){let n=t.perSeat?"/seat":"",e=t.monthlyUsd===0?"$0":`$${t.monthlyUsd}${n}/mo or $${t.annualUsd}${n}/yr`,r=t.analyses===void 0?"unlimited analyses and fixes":`${t.analyses} analyses and ${t.repairs} fixes a month${t.perSeat?" per seat, shared":""}`,i=[...t.hosted?[]:["your OpenRouter key"],...t.perSeat?[`${t.minSeats}+ seats`]:[]];return{price:e,limits:i.length===0?r:`${r} (${i.join(", ")})`}}async function Ev(t,n,e={annual:!1}){return fn(t,async()=>{let r=await ln(t.env),i=await new Tt(cn(t.env,r?.apiUrl),void 0,t.fetch).plans(),s=i.paidPlansOpen!==!1,o=i.plans.filter(m=>m.id!=="free").find(m=>m.id===n);if(o===void 0||!s){n!==void 0&&o===void 0&&t.io.error(`Unknown plan: ${n}`),t.io.print(`Plans (monthly, or yearly with ${12-i.annualMonthsCharged} months free):`);let m=Math.max(...i.plans.map(g=>g.id.length));for(let g of i.plans){let{price:y,limits:w}=ND(g);t.io.print(` ${g.id.padEnd(m)} ${y}: ${w}`)}if(s)t.io.print(`Run \`${Pt(t.env)} upgrade <plan> [--annual] [--seats <n>]\` to get a checkout link.`);else if(t.io.print("Paid plans are coming soon. Until they open, every account uses Free."),o!==void 0)return U.account;return n===void 0?U.ok:U.usage}let d;if(e.seats!==void 0&&(d=Number(e.seats),!(o.perSeat?Number.isInteger(d)&&d>=o.minSeats&&d<=i.maxSeats:d===1)))return t.io.error(o.perSeat?`${o.name} needs ${o.minSeats} to ${i.maxSeats} seats.`:`${o.name} is for one person; --seats applies to team plans.`),U.usage;let c=await Sv(t);if(c===void 0)return U.account;let l=await c.status();if(l.team?.role==="member")return t.io.print(`You're on ${l.team.owner}'s team, so ${l.team.owner} manages billing.`),U.ok;if(l.plan!=="free")return t.io.print(`You're on the ${l.plan} plan. Change plans, seats, or billing period in Billing, where you see the charge before you confirm:`),t.io.print(`${Zr}billing/`),U.ok;let u=e.annual?"year":"month",p=await c.checkout(o.id,{interval:u,...d===void 0?{}:{seats:d}}),f=o.perSeat?d??o.minSeats:1,h=(e.annual?o.annualUsd:o.monthlyUsd)*f;return t.io.print(`Open this link to subscribe to ${o.name}${o.perSeat?` with ${f} seats`:""} for $${h} a ${e.annual?"year":"month"}:`),t.io.print(p.url),U.ok})}async function Cv(t){return fn(t,async()=>{let n=await Sv(t);if(n===void 0)return U.account;try{let{url:e}=await n.billingPortal();return t.io.print("Open this link to update your payment method or download invoices:"),t.io.print(e),t.io.print(`To change or cancel your plan: ${Zr}billing/`),U.ok}catch(e){if(e instanceof yt&&e.code==="no-billing-account")return t.io.print("You don't have a paid subscription yet."),t.io.print(`Run \`${Pt(t.env)} upgrade <plan>\` to choose one.`),U.ok;if(e instanceof yt&&e.code==="team-member")return t.io.print(e.message),U.ok;throw e}})}async function Nv(t){let n=await Ut(t.cwd),e=He(n,"kwikqa.config.json");if(await ti(e))t.io.print("kwikqa.config.json already exists; review it to change what KwikQA may edit.");else{let p=Op({repositoryPaths:await Wp(n)});t.io.print("Proposed kwikqa.config.json (what KwikQA may edit when repairing tests):");for(let f of p.canonicalContents.trimEnd().split(`
234
+ `))t.io.print(` ${f}`);for(let f of[...p.reasons,...p.ambiguities])t.io.print(` - ${f}`);await t.io.confirm("Write kwikqa.config.json?")&&(await vv(e,p.canonicalContents,{flag:"wx"}),t.io.print("Wrote kwikqa.config.json. Commit it so the policy is reviewed like code."))}let r=He(n,".gitignore"),i=await ti(r)?await kd(r,"utf8"):"",s=p=>p.trim().replace(/^\//,"").replace(/\/$/,""),a=new Set(i.split(/\r?\n/).map(s)),o=[{entry:".kwikqa/",what:"local run records"},{entry:Ya,what:"the failure report"}].filter(p=>!a.has(s(p.entry))),d=o.map(p=>`${p.entry} (${p.what})`).join(" and ");o.length>0&&await t.io.confirm(`Add ${d} to .gitignore?`)&&await xD(r,`
235
235
  ${o.map(p=>p.entry).join(`
236
236
  `)}
237
- `);let c=new Set((await Qw(n)).map(p=>p.framework)),l=p=>c.size===0||c.has(p),u=Pt(t.env);return l("playwright")&&(t.io.print(""),t.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),t.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),t.io.print(' use: { trace: "retain-on-failure" },')),l("cypress")&&(t.io.print(""),t.io.print(`Cypress: with kwikqa installed (${sf(t.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),t.io.print("so every attempt and its code frame is kept:"),t.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),t.io.print(` Mochawesome and JUnit reports work too: ${u} analyze --report mochawesome-report`)),l("webdriverio")&&(t.io.print(""),t.io.print(`WebdriverIO: with kwikqa installed (${sf(t.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),t.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),t.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),t.io.print(` @wdio/json-reporter and JUnit reports work too: ${u} analyze --report <directory>`)),(c.has("cypress")||c.has("webdriverio"))&&(t.io.print(""),t.io.print(`Then \`${u} analyze --capture\` re-runs failing specs and records each failure's page.`)),U.ok}async function Ov(t,n){return fn(t,async()=>{let e=await Ut(t.cwd);if(n.output!==void 0&&n.html!==!0)return t.io.error("--output names where --html writes the report; add --html."),U.usage;let r=n.html===!0?await kr(e,n.output):void 0;if(r?.kind==="refused")return t.io.error(r.message),U.usage;let i=await js(t,e,n.report);if(n.capture===!0&&!t.io.interactive&&!n.yes)return t.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),U.usage;let s=n.local?void 0:await _s(t,"analysis");if(s!==void 0&&"exit"in s)return Ad(t,s);if(s!==void 0&&!t.io.interactive&&!n.yes)return t.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),U.usage;let a=n.capture===!0?await RD(t,e,i,{yes:n.yes,probe:n.probe!==!1,...n.framework===void 0?{}:{framework:n.framework}}):void 0,o=a?.reportPath??i,d=await er(e),c=await ld({reportPath:o,...n.framework===void 0?{}:{framework:n.framework},...a?.probePath===void 0?{}:{probePath:a.probePath},workspaceRoot:e,...d.kind==="read"?{gitRoot:d.status.gitRoot}:{},evidencePolicy:Td(s),includeChangeHistory:n.changes!==!1,...s===void 0?{}:{remote:s.diagnosis},interaction:Pd(t,s?.destination??"",n.yes)}),l=pn(t,c),u=r===void 0?l:await ND(t,e,r.path,c,l);return s!==void 0&&await tr(t.io,s.client,s.status,rf(c)),u})}async function CD(t,n,e,r){if(n)return{notDiagnosed:"--local analyzes without asking a model."};if(await ln(t.env)===void 0)return{notDiagnosed:r?`${e==="gitlab"?"the merge request comes from a fork, whose pipeline gets none of this project's variables":e==="azure"?"the pull request comes from a fork, and Azure Pipelines gives a fork's build no secrets unless the pipeline allows it":"the pull request comes from a fork, and GitHub gives its workflows no secrets"}, so there is no KWIKQA_TOKEN.`:`there is no KwikQA token. Set KWIKQA_TOKEN${e==="azure"?", mapped in the step's env,":e==="jenkins"?", bound with withCredentials,":""} to a CI token from ${Zr}account/ to diagnose failures.`};try{let i=await _s(t,"analysis");return"exit"in i?{notDiagnosed:i.messages.join(" ")}:{setup:i}}catch(i){if(i instanceof yt)return{notDiagnosed:i.message};throw i}}async function $v(t,n){return fn(t,async()=>{let e=await Ut(t.cwd),r=await kr(e,n.output);if(r.kind==="refused")return t.io.error(r.message),U.usage;let i=await bo(t.env),s=i===void 0?zs(t.env):void 0,a=i===void 0&&s===void 0?ko(t.env):void 0,o=i===void 0&&s===void 0&&a===void 0?Ro(t.env):void 0,d=i??s??a??o,c=await js(t,e,n.report),l=await CD(t,n.local,i!==void 0?"github":s!==void 0?"azure":a!==void 0?"gitlab":o!==void 0?"jenkins":void 0,d?.pullRequest?.fork===!0);l.notDiagnosed!==void 0&&t.io.print(`Not diagnosed: ${l.notDiagnosed} Analyzing locally.`);let u=await er(e),p=await ld({reportPath:c,...n.framework===void 0?{}:{framework:n.framework},workspaceRoot:e,...u.kind==="read"?{gitRoot:u.status.gitRoot}:{},evidencePolicy:Td(l.setup),includeChangeHistory:n.changes!==!1,...l.setup===void 0?{}:{remote:l.setup.diagnosis},interaction:Pd(t,l.setup?.destination??"",!0)}),f=await hd(e)===void 0?{}:{ciFix:"policy"},h=pn(t,p,{ci:!0,...f}),m=p.run===void 0||p.record===void 0?void 0:Dv(p.run,p.record,p),g=m===void 0?void 0:await hf(t,e,r.path,Ui(m));l.setup!==void 0&&await tr(t.io,l.setup.client,l.setup.status,rf(p));let y=Tu({model:m,message:p.message,...l.notDiagnosed===void 0?{}:{notDiagnosed:l.notDiagnosed},...g===void 0?{}:{reportFile:g.split(lf).join("/")},...d?.runUrl===void 0?{}:{runUrl:d.runUrl}}),w=m?.run.counts.find(R=>R.label==="Failed")?.value??0,x=m===void 0||w>0;i!==void 0?await Au(t.io,t.fetch,i,y,{failures:x}):s!==void 0?await Ld(t.io,t.fetch,s,y,{failures:x}):a!==void 0?await _u(t.io,t.fetch,a,y,{failures:x}):o!==void 0?await zu(t.io,t.fetch,o,y,{failures:x}):t.io.print("Not running in GitHub Actions, Azure Pipelines, GitLab CI/CD, or Jenkins, the CI systems supported so far: no summary or comment.");let v=Du({model:m,message:p.message,...l.notDiagnosed===void 0?{}:{notDiagnosed:l.notDiagnosed},...d===void 0?{}:{run:d}});return await Lu(t.io,t.fetch,Iv(t),t.env,v,{when:n.notify??"on-failure",failures:x}),h})}async function hf(t,n,e,r){let i=await Fl(e,r);if(i.kind==="refused"){t.io.error(i.message);return}let s=ei(n,e),a=s.startsWith("..")||Rd(s)?e:s;return t.io.print(`Report: ${a}`),a}async function ND(t,n,e,r,i){if(r.run===void 0||r.record===void 0)return t.io.error("No failure report: the test report could not be read."),i;let s=Ui(Dv(r.run,r.record,r));return await hf(t,n,e,s)===void 0?U.usage:i}function Dv(t,n,e){return wo({run:t,record:n,...e.detail===void 0?{}:{detail:e.detail},kwikqaVersion:Ls})}async function Lv(t,n){let e=await Ut(t.cwd),r=Pt(t.env);if(n.run!==void 0&&!/^run_[a-f0-9]{24}$/.test(n.run))return t.io.error("--run takes a run id as named under .kwikqa/runs/, such as run_0123456789abcdef01234567."),U.usage;let i=await kr(e,n.output);if(i.kind==="refused")return t.io.error(i.message),U.usage;let s=n.run??await Hp(e),a=s===void 0?[]:await Bp(e,s),o=h=>[...a].reverse().find(h),d=o(h=>h.command==="analyze")??o(h=>h.command==="fix"&&h.clusters!==void 0);if(d===void 0)return t.io.error(s===void 0?`No analysis is recorded here yet. Run \`${r} analyze\` first.`:`Run ${s} has no recorded analysis. Run \`${r} analyze\` first.`),U.usage;let c=o(h=>h.command!=="analyze"&&h.recordedAt>d.recordedAt),l=d.inputs??{report:ei(e,await js(t,e)).split(lf).join("/"),changeHistory:!0,currentDiff:!1,maxPacketBytes:Ms.maxPacketBytes},u=await er(e),p=await zp({reportPath:Id(e,l.report),...l.framework===void 0?{}:{framework:l.framework},workspaceRoot:e,...u.kind==="read"?{gitRoot:u.status.gitRoot}:{},evidencePolicy:{...Ms,maxPacketBytes:l.maxPacketBytes},includeChangeHistory:l.changeHistory,includeCurrentDiff:l.currentDiff,...l.probe===void 0?{}:{probePath:Id(e,l.probe)}},(d.clusters??[]).map(h=>h.clusterId));if(p.kind==="unreadable"||p.run.runId!==d.runId)return t.io.error(`The test report this analysis read (${l.report}) has changed or is gone, so its tests can't be shown. Run \`${r} analyze --html\` on the current report.`),U.failed;let f=Ui(wo({run:p.run,record:d,...p.detail===void 0?{}:{detail:p.detail},...c===void 0?{}:{repair:c},kwikqaVersion:Ls}));return await hf(t,e,i.path,f)===void 0?U.usage:U.ok}async function Mv(t,n){if(!t.io.interactive){let e=await bo(t.env);if(e!==void 0)return df(t,n,iv(t,e));let r=zs(t.env);if(r!==void 0)return df(t,n,sv(t,r));let i=ko(t.env);return i!==void 0?df(t,n,av(t,i)):(t.io.error(Ro(t.env)===void 0?"`kwikqa fix` needs a terminal: every request and patch is approved by a person. In GitHub Actions, Azure Pipelines, and GitLab CI/CD, a committed ci.fix policy approves it instead.":"`kwikqa fix` needs a terminal on Jenkins: a committed ci.fix policy approves it only in GitHub Actions, Azure Pipelines, and GitLab CI/CD, so far."),U.usage)}return fn(t,async()=>{let e=await Ut(t.cwd),r=await pf(e),i=n.retry?r.pendingRetry:void 0;if(n.retry&&i===void 0)return t.io.error("There is no failed validation to retry."),U.usage;let s=i===void 0?void 0:r.tickets?.[i.repairSessionId],a=await _s(t,"repair",s);if("exit"in a)return Ad(t,a);let o=i===void 0?await js(t,e,n.report):void 0,d=o===void 0?void 0:await kD(e,r,o);d!==void 0&&t.io.print(`Using the evidence captured by \`analyze --capture\`: ${ei(e,d.reportPath)}`);let c=await md({reportPath:i===void 0?d?.reportPath??o??He(e,"report.json"):He(e,i.reportPath),...n.framework===void 0?{}:{framework:n.framework},...d?.probePath===void 0?{}:{probePath:d.probePath},workspaceRoot:e,evidencePolicy:Td(a),includeChangeHistory:n.changes!==!1,remote:a.diagnosis,repairModel:a.repairModel,repairCaps:a.repairCaps,...a.repairSession===void 0?{}:{repairSession:a.repairSession},...n.group===void 0?{}:{group:n.group},interaction:{...Pd(t,a.destination,!1),confirmFailure:(m,g)=>Sd(t,e,m,g,{purpose:"confirm",intro:"Before asking for a repair, re-run the failing tests once: a test that passes now is flaky, and KwikQA does not patch it.",question:"Re-run them first?"})},reuseDiagnosis:i===void 0,proposeOnly:n.proposeOnly,...i===void 0?{}:{retryRepairSessionId:i.repairSessionId}}),l=c.record?.repair?.repairSessionId,u=a.ticket(),{pendingRetry:p,...f}=r;await ff(e,{...i===void 0?r:f,...l===void 0||u===void 0?{}:{tickets:{...r.tickets,[l]:u}}});let h=pn(t,c);return await tr(t.io,a.client,a.status,bd(c)),h})}var vd="the committed ci.fix policy",xd={ciFix:"running"};function OD(t,n,e,r){return{...Pd(t,n,vd),approveApplication:async(i,s)=>{for(let o of af(i,s,{validatedNow:!0}))t.io.print(o);let{approver:a}=i;return a.kind!=="ci-policy"?!1:(r(s),t.io.print(`Apply this patch? yes (${vd}, ${a.policyHash.slice(0,12)}, for run ${a.runId} attempt ${a.runAttempt}, on this runner's checkout)`),!0)},confirmFailure:(i,s)=>Sd(t,e,i,s,{purpose:"confirm",intro:"Before asking for a repair, re-run the failing tests once: a test that passes now is flaky, and KwikQA does not patch it.",question:"Re-run them first?",approvedBy:vd})}}async function $D(t,n){try{let e=ei(await Ut(t),await Ut(n));return e===""||!Rd(e)&&e!==".."&&!e.startsWith(`..${lf}`)}catch{return!1}}async function df(t,n,e){if(n.retry)return t.io.error("In CI, the ci.fix policy's `retry` decides whether a failed validation is retried; --retry is for a terminal."),U.usage;if(typeof e=="string")return t.io.error(e),U.usage;let{ci:r,checkout:i,host:s}=e;if(i.path===void 0||!await $D(i.path,t.cwd))return t.io.error(`\`kwikqa fix\` without a terminal patches only the runner's checkout, inside ${i.variable}.`),U.usage;if("reason"in s){let a=`No fix in CI: ${s.reason}.`;return s.misconfigured?(t.io.error(a),U.usage):(t.io.print(a),await s.note?.(),U.ok)}return fn(t,async()=>{let a=await Ut(t.cwd),o=await _s(t,"repair");if("exit"in o)return Ad(t,o);let d=await js(t,a,n.report),c,l=(g,y)=>md({reportPath:y.reportPath,...n.framework===void 0?{}:{framework:n.framework},workspaceRoot:a,evidencePolicy:Td(g),includeChangeHistory:n.changes!==!1,remote:g.diagnosis,repairModel:g.repairModel,repairCaps:g.repairCaps,...g.repairSession===void 0?{}:{repairSession:g.repairSession},...n.group===void 0?{}:{group:n.group},interaction:OD(t,g.destination,a,w=>{c=w}),reuseDiagnosis:y.retryRepairSessionId===void 0,proposeOnly:n.proposeOnly,...y.retryRepairSessionId===void 0?{}:{retryRepairSessionId:y.retryRepairSessionId},ci:r,fixInReview:w=>s.fixInReview(w)}),u=()=>yd({workspaceRoot:a,checkGroup:(g,y)=>Sd(t,a,g,y,{purpose:"group",intro:`The repair passed. Re-run the ${y.length===1?"other test":`${y.length} other tests`} with the same cause once, to see whether the patch fixed ${y.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?",approvedBy:vd})}),p=await l(o,{reportPath:d}),f=pn(t,p,xd);if(await tr(t.io,o.client,o.status,bd(p)),p.outcome!=="awaiting-validation")return f;let h=await u();f=pn(t,h,xd),await cf(t,h);let m=h.record?.repair;if(m?.retryAvailable===!0&&m.retryReportPath!==void 0){if((await hd(a))?.retry!==!0)return t.io.print("The ci.fix policy doesn't retry a failed validation, so the patch was rolled back and nothing else was sent."),f;let g=o.ticket(),y=await _s(t,"repair",g);if("exit"in y)return Ad(t,y);if(p=await l(y,{reportPath:He(a,m.retryReportPath),retryRepairSessionId:m.repairSessionId}),f=pn(t,p,xd),await tr(t.io,y.client,y.status,bd(p)),p.outcome!=="awaiting-validation")return f;h=await u(),f=pn(t,h,xd),await cf(t,h)}return h.outcome==="repaired"&&p.record!==void 0&&await s.publish({fix:p.record,...h.record===void 0?{}:{validation:h.record},...c===void 0?{}:{plan:c}},{root:a,gitRoot:await Os(a)}),f})}async function cf(t,n){let e=lv(n),r=e===void 0?void 0:await ln(t.env);if(r===void 0)return;let i=new Tt(cn(t.env,r.apiUrl),r.token,t.fetch),s;try{s=await i.status()}catch{return}await tr(t.io,i,s,e)}async function _v(t){let n=await Ut(t.cwd),e=await yd({workspaceRoot:n,checkGroup:(s,a)=>Sd(t,n,s,a,{purpose:"group",intro:`The repair passed. ${a.length} other test${a.length===1?"":"s"} failed with the same cause; re-run ${a.length===1?"it":"them"} once to see whether the patch fixed ${a.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?"})}),r=e.record?.repair;if(r?.retryAvailable===!0&&r.retryReportPath!==void 0){let s=await pf(n);await ff(n,{...s,pendingRetry:{repairSessionId:r.repairSessionId,reportPath:r.retryReportPath}})}let i=pn(t,e);return await cf(t,e),i}import{createInterface as DD}from"node:readline/promises";function jv(t){let n=e=>e.replace(/##vso\[/gi,"##vso [");return{interactive:t.interactive,print:(e="")=>t.print(n(e)),error:e=>t.error(n(e)),confirm:e=>t.confirm(n(e)),command:e=>t.print(e)}}function Fv(){return{interactive:process.stdin.isTTY===!0,print:(t="")=>{process.stdout.write(`${t}
237
+ `);let c=new Set((await Qw(n)).map(p=>p.framework)),l=p=>c.size===0||c.has(p),u=Pt(t.env);return l("playwright")&&(t.io.print(""),t.io.print("Playwright: add a JSON reporter to playwright.config so KwikQA can read your runs:"),t.io.print(' reporter: [["list"], ["json", { outputFile: "test-results/kwikqa-report.json" }]],'),t.io.print(' use: { trace: "retain-on-failure" },')),l("cypress")&&(t.io.print(""),t.io.print(`Cypress: with kwikqa installed (${sf(t.env,"kwikqa")}), set KwikQA's reporter in cypress.config`),t.io.print("so every attempt and its code frame is kept:"),t.io.print(' reporter: "node_modules/kwikqa/dist/cypress-reporter.cjs",'),t.io.print(` Mochawesome and JUnit reports work too: ${u} analyze --report mochawesome-report`)),l("webdriverio")&&(t.io.print(""),t.io.print(`WebdriverIO: with kwikqa installed (${sf(t.env,"kwikqa")}), add KwikQA's reporter in wdio.conf:`),t.io.print(' import KwikqaReporter from "kwikqa/wdio-reporter";'),t.io.print(' reporters: ["spec", [KwikqaReporter, {}]],'),t.io.print(` @wdio/json-reporter and JUnit reports work too: ${u} analyze --report <directory>`)),(c.has("cypress")||c.has("webdriverio"))&&(t.io.print(""),t.io.print(`Then \`${u} analyze --capture\` re-runs failing specs and records each failure's page.`)),U.ok}async function Ov(t,n){return fn(t,async()=>{let e=await Ut(t.cwd);if(n.output!==void 0&&n.html!==!0)return t.io.error("--output names where --html writes the report; add --html."),U.usage;let r=n.html===!0?await Rr(e,n.output):void 0;if(r?.kind==="refused")return t.io.error(r.message),U.usage;let i=await js(t,e,n.report);if(n.capture===!0&&!t.io.interactive&&!n.yes)return t.io.error("Capturing re-runs your failing tests: run in a terminal, or pass --yes."),U.usage;let s=n.local?void 0:await _s(t,"analysis");if(s!==void 0&&"exit"in s)return Ad(t,s);if(s!==void 0&&!t.io.interactive&&!n.yes)return t.io.error("Sending evidence needs approval: run in a terminal, or pass --yes, or use --local."),U.usage;let a=n.capture===!0?await AD(t,e,i,{yes:n.yes,probe:n.probe!==!1,...n.framework===void 0?{}:{framework:n.framework}}):void 0,o=a?.reportPath??i,d=await tr(e),c=await ld({reportPath:o,...n.framework===void 0?{}:{framework:n.framework},...a?.probePath===void 0?{}:{probePath:a.probePath},workspaceRoot:e,...d.kind==="read"?{gitRoot:d.status.gitRoot}:{},evidencePolicy:Td(s),includeChangeHistory:n.changes!==!1,...s===void 0?{}:{remote:s.diagnosis},interaction:Pd(t,s?.destination??"",n.yes)}),l=pn(t,c),u=r===void 0?l:await $D(t,e,r.path,c,l);return s!==void 0&&await nr(t.io,s.client,s.status,rf(c)),u})}async function OD(t,n,e,r){if(n)return{notDiagnosed:"--local analyzes without asking a model."};if(await ln(t.env)===void 0)return{notDiagnosed:r?`${e==="gitlab"?"the merge request comes from a fork, whose pipeline gets none of this project's variables":e==="azure"?"the pull request comes from a fork, and Azure Pipelines gives a fork's build no secrets unless the pipeline allows it":"the pull request comes from a fork, and GitHub gives its workflows no secrets"}, so there is no KWIKQA_TOKEN.`:`there is no KwikQA token. Set KWIKQA_TOKEN${e==="azure"?", mapped in the step's env,":e==="jenkins"?", bound with withCredentials,":""} to a CI token from ${Zr}account/ to diagnose failures.`};try{let i=await _s(t,"analysis");return"exit"in i?{notDiagnosed:i.messages.join(" ")}:{setup:i}}catch(i){if(i instanceof yt)return{notDiagnosed:i.message};throw i}}async function $v(t,n){return fn(t,async()=>{let e=await Ut(t.cwd),r=await Rr(e,n.output);if(r.kind==="refused")return t.io.error(r.message),U.usage;let i=await bo(t.env),s=i===void 0?zs(t.env):void 0,a=i===void 0&&s===void 0?ko(t.env):void 0,o=i===void 0&&s===void 0&&a===void 0?Ro(t.env):void 0,d=i??s??a??o,c=await js(t,e,n.report),l=await OD(t,n.local,i!==void 0?"github":s!==void 0?"azure":a!==void 0?"gitlab":o!==void 0?"jenkins":void 0,d?.pullRequest?.fork===!0);l.notDiagnosed!==void 0&&t.io.print(`Not diagnosed: ${l.notDiagnosed} Analyzing locally.`);let u=await tr(e),p=await ld({reportPath:c,...n.framework===void 0?{}:{framework:n.framework},workspaceRoot:e,...u.kind==="read"?{gitRoot:u.status.gitRoot}:{},evidencePolicy:Td(l.setup),includeChangeHistory:n.changes!==!1,...l.setup===void 0?{}:{remote:l.setup.diagnosis},interaction:Pd(t,l.setup?.destination??"",!0)}),f=await hd(e)===void 0?{}:{ciFix:"policy"},h=pn(t,p,{ci:!0,...f}),m=p.run===void 0||p.record===void 0?void 0:Dv(p.run,p.record,p),g=m===void 0?void 0:await hf(t,e,r.path,Ui(m));l.setup!==void 0&&await nr(t.io,l.setup.client,l.setup.status,rf(p));let y=Tu({model:m,message:p.message,...l.notDiagnosed===void 0?{}:{notDiagnosed:l.notDiagnosed},...g===void 0?{}:{reportFile:g.split(lf).join("/")},...d?.runUrl===void 0?{}:{runUrl:d.runUrl}}),w=m?.run.counts.find(R=>R.label==="Failed")?.value??0,x=m===void 0||w>0;i!==void 0?await Au(t.io,t.fetch,i,y,{failures:x}):s!==void 0?await Ld(t.io,t.fetch,s,y,{failures:x}):a!==void 0?await _u(t.io,t.fetch,a,y,{failures:x}):o!==void 0?await zu(t.io,t.fetch,o,y,{failures:x}):t.io.print("Not running in GitHub Actions, Azure Pipelines, GitLab CI/CD, or Jenkins, the CI systems supported so far: no summary or comment.");let v=Du({model:m,message:p.message,...l.notDiagnosed===void 0?{}:{notDiagnosed:l.notDiagnosed},...d===void 0?{}:{run:d}});return await Lu(t.io,t.fetch,Iv(t),t.env,v,{when:n.notify??"on-failure",failures:x}),h})}async function hf(t,n,e,r){let i=await Fl(e,r);if(i.kind==="refused"){t.io.error(i.message);return}let s=ei(n,e),a=s.startsWith("..")||Rd(s)?e:s;return t.io.print(`Report: ${a}`),a}async function $D(t,n,e,r,i){if(r.run===void 0||r.record===void 0)return t.io.error("No failure report: the test report could not be read."),i;let s=Ui(Dv(r.run,r.record,r));return await hf(t,n,e,s)===void 0?U.usage:i}function Dv(t,n,e){return wo({run:t,record:n,...e.detail===void 0?{}:{detail:e.detail},kwikqaVersion:Ls})}async function Lv(t,n){let e=await Ut(t.cwd),r=Pt(t.env);if(n.run!==void 0&&!/^run_[a-f0-9]{24}$/.test(n.run))return t.io.error("--run takes a run id as named under .kwikqa/runs/, such as run_0123456789abcdef01234567."),U.usage;let i=await Rr(e,n.output);if(i.kind==="refused")return t.io.error(i.message),U.usage;let s=n.run??await Hp(e),a=s===void 0?[]:await Bp(e,s),o=h=>[...a].reverse().find(h),d=o(h=>h.command==="analyze")??o(h=>h.command==="fix"&&h.clusters!==void 0);if(d===void 0)return t.io.error(s===void 0?`No analysis is recorded here yet. Run \`${r} analyze\` first.`:`Run ${s} has no recorded analysis. Run \`${r} analyze\` first.`),U.usage;let c=o(h=>h.command!=="analyze"&&h.recordedAt>d.recordedAt),l=d.inputs??{report:ei(e,await js(t,e)).split(lf).join("/"),changeHistory:!0,currentDiff:!1,maxPacketBytes:Ms.maxPacketBytes},u=await tr(e),p=await zp({reportPath:Id(e,l.report),...l.framework===void 0?{}:{framework:l.framework},workspaceRoot:e,...u.kind==="read"?{gitRoot:u.status.gitRoot}:{},evidencePolicy:{...Ms,maxPacketBytes:l.maxPacketBytes},includeChangeHistory:l.changeHistory,includeCurrentDiff:l.currentDiff,...l.probe===void 0?{}:{probePath:Id(e,l.probe)}},(d.clusters??[]).map(h=>h.clusterId));if(p.kind==="unreadable"||p.run.runId!==d.runId)return t.io.error(`The test report this analysis read (${l.report}) has changed or is gone, so its tests can't be shown. Run \`${r} analyze --html\` on the current report.`),U.failed;let f=Ui(wo({run:p.run,record:d,...p.detail===void 0?{}:{detail:p.detail},...c===void 0?{}:{repair:c},kwikqaVersion:Ls}));return await hf(t,e,i.path,f)===void 0?U.usage:U.ok}async function Mv(t,n){if(!t.io.interactive){let e=await bo(t.env);if(e!==void 0)return df(t,n,iv(t,e));let r=zs(t.env);if(r!==void 0)return df(t,n,sv(t,r));let i=ko(t.env);return i!==void 0?df(t,n,av(t,i)):(t.io.error(Ro(t.env)===void 0?"`kwikqa fix` needs a terminal: every request and patch is approved by a person. In GitHub Actions, Azure Pipelines, and GitLab CI/CD, a committed ci.fix policy approves it instead.":"`kwikqa fix` needs a terminal on Jenkins: a committed ci.fix policy approves it only in GitHub Actions, Azure Pipelines, and GitLab CI/CD, so far."),U.usage)}return fn(t,async()=>{let e=await Ut(t.cwd),r=await pf(e),i=n.retry?r.pendingRetry:void 0;if(n.retry&&i===void 0)return t.io.error("There is no failed validation to retry."),U.usage;let s=i===void 0?void 0:r.tickets?.[i.repairSessionId],a=await _s(t,"repair",s);if("exit"in a)return Ad(t,a);let o=i===void 0?await js(t,e,n.report):void 0,d=o===void 0?void 0:await ID(e,r,o);d!==void 0&&t.io.print(`Using the evidence captured by \`analyze --capture\`: ${ei(e,d.reportPath)}`);let c=await md({reportPath:i===void 0?d?.reportPath??o??He(e,"report.json"):He(e,i.reportPath),...n.framework===void 0?{}:{framework:n.framework},...d?.probePath===void 0?{}:{probePath:d.probePath},workspaceRoot:e,evidencePolicy:Td(a),includeChangeHistory:n.changes!==!1,remote:a.diagnosis,repairModel:a.repairModel,repairCaps:a.repairCaps,...a.repairSession===void 0?{}:{repairSession:a.repairSession},...n.group===void 0?{}:{group:n.group},interaction:{...Pd(t,a.destination,!1),confirmFailure:(m,g)=>Sd(t,e,m,g,{purpose:"confirm",intro:"Before asking for a repair, re-run the failing tests once: a test that passes now is flaky, and KwikQA does not patch it.",question:"Re-run them first?"})},reuseDiagnosis:i===void 0,proposeOnly:n.proposeOnly,...i===void 0?{}:{retryRepairSessionId:i.repairSessionId}}),l=c.record?.repair?.repairSessionId,u=a.ticket(),{pendingRetry:p,...f}=r;await ff(e,{...i===void 0?r:f,...l===void 0||u===void 0?{}:{tickets:{...r.tickets,[l]:u}}});let h=pn(t,c);return await nr(t.io,a.client,a.status,bd(c)),h})}var vd="the committed ci.fix policy",xd={ciFix:"running"};function DD(t,n,e,r){return{...Pd(t,n,vd),approveApplication:async(i,s)=>{for(let o of af(i,s,{validatedNow:!0}))t.io.print(o);let{approver:a}=i;return a.kind!=="ci-policy"?!1:(r(s),t.io.print(`Apply this patch? yes (${vd}, ${a.policyHash.slice(0,12)}, for run ${a.runId} attempt ${a.runAttempt}, on this runner's checkout)`),!0)},confirmFailure:(i,s)=>Sd(t,e,i,s,{purpose:"confirm",intro:"Before asking for a repair, re-run the failing tests once: a test that passes now is flaky, and KwikQA does not patch it.",question:"Re-run them first?",approvedBy:vd})}}async function LD(t,n){try{let e=ei(await Ut(t),await Ut(n));return e===""||!Rd(e)&&e!==".."&&!e.startsWith(`..${lf}`)}catch{return!1}}async function df(t,n,e){if(n.retry)return t.io.error("In CI, the ci.fix policy's `retry` decides whether a failed validation is retried; --retry is for a terminal."),U.usage;if(typeof e=="string")return t.io.error(e),U.usage;let{ci:r,checkout:i,host:s}=e;if(i.path===void 0||!await LD(i.path,t.cwd))return t.io.error(`\`kwikqa fix\` without a terminal patches only the runner's checkout, inside ${i.variable}.`),U.usage;if("reason"in s){let a=`No fix in CI: ${s.reason}.`;return s.misconfigured?(t.io.error(a),U.usage):(t.io.print(a),await s.note?.(),U.ok)}return fn(t,async()=>{let a=await Ut(t.cwd),o=await _s(t,"repair");if("exit"in o)return Ad(t,o);let d=await js(t,a,n.report),c,l=(g,y)=>md({reportPath:y.reportPath,...n.framework===void 0?{}:{framework:n.framework},workspaceRoot:a,evidencePolicy:Td(g),includeChangeHistory:n.changes!==!1,remote:g.diagnosis,repairModel:g.repairModel,repairCaps:g.repairCaps,...g.repairSession===void 0?{}:{repairSession:g.repairSession},...n.group===void 0?{}:{group:n.group},interaction:DD(t,g.destination,a,w=>{c=w}),reuseDiagnosis:y.retryRepairSessionId===void 0,proposeOnly:n.proposeOnly,...y.retryRepairSessionId===void 0?{}:{retryRepairSessionId:y.retryRepairSessionId},ci:r,fixInReview:w=>s.fixInReview(w)}),u=()=>yd({workspaceRoot:a,checkGroup:(g,y)=>Sd(t,a,g,y,{purpose:"group",intro:`The repair passed. Re-run the ${y.length===1?"other test":`${y.length} other tests`} with the same cause once, to see whether the patch fixed ${y.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?",approvedBy:vd})}),p=await l(o,{reportPath:d}),f=pn(t,p,xd);if(await nr(t.io,o.client,o.status,bd(p)),p.outcome!=="awaiting-validation")return f;let h=await u();f=pn(t,h,xd),await cf(t,h);let m=h.record?.repair;if(m?.retryAvailable===!0&&m.retryReportPath!==void 0){if((await hd(a))?.retry!==!0)return t.io.print("The ci.fix policy doesn't retry a failed validation, so the patch was rolled back and nothing else was sent."),f;let g=o.ticket(),y=await _s(t,"repair",g);if("exit"in y)return Ad(t,y);if(p=await l(y,{reportPath:He(a,m.retryReportPath),retryRepairSessionId:m.repairSessionId}),f=pn(t,p,xd),await nr(t.io,y.client,y.status,bd(p)),p.outcome!=="awaiting-validation")return f;h=await u(),f=pn(t,h,xd),await cf(t,h)}return h.outcome==="repaired"&&p.record!==void 0&&await s.publish({fix:p.record,...h.record===void 0?{}:{validation:h.record},...c===void 0?{}:{plan:c}},{root:a,gitRoot:await Os(a)}),f})}async function cf(t,n){let e=lv(n),r=e===void 0?void 0:await ln(t.env);if(r===void 0)return;let i=new Tt(cn(t.env,r.apiUrl),r.token,t.fetch),s;try{s=await i.status()}catch{return}await nr(t.io,i,s,e)}async function _v(t){let n=await Ut(t.cwd),e=await yd({workspaceRoot:n,checkGroup:(s,a)=>Sd(t,n,s,a,{purpose:"group",intro:`The repair passed. ${a.length} other test${a.length===1?"":"s"} failed with the same cause; re-run ${a.length===1?"it":"them"} once to see whether the patch fixed ${a.length===1?"it":"them"} too. The patch stays either way.`,question:"Re-run them now?"})}),r=e.record?.repair;if(r?.retryAvailable===!0&&r.retryReportPath!==void 0){let s=await pf(n);await ff(n,{...s,pendingRetry:{repairSessionId:r.repairSessionId,reportPath:r.retryReportPath}})}let i=pn(t,e);return await cf(t,e),i}import{createInterface as MD}from"node:readline/promises";function jv(t){let n=e=>e.replace(/##vso\[/gi,"##vso [");return{interactive:t.interactive,print:(e="")=>t.print(n(e)),error:e=>t.error(n(e)),confirm:e=>t.confirm(n(e)),command:e=>t.print(e)}}function Fv(){return{interactive:process.stdin.isTTY===!0,print:(t="")=>{process.stdout.write(`${t}
238
238
  `)},error:t=>{process.stderr.write(`${t}
239
- `)},confirm:async t=>{if(process.stdin.isTTY!==!0)return!1;let n=DD({input:process.stdin,output:process.stdout});try{let e=await n.question(`${t} [y/N] `);return/^y(?:es)?$/i.test(e.trim())}finally{n.close()}}}}var MD=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
239
+ `)},confirm:async t=>{if(process.stdin.isTTY!==!0)return!1;let n=MD({input:process.stdin,output:process.stdout});try{let e=await n.question(`${t} [y/N] `);return/^y(?:es)?$/i.test(e.trim())}finally{n.close()}}}}var jD=`KwikQA turns failed Playwright, Cypress, and WebdriverIO runs into evidence-backed diagnoses and safe, validated test repairs.
240
240
 
241
241
  Usage:
242
242
  npx kwikqa init Create kwikqa.config.json and set up your reporter
@@ -270,8 +270,8 @@ Usage:
270
270
  npx kwikqa logout Sign out and revoke this machine's token
271
271
 
272
272
  Docs: https://kwikqa.com/docs/
273
- Dashboard: https://kwikqa.com/dashboard/`;function Bv(t){let n=Pt(t),e=" ".repeat(n.length-10);return MD.split(`
273
+ Dashboard: https://kwikqa.com/dashboard/`;function Bv(t){let n=Pt(t),e=" ".repeat(n.length-10);return jD.split(`
274
274
  `).map(r=>r.startsWith(" npx kwikqa ")?r.replace("npx kwikqa",n):/^ +\[/.test(r)?`${e}${r}`:r).join(`
275
- `)}async function _D(t,n){let e=n.env.TF_BUILD==="True"?{...n,env:$d(n.env),io:jv(n.io)}:n,[r,...i]=t,s;try{s=LD({args:[...i],allowPositionals:!0,strict:!0,options:{report:{type:"string"},framework:{type:"string"},local:{type:"boolean",default:!1},yes:{type:"boolean",default:!1},capture:{type:"boolean",default:!1},"no-probe":{type:"boolean",default:!1},"no-changes":{type:"boolean",default:!1},group:{type:"string"},html:{type:"boolean",default:!1},output:{type:"string"},notify:{type:"string"},run:{type:"string"},retry:{type:"boolean",default:!1},"propose-only":{type:"boolean",default:!1},annual:{type:"boolean",default:!1},seats:{type:"string"},help:{type:"boolean",short:"h",default:!1}}})}catch(l){return e.io.error(l.message),U.usage}let a=s.values;if(a.help||r===void 0||r==="help"||r==="--help")return e.io.print(Bv(e.env)),U.ok;if(a.framework!==void 0&&!kt.includes(a.framework))return e.io.error(`--framework must be one of: ${kt.join(", ")}`),U.usage;let o=a.framework;if(a.notify!==void 0&&!vo.includes(a.notify))return e.io.error(`--notify must be one of: ${vo.join(", ")}`),U.usage;let d=a.notify,c=a.group===void 0?void 0:Number(a.group);if(c!==void 0&&!(Number.isInteger(c)&&c>=1))return e.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),U.usage;switch(r){case"--version":case"version":return e.io.print(Ls),U.ok;case"init":return Nv(e);case"login":return Av(e);case"logout":return Tv(e);case"status":return Pv(e);case"upgrade":return Ev(e,s.positionals[0],{annual:a.annual,...a.seats===void 0?{}:{seats:a.seats}});case"billing":return Cv(e);case"analyze":return Ov(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},local:a.local,yes:a.yes,capture:a.capture,probe:!a["no-probe"],changes:!a["no-changes"],html:a.html,...a.output===void 0?{}:{output:a.output}});case"ci":return $v(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},local:a.local,changes:!a["no-changes"],...a.output===void 0?{}:{output:a.output},...d===void 0?{}:{notify:d}});case"report":return Lv(e,{...a.run===void 0?{}:{run:a.run},...a.output===void 0?{}:{output:a.output}});case"fix":return Mv(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},retry:a.retry,proposeOnly:a["propose-only"],changes:!a["no-changes"],...c===void 0?{}:{group:c}});case"validate":return _v(e);default:return e.io.error(`Unknown command: ${r}
275
+ `)}async function FD(t,n){let e=n.env.TF_BUILD==="True"?{...n,env:$d(n.env),io:jv(n.io)}:n,[r,...i]=t,s;try{s=_D({args:[...i],allowPositionals:!0,strict:!0,options:{report:{type:"string"},framework:{type:"string"},local:{type:"boolean",default:!1},yes:{type:"boolean",default:!1},capture:{type:"boolean",default:!1},"no-probe":{type:"boolean",default:!1},"no-changes":{type:"boolean",default:!1},group:{type:"string"},html:{type:"boolean",default:!1},output:{type:"string"},notify:{type:"string"},run:{type:"string"},retry:{type:"boolean",default:!1},"propose-only":{type:"boolean",default:!1},annual:{type:"boolean",default:!1},seats:{type:"string"},help:{type:"boolean",short:"h",default:!1}}})}catch(l){return e.io.error(l.message),U.usage}let a=s.values;if(a.help||r===void 0||r==="help"||r==="--help")return e.io.print(Bv(e.env)),U.ok;if(a.framework!==void 0&&!kt.includes(a.framework))return e.io.error(`--framework must be one of: ${kt.join(", ")}`),U.usage;let o=a.framework;if(a.notify!==void 0&&!vo.includes(a.notify))return e.io.error(`--notify must be one of: ${vo.join(", ")}`),U.usage;let d=a.notify,c=a.group===void 0?void 0:Number(a.group);if(c!==void 0&&!(Number.isInteger(c)&&c>=1))return e.io.error("--group takes a failure group's number as analyze printed it: 1, 2, ..."),U.usage;switch(r){case"--version":case"version":return e.io.print(Ls),U.ok;case"init":return Nv(e);case"login":return Av(e);case"logout":return Tv(e);case"status":return Pv(e);case"upgrade":return Ev(e,s.positionals[0],{annual:a.annual,...a.seats===void 0?{}:{seats:a.seats}});case"billing":return Cv(e);case"analyze":return Ov(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},local:a.local,yes:a.yes,capture:a.capture,probe:!a["no-probe"],changes:!a["no-changes"],html:a.html,...a.output===void 0?{}:{output:a.output}});case"ci":return $v(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},local:a.local,changes:!a["no-changes"],...a.output===void 0?{}:{output:a.output},...d===void 0?{}:{notify:d}});case"report":return Lv(e,{...a.run===void 0?{}:{run:a.run},...a.output===void 0?{}:{output:a.output}});case"fix":return Mv(e,{...a.report===void 0?{}:{report:a.report},...o===void 0?{}:{framework:o},retry:a.retry,proposeOnly:a["propose-only"],changes:!a["no-changes"],...c===void 0?{}:{group:c}});case"validate":return _v(e);default:return e.io.error(`Unknown command: ${r}
276
276
 
277
- ${Bv(e.env)}`),U.usage}}async function Hv(){let t=await _D(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:Fv(),fetch});process.exitCode=t}await Hv();
277
+ ${Bv(e.env)}`),U.usage}}async function Hv(){let t=await FD(process.argv.slice(2),{cwd:process.cwd(),env:process.env,io:Fv(),fetch});process.exitCode=t}await Hv();