momentic 3.16.2 → 3.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8c39e463-cfe2-5529-b4fd-e08b9a5ce37b")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="86404b74-7b88-53d0-b555-5f571622f70d")}catch(e){}}();
4
4
  import * as Oo from 'fs';
5
5
  import Oo__default, { statSync, mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, renameSync, readdir, readdirSync, createReadStream, rmSync } from 'fs';
6
6
  import * as O from 'zod';
@@ -169,7 +169,7 @@ ${this.decisions.map(t=>t.toString()).join(`
169
169
  `).map((o,r)=>r>0?`${n}${o}`:o).join(`
170
170
  `)}logWithLevelHelper(t,n,...o){if(t<this.minLogLevel)return;let r=this.forcedStream??(t>=40?"stderr":"stdout"),i=(...d)=>r==="stderr"?console.error(...d):console.log(...d),s;Array.isArray(o[0])?(s=o[0],o=o.slice(1)):typeof o[0]=="object"&&!(o[0]instanceof Error)&&Object.entries(o[0]).length&&(s={...o[0],...this.logBindings},o=o.slice(1));let a=$a.level===0,l=a&&t===50?"Error:":a&&t===40?"Warning:":"",c=[];if(l&&c.push(l),c.push(...o),i(n(...c)),s&&!Array.isArray(s)){let d=Object.entries(s);for(let[u,p]of d){let m=p;if(p instanceof Error){m=p.message,i(n(` ${u}:`,m)),i(n(" stack:",p.stack));let g=Object.entries(p).filter(([f])=>f!=="message"&&f!=="stack");for(let[f,y]of g){if(y instanceof Error){i(n(` ${u}.${f}:`,y.message)),y.stack&&i(n(` ${u}.${f}.stack:`,y.stack));continue}if(typeof y=="object"&&y!==null){let S=this.indentMultiline(Va(y,void 0,2)," ");i(n(` ${u}.${f}:`,S));continue}i(n(` ${u}.${f}:`,y));}}else typeof p=="object"?(m=Va(p,void 0,2),m=this.indentMultiline(m),i(n(` ${u}:`,m))):i(n(` ${u}:`,m));}}else if(s)for(let d of s){let u=d;typeof d=="object"&&(u=Va(d,void 0,2),u=u.split(`
171
171
  `).map((p,m)=>m>0?` ${p}`:p).join(`
172
- `)),i(" ",n(u));}}setMinLevel(t){typeof t=="string"?this.minLogLevel=_S[t]:this.minLogLevel=t;}setOutputStream(t){this.forcedStream=t;}log(...t){this.logWithLevel(30,$a.reset,...t);}info(...t){this.logWithLevel(30,$a.white,...t);}debug(...t){this.logWithLevel(20,$a.dim,...t);}warn(...t){this.logWithLevel(40,$a.yellow,...t);}error(...t){this.logWithLevel(50,$a.red,...t);}success(...t){this.logWithLevel(30,$a.green,...t);}dimmed(...t){this.logWithLevel(30,$a.dim,...t);}underline(...t){this.logWithLevel(30,$a.underline,...t);}bold(...t){this.logWithLevel(30,$a.bold,...t);}grey(...t){this.logWithLevel(30,$a.grey,...t);}child(t){let n=new e(this.minLogLevel,{...this.logBindings,...t});return n.forcedStream=this.forcedStream,n}async flush(){}bindings(){return this.logBindings}},R=tM._internalSingleton(),Dr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Dr,flush:async()=>{},bindings:()=>({})},gC={},oM=({logger:e,logKey:t,maxCount:n,intervalMs:o},r,i,...s)=>{let a=gC[t];a?clearTimeout(a.timer):(a={count:0,totalCount:0},gC[t]=a),a.totalCount++,a.count<n&&(a.count++,e.debug(r,i,...s)),a.timer=setTimeout(()=>{let l=gC[t];l?.totalCount!==l?.count&&e.debug({logKey:t,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${t}`),delete gC[t];},o);};var pV=1e4,mV=1,eg=Ga.extend({browserType:z$1.enum(jl).optional(),slowMoMs:z$1.number().optional().refine(e=>e===void 0||e<=pV&&e>=-1,{message:`Slow motion must be between 0 and ${pV} milliseconds`}),basicAuthorization:z$1.object({username:z$1.string().optional(),password:z$1.string().optional()}).optional(),geolocation:z$1.object({latitude:z$1.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:z$1.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:z$1.boolean().optional(),locale:z$1.string().optional(),timezone:z$1.enum(oC).optional(),colorScheme:z$1.enum(["light","dark"]).optional()}),hV=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],rM=z$1.object({useMemory:z$1.boolean().optional(),failureRecovery:z$1.boolean().optional().describe("undefined means inherit org settings")}),iM=rM.extend({disableAICaching:z$1.boolean().optional(),failureRecoveryInstructions:z$1.string().optional()}),tfe=z$1.object({viewport:Jc.optional()}),Cs=tfe.extend(iM.shape).extend(eg.shape),fC=z$1.object({cron:z$1.string().refine(e=>isValidCron(e),{error:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:z$1.boolean().default(false),env:z$1.string().optional(),timeZone:z$1.string().default("America/Los_Angeles"),jobKey:z$1.string().optional()}),yC=z$1.object({onSuccess:z$1.boolean().default(false),failureMessage:z$1.string().optional(),onFailure:z$1.boolean().default(true),successMessage:z$1.string().optional()}),nfe=z$1.object({name:z$1.string(),required:z$1.boolean().optional(),defaultValue:z$1.string().describe("this is not optional because we need a value when the editor is first loaded")}),gV=nfe.array(),ofe=z$1.object({name:z$1.string(),value:z$1.string()}),SC=ofe.array(),fV=z$1.object({name:z$1.string(),default:z$1.boolean().optional(),fixtures:V$.array().optional()});var sa=rM.extend({agentConfig:z$1.record(z$1.string(),z$1.string()).optional(),aiFailureAnalysis:z$1.boolean().optional(),classification:XG.optional(),triage:JG.optional(),healing:EE.optional(),explore:vE.optional(),select:eV.optional()}),rfe=z$1.object({cliOnly:z$1.boolean().optional(),neverShowUsageBanner:z$1.boolean().optional(),hideInternalTraceInfo:z$1.boolean().optional(),bypassUsageLimits:z$1.boolean().optional()}),PS=z$1.object({fakerConstantSeed:z$1.boolean().optional(),isolateCachesByEnvironment:z$1.boolean().optional()}),ife=z$1.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),sfe=z$1.enum(["ios","android","web"]),afe=z$1.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),lfe=z$1.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","other"]),cfe=z$1.object({helpIntents:z$1.array(ife).optional(),helpIntentOtherText:z$1.string().optional(),deviceTypeIntent:sfe.optional(),currentTestingTool:afe.optional(),heardAboutSource:lfe.optional()}),dfe=z$1.object({discovery:cfe.optional(),needsToCompleteOnboarding:z$1.boolean().optional(),wizardCompletedAt:z$1.iso.datetime().optional()}),tg=z$1.object({ai:sa.optional(),githubAppInstallationId:z$1.number().nullish(),githubAppSummaryMessageEnabled:z$1.boolean().nullish(),githubReleaseAppInstallationId:z$1.number().nullish(),gitlabAppAccessToken:z$1.string().nullish(),gitlabAppBaseUrl:z$1.string().nullish(),browser:$O.optional(),internal:rfe.optional(),advanced:PS.optional(),onboarding:dfe.optional()});function yV(e){try{return tg.parse(e)}catch{return R.warn("Cloud settings contain values this version of the CLI does not support. Please upgrade. Falling back to defaults."),tg.parse({})}}z$1.object({globalOverrides:z$1.record(z$1.string(),z$1.string()).optional(),agentConfig:z$1.record(z$1.string(),z$1.string()).optional()});z$1.record(z$1.string(),z$1.string()).nullish();var Vl=(n=>(n.CANNOT_FIX_TEST="CANNOT_FIX_TEST",n.FIXED="FIXED",n))(Vl||{}),SV=z$1.object({index:z$1.int().nonnegative(),section:kO,step:Nt}),ufe=z$1.object({additions:SV.array(),deletions:SV.array()}),OS=z$1.object({subAgentStatus:z$1.enum(Vl).default("CANNOT_FIX_TEST"),rootCause:z$1.string(),solution:z$1.string(),verificationNotes:z$1.string().optional().default(""),diffs:ufe.optional(),pullRequestUrl:z$1.string().optional(),branchUrl:z$1.string().optional()}),bV=OS.optional().catch(void 0),TV=z$1.object({subAgentStatus:z$1.literal("FIXED").default("FIXED"),rootCause:z$1.string(),solution:z$1.string(),verificationNotes:z$1.string().optional().default(""),gitPatch:z$1.string().min(1)});var vs={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ht=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(ht||{});var MS=(r=>(r.NOT_ATTEMPTED="NOT_ATTEMPTED",r.PERM_HEAL_SUCCEEDED="PERM_HEAL_SUCCEEDED",r.PERM_HEAL_FAILED="PERM_HEAL_FAILED",r.PERM_HEAL_ON_SUCCESS_FAILED="PERM_HEAL_ON_SUCCESS_FAILED",r))(MS||{});var NS=z$1.enum(MS).default("NOT_ATTEMPTED"),bC=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(bC||{});var pfe=z$1.object({attempts:z$1.int().nonnegative()}),uo=z$1.string().pipe(z$1.coerce.date()).or(z$1.date()),Qi=z$1.object({id:z$1.string(),runKey:z$1.string(),organizationId:z$1.string(),executionType:mu.optional().default("WEB"),createdAt:uo,createdBy:z$1.string(),flake:z$1.boolean().nullish(),scheduledAt:uo.or(z$1.null()),startedAt:uo.or(z$1.null()),updatedAt:uo.nullish(),finishedAt:uo.or(z$1.null()),resolvedBaseUrl:z$1.string().nullish(),environmentName:z$1.string().nullish(),gitBranchName:z$1.string().nullish(),gitMainBranch:z$1.string().nullish(),githubRepository:z$1.string().nullish(),gitlabProjectPath:z$1.string().nullish(),labels:z$1.array(z$1.string()).optional(),gitOriginUrl:z$1.string().nullish(),gitCommitSha:z$1.string().nullish(),gitCommitShaShort:z$1.string().nullish(),gitCommitAuthorName:z$1.string().nullish(),gitCommitTimestamp:uo.nullish(),gitCommitMessage:z$1.string().nullish(),schemaVersion:z$1.string().nullish(),cliVersion:z$1.string().nullish(),section:z$1.enum(bC).nullish(),status:z$1.enum(ht),healStatus:NS,healDetails:bV.nullish(),trigger:z$1.enum(vs),attempts:z$1.number(),runAttempts:z$1.array(z$1.object({id:z$1.string(),status:z$1.enum(ht),startedAt:uo.or(z$1.null()),finishedAt:uo.or(z$1.null())})).optional(),videos:z$1.array(z$1.string()).optional(),failureReason:z$1.string().nullish(),failureDetails:Zj.nullish(),failureRecoveryDetails:pfe.nullish(),pipelineId:z$1.string().nullish(),resolvedInputs:z$1.record(z$1.string(),z$1.string()).nullish(),quarantined:z$1.boolean().nullish().default(false),quarantinedReason:z$1.string().nullish(),localTestId:z$1.string().nullish(),testId:z$1.string().nullish(),testName:z$1.string().nullish(),description:z$1.string().nullish(),directory:z$1.string().nullish(),test:z$1.object({name:z$1.string(),id:z$1.string()}).nullish().default(null),suiteId:z$1.string().nullish(),aiSettings:sa.nullish(),stepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),beforeStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),afterStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish()}),mfe={id:true,status:true,healStatus:true,healDetails:true,testName:true,localTestId:true,testId:true,test:{select:{name:true,id:true}},finishedAt:true,failureReason:true,failureDetails:true},TC=Qi.pick({...mfe,test:true}),AV=Qi.omit({failureReason:true,failureDetails:true,test:true}),sM=Qi.extend({stepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),beforeStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),afterStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),resolvedInputs:z$1.record(z$1.string(),z$1.string()).nullish(),test:z$1.object({name:z$1.string(),id:z$1.string(),description:z$1.string().nullish(),baseUrl:z$1.string().nullish(),advanced:Cs.nullish()}).nullish()}).extend(KO.shape),EV=e=>e.includes("PASSED")&&e.includes("FAILED");var hfe=z$1.object({category:z$1.string(),reasoning:z$1.string(),citations:z$1.array(No).optional()}),gfe=z$1.object({testInputs:z$1.record(z$1.string(),z$1.string()).optional(),envName:z$1.string().optional(),urlOverride:z$1.string().optional()}),ffe=z$1.object({reason:z$1.string().optional(),message:z$1.string().optional()}),yfe=z$1.object({runId:z$1.string().optional(),testId:z$1.string(),testName:z$1.string(),filePath:z$1.string(),labels:z$1.array(z$1.string()).optional(),status:z$1.enum(ht),startedAt:z$1.string(),finishedAt:z$1.string(),durationMs:z$1.number(),attempts:z$1.number(),quarantined:z$1.boolean(),recovered:z$1.boolean(),parameters:gfe.optional(),failure:ffe.nullable(),classification:hfe.nullable()}),Sfe=z$1.object({testId:z$1.string(),testName:z$1.string(),filePath:z$1.string(),labels:z$1.array(z$1.string()).optional(),quarantined:z$1.boolean()}),bfe=z$1.object({total:z$1.number(),executed:z$1.number(),skipped:z$1.number(),passed:z$1.number(),failed:z$1.number(),cancelled:z$1.number(),quarantined:z$1.number(),recovered:z$1.number()}),CV=z$1.object({version:z$1.literal(1),runGroup:z$1.object({startedAt:z$1.string(),finishedAt:z$1.string(),durationMs:z$1.number()}),summary:bfe,runs:z$1.array(yfe),skipped:z$1.array(Sfe)});var vV=z$1.enum(["error","warning","passing"]);var RV=z$1.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]);var wV=z$1.object({kind:RV,detail:z$1.string().min(1).max(280)}),zp=z$1.object({riskLevel:z$1.string(),headline:z$1.string().min(1).max(200).describe("One-sentence summary of what happened in this run. Plain text, no markdown."),overview:z$1.string().min(1).max(280).optional().describe("One plain-text sentence giving the bottom line of the run. No markdown."),summaryMarkdown:z$1.string().min(1).max(4e3).describe("Markdown body. Several short paragraphs or a tight list. No emojis, no top-level heading. Max 5 sentences."),recommendedAction:wV.optional()}),IV=zp.extend({riskLevel:vV.describe("Traffic-light validation signal. Use passing when validation is trustworthy with no real concern, warning when review or follow-up is needed, and error when the evidence shows the PR may hide or cause a product regression or another material concern that requires review."),headline:z$1.string().min(1).max(60).describe("Short, factual, title-case status of the validation signal, 6 words max, no punctuation. Describe the outcome only - never name the process or mode (no 'dry run', 'auto-heal', 'triage', 'pending'); those are shown separately. Examples: 'Review Required', 'Sign In Failing Across 5 Tests', 'All Tests Passed'."),overview:z$1.string().min(1).max(280).describe("The bottom-line verdict in one plain sentence: what the Momentic validation means for user-visible behavior and how trustworthy the signal is. This is the conclusion only, not the evidence. No markdown, headings, lists, or emojis. Do not prescribe a merge decision (use recommendedAction)."),summaryMarkdown:z$1.string().min(1).max(1e3).describe("The supporting evidence behind the overview, in GitHub-flavored markdown: a few short sentences or a tight list with the specific tests, errors, and signals that justify the verdict. Must carry information the overview does not - never paraphrase or restate the overview. Do not prescribe a merge decision or restate repair mechanics. Max 4 sentences. No emojis or top-level heading."),recommendedAction:wV.extend({kind:RV.describe("The kind of action a reviewer should take. safe_to_merge = signal is trustworthy and can be merged as-is; confirm_intended_change = a product or UI change was detected (or a heal relaxed an expectation) and a human must confirm it is intentional; investigate_regression = evidence points to a real product bug or regression to investigate before merging; fix_test = a broken or stale test or test setup needs repair; resolve_infra = an infrastructure or environment problem needs resolving and a re-run; review_coverage = quarantine has materially reduced coverage that should be reviewed."),detail:z$1.string().min(1).max(280).describe("One plain-text sentence naming the specific next step (e.g. 'Confirm the new success-indicator color is an intended design change'). No markdown.")}).describe("The single most important next step a reviewer should take. Omit entirely when the signal is clean and there is genuinely nothing to do.").optional()});var xV=z$1.object({id:z$1.string(),status:z$1.enum(ht),trigger:z$1.enum(vs),createdAt:uo,startedAt:uo.nullish(),finishedAt:uo.nullish(),gitCommitSha:z$1.string().nullish(),gitCommitShaShort:z$1.string().nullish(),gitCommitTimestamp:uo.nullish(),gitBranchName:z$1.string().nullish(),gitOriginUrl:z$1.string().nullish(),gitCommitMessage:z$1.string().nullish(),gitCommitAuthorName:z$1.string().nullish(),githubRepository:z$1.string().nullish(),gitlabProjectPath:z$1.string().nullish(),pipelineId:z$1.string().nullish(),ciProvider:z$1.string().nullish(),cliVersion:z$1.string().nullish(),labels:z$1.string().array().optional(),healRiskSummary:zp.optional(),localSuiteName:z$1.string().optional(),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:z$1.object({executionType:mu,status:z$1.enum(ht),environmentName:z$1.string().nullish()}).array()}),_V=xV.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:TC.array()}),PV=xV.extend({runs:Qi.array()});var Afe=z$1.object({type:z$1.literal("TARGETING"),name:z$1.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:U$.array(),pageState:z$1.string().optional(),targetSource:z$1.enum(vl).optional(),targetUpdateTime:z$1.string().optional()}),Efe=z$1.object({type:z$1.literal("AI_LOCATION"),matched:z$1.boolean(),pageState:z$1.string().optional(),ragUsed:z$1.boolean().optional(),thoughts:z$1.string().optional()}),Cfe=z$1.object({type:z$1.literal("ASSERTION"),relevantElementsSerialized:z$1.string().array().optional(),pageState:z$1.string().optional(),ragUsed:z$1.boolean().optional()}),OV=z$1.discriminatedUnion("type",[Afe,Efe,Cfe]);var vfe=z$1.object({id:z$1.string(),name:z$1.string()});vfe.extend(z$1.object({createdAt:uo,createdBy:z$1.string(),schedule:fC,notification:yC,environment:z$1.object({name:z$1.string()}).nullish(),beforeTests:z$1.object({id:z$1.string()}).array().nullish(),afterTests:z$1.object({id:z$1.string()}).array().nullish()}).shape);var MV=z$1.object({id:z$1.guid(),orgId:z$1.string(),createdAt:uo,startedAt:uo.or(z$1.null()),finishedAt:uo.or(z$1.null()),status:z$1.enum(ht),trigger:z$1.enum(vs),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:Qi.array()});MV.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var NV=MV.extend({runs:TC.array()});function LV({beforeStatus:e,mainStatus:t,afterStatus:n}){return e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":"PASSED"}function AC(e,t){return e.some(r=>t?.onlyQuarantined?r.status==="FAILED":!r.quarantined&&r.status==="FAILED")?"FAILED":e.some(r=>r.status==="CANCELLED")?"CANCELLED":"PASSED"}function kV(e){switch(e){case "PASSED":return "SUCCESS";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":case "PENDING":case "RETRYING":case "WAITING_FOR_USER":return "RUNNING"}}var aM=z$1.object({content:z$1.string(),ids:z$1.string().array(),tokenLength:z$1.number()}),Rfe=z$1.object({chunks:aM.array()});z$1.object({ids:z$1.string().array(),score:z$1.number(),tokenLength:z$1.number()});Rfe.extend({description:z$1.string().describe("Input to pass to RAG engine"),tokenLimit:z$1.number()});var DV=z$1.object({ids:z$1.number().array()}),FV=z$1.object({indices:z$1.number().array()});var zl=(n=>(n.Interactive="interactive",n.Runner="runner",n))(zl||{}),wfe=z$1.enum(zl),rr=z$1.object({disableCache:z$1.boolean().optional(),useMemory:z$1.boolean().optional(),clientMode:wfe.optional(),loggerTags:z$1.record(z$1.string(),z$1.string()).optional(),langfuseSessionId:z$1.string().optional(),agentConfigVersion:z$1.string().optional(),cacheBustReason:z$1.enum(Gy).optional()});rr.extend({chunks:aM.array(),description:z$1.string().describe("Input to pass to AI"),type:z$1.union([z$1.literal("locator"),z$1.literal("assertion"),z$1.literal("ai-action")]),softTokenLimit:z$1.number(),mediumTokenLimit:z$1.number().optional(),hardTokenLimit:z$1.number(),callId:z$1.string().optional()});var Ife=z$1.object({screenshotBase64AfterCommand:z$1.string(),urlAfterCommand:z$1.string(),serializedCommand:z$1.string(),elementInteracted:z$1.string().optional(),thoughts:z$1.string().optional()}),BV=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),source:B$.optional().catch(void 0),isTieBreakerCall:z$1.boolean().optional(),memory:z$1.discriminatedUnion("type",[ka,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),firstPassModelResults:ZE.array().optional(),knowledgeBaseSection:z$1.string().optional()}),UV=z$1.object({target:z$1.string().or(z$1.number()),browserState:z$1.string().optional(),screenshot:z$1.string().optional(),boundingBox:z$1.object({x:z$1.number(),y:z$1.number(),height:z$1.number(),width:z$1.number()}).optional()}),HV=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),GV=z$1.object({goal:z$1.string(),emulatorState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),lM=z$1.union([z$1.literal("NEGATED_CHECK"),z$1.literal("CONDITIONAL_CHECK")]),jV=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),url:z$1.string(),contextChoice:kp.optional(),memory:z$1.discriminatedUnion("type",[Mp,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),source:lM.optional(),recoveryHint:z$1.string().optional(),knowledgeBaseSection:z$1.string().optional()}),$V=z$1.object({command:ru}),cM=z$1.object({goal:z$1.string(),browserState:z$1.string(),startingScreenshot:z$1.string().optional(),screenshot:z$1.string(),url:z$1.string(),history:Ife.array(),actionHint:z$1.string().optional(),lastError:z$1.string().optional()}),VV=z$1.object({results:lC.array(),errorMessage:z$1.string(),errorStack:z$1.string().optional()}),zV=z$1.object({results:lC.array(),goal:z$1.string(),errorMessage:z$1.string()}),WV=z$1.object({failedResults:lC.array(),nextStepsSerialized:z$1.string().array(),currentUrl:z$1.string(),currentPageState:z$1.string(),currentScreenshot:z$1.string(),customInstructions:z$1.string().optional(),testDescription:z$1.string().optional()});z$1.object({description:z$1.string(),type:z$1.union([z$1.literal("locator"),z$1.literal("assertion"),z$1.literal("ai-action")]),excerpt:z$1.string()});var qV=z$1.object({type:z$1.string(),browserContext:z$1.string(),currentStep:z$1.string(),screenshot:z$1.string()}),KV=z$1.object({description:z$1.string(),browserState:z$1.string().optional(),screenshot:z$1.string()}),xfe=z$1.enum(["locator","assertion"]);z$1.object({completionType:xfe,currentGoal:z$1.string(),pastGoal:z$1.string().optional(),currentScreenshot:z$1.string(),pastScreenshot:z$1.string(),pastResult:z$1.union([z$1.boolean(),z$1.number()])});z$1.object({goal:z$1.string()});var YV=z$1.object({keywords:z$1.array(z$1.string())});var EC=(i=>(i.LOCATOR="locator",i.ASSERTION="assertion",i.VISUAL_ASSERTION="visual-assertion",i.TEXT_EXTRACTION="text-extraction",i.FAILURE_RECOVERY="failure-recovery",i))(EC||{}),_fe=["locator","assertion","visual-assertion","text-extraction","failure-recovery"];z$1.enum(EC);var Pfe=new Set(_fe);function Ofe(e){return Pfe.has(e)}var Mfe=z$1.enum(["v1","v2","v3","v4"]),Nfe=z$1.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1");z$1.union([Mfe,Nfe,z$1.string().describe("for people with special configurations")]);var og={locator:"v4.2",assertion:"v4.1","visual-assertion":"v4.0","text-extraction":"v3.0","failure-recovery":"v2.1"},JV={locator:{v4:["v4.2","v4.1","v4.0"],v3:["v3.3","v3.2","v3.1","v3.0"],v2:["v2.2","v2.1","v2.0"],v1:["v1.0"]},assertion:{v4:["v4.1","v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.3","v2.2","v2.1","v2.0"],v1:["v1.0"]},"visual-assertion":{v4:["v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.0"],v1:["v1.0"]},"text-extraction":{v3:["v3.0"],v2:["v2.0"],v1:["v1.0"]},"failure-recovery":{v2:["v2.1","v2.0"],v1:["v1.0"]}},XV=(s=>(s.ANDROID_LOCATOR="android-locator",s.IOS_LOCATOR="ios-locator",s.ANDROID_ASSERTION="android-assertion",s.IOS_ASSERTION="ios-assertion",s.ANDROID_TEXT_EXTRACTION="android-text-extraction",s.IOS_TEXT_EXTRACTION="ios-text-extraction",s))(XV||{});z$1.enum(XV);var Lfe={locator:["v1"],assertion:["v1"],"visual-assertion":["v1"],"text-extraction":["v1"]};function kfe(e){let t=Lfe[e];if(!t)return new Set;let n=JV[e],o=new Set;for(let r of t){o.add(r);for(let i of n[r]??[])o.add(i);}return o}function CC(e){for(let[t,n]of Object.entries(e)){if(!Ofe(t))continue;let o=JV[t];if(!o)continue;let r=new Set;for(let[i,s]of Object.entries(o)){r.add(i);for(let a of s)r.add(a);}if(!r.has(n)){let i=[...r].sort();throw new te("UserConfigurationError",`Invalid agent config: "${n}" is not a valid version for "${t}". Valid versions: ${i.join(", ")}`)}if(kfe(t).has(n))throw new te("UserConfigurationError",`Agent config "${n}" for "${t}" is no longer supported because it relies on a legacy model. Upgrade to a newer version.`)}}var Xc=O__default.object({id:O__default.guid(),envKey:O__default.string().optional(),skipped:O__default.boolean().optional(),retries:O__default.number().optional()});var gu=(r=>(r.PRESET="MOBILE_PRESET_STEP",r.MODULE="MOBILE_MODULE_STEP",r.AI_ACTION="MOBILE_AI_ACTION_STEP",r.CONDITIONAL="MOBILE_CONDITIONAL_STEP",r))(gu||{});var rg=Xc.extend({type:O__default.literal("MOBILE_CONDITIONAL_STEP")});var Zr=z$1.object({id:z$1.string(),name:qE,baseUrl:KE,description:z$1.string().optional().nullish(),schemaVersion:z$1.string(),advanced:Cs,retries:z$1.number().optional().nullish(),envs:z$1.array(fV).nullish(),parameters:gV.nullish(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional().catch([])}),QV=z$1.enum(["INHERIT","ENABLED","DISABLED"]);var Ffe=Cs.extend({failureRecovery:QV.optional(),useMemory:QV.optional()});Zr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true}).extend({advanced:Ffe});Zr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true});var Bfe=z$1.object({labels:z$1.array(z$1.string()).optional(),outputs:SC.nullish()}),Zn=Zr.extend(Bfe.shape),Ufe=z$1.object({createdAt:z$1.coerce.date(),updatedAt:z$1.coerce.date(),updatedBy:z$1.string().nullable(),schedule:fC,notification:yC,createdBy:z$1.string(),organizationId:z$1.string(),folderId:z$1.string().nullable().optional()}),Hfe=Zr.extend(Ufe.shape);Hfe.extend(Dl.shape);var dM=Zr.extend(Dl.shape);Zr.extend(Vc.shape);var Gfe="test",jfe="module",$fe="mobile-test",Vfe="mobile-module",zfe="test/v2",Wfe="module/v2",qfe="mobile-test/v2",Kfe="mobile-module/v2";var De=(l=>(l.TEST=`momentic/${Gfe}`,l.MODULE=`momentic/${jfe}`,l.TEST_V2=`momentic/${zfe}`,l.MODULE_V2=`momentic/${Wfe}`,l.MOBILE_TEST=`momentic/${$fe}`,l.MOBILE_MODULE=`momentic/${Vfe}`,l.MOBILE_TEST_V2=`momentic/${qfe}`,l.MOBILE_MODULE_V2=`momentic/${Kfe}`,l))(De||{});Zr.merge(Vc);var Yfe=Xn.extend({steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())),schemaVersion:z$1.string()}),DS=Yfe.extend({fileType:z$1.literal(De.MODULE)});z$1.object({test:z$1.string().describe("YAML for the test, including metadata and steps"),modules:z$1.record(z$1.string(),z$1.string()).describe("Map of module name to YAML for the module")});function vC(e){if(e===void 0)return "__undefined__";if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(vC);let t={};for(let[n,o]of Object.entries(e))t[n]=vC(o);return t}var Jfe=/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/,ZV=36,mo=z$1.union([z$1.guid().max(ZV,"V2 IDs must be 36 characters or fewer"),z$1.string().max(ZV,"V2 IDs must be 36 characters or fewer").regex(Jfe,"V2 IDs must be lowercase kebab-case with at least three words, e.g. silver-river-lantern")],{error:"ID must be a UUID or lowercase kebab-case with at least three words, e.g. silver-river-lantern (36 characters max)"});var RC=O.discriminatedUnion("type",[O.object({type:O.literal("SCREEN")}),O.object({type:O.literal("OPEN_APP")}),O.object({type:O.literal("OPEN_WEBVIEW")})]),Qc=O.object({type:O.literal("description"),description:O.string()}),pM=O.object({type:O.literal("CUSTOM_COORDINATES"),startX:O.number().describe("Starting X coordinate in pixels"),startY:O.number().describe("Starting Y coordinate in pixels"),deltaPixels:O.number().describe("Number of pixels to scroll in the specified direction")}),wC=O.discriminatedUnion("type",[...RC.options,O.object({type:O.literal("CUSTOM"),target:Qc}),pM]);function Xfe(e){return e.toLowerCase().replaceAll("_"," ")}function mM(e){switch(e.type){case "CUSTOM":return e.target.description;case "CUSTOM_COORDINATES":return `custom coordinates (x: ${Math.round(e.startX)}, y: ${Math.round(e.startY)}, delta: ${Math.round(e.deltaPixels)}px)`;case "SCREEN":case "OPEN_APP":case "OPEN_WEBVIEW":return Xfe(e.type);default:{throw new Error("Unreachable")}}}var Qfe=O.object({type:O.literal("coordinates"),xPercent:O.number(),yPercent:O.number()}),Zfe=O.object({type:O.literal("absolute_percent"),x:O.number(),y:O.number()}),ig=O.discriminatedUnion("type",[Qc,Qfe,Zfe]);var eye=O.object({x1:O.number(),y1:O.number(),x2:O.number(),y2:O.number(),tolerance:O.nativeEnum(Ki),preciseTolerance:O.boolean().optional()}),tye=O.object({width:O.number(),height:O.number(),tolerance:O.nativeEnum(Ki),preciseTolerance:O.boolean().optional()}),hM=O.object({requiredText:O.string().optional(),requiredAttributes:O.record(O.string(),O.string()).optional(),requiredBounds:O.boolean().optional(),position:eye.optional(),shape:tye.optional()}),ez=O.object({xPath:O.string(),requirements:hM.optional()}),nye=O.object({type:O.literal("CUSTOM"),target:Qc,cache:O.lazy(()=>tz).optional()}),oye=O.object({pixelDelta:O.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:O.union([RC,nye,pM]),direction:O.enum(["up","down"])}),tz=O.object({type:O.literal("NATIVE"),bounds:O.number().array().optional(),resolvedDescription:O.string().optional(),xPath:O.string().optional(),elementOnlySerializedXml:O.string().optional(),scrollDetails:oye.optional(),requirements:hM.optional(),requiredRelatedElements:ez.array().optional(),memory:ka.optional()}),rye=O.object({type:O.literal("WEBVIEW"),resolvedDescription:O.string().optional(),xPath:O.string().optional(),browserCache:Rl.optional(),memory:ka.optional()}),IC=O.union([tz,rye]);var iye=O.object({left:O.number(),top:O.number(),right:O.number(),bottom:O.number()});O.object({newViewportBounds:iye});var sye=O.object({type:O.literal("CUSTOM"),target:Qc,cache:O.lazy(()=>iz).optional()}),nz=O.object({pixelDelta:O.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:O.union([RC,sye,pM]),direction:O.enum(["up","down"])}),oz=(n=>(n.Native="native",n.Appium="appium",n))(oz||{}),gM=O.tuple([O.number(),O.number(),O.number(),O.number()]),rz=ez.extend({bounds:gM.optional(),browserCache:Rl.optional()}),iz=O.object({type:O.literal("NATIVE"),bounds:gM.optional(),resolvedDescription:O.string().optional(),sourceTree:O.nativeEnum(oz).optional(),xPath:O.string().optional(),elementOnlySerializedXml:O.string().optional(),scrollDetails:nz.optional(),requirements:hM.optional(),requiredRelatedElements:rz.array().optional(),memory:ka.optional()}),aye=O.object({type:O.literal("WEBVIEW"),bounds:gM.optional(),resolvedDescription:O.string().optional(),xPath:O.string().optional(),scrollDetails:nz.optional(),browserCache:Rl.optional(),requiredRelatedElements:rz.array().optional(),memory:ka.optional()}),xC=O.discriminatedUnion("type",[iz,aye]);var zt=(_=>(_.AI_CHECK="AI_CHECK",_.AI_EXTRACT="AI_EXTRACT",_.TAP="TAP",_.TYPE="TYPE",_.PRESS="PRESS",_.PRESS_KEYBOARD="PRESS_KEYBOARD",_.OPEN_APP="OPEN_APP",_.KILL_APP="KILL_APP",_.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",_.SWIPE="SWIPE",_.SCROLL_TO="SCROLL_TO",_.SCREEN_CHECK="SCREEN_CHECK",_.ELEMENT_CHECK="ELEMENT_CHECK",_.VISUAL_DIFF="VISUAL_DIFF",_.DRAG_AND_DROP="DRAG_AND_DROP",_.JAVASCRIPT="JAVASCRIPT",_.REQUEST="REQUEST",_.WAIT="WAIT",_.ADD_FILE="ADD_FILE",_.INSTALL_APP="INSTALL_APP",_.UNINSTALL_APP="UNINSTALL_APP",_.TOGGLE_SETTINGS="TOGGLE_SETTINGS",_.ROTATE_ORIENTATION="ROTATE_ORIENTATION",_.ADB_COMMAND="ADB_COMMAND",_.APPIUM_EXECUTE="APPIUM_EXECUTE",_.STATE="STATE",_))(zt||{}),Xe=O__default.object({id:O__default.guid(),disableCache:O__default.boolean().optional()}),sg=O__default.object({updatedAt:O__default.coerce.date().optional(),updatedAtLoggerTags:O__default.record(O__default.string(),O__default.string()).optional()}),la=sg.extend({target:IC}),_C=sg.extend({fromTarget:IC,toTarget:IC}),Wl=sg.extend({target:xC}),sz=sg.extend({fromTarget:xC,toTarget:xC}),Zc=e=>{switch(e.type){case "description":return e.description;case "coordinates":return `${Math.round(e.xPercent*100)}%, ${Math.round(e.yPercent*100)}%`;case "absolute_percent":return `x: ${e.x}%, y: ${e.y}%`}};var az=Xe.extend({type:O__default.literal("ADB_COMMAND"),command:O__default.string(),jsonArgs:O__default.string().optional()});var lye=O__default.string().trim(),cz=Xe.extend({type:O__default.literal("INSTALL_APP"),uri:lye});var dz=Xe.extend({type:O__default.literal("OPEN_NOTIFICATION_DRAWER")});var FS=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(FS||{}),pz=Xe.extend({type:O__default.literal("TOGGLE_SETTINGS"),settingsType:O__default.nativeEnum(FS)});var hz=Xe.extend({type:O__default.literal("UNINSTALL_APP"),packageName:O__default.string()});var PC=Xe.extend({type:O__default.literal("APPIUM_EXECUTE"),command:O__default.string(),jsonArgs:O__default.string().optional()});var gz=Xe.extend({type:O__default.literal("ADD_FILE"),file:O__default.string(),storageLocation:O__default.string()});var ed=Xe.extend({type:O__default.literal("AI_CHECK"),assertion:O__default.string(),timeoutSecs:O__default.number().optional(),contextChoice:kp.optional(),cache:sg.extend({memory:Mp.optional()}).optional()});var fz=Xe.extend({type:O__default.literal("AI_EXTRACT"),goal:O__default.string(),schema:O__default.string().optional()});var ag=Xe.extend({type:O__default.literal("JAVASCRIPT"),code:O__default.string(),timeout:O__default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var yz=Xe.extend({type:O__default.literal("KILL_APP")});var US=(n=>(n.HOME="HOME",n.POWER="POWER",n))(US||{}),OC=(s=>(s.BACK="BACK",s.APP_SWITCHER="APP_SWITCHER",s.SEARCH="SEARCH",s.VOLUME_UP="VOLUME_UP",s.VOLUME_DOWN="VOLUME_DOWN",s.VOLUME_MUTE="VOLUME_MUTE",s))(OC||{}),MC=Xe.extend({type:O__default.literal("PRESS"),key:O__default.nativeEnum(US),longPress:O__default.boolean().optional()}),Sz=MC.extend({key:O__default.nativeEnum(OC).or(O__default.nativeEnum(US))}),bz=MC;var Tz=Xe.extend({type:O__default.literal("REQUEST")}).merge(Vy);var EM=(n=>(n.PORTRAIT="PORTRAIT",n.LANDSCAPE="LANDSCAPE",n))(EM||{}),Ez=Xe.extend({type:O__default.literal("ROTATE_ORIENTATION"),orientation:O__default.nativeEnum(EM)});var pye=O__default.object({type:O__default.literal("CONTENT"),negated:O__default.boolean().optional(),value:O__default.string()}),cg=Xe.extend({type:O__default.literal("SCREEN_CHECK"),assertion:pye,timeout:O__default.number().int().min(0).max(Ih).optional().describe("max seconds to wait for the assertion to be true")});var Cz=Xe.extend({type:O__default.literal("STATE")});var vz=Xe.extend({type:O__default.literal("VISUAL_DIFF"),path:O__default.string().describe("path to the golden screenshot to compare against"),threshold:O__default.number().min(0).max(1).optional().describe("max allowed fraction of differing pixels before the diff fails (default 0.1)")});O__default.object({created:O__default.boolean(),goldenPath:O__default.string(),threshold:O__default.number(),goldenScreenshotBase64:O__default.string().optional(),currentScreenshotBase64:O__default.string().optional(),diffScreenshotBase64:O__default.string().optional(),goldenScreenshotSnapshotId:O__default.string().optional(),currentScreenshotSnapshotId:O__default.string().optional(),diffScreenshotSnapshotId:O__default.string().optional(),diffPercent:O__default.number().optional(),pass:O__default.boolean().optional(),dimensionMismatch:O__default.boolean().optional()});var wz=Xe.extend({type:O__default.literal("WAIT"),timeoutSecs:O__default.number()});var HS=O__default.discriminatedUnion("type",[Cz,ed,fz,ag,wz,Tz,Ez,cg,vz,gz,yz]);O__default.discriminatedUnion("type",[...HS.options,MC]);var vM=Xe.extend({type:O__default.literal("DRAG_AND_DROP"),fromTarget:Qc,toTarget:Qc,hoverDuration:O__default.number().optional(),dragDuration:O__default.number().optional()}),GS=vM.extend({cache:_C.optional()}),jS=vM.extend({cache:sz.optional()});var RM=Xe.extend({type:O__default.literal("ELEMENT_CHECK"),target:ig,assertion:xE,timeout:O__default.number().int().min(0).max(Ih).optional().describe("max seconds to wait for the assertion to be true")}),Wp=RM.extend({cache:la.optional()}),qp=RM.extend({cache:Wl.optional()});var $S=(n=>(n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))($S||{}),NC=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(NC||{}),_z={repeat:O__default.number().int().min(1).optional(),keyPressDelayMs:O__default.number().min(0).optional()},Pz=Xe.extend({type:O__default.literal("PRESS_KEYBOARD"),key:O__default.nativeEnum($S),..._z}),Oz=Xe.extend({type:O__default.literal("PRESS_KEYBOARD"),key:O__default.nativeEnum(NC).or(O__default.nativeEnum($S)),..._z});var Mz=Xe.extend({type:O__default.literal("OPEN_APP"),packageName:O__default.string(),activityName:O__default.string().optional(),intentExtras:O__default.string().optional()}),Nz=Xe.extend({type:O__default.literal("OPEN_APP"),packageName:O__default.string(),intentExtras:O__default.string().optional()});var wM=Xe.extend({type:O__default.literal("SCROLL_TO"),target:Qc,direction:O__default.enum(["down","up"]),scrollableElement:wC,scrollStepPercent:O__default.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.9 (90%)."),maxScrollAttempts:O__default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),VS=wM.extend({cache:la.optional()}),zS=wM.extend({cache:Wl.optional()});var IM=Xe.extend({type:O__default.literal("SWIPE"),direction:O__default.enum(["up","down","left","right"]),scrollableElement:wC,viewportPercent:O__default.number().optional(),durationMs:O__default.number().optional(),relativePosition:wE.optional()}),WS=IM.extend({cache:la.optional()}),qS=IM.extend({cache:Wl.optional()});var xM=Xe.extend({type:O__default.literal("TAP"),target:ig,longPress:O__default.boolean().optional(),longPressDurationMs:O__default.number().optional(),iterations:O__default.number().optional(),tapDelayMs:O__default.number().optional(),relativePosition:wE.optional(),doubleTap:O__default.boolean().optional(),doubleTapDelayMs:O__default.number().optional()}),KS=xM.extend({cache:la.optional()}),YS=xM.extend({cache:Wl.optional()});var JS=(r=>(r.AUTO="auto",r.PROGRAMMATIC="programmatic",r.LONG_PRESS="long-press",r.BACKSPACE="backspace",r))(JS||{});var _M=Xe.extend({type:O__default.literal("TYPE"),target:ig.optional(),keyPressDelayMs:O__default.number().optional(),text:O__default.string(),clearContent:O__default.boolean().optional(),forceClearContent:O__default.boolean().optional(),replaceStrategy:O__default.nativeEnum(JS).optional()});var XS=_M.extend({cache:la.optional()}),QS=_M.extend({cache:Wl.optional()});var ZS=O__default.discriminatedUnion("type",[...HS.options,KS,XS,Sz,Oz,hz,cz,az,PC,GS,dz,VS,WS,pz,Wp,Mz]);var eb=O__default.discriminatedUnion("type",[...HS.options,YS,QS,bz,Pz,Nz,qS,jS,zS,qp,PC]);var Dz=O__default.union([O__default.string(),O__default.record(O__default.string(),O__default.unknown().optional())]),DC=Xc.extend({type:O__default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:O__default.number().optional()}),yu=DC.extend({command:ZS}),Su=DC.extend({command:eb}),ug=O__default.object({moduleId:O__default.string(),inputs:O__default.record(O__default.string(),O__default.string()).optional()}),tb=Xc.merge(ug.extend({type:O__default.literal("MOBILE_MODULE_STEP")}));ug.extend({steps:O__default.lazy(()=>ql.array())});ug.extend({steps:O__default.lazy(()=>td.array())});var PM=(n=>(n.V2="2",n.V3="3",n))(PM||{});var OM=O__default.nativeEnum(PM),yye=Cl.extend({platform:O__default.literal("ANDROID"),resolvedGoal:O__default.string(),steps:O__default.lazy(()=>yu.array()),autoGeneratedPostcondition:O__default.string().optional()}),Sye=Cl.extend({platform:O__default.literal("IOS"),resolvedGoal:O__default.string(),steps:O__default.lazy(()=>Su.array()),autoGeneratedPostcondition:O__default.string().optional()}),MM=O__default.discriminatedUnion("platform",[yye,Sye]),bu=Xc.extend({type:O__default.literal("MOBILE_AI_ACTION_STEP"),text:O__default.string(),version:OM.optional(),cache:MM.optional(),precondition:O__default.string().optional(),postcondition:O__default.string().optional()});var Tye=O__default.discriminatedUnion("type",[ed,cg,Wp,ag]),NM=DC.extend({command:Tye}),Aye=O__default.discriminatedUnion("type",[ed,cg,qp,ag]),LM=DC.extend({command:Aye}),Eye=O__default.object({assertion:NM,steps:O__default.lazy(()=>ql.array())}),Cye=O__default.object({assertion:LM,steps:O__default.lazy(()=>td.array())}),vye=rg.extend({blocks:O__default.lazy(()=>Eye.array()),elseSteps:O__default.lazy(()=>ql.array()).optional()}),Rye=rg.extend({blocks:O__default.lazy(()=>Cye.array()),elseSteps:O__default.lazy(()=>td.array()).optional()}),ql=O__default.discriminatedUnion("type",[yu,tb,bu,vye]),td=O__default.discriminatedUnion("type",[Su,tb,bu,Rye]);O__default.union([ql.array(),td.array()]);var kM=O__default.object({parameterNames:O__default.string().array(),defaultParameters:O__default.record(O__default.string(),O__default.string()).optional(),parameterEnums:O__default.record(O__default.string(),O__default.string().array()).optional()}),FC=O__default.object({moduleId:mo,name:O__default.string(),description:O__default.string().nullish(),platform:O__default.nativeEnum(ja).optional().default("ANDROID"),parameters:kM.optional(),enabled:O__default.boolean().nullish(),schemaVersion:O__default.string()}),DM=FC.omit({name:true}),wye=DM.extend({steps:Dz.array()});O__default.object({fileType:O__default.literal(De.MOBILE_MODULE)}).merge(wye);var Fz=FC.omit({platform:true,schemaVersion:true});({ANDROID:Fz.extend({platform:O__default.literal("ANDROID"),steps:ql.array()}),IOS:Fz.extend({platform:O__default.literal("IOS"),steps:td.array()})});var pg=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(pg||{}),Bz=O__default.object({description:O__default.string().optional(),name:O__default.string().describe("name of the module"),parameters:kM.optional()}),Uz=ug.merge(Bz).extend({platform:O__default.literal("ANDROID"),get steps(){return Wa.array()}}),Hz=ug.merge(Bz).extend({platform:O__default.literal("IOS"),get steps(){return qa.array()}});O__default.discriminatedUnion("platform",[Uz,Hz]);var FM=Xc.merge(Uz).extend({type:O__default.literal("RESOLVED_MOBILE_MODULE")}),BM=Xc.merge(Hz).extend({type:O__default.literal("RESOLVED_MOBILE_MODULE")});O__default.discriminatedUnion("platform",[FM,BM]);var Iye=O__default.object({assertion:NM,get steps(){return Wa.array()}}),UM=rg.extend({get blocks(){return Iye.array()},get elseSteps(){return Wa.array().optional()}}),xye=O__default.object({assertion:LM,get steps(){return qa.array()}}),HM=rg.extend({get blocks(){return xye.array()},get elseSteps(){return qa.array().optional()}}),Wa=O__default.discriminatedUnion("type",[FM,yu,bu,UM]),qa=O__default.discriminatedUnion("type",[BM,Su,bu,HM]);function Gz(e){return Object.values(pg).includes(e)||Object.values(gu).includes(e)}var jz=(i=>(i.PRECONDITION="PRECONDITION",i.REPLAY="REPLAY",i.GENERATE="GENERATE",i.AUTOHEAL="AUTOHEAL",i.POSTCONDITION="POSTCONDITION",i))(jz||{}),$z=z$1.enum(["pending","running","success","failed"]),Vz=z$1.object({type:z$1.literal("THOUGHT"),text:z$1.string(),blockId:z$1.string().optional()}),zz=z$1.object({type:z$1.literal("TOOL_CALL"),toolName:z$1.string()}),Wz=z$1.object({type:z$1.literal("PHASE"),phase:z$1.nativeEnum(jz),failureMessage:z$1.string().optional()}),_ye=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:Wa,status:$z,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),Pye=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:qa,status:$z,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),qz=z$1.object({type:z$1.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z$1.string()}),Oye=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:yu.array(),resolvedGoal:z$1.string()}),Mye=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:Su.array(),resolvedGoal:z$1.string()}),Kz=z$1.discriminatedUnion("type",[Vz,zz,Wz,_ye,Oye,qz]),Yz=z$1.discriminatedUnion("type",[Vz,zz,Wz,Pye,Mye,qz]);var Kl=O__default.object({message:O__default.string().optional(),startTime:O__default.number(),endTime:O__default.number(),status:O__default.nativeEnum(Mt),trace:O__default.unknown().optional().optional(),beforeSnapshot:O__default.string().optional(),afterSnapshot:O__default.string().optional(),data:O__default.unknown().optional().optional().describe("output data from the step"),aiSuggested:O__default.boolean().optional(),beforeTestContext:Jh.optional(),afterTestContext:Jh.optional()}),Jz=Kl.merge(yu).extend({previousAttempts:O__default.lazy(()=>ws.array()).optional()}),Nye=Kl.merge(tb).extend({steps:O__default.lazy(()=>ws.array()),name:O__default.string().optional(),previousAttempts:O__default.lazy(()=>ws.array()).optional()}),Lye=Kl.merge(bu).extend({steps:O__default.lazy(()=>ws.array()),previousAttempts:O__default.lazy(()=>ws.array()).optional(),failureRecoveryReason:O__default.string().optional(),trajectory:Kz.array().optional()}),kye=Kl.merge(UM).extend({assertionResult:Jz.optional(),steps:O__default.lazy(()=>ws.array()),previousAttempts:O__default.lazy(()=>ws.array()).optional()}),ws=O__default.discriminatedUnion("type",[Jz,Nye,Lye,kye]),Xz=Kl.merge(Su).extend({previousAttempts:O__default.lazy(()=>Is.array()).optional()}),Dye=Kl.merge(tb).extend({steps:O__default.lazy(()=>Is.array()),name:O__default.string().optional(),previousAttempts:O__default.lazy(()=>Is.array()).optional()}),Fye=Kl.merge(bu).extend({steps:O__default.lazy(()=>Is.array()),previousAttempts:O__default.lazy(()=>Is.array()).optional(),failureRecoveryReason:O__default.string().optional(),trajectory:Yz.array().optional()}),Bye=Kl.merge(HM).extend({assertionResult:Xz.optional(),steps:O__default.lazy(()=>Is.array()),previousAttempts:O__default.lazy(()=>Is.array()).optional()}),Is=O__default.discriminatedUnion("type",[Xz,Dye,Fye,Bye]);var Uye=Kl.extend({index:O__default.number().optional(),userFacingStepReference:O__default.string().optional(),description:O__default.string()}),Qz=Uye.extend({beforeScreenshot:O__default.string().optional(),afterScreenshot:O__default.string().optional()});var Zz=z$1.object({attributesRequired:z$1.array(z$1.string()).optional(),textRequired:z$1.boolean().optional(),boundsRequired:z$1.boolean().optional(),positionSpecificity:z$1.enum(Ki).optional(),shapeSpecificity:z$1.enum(Ki).optional()}),Hye=z$1.object({id:z$1.number(),requirements:Zz}).array();z$1.object({thoughts:z$1.string(),id:z$1.number(),updatedMemory:Uy.optional(),inWebview:z$1.boolean().optional(),requirements:Zz.optional(),additionalElements:Hye.optional()});var Gye=z$1.literal("SCROLL_TO"),eW=z$1.object({description:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),source:Gye.optional(),memory:z$1.discriminatedUnion("type",[ka,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional()}),tW=z$1.object({assertion:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),contextChoice:kp.optional(),memory:z$1.discriminatedUnion("type",[Mp,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional()});z$1.object({thoughts:z$1.string(),result:z$1.boolean(),relevantElements:z$1.array(z$1.number()).optional(),updatedMemory:Hy.optional()});var nW=z$1.object({failedResults:Qz.array(),nextStepsSerialized:z$1.string().array(),currentScreenXml:z$1.string(),currentScreenshot:z$1.string(),customInstructions:z$1.string().optional(),testDescription:z$1.string()}),oW=(o=>(o.LEGITIMATE="LEGITIMATE",o.RECOVERABLE="RECOVERABLE",o.INELIGIBLE="INELIGIBLE",o))(oW||{});z$1.object({thoughts:z$1.string(),scenario:z$1.enum(oW),instructions:z$1.string().nullish(),reasonSummary:z$1.string().nullish()});z$1.looseObject({type:z$1.literal("response.create")});var rW=z$1.union([z$1.looseObject({response:z$1.looseObject({id:z$1.string()}),sequence_number:z$1.number(),type:z$1.literal("response.completed")}),z$1.looseObject({code:z$1.string().nullable(),message:z$1.string(),sequence_number:z$1.number(),type:z$1.literal("error")})]);var iW="ui_states.jsonl";z$1.object({stepId:z$1.string(),parentStepIdChain:z$1.array(z$1.string()),fingerprintHash:z$1.string(),minhash:z$1.array(z$1.number().int()),canonicalUrl:z$1.string(),capturedAt:z$1.number().describe("Unix timestamp in milliseconds")});var mg=(a=>(a.TestRun="test-run",a.MobileTestRun="mobile-test-run",a.CreditsUsed="credits-used",a.CreditsUsedV2="credits-used-v2",a.StepsExecuted="steps-executed",a.LLMTokensUsed="llm-tokens-used",a.HostedBrowserSecondsUsed="hosted-browser-seconds-used",a))(mg||{}),Zi=(c=>(c.TestRunner="test-runner",c.Editor="editor",c.Mcp="mcp",c.Explore="explore",c.Heal="heal",c.ResultClassification="result-classification",c.GithubPrSummary="github-pr-summary",c.AppGraph="app-graph",c.RunViewer="run-viewer",c))(Zi||{}),jye=3;function $ye(e){return e==="MODULE"||e==="CONDITIONAL"||e==="WHILE_LOOP"||e==="SECTION"||e==="RESOLVED_MODULE"}function sW(e){if(!$ye(e))switch(e){case "PRESET_ACTION":return 0;case "AI_ACTION":return 3;case "AI_ACTION_DYNAMIC":return 5;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}function aW(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return jye;case "CAPTCHA":return 3;case "CLICK":case "TYPE":case "SELECT_OPTION":case "HOVER":case "ELEMENT_CHECK":case "FOCUS":case "BLUR":case "SCROLL_DOWN":case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_UP":case "MOUSE_DRAG":return e.useSelector||!e.target||e.target.type!=="description"?0:1;case "DRAG":return e.useSelector?0:1;case "VISUAL_DIFF":case "TAB":case "JAVASCRIPT":case "NAVIGATE":case "WAIT":case "SUCCESS":case "AUTH_LOAD":case "AUTH_SAVE":case "COOKIE":case "DIALOG":case "FILE_UPLOAD":case "GO_BACK":case "GO_FORWARD":case "LOCAL_STORAGE":case "NEW_TAB":case "CLOSE_TAB":case "PAGE_CHECK":case "PRESS":case "KEY_DOWN":case "KEY_UP":case "COPY":case "PASTE":case "REFRESH":case "REQUEST":case "GRAPHQL_REQUEST":case "WAIT_FOR_URL":case "REGISTER_REQUEST_LISTENER":case "AWAIT_LISTENER":case "RECORD_REQUESTS":case "GET_RECORDED_REQUESTS":case "SET_HEADER":case "MOCK_ROUTE":case "REMOVE_ROUTE_MOCK":case "OFFLINE_MODE":return 0;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}var GM=z$1.object({name:z$1.string(),value:z$1.string(),url:z$1.string().optional(),domain:z$1.string().optional(),path:z$1.string().optional(),expires:z$1.number().default(Date.now()/1e3+60*60*24*365),httpOnly:z$1.boolean().optional(),secure:z$1.boolean().default(true),sameSite:z$1.union([z$1.literal("Strict"),z$1.literal("Lax"),z$1.literal("None")]).default("None")});function BC(e,t){let n=[],o=splitCookiesString(e);for(let r of o){let i=parseString(r,{decodeValues:false});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let s;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")s="Strict";else if(d==="lax")s="Lax";else if(d==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=false),!i.path&&i.domain&&(i.path="/"),!i.domain&&t&&(i.domain=t);let a=GM.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:s});n.push(a);let l=[a.name,...Object.keys(a)].map(d=>d.toLowerCase()),c=r.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,p]=d.split("=");if(!u||!p)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||n.push({...a,name:u,value:p});}}return n}var Wye=z$1.object({origin:z$1.string(),localStorage:z$1.array(z$1.object({name:z$1.string(),value:z$1.string()})),sessionStorage:z$1.array(z$1.object({name:z$1.string(),value:z$1.string()})).optional()}),qye=z$1.object({entries:z$1.record(z$1.string(),z$1.array(z$1.tuple([z$1.unknown().optional(),z$1.unknown().optional()]))),version:z$1.number().optional()}),UC=z$1.object({cookies:GM.array().optional(),origins:Wye.array().optional(),idb:z$1.record(z$1.string(),qye).optional().describe("key is db name")});function lW(e,t){let n=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(o=>{let r=GM.safeParse({name:o.key,...o});if(!r.success)return;let i=r.data;!i.domain&&!i.url&&(i.domain=t),n.push(i);}),n}var es={type:true,cache:true},cW=[ed.pick(es),Wp.pick(es),KS.pick(es),XS.pick(es),WS.pick(es),VS.pick(es),GS.pick(es)],jM=O__default.discriminatedUnion("type",cW),dW=[ed.pick(es),qp.pick(es),YS.pick(es),QS.pick(es),qS.pick(es),jS.pick(es),zS.pick(es)],$M=O__default.discriminatedUnion("type",dW);Object.values(zt).filter(e=>cW.some(t=>t.shape.type.safeParse(e).success));Object.values(zt).filter(e=>dW.some(t=>t.shape.type.safeParse(e).success));var VM=O__default.object({type:O__default.literal("MOBILE_AI_ACTION_STEP"),cache:MM}),HC=O__default.union([jM,VM]),GC=O__default.union([$M,VM]);var zM=(s=>(s.US_EAST_1="us-east1",s.US_EAST_2="us-east2",s.US_WEST_1="us-west1",s.US_WEST_2="us-west2",s.EU_NORTH_1="eu-north1",s.AS_SOUTH_1="as-south1",s))(zM||{}),WM=(o=>(o.US="us",o.EU="eu",o.AS="as",o))(WM||{}),uW=(t=>(t.LOCAL="local",t))(uW||{}),qM=O__default.nativeEnum(zM).or(O__default.nativeEnum(WM)),KM=O__default.nativeEnum(zM).or(O__default.nativeEnum(WM)).or(O__default.nativeEnum(uW)),Yye="closest";KM.or(O__default.literal(Yye));var gg=(n=>(n.ANDROID_14="14",n.ANDROID_15="15",n))(gg||{});var jC=(t=>(t.IOS_26="26",t))(jC||{});var Jye=["1.56.1-lim.1","1.60.0-lim.1"],pW=O__default.enum(Jye);var mW=O__default.nativeEnum(gg).or(O__default.nativeEnum(jC));var Xye=O__default.object({disableMomenticAccessibilityTree:O__default.boolean().optional(),autoGrantPermissions:O__default.boolean().optional().describe("Automatically grant app permission prompts during the run. Android only."),autoAcceptAlerts:O__default.boolean().optional().describe("Automatically accept native alert dialogs. iOS only."),autoDismissAlerts:O__default.boolean().optional().describe("Automatically dismiss native alert dialogs. iOS only."),disableXmlSnapshots:O__default.boolean().optional().describe("Skip collecting XML snapshots during test runs. This can speed up test runs, but will cause the run viewer to show less information."),browserSettings:eg.optional(),locale:O__default.string().optional().describe("Device locale code (e.g. 'fr', 'en-us'). Sets the device language and region. iOS and Android.")}),Qye="avdId",Zye="iosDeviceType",eSe="iosVersion",YM=Xye.extend({region:KM.optional().describe('Where the emulator runs: "local" for an emulator on your machine, or a region for hosted emulators. Defaults to hosted emulators.'),remoteEmulatorSettings:O__default.object({androidVersion:O__default.nativeEnum(gg).optional()}).optional(),localEmulatorSettings:O__default.object({[Qye]:Qh,[Zye]:Qh,[eSe]:Qh}).optional(),geolocation:O__default.object({latitude:O__default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:O__default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:O__default.boolean().optional().describe("wait for stability before every targeting action")});var ob=O__default.object({retries:O__default.number().optional().describe("number of retries to run"),defaultChannel:O__default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:O__default.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:O__default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:Qh.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:Qh.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:YM.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:iM.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),hW=O__default.object({id:mo,description:O__default.string(),schemaVersion:O__default.string(),settings:ob.optional(),disabled:O__default.boolean().optional(),labels:O__default.array(O__default.string()).optional()}),fg=hW.extend({platform:O__default.literal("ANDROID").optional().default("ANDROID")}),yg=hW.extend({platform:O__default.literal("IOS")}),gW=O__default.discriminatedUnion("platform",[fg,yg]),fW=O__default.object({fileType:O__default.literal(De.MOBILE_TEST)}),yW=fW.merge(fg),SW=fW.merge(yg);O__default.discriminatedUnion("platform",[yW,SW]);var bW=fg.merge(O__default.object({steps:O__default.array(ql)})),TW=yg.merge(O__default.object({steps:O__default.array(td)}));O__default.discriminatedUnion("platform",[bW,TW]);var tSe=yW.merge(bW),nSe=SW.merge(TW);O__default.discriminatedUnion("platform",[tSe,nSe]);O__default.object({name:O__default.string(),steps:O__default.array(ql).optional(),settings:ob.optional()});var AW=fg.extend({steps:Wa.array(),beforeSteps:Wa.array().optional(),afterSteps:Wa.array().optional()}),EW=yg.extend({steps:qa.array(),beforeSteps:qa.array().optional(),afterSteps:qa.array().optional()});O__default.discriminatedUnion("platform",[AW,EW]);var oSe=AW.extend({name:O__default.string()}),rSe=EW.extend({name:O__default.string()});O__default.discriminatedUnion("platform",[oSe,rSe]);var Er=O__default.object({startTime:O__default.number(),endTime:O__default.number().optional(),durationMs:O__default.number().optional(),error:O__default.string().optional(),result:O__default.unknown().optional().optional(),attributes:O__default.record(O__default.string(),O__default.unknown().optional()),subSpans:O__default.lazy(()=>ESe.array())});var JM=Er.extend({type:O__default.literal("SECTION"),name:O__default.string()}),iSe=Er.extend({type:O__default.literal("GET_PAGE_STATE")}),sSe=Er.extend({type:O__default.literal("GET_PAGE_SCREENSHOT")}),aSe=Er.extend({type:O__default.literal("SMART_WAITING")}),lSe=Er.extend({type:O__default.literal("SCROLL_ELEMENT_INTO_VIEW")}),cSe=Er.extend({type:O__default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:O__default.string().optional(),result:O__default.object({id:O__default.number(),thoughts:O__default.string(),citations:No.array().optional()}).optional()}),dSe=Er.extend({type:O__default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:O__default.string().optional(),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({thoughts:O__default.string(),result:O__default.boolean(),citations:No.array().optional()}).optional()}),uSe=Er.extend({type:O__default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:O__default.string().optional(),browserStateSnapshotId:O__default.string().optional(),result:O__default.object({thoughts:O__default.string().optional(),result:O__default.unknown().optional().optional()}).optional()}),pSe=Er.extend({type:O__default.literal("ELEMENT_ASSERTION"),name:O__default.string(),result:O__default.object({success:O__default.boolean(),message:O__default.string().optional()}).optional()}),mSe=Er.extend({type:O__default.literal("BROWSER_INTERACTION"),name:O__default.string(),coordinates:O__default.object({x:O__default.number(),y:O__default.number()}).optional(),value:O__default.string().optional(),selector:O__default.string().optional()}),hSe=Er.extend({type:O__default.literal("CACHE_RESOLUTION"),resolutionMethod:O__default.string().optional(),cacheMissReason:O__default.nativeEnum(bh).optional(),targetSource:O__default.string().optional(),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({serializedElement:O__default.string()}).optional()}),gSe=Er.extend({type:O__default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({serializedElement:O__default.string()}).optional()}),fSe=Er.extend({type:O__default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({outcome:O__default.string(),logs:O__default.string().array().optional(),serializedElement:O__default.string().optional(),relativeClickPoint:O__default.object({x:O__default.number(),y:O__default.number()}).optional(),force:O__default.boolean().optional()}).optional()}),ySe=Er.extend({type:O__default.literal("WAIT_FOR_STABILITY")}),SSe=Er.extend({type:O__default.literal("GENERIC"),name:O__default.string()}),bSe=Er.extend({type:O__default.literal("PAGE_ASSERTION"),name:O__default.string(),result:O__default.object({success:O__default.boolean(),message:O__default.string().optional()}).optional()}),TSe=Er.extend({type:O__default.literal("AUTO_FOLLOW_NEW_TABS"),result:O__default.object({followed:O__default.boolean()}).optional()}),ASe=Er.extend({type:O__default.literal("VISUAL_DIFF"),name:O__default.string(),result:O__default.object({success:O__default.boolean(),message:O__default.string().optional()}).optional()});function CW(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var ESe=O__default.discriminatedUnion("type",[JM,iSe,sSe,aSe,lSe,cSe,dSe,uSe,pSe,mSe,gSe,hSe,fSe,ySe,bSe,ASe,SSe,TSe]);z$1.object({testId:z$1.string(),sessionId:z$1.string()});var vW=z$1.object({uploadUrl:z$1.string(),id:z$1.string()});new Set(Object.values(Vn));var bn={AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of a conditional check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",BLUR:"Remove focus from an element on the page.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",CLOSE_TAB:"Close a specified open tab or current tab if none specified.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock."};var CSe=z$1.string().refine(e=>Ld.valid(e),{error:"must be a valid semver string"});function XM(e){return Ld.parse(e)||void 0}function rb(e){if(e!==void 0)return e===true||e==="true"||e==="1"}var wW="on-fail";function IW(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var xW=(n=>(n.CLI="cli",n.MobileCLI="mobile-cli",n))(xW||{}),vSe=z$1.nativeEnum(xW),_W=(o=>(o.Error="error",o.Warn="warn",o.Info="info",o))(_W||{}),RSe=z$1.nativeEnum(_W),wSe=z$1.object({id:z$1.string(),level:RSe,versionRange:z$1.string(),announcement:z$1.string()});z$1.object({cliType:vSe,version:CSe});var PW=z$1.object({announcements:z$1.array(wSe)});var ib=55555,$C="momentic-code-eval.js";z$1.object({body:z$1.string(),to:z$1.string(),from:z$1.string()});z$1.object({from:z$1.string().optional(),to:z$1.string(),timeout:z$1.number().optional(),beforeDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional(),afterDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional()});z$1.object({timeoutMs:z$1.number().nonnegative().optional()}).optional();z$1.object({phoneNumber:z$1.string(),leaseToken:z$1.string()});var ISe=z$1.union([z$1.string(),z$1.date()]).transform(e=>e instanceof Date?e:new Date(e)),OW=z$1.object({phoneNumber:z$1.string(),expiresAt:ISe,leaseToken:z$1.string()});z$1.object({to:z$1.email(),from:z$1.string(),subject:z$1.string(),body:z$1.string(),html:z$1.string().optional()});z$1.object({inbox:z$1.string().transform(e=>e.toLowerCase()),afterDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional(),timeout:z$1.number().optional(),trimWhitespace:z$1.boolean().optional()});z$1.object({inbox:z$1.string(),limit:z$1.number().optional(),afterDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional(),trimWhitespace:z$1.boolean().optional()});var MW=z$1.object({email:z$1.string(),prefix:z$1.string(),expiresAt:z$1.coerce.date()}),VC=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(VC||{}),NW=z$1.object({body:z$1.string().nullish(),status:z$1.number().optional(),headers:z$1.array(z$1.tuple([z$1.string(),z$1.string()])).optional()}),xSe=z$1.object({url:z$1.string(),options:z$1.object({method:z$1.string(),body:z$1.string().nullish(),headers:z$1.array(z$1.tuple([z$1.string(),z$1.string()])).optional()}).optional()}).optional(),_Se=z$1.object({body:z$1.string().nullish(),options:z$1.object({status:z$1.number(),statusText:z$1.string().optional(),headers:z$1.array(z$1.tuple([z$1.string(),z$1.string()])).optional()}).optional()}).optional(),LW=z$1.object({result:z$1.unknown().optional(),variableUpdates:z$1.record(z$1.string(),z$1.unknown().optional()).optional(),persistentVariableUpdates:z$1.record(z$1.string(),z$1.unknown().optional()).optional(),error:z$1.string().optional(),success:z$1.boolean()});z$1.object({id:z$1.string().optional(),orgId:z$1.string(),momenticLambdaAuthHash:z$1.string(),code:z$1.string(),fragment:z$1.boolean(),state:z$1.object({env:z$1.record(z$1.string(),z$1.unknown().optional()),request:xSe,response:_Se,additionalBindings:z$1.record(z$1.string(),z$1.unknown().optional()).optional()}),timeoutMs:z$1.number().optional(),disallowVariableUpdates:z$1.boolean().optional(),responseSerialization:z$1.enum(VC).optional()});var Tu=9e4;var PSe=O.object({url:O.string(),lineNumber:O.number(),columnNumber:O.number()}),kW=O.object({timestamp:O.number(),text:O.string(),type:O.string(),tabIndex:O.number(),args:O.unknown().optional().array().optional(),url:O.string().optional(),location:PSe.optional()}),DW=kW.array(),QM=DW.array();var sb=class{async getConsoleLogsForRunAttempt(t,n,o){}async getNetworkLogsForRunAttempt(t,n,o){}async getHtmlSnapshot(t,n){}async getA11yTreeSnapshot(t,n){}async getScreenshot(t,n){}async storeConsoleLogsForRunAttempt(t,n,o,r){}async storeNetworkLogsForRunAttempt(t,n,o,r){}listVideoAssetPaths(){return []}close(){}async storeScreenshot(t,n,o){}async storeOnDemandScreenshotById(t,n,o,r){}async storeHtmlSnapshot(t,n,o){}};var OSe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),MSe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),NSe=z$1.object({onContentLoad:z$1.number().optional(),onLoad:z$1.number().optional(),comment:z$1.string().optional()}),ab=z$1.object({startedDateTime:z$1.string(),id:z$1.string(),title:z$1.string().optional(),pageTimings:NSe,comment:z$1.string().optional()}),LSe=z$1.array(ab),kSe=z$1.object({name:z$1.string(),value:z$1.string(),path:z$1.string().optional(),domain:z$1.string().optional(),expires:z$1.string().optional(),httpOnly:z$1.boolean().optional(),secure:z$1.boolean().optional(),comment:z$1.string().optional()}),BW=z$1.array(kSe),DSe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),UW=z$1.array(DSe),FSe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),BSe=z$1.array(FSe),USe=z$1.object({name:z$1.string(),value:z$1.string().optional(),fileName:z$1.string().optional(),contentType:z$1.string().optional(),comment:z$1.string().optional()}),HSe=z$1.array(USe),GSe=z$1.object({mimeType:z$1.string(),params:HSe,text:z$1.string(),comment:z$1.string().optional(),_redactedReason:z$1.string().optional()}),jSe=z$1.object({method:z$1.string(),url:z$1.string(),httpVersion:z$1.string().optional(),cookies:BW,headers:UW,queryString:BSe,postData:GSe.optional(),headersSize:z$1.number().optional(),bodySize:z$1.number().optional(),comment:z$1.string().optional()}),$Se=z$1.object({size:z$1.number().optional(),compression:z$1.number().optional(),mimeType:z$1.string().optional(),text:z$1.string().optional(),encoding:z$1.string().optional(),comment:z$1.string().optional(),_redactedReason:z$1.string().optional()}),VSe=z$1.object({status:z$1.number(),statusText:z$1.string(),httpVersion:z$1.string().optional(),cookies:BW,headers:UW,content:$Se,redirectURL:z$1.string().optional(),headersSize:z$1.number().optional(),bodySize:z$1.number().optional(),comment:z$1.string().optional(),_mocked:z$1.boolean().optional()}),FW=z$1.object({expires:z$1.string().optional(),lastAccess:z$1.string(),eTag:z$1.string(),hitCount:z$1.number(),comment:z$1.string().optional()}),zSe=z$1.object({beforeRequest:FW.optional(),afterRequest:FW.optional(),comment:z$1.string().optional()}),WSe=z$1.object({blocked:z$1.number().optional(),dns:z$1.number().optional(),connect:z$1.number().optional(),send:z$1.number(),wait:z$1.number(),receive:z$1.number(),ssl:z$1.number().optional(),comment:z$1.string().optional()}),lb=z$1.object({pageref:z$1.string().optional(),startedDateTime:z$1.string(),time:z$1.number().optional(),request:jSe,response:VSe.optional(),cache:zSe.optional(),timings:WSe,serverIPAddress:z$1.string().optional(),connection:z$1.string().optional(),comment:z$1.string().optional(),_resourceType:z$1.string().optional()}),qSe=z$1.array(lb),KSe=z$1.object({version:z$1.string().default("1.1"),creator:OSe.optional(),browser:MSe.optional(),pages:LSe.optional(),entries:qSe,comment:z$1.string().optional()});z$1.object({log:KSe});z$1.record(z$1.string(),ab);z$1.record(z$1.string(),lb);function ZM(e,t){return {log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(e).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime()),entries:Object.values(t).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime())}}}var eN=(E=>(E.DisableClickhouseCaches="disable_clickhouse_caches",E.ShowZeroOpacityElements="show_zero_opacity_elements",E.VisualActions="visual_actions",E.RagV2="rag_v2",E.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",E.GlobalLocatorRedirect="global_locator_redirect",E.FakerConstantSeed="faker_constant_seed",E.AutoExpandIframes="auto_expand_iframes",E.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",E.PerformanceInsights="performance_insights",E.ShowKnowledgeBase="show_knowledge_base",E.AppGraphBackend="app_graph_backend",E.AppGraphUI="app_graph_ui",E.ClassificationUI="classification_ui",E.HealingUI="healing_ui",E.ExploreUI="explore_ui",E.SlackNotifications="slack_notifications",E.SlackNotificationDms="slack_notification_dms",E.ResultClassificationCache="result_classification_cache",E.HealTraceUI="heal_trace_ui",E))(eN||{});var Au=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null(),z$1.record(z$1.string(),z$1.lazy(()=>Au)),z$1.array(z$1.lazy(()=>Au))]),cb=class{flags;payloads;constructor(t,n){this.flags=t,this.payloads=n;}isBooleanFlagEnabled(t){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="true"?true:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="false"?false:this.flags[t]===true}getAllFlags(){let t=cloneDeep(this.flags);return Object.entries(t).forEach(([n,o])=>{typeof o=="boolean"&&Object.values(eN).includes(n)&&(t[n]=this.isBooleanFlagEnabled(n));}),t}getFlagPayload(t){let n=this.payloads[t];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}};var db={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},HW=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var GW=z$1.discriminatedUnion("operation",[z$1.object({operation:z$1.literal("upsert"),path:z$1.string().min(1),content:z$1.string()}),z$1.object({operation:z$1.literal("delete"),path:z$1.string().min(1)})]),XSe=z$1.object({githubLogin:z$1.string().optional(),email:z$1.string().optional()}),QSe=z$1.object({baseSha:z$1.string().min(1),headSha:z$1.string().min(1)}),ZSe=z$1.object({baseBranch:z$1.string().min(1).max(255),baseCommitSha:z$1.string().min(1),headBranch:z$1.string().min(1).max(255).optional(),branchPrefix:z$1.string().min(1).max(255).optional(),idempotencyKey:z$1.string().min(1).optional()}),ebe=z$1.object({commitMessage:z$1.string().min(1),title:z$1.string().min(1),body:z$1.string(),reviewers:z$1.array(z$1.string().min(1)).optional(),draft:z$1.boolean().optional()});ZSe.extend(ebe.shape).extend({changes:z$1.array(GW).min(1),coAuthorRange:QSe.optional(),requestCommitAuthorsAsReviewers:z$1.boolean().optional()}).superRefine((e,t)=>{e.headBranch||(!e.branchPrefix||!e.idempotencyKey)&&t.addIssue({code:"custom",message:"branchPrefix and idempotencyKey are required when headBranch is omitted",path:["idempotencyKey"]});});var jW=z$1.object({pullRequestUrl:z$1.url(),pullRequestNumber:z$1.number(),headBranch:z$1.string(),commitSha:z$1.string(),created:z$1.boolean(),authors:z$1.array(XSe).optional()});z$1.object({branch:z$1.string().min(1).max(255),commitMessage:z$1.string().min(1),changes:z$1.array(GW).min(1)});var $W=z$1.object({branch:z$1.string(),commitSha:z$1.string(),committed:z$1.boolean()}),VW=z$1.object({issueNumber:z$1.number(),htmlUrl:z$1.url(),headBranch:z$1.string().min(1),baseBranch:z$1.string().min(1),latestCommitSha:z$1.string().min(1),draft:z$1.boolean().optional(),title:z$1.string().optional(),body:z$1.string().optional()});z$1.object({number:z$1.number(),htmlUrl:z$1.url()});var tbe=z$1.object({path:z$1.string().min(1),status:z$1.string().min(1),additions:z$1.number(),deletions:z$1.number(),previousPath:z$1.string().optional(),patch:z$1.string().optional()}),nbe=z$1.object({sha:z$1.string().min(1),author:z$1.string().optional(),email:z$1.string().optional(),date:z$1.string().optional(),message:z$1.string()}),zW=z$1.object({mergeBaseSha:z$1.string().min(1),totalCommits:z$1.number(),commits:z$1.array(nbe),files:z$1.array(tbe)}),WW=z$1.object({content:z$1.string().nullable()}),qW=z$1.object({name:z$1.string().min(1),protected:z$1.boolean()}),KW=z$1.object({iid:z$1.number(),webUrl:z$1.url(),sourceBranch:z$1.string().min(1),targetBranch:z$1.string().min(1),latestCommitSha:z$1.string().min(1)}),obe=z$1.object({name:z$1.string(),path:z$1.string(),body:z$1.string()}),YW=z$1.object({template:obe});function ir(e){let[t,n,...o]=e.split("/");if(!(!t||!n||o.length>0))return {owner:t,repo:n}}function JW(e){let t=ir(e);if(t)return t;throw new mt(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var rbe=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,ibe=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function zC(e){return e.match(ibe)?.[1]}function XW(e){let t=[];for(let n of e.matchAll(rbe)){let o=n[1]?.trim();o&&t.push({email:o,githubLogin:zC(o)});}return t}function sbe(e){return (e.githubLogin??(e.email?zC(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function QW(e){return e.filter(t=>!sbe(t))}var ZW="https://static.momentic.ai";function ub(e,t){return {light:`${ZW}/${e}.svg`,dark:`${ZW}/${e}-dark.svg`,alt:t}}var pb={runGroup:ub("run-group-button","View run group"),basePr:ub("view-base-pr-button","View base PR"),branch:ub("view-branch-button","View branch"),commit:ub("view-commit-button","View commit")};function mb({href:e,button:t}){return `<a href="${e}"><picture><source media="(prefers-color-scheme: dark)" srcset="${t.dark}" /><img src="${t.light}" alt="${t.alt}" /></picture></a>`}var tN=O__default.object({platformSep:O__default.string(),fullPathSegments:O__default.string().array(),relativePathSegments:O__default.string().array(),relativePath:O__default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:O__default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:O__default.coerce.date(),createdAt:O__default.coerce.date()});var abe=z$1.array(tN.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),labels:z$1.string().array().optional()})),lbe=tN.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),content:WE}),cbe=z$1.array(lbe);z$1.object({tests:abe,modules:cbe,labels:z$1.string().array()});z$1.string().array();var e1=z$1.object({pathSegments:z$1.string().array()});dM.merge(Zn);var t1=z$1.object({schemaVersion:z$1.string(),stepLists:Dl}),n1=Zn.partial().merge(Zr.pick({id:true})),Xp="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",nN={name:z$1.string().min(1).max(255).describe(Xp),description:z$1.string().optional(),baseUrl:z$1.url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:z$1.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:z$1.enum(jl).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Jc.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:z$1.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder. Paths are relative to the project root.")},o1=z$1.object(nN);dM.extend(z$1.object({relativeFilePath:z$1.string().describe("relative to project root")}).shape);var r1=z$1.object({name:z$1.string()});z$1.object({relativeFilePath:z$1.string()});var i1=z$1.object({name:z$1.string(),sourceModuleContent:WE});z$1.object({relativeFilePath:z$1.string()});var s1=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean(),steps:z$1.lazy(()=>Gt.array()),testFilePath:z$1.string().describe("relative to the project root"),folderPath:z$1.string().optional().describe("user selected folder path")}),a1=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean()}).partial(),l1=z$1.object({folderPath:z$1.string()}),c1=z$1.object({folderPath:z$1.string()});z$1.array(CS);var d1=z$1.object({defaultEnv:z$1.string().optional().describe("name of the default env, or undefined to unset")}),u1=z$1.object({configFilePath:z$1.string().describe("full path on disk")});z$1.string().array();z$1.object({message:z$1.string(),newRelativeTestPath:z$1.string().optional()});var oN=z$1.object({name:z$1.string(),absolutePath:z$1.string(),relativePath:z$1.string(),pathSegments:z$1.array(z$1.string()),isDirectory:z$1.boolean(),size:z$1.number(),createdAt:z$1.coerce.date(),modifiedAt:z$1.coerce.date(),accessedAt:z$1.coerce.date()}),p1=z$1.object({pathSegments:z$1.array(z$1.string())});z$1.object({absolutePath:z$1.string(),pathSegments:z$1.array(z$1.string()),contents:z$1.array(oN)});var m1=z$1.object({sourceDirectoryPath:z$1.string().optional(),value:z$1.string(),allowedExtensions:z$1.array(z$1.string()).optional()}),dbe=z$1.object({name:z$1.string(),value:z$1.string(),isDirectory:z$1.boolean()});z$1.object({suggestions:z$1.array(dbe)});var h1=z$1.object({pathSegments:z$1.array(z$1.string())}),g1=z$1.object({pathSegments:z$1.array(z$1.string()),newPathSegments:z$1.array(z$1.string())}),f1=z$1.object({pathSegments:z$1.array(z$1.string()),recursive:z$1.boolean().optional()});z$1.object({success:z$1.boolean(),message:z$1.string(),pathSegments:z$1.array(z$1.string()).optional()});z$1.object({gitBranch:z$1.string(),fileMtime:z$1.coerce.date(),gitCommitSha:z$1.string()});var y1=typeof process<"u"&&true&&true,WC=58889,bg=24*60*60*1e3;var S1=z$1.object({id:z$1.string(),createdAt:z$1.coerce.date(),createdBy:z$1.string(),organizationId:z$1.string(),name:z$1.string(),description:z$1.string().nullish(),enabled:z$1.boolean(),schemaVersion:z$1.string().describe("Schema version for steps"),parameters:z$1.string().array().nullish().describe("Parameter list"),parameterEnums:z$1.record(z$1.string(),z$1.string().array()).nullish(),defaultParameters:z$1.record(z$1.string(),z$1.string()).nullish(),defaultCacheKey:z$1.string().nullish(),defaultCacheTtl:z$1.number().nullish(),defaultCacheAllInvocations:z$1.boolean().nullish(),autoAuth:z$1.boolean().nullish(),defaultRetries:z$1.int().min(0).nullish(),advanced:OO.nullish()});S1.extend({steps:z$1.lazy(()=>Nt.array())});var b1=5*60*1e3,hb=Xn.extend(S1.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var ube="org_01HMJTX4GT1KG94KZRCT8MZ6YB",pbe="org_01HMSCJQBCCG51M2ZF65YC5B8W",mbe="org_01JPR6MGFQSHF3W234R3XJDPMB",hbe=[ube,pbe,mbe];function T1(e){return hbe.includes(e)}var A1=(o=>(o.AZURE="AZURE",o.KERNEL="KERNEL",o.BROWSERBASE="BROWSERBASE",o))(A1||{}),rN=z$1.enum(A1);z$1.object({azureRegion:z$1.string().optional(),azureWorkspaceId:z$1.string().optional()});z$1.object({});var gbe=z$1.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z$1.object({region:gbe.optional()});var iN=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(iN||{});var fbe=z$1.object({type:z$1.literal("DESCRIPTION_UPDATE"),thoughts:z$1.string()}),qC=z$1.discriminatedUnion("type",[fbe]),ybe=z$1.object({testId:z$1.string(),name:z$1.string(),orgId:z$1.string(),runId:z$1.string(),steps:Gt.array(),purpose:z$1.enum(iN),details:qC.or(qC.array()).optional()});ybe.pick({name:true,orgId:true});var Sbe=z$1.object({id:z$1.string(),name:z$1.string().nullish(),createdAt:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()),organizationId:z$1.string(),schemaVersion:z$1.string(),runId:z$1.string().nullish(),purpose:z$1.enum(iN),details:qC.or(qC.array()).optional(),applied:z$1.boolean().nullish(),appliedAt:z$1.coerce.date().nullish()}),E1=Sbe.extend({steps:Gt.array()});var C1=z$1.enum(["v1","v2"]);var Tbe=z$1.enum(["element","content","attribute","tag_name","style"]),KC=z$1.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...dj,...cj].forEach(e=>{if(!KC.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var sN={element:{aliasPrefix:"",assertionType:"ELEMENT_EXISTENCE",requiresName:false},content:{aliasPrefix:"Content",assertionType:"ELEMENT_CONTENT",requiresName:false},attribute:{aliasPrefix:"Attribute",assertionType:"ELEMENT_ATTRIBUTE",requiresName:true},tag_name:{aliasPrefix:"Name",assertionType:"ELEMENT_NAME",requiresName:false},style:{aliasPrefix:"Style",assertionType:"ELEMENT_STYLE",requiresName:true}},w1={exists:{positiveAliasSuffix:"Exists",negativeAliasSuffix:"DoesNotExist",elementCondition:"EXISTS",contentOperation:"EXISTS"},visible:{positiveAliasSuffix:"Visible",negativeAliasSuffix:"NotVisible",elementCondition:"VISIBLE"},enabled:{positiveAliasSuffix:"Enabled",negativeAliasSuffix:"NotEnabled",elementCondition:"ENABLED"},editable:{positiveAliasSuffix:"Editable",negativeAliasSuffix:"NotEditable",elementCondition:"EDITABLE"},focused:{positiveAliasSuffix:"Focused",negativeAliasSuffix:"NotFocused",elementCondition:"FOCUSED"},contains:{positiveAliasSuffix:"Contains",negativeAliasSuffix:"DoesNotContain",contentOperation:"CONTAINS"},equals:{positiveAliasSuffix:"Equals",negativeAliasSuffix:"DoesNotEqual",contentOperation:"EQUALS"},starts_with:{positiveAliasSuffix:"StartsWith",negativeAliasSuffix:"DoesNotStartWith",contentOperation:"STARTS_WITH"}},I1={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function v1(e){return {alias:aN(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:sN[e.subject].assertionType,requiresName:sN[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function aN(e){let t=sN[e.subject],n=w1[e.condition];if(!x1(e.subject,e.condition))throw new Error(`Unsupported element check alias for subject '${e.subject}' and condition '${e.condition}'.`);let o=e.negated?n.negativeAliasSuffix:n.positiveAliasSuffix;return `checkElement${t.aliasPrefix}${o}`}function x1(e,t){let n=w1[t],o=n.elementCondition,r=n.contentOperation;return e==="element"?o!==void 0:r!==void 0}var Abe=Tbe.options.flatMap(e=>KC.options.flatMap(t=>x1(e,t)?[v1({subject:e,condition:t,negated:false}),v1({subject:e,condition:t,negated:true})]:[])),_1=new Map(Abe.map(e=>[e.alias,e]));var Ebe=z$1.enum(_l),Cbe=z$1.enum(fs);function _i(e){return _1.get(e)}function O1(e){let t=I1[e.type],n=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return aN({subject:t,condition:vbe(n),negated:e.negated})}function M1(e){return Ebe.parse(e.toUpperCase())}function gb(e){return Cbe.parse(e.toUpperCase())}function vbe(e){return KC.parse(e.toLowerCase())}var tt={saveAs:z$1.string().optional(),retries:z$1.number().optional(),skipped:z$1.boolean().optional(),comment:z$1.string().optional()};z$1.object(tt);var fb=Object.keys(tt);function qe(e){return z$1.union([z$1.strictObject({[e.key]:e.simplified}),z$1.strictObject({[e.key]:e.detailed})])}function qn(e){return z$1.strictObject({[e.key]:e.detailed})}var N1='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Tg=z$1.union([wl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,N1)],{error:N1});z$1.union([z$1.string(),wl]);var Ps={css:z$1.string().optional(),coords:Tg.optional(),x:z$1.union([z$1.number(),z$1.string()]).optional(),y:z$1.union([z$1.number(),z$1.string()]).optional()},cN={on:z$1.string().optional(),...Ps},Os={...tt,useSelector:z$1.boolean().optional(),force:z$1.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional()},yb={...Os,offset:Tg.optional()};function Pi({schema:e,descriptionKey:t,required:n=true}){return e.superRefine((o,r)=>{let s=[t in o?Object.entries(o).find(([a])=>a===t)?.[1]:void 0,"css"in o?o.css:void 0,"coords"in o?o.coords:void 0,"x"in o||"y"in o?true:void 0].filter(a=>a!==void 0).length;n&&s!==1&&r.addIssue({code:"custom",message:`Use exactly one target: ${t}, css, coords, or x/y.`}),!n&&s>1&&r.addIssue({code:"custom",message:`Use at most one target: ${t}, css, coords, or x/y.`}),("x"in o||"y"in o)&&(!("x"in o)||o.x===void 0||!("y"in o)||o.y===void 0)&&r.addIssue({code:"custom",message:"x and y must be provided together."});})}var Rbe=Pi({descriptionKey:"on",schema:z$1.strictObject({...cN,...yb,times:z$1.int().min(1).optional(),rightClick:z$1.boolean().optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),wbe=Pi({descriptionKey:"on",schema:z$1.strictObject({...cN,...yb,rightClick:z$1.boolean().optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),Ibe=Pi({descriptionKey:"on",schema:z$1.strictObject({...cN,...yb,times:z$1.int().min(1).optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),L1=qe({key:"click",simplified:z$1.string(),detailed:Rbe}),k1=qe({key:"doubleClick",simplified:z$1.string(),detailed:wbe}),D1=qe({key:"rightClick",simplified:z$1.string(),detailed:Ibe}),xbe=Pi({descriptionKey:"into",required:false,schema:z$1.strictObject({text:z$1.string(),into:z$1.string().optional(),...Ps,...yb,pressEnter:z$1.boolean().optional(),clear:z$1.union([z$1.literal("inputs"),z$1.literal("always"),z$1.literal("never"),z$1.boolean()]).optional(),delay:z$1.number().optional()})}),F1=qe({key:"type",simplified:z$1.string(),detailed:xbe}),B1=qn({key:"select",detailed:Pi({descriptionKey:"from",schema:z$1.strictObject({from:z$1.string().optional(),...Ps,label:z$1.string().optional(),value:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),...Os})}).superRefine((e,t)=>{[e.label,e.value,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"select requires exactly one of label, value, or index"});})}),U1=qe({key:"hover",simplified:z$1.string(),detailed:Pi({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...Ps,...yb})})}),H1=qn({key:"blur",detailed:Pi({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...Ps,...Os})})}),G1=qe({key:"focus",simplified:z$1.string(),detailed:Pi({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...Ps,...Os})})}),j1=qn({key:"dragAndDrop",detailed:z$1.strictObject({from:z$1.string().optional(),to:z$1.string().optional(),fromCss:z$1.string().optional(),toCss:z$1.string().optional(),fromCoords:Tg.optional(),toCoords:Tg.optional(),fromX:z$1.union([z$1.number(),z$1.string()]).optional(),fromY:z$1.union([z$1.number(),z$1.string()]).optional(),toX:z$1.union([z$1.number(),z$1.string()]).optional(),toY:z$1.union([z$1.number(),z$1.string()]).optional(),steps:z$1.number().optional(),hover:z$1.number().optional(),...Os}).superRefine((e,t)=>{let n=[e.from,e.fromCss,e.fromCoords,e.fromX!==void 0||e.fromY!==void 0?true:void 0].filter(r=>r!==void 0).length,o=[e.to,e.toCss,e.toCoords,e.toX!==void 0||e.toY!==void 0?true:void 0].filter(r=>r!==void 0).length;n!==1&&t.addIssue({code:"custom",message:"Use exactly one from target."}),o!==1&&t.addIssue({code:"custom",message:"Use exactly one to target."}),(e.fromX!==void 0||e.fromY!==void 0)&&(e.fromX===void 0||e.fromY===void 0)&&t.addIssue({code:"custom",message:"fromX and fromY must be provided together."}),(e.toX!==void 0||e.toY!==void 0)&&(e.toX===void 0||e.toY===void 0)&&t.addIssue({code:"custom",message:"toX and toY must be provided together."});})}),$1=z$1.union([z$1.strictObject({mouseDrag:Tg}),z$1.strictObject({mouseDrag:Pi({descriptionKey:"from",required:false,schema:z$1.strictObject({from:z$1.string().optional(),...Ps,delta:Tg,steps:z$1.number().optional(),...Os})})})]),V1=qe({key:"press",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),repeat:z$1.number().optional(),delay:z$1.number().optional(),convertMeta:z$1.boolean().optional(),...tt})}),z1=qe({key:"keyDown",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...tt})}),W1=qe({key:"keyUp",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...tt})}),q1=qe({key:"navigate",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:z$1.number().optional(),...tt})}),K1=qe({key:"newTab",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:z$1.number().optional(),...tt})}),Y1=qe({key:"switchTab",simplified:z$1.union([z$1.number(),z$1.string()]),detailed:z$1.strictObject({substring:z$1.string().optional(),regex:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"switchTab requires exactly one of substring, regex, or index"});})}),J1=qn({key:"closeTab",detailed:z$1.strictObject({substring:z$1.string().optional(),regex:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length<=1||t.addIssue({code:"custom",message:"closeTab accepts at most one of substring, regex, or index"});})}),X1=qn({key:"goBack",detailed:z$1.strictObject(tt)}),Q1=qn({key:"goForward",detailed:z$1.strictObject(tt)}),Z1=qn({key:"refresh",detailed:z$1.strictObject({timeout:z$1.number().optional(),...tt})}),YC=z$1.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),eq=qe({key:"scrollUp",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),tq=qe({key:"scrollDown",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),nq=qe({key:"scrollLeft",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),oq=qe({key:"scrollRight",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),rq=qe({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...tt})}),_be=qe({key:"assert",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),source:z$1.string().optional(),...tt})}),Pbe=qe({key:"assertVisually",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),source:z$1.string().optional(),...tt})}),JC=_be,XC=Pbe,iq=qe({key:"checkPageContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...tt})}),sq=qe({key:"checkPageDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...tt})}),dN=z$1.union([iq,sq]),Obe=z$1.record(z$1.string(),z$1.unknown().optional()),QC=Obe.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=_i(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=Pi({descriptionKey:"element",schema:z$1.looseObject({element:z$1.string().optional(),...Ps,...Os,timeout:z$1.number().optional(),name:z$1.string().optional(),value:z$1.string().optional()})}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),aq=qe({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:Au.optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),...tt})}),lq=qe({key:"cookie",simplified:z$1.string(),detailed:z$1.strictObject({value:z$1.string(),...tt})}),cq=qn({key:"localStorage",detailed:z$1.strictObject({key:z$1.string(),value:z$1.string(),...tt})}),dq=qe({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:Gc.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),params:z$1.record(z$1.string(),z$1.string()).optional(),body:Au.optional(),contentType:z$1.enum(Pl).optional(),timeout:z$1.number().optional(),...tt})}),uq=qn({key:"graphqlRequest",detailed:z$1.strictObject({url:z$1.string(),query:z$1.string(),variables:Au.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),timeout:z$1.number().optional(),...tt})}),ZC=qe({key:"javascript",simplified:z$1.string(),detailed:z$1.strictObject({code:z$1.string(),environment:z$1.enum(["node","browser","NODE","BROWSER"]).optional(),fragment:z$1.boolean().optional(),timeout:z$1.number().optional(),...tt})}),Ag={substring:z$1.string().optional(),glob:z$1.string().optional(),regex:z$1.string().optional(),domain:z$1.string().optional()};function Mbe(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Eg(e){let t=Mbe(e.payload);if(e.required&&t!==1||!e.required&&t>1){e.ctx.addIssue({code:"custom",message:e.required?"requires exactly one of substring, glob, regex, or domain":"requires at most one of substring, glob, regex, or domain"});return}!e.required&&t===0&&e.payload.method&&e.ctx.addIssue({code:"custom",message:"method requires a URL matcher"});}var pq=qn({key:"header",detailed:z$1.strictObject({name:z$1.string(),value:z$1.string(),...Ag,method:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:false});})}),mq=qn({key:"mock",detailed:z$1.strictObject({...Ag,method:z$1.string().optional(),responseGenerator:z$1.string(),fetchOriginalResponse:z$1.boolean().optional(),key:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),hq=qe({key:"removeRouteMock",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string().optional(),...tt})}),gq=qe({key:"waitForUrl",simplified:z$1.string(),detailed:z$1.strictObject({...Ag,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),fq=qe({key:"waitForUrlNotToMatch",simplified:z$1.string(),detailed:z$1.strictObject({...Ag,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),Nbe=z$1.union([gq,fq]),yq=qe({key:"dialog",simplified:z$1.enum(["ACCEPT","DISMISS"]),detailed:z$1.strictObject({action:z$1.enum(["ACCEPT","DISMISS"]),...tt})}),Sq=qe({key:"fileUpload",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),name:z$1.string().optional(),...tt})}),bq=qe({key:"copy",simplified:z$1.union([z$1.string(),z$1.boolean(),z$1.null()]),detailed:z$1.strictObject({value:z$1.union([z$1.string(),z$1.boolean(),z$1.null()]),...tt})}),Tq=qn({key:"paste",detailed:z$1.strictObject(tt)}),Aq=qn({key:"captcha",detailed:z$1.strictObject({...Os})}),Lbe=z$1.strictObject({data:z$1.union([z$1.string(),La]),width:z$1.number(),height:z$1.number()}),Eq=qe({key:"visualDiff",simplified:z$1.string(),detailed:Pi({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...Ps,threshold:z$1.number().optional(),screenshot:Lbe.optional(),...Os})})}),Cq=qn({key:"offline",detailed:z$1.strictObject(tt)}),vq=qn({key:"online",detailed:z$1.strictObject(tt)}),Rq=qn({key:"registerRequestListener",detailed:z$1.strictObject({...Ag,key:z$1.string(),method:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),wq=qe({key:"awaitListener",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),timeout:z$1.number().optional(),...tt})}),Iq=qn({key:"recordRequests",detailed:z$1.strictObject({...Ag,key:z$1.string(),method:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),xq=qe({key:"getRecordedRequests",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),...tt})}),_q=qe({key:"authLoad",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...tt})}),Pq=qe({key:"authSave",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string().optional(),...tt})});z$1.union([L1,k1,D1,Y1,J1,F1,B1,U1,H1,G1,j1,$1,V1,z1,W1,q1,K1,X1,Q1,Z1,eq,tq,nq,oq,rq,JC,XC,dN,aq,lq,cq,dq,uq,ZC,pq,mq,hq,Nbe,yq,Sq,bq,Tq,Aq,Eq,Cq,vq,Rq,wq,Iq,xq,_q,Pq,QC]);var Oq=new Map([["click",L1],["doubleClick",k1],["rightClick",D1],["switchTab",Y1],["closeTab",J1],["type",F1],["select",B1],["hover",U1],["blur",H1],["focus",G1],["dragAndDrop",j1],["mouseDrag",$1],["press",V1],["keyDown",z1],["keyUp",W1],["navigate",q1],["newTab",K1],["goBack",X1],["goForward",Q1],["refresh",Z1],["scrollUp",eq],["scrollDown",tq],["scrollLeft",nq],["scrollRight",oq],["wait",rq],["assert",JC],["assertVisually",XC],["checkPageContains",iq],["checkPageDoesNotContain",sq],["extract",aq],["cookie",lq],["localStorage",cq],["request",dq],["graphqlRequest",uq],["javascript",ZC],["header",pq],["mock",mq],["removeRouteMock",hq],["waitForUrl",gq],["waitForUrlNotToMatch",fq],["dialog",yq],["fileUpload",Sq],["copy",bq],["paste",Tq],["captcha",Aq],["visualDiff",Eq],["offline",Cq],["online",vq],["registerRequestListener",Rq],["awaitListener",wq],["recordRequests",Iq],["getRecordedRequests",xq],["authLoad",_q],["authSave",Pq]]),Mq=Object.freeze([...Oq.keys()]),Xl=z$1.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"Steps must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"Steps must have exactly one action key."});return}let r=Oq.get(o)??(_i(o)?QC:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported step type '${o}'.`});return}let i=r.safeParse(e);if(!i.success){let s=kbe(i.error.issues,o);s.length>0&&Nq(t,s);}});function kbe(e,t){return Dbe(e).filter(n=>!Fbe(n,t))}function Nq(e,t){for(let n of t){if(n.code==="invalid_union"){Nq(e,uN(n));continue}e.addIssue({...n});}}function Dbe(e){let t=[];for(let n of e){if(n.code==="invalid_union"){t.push(...uN(n));continue}t.push(n);}return t}function Fbe(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function uN(e){let t=e.errors[0]??[],n=lN(t);for(let o of e.errors.slice(1)){let r=lN(o);r>n&&(t=o,n=r);}return t}function lN(e){return e.reduce((t,n)=>{let o=n.code==="invalid_union"?lN(uN(n)):0;return t+n.path.length+o},0)}var Lq=z$1.strictObject({string:z$1.string()}),Bbe=z$1.strictObject({javascript:z$1.string()}),kq=z$1.union([Lq,Bbe]),Ube=z$1.union([z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),default:Lq.optional()}),z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),defaultValue:z$1.string()})]),Dq=Ube.array(),Hbe=z$1.strictObject({name:z$1.string(),default:kq.optional(),enum:z$1.array(z$1.string()).optional()}),Fq=Hbe.array(),Sb=z$1.union([kq,z$1.string()]),Bq=z$1.record(z$1.string(),Sb);var Gbe=z$1.preprocess(e=>typeof e=="number"?String(e):e,bO),ev=z$1.looseObject({goal:z$1.string(),version:Gbe.optional(),...tt}),jbe=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:ev})]),pN=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),Sb).optional(),...tt}),$be=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:pN})]),id=z$1.union([JC,XC,dN,ZC,QC]),Vbe=new Set(["then",...fb]),zbe=z$1.looseObject({then:z$1.lazy(()=>Ka.array()),...tt}).superRefine((e,t)=>{Object.entries(e).filter(([o,r])=>!Vbe.has(o)&&id.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),Wbe=z$1.strictObject({if:zbe}),qbe=new Set(["do","maxIterations",...fb]),Kbe=z$1.looseObject({do:z$1.lazy(()=>Ka.array()),maxIterations:z$1.number().int().positive().optional(),...tt}).superRefine((e,t)=>{let n=Object.entries(e).filter(([o,r])=>!qbe.has(o)&&id.safeParse({[o]:r}).success).length;if(n>1){t.addIssue({code:"custom",message:"While loops accept at most one condition at the top level."});return}n===0&&e.maxIterations===void 0&&t.addIssue({code:"custom",message:"While loops require a condition or a maximum number of iterations."});}),Ybe=z$1.strictObject({while:Kbe}),Ka=z$1.lazy(()=>z$1.union([YC,jbe,$be,Wbe,Ybe,Xl]));z$1.object({before:Ka.array().optional(),steps:Ka.array(),after:Ka.array().optional()});var Jbe=z$1.union([Jc,z$1.string().refine(e=>{let t=e.match(/^\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*$/);if(!t)return false;let[,n,o]=t;return Jc.safeParse({width:Number(n),height:Number(o)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),Xbe=Cs.omit({viewport:true}).extend({viewport:Jbe.optional()}),mN=z$1.object({id:mo,version:z$1.string().optional(),url:KE.optional(),description:z$1.string().optional(),retries:z$1.number().optional(),defaultEnv:z$1.string().optional(),parameters:Dq.optional(),outputs:SC.optional(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional()}).extend(Xbe.shape),Cu=z$1.looseObject({fileType:z$1.literal(De.TEST_V2)}).extend(mN.shape).extend({before:Ka.array().optional(),steps:Ka.array(),after:Ka.array().optional()});var Qbe=z$1.array(z$1.string()),Zbe=z$1.union([z$1.string(),z$1.record(z$1.string(),z$1.unknown().optional())]),tv=Xn.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:mo,version:z$1.string().optional(),name:z$1.string().optional(),parameters:z$1.union([Fq,Qbe]).optional(),defaultParameters:z$1.record(z$1.string(),z$1.string()).optional(),parameterEnums:z$1.record(z$1.string(),z$1.array(z$1.string())).optional()}),nv=z$1.looseObject(tv.extend({fileType:z$1.literal(De.MODULE_V2),steps:Zbe.array().optional()}).shape).superRefine(Hq),ov=z$1.looseObject(tv.extend({fileType:z$1.literal(De.MODULE_V2),steps:Ka.array().optional()}).shape).superRefine(Hq);function Uq(e){return e.steps??[]}function Hq(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var hN=(n=>(n.TEST="TEST",n.MODULE="MODULE",n))(hN||{}),eTe=z$1.enum(hN),Gq=z$1.object({orgId:z$1.string(),entityType:eTe,entityId:z$1.string()}),gN=Gq.extend({entityType:z$1.literal("TEST"),stepLists:Da}),fN=Gq.extend({entityType:z$1.literal("MODULE"),steps:Nt.array()});z$1.discriminatedUnion("entityType",[gN,fN]);var jq=(o=>(o.WEB="web",o.ANDROID="android",o.IOS="ios",o))(jq||{}),yN=z$1.nativeEnum(jq);var $q=z$1.object({entity_type:z$1.string(),value:z$1.string(),schema_version:z$1.string().optional()}),Vq=Qy($q),zq=$q.extend({cache_key:z$1.string()});function bb({entityType:e,entityId:t}){return `${e}:${t}`}var em=z$1.string();var Wq='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Jq=z$1.union([wl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,Wq)],{error:Wq}),qq='Percent must be a number or a percent string, e.g. 90 or "90%"',Xq=z$1.union([z$1.number(),z$1.string().regex(/^-?\d+(?:\.\d+)?%$/,qq)],{error:qq}).transform(e=>typeof e=="number"?e:Number(e.slice(0,-1))).pipe(z$1.number().min(0,{message:"Percent must be >= 0"}).max(100,{message:"Percent must be <= 100"})),tTe=z$1.strictObject({x:z$1.number(),y:z$1.number(),delta:z$1.number()}),Qq=z$1.union([z$1.string(),tTe]),Pn={...tt,DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional()},nTe=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],oTe=["enter","backspace","close_keyboard"],Kq=["airplane_mode","data","wifi","location"],Yq=["portrait","landscape"],rTe=z$1.strictObject({on:em.optional(),longPress:z$1.boolean().optional(),longPressDuration:z$1.number().optional(),iterations:z$1.number().optional(),tapDelay:z$1.number().optional(),offset:Jq.optional(),...Pn}),Zq=qe({key:"tap",simplified:em,detailed:rTe}),iTe=z$1.strictObject({text:z$1.string(),into:em.optional(),clearContent:z$1.boolean().optional(),forceClearContent:z$1.boolean().optional(),delay:z$1.number().optional(),replaceStrategy:z$1.nativeEnum(JS).optional(),keyPressDelay:z$1.number().optional(),...Pn}),e2=qe({key:"type",simplified:z$1.string(),detailed:iTe}),t2=z$1.enum(nTe),sTe=z$1.strictObject({key:t2,longPress:z$1.boolean().optional(),...Pn}),n2=qe({key:"press",simplified:t2,detailed:sTe}),o2=z$1.enum(oTe),aTe=z$1.strictObject({key:o2,repeat:z$1.number().optional(),delay:z$1.number().optional(),keyPressDelay:z$1.number().optional(),...Pn}),r2=qe({key:"pressKey",simplified:o2,detailed:aTe}),lTe=z$1.strictObject({package:z$1.string(),activity:z$1.string().optional(),intentExtras:z$1.string().optional(),...Pn}),i2=qe({key:"openApp",simplified:z$1.string(),detailed:lTe}),s2=qn({key:"killApp",detailed:z$1.strictObject(Pn)}),a2=qn({key:"openNotifications",detailed:z$1.strictObject(Pn)}),l2=z$1.enum(["up","down","left","right"]),cTe=z$1.strictObject({direction:l2,in:Qq.optional(),viewportPercent:Xq.optional(),duration:z$1.number().optional(),offset:Jq.optional(),...Pn}),c2=qe({key:"swipe",simplified:l2,detailed:cTe}),dTe=z$1.enum(["up","down"]),uTe=z$1.strictObject({on:em,direction:dTe.optional(),in:Qq.optional(),scrollStepPercent:Xq.optional(),maxScrollAttempts:z$1.number().optional(),...Pn}),d2=qe({key:"scrollTo",simplified:z$1.string(),detailed:uTe}),SN=qe({key:"assert",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Pn})}),bN=qe({key:"assertVisually",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Pn})}),u2=qe({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:Au.optional(),...Pn})}),p2=qe({key:"checkScreenContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Pn})}),m2=qe({key:"checkScreenDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Pn})}),h2=z$1.union([p2,m2]),pTe=z$1.record(z$1.string(),z$1.unknown().optional()),TN=pTe.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=_i(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=z$1.looseObject({on:em.optional(),timeout:z$1.number().optional(),name:z$1.string().optional(),value:z$1.string().optional(),...Pn}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}i.data.on===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a target via 'on'`,path:[r.alias,"on"]}),r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),mTe=z$1.strictObject({from:em,to:em,hoverDuration:z$1.number().optional(),dragDuration:z$1.number().optional(),...Pn}),g2=qn({key:"dragAndDrop",detailed:mTe}),AN=qe({key:"javascript",simplified:z$1.string(),detailed:z$1.strictObject({code:z$1.string(),timeout:z$1.number().optional(),...Pn})}),f2=qe({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:Gc.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),params:z$1.record(z$1.string(),z$1.string()).optional(),body:z$1.string().optional(),bodyType:z$1.nativeEnum(Pl).optional(),timeout:z$1.number().optional(),...Pn})}),y2=qe({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...Pn})}),S2=qe({key:"visualDiff",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),threshold:z$1.number().min(0).max(1).optional(),...Pn})}),b2=qn({key:"addFile",detailed:z$1.strictObject({path:z$1.string(),location:z$1.string(),...Pn})}),T2=qe({key:"installApp",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...Pn})}),A2=qe({key:"uninstallApp",simplified:z$1.string(),detailed:z$1.strictObject({package:z$1.string(),...Pn})}),E2=qe({key:"toggleSettings",simplified:z$1.enum(Kq),detailed:z$1.strictObject({setting:z$1.enum(Kq),...Pn})}),C2=qe({key:"rotate",simplified:z$1.enum(Yq),detailed:z$1.strictObject({orientation:z$1.enum(Yq),...Pn})}),v2=qe({key:"adb",simplified:z$1.string(),detailed:z$1.strictObject({command:z$1.string(),args:z$1.string().optional(),...Pn})}),R2=qn({key:"appium",detailed:z$1.strictObject({script:z$1.string(),args:z$1.string().optional(),...Pn})}),w2=qn({key:"debugState",detailed:z$1.strictObject(Pn)}),I2=z$1.enum(["killApp","openNotifications","debugState"]);z$1.union([Zq,e2,n2,r2,i2,s2,a2,c2,d2,SN,bN,u2,h2,g2,AN,f2,y2,S2,b2,T2,A2,E2,C2,v2,R2,w2,TN]);var x2=new Map([["tap",Zq],["type",e2],["press",n2],["pressKey",r2],["openApp",i2],["killApp",s2],["openNotifications",a2],["swipe",c2],["scrollTo",d2],["assert",SN],["assertVisually",bN],["extract",u2],["checkScreenContains",p2],["checkScreenDoesNotContain",m2],["dragAndDrop",g2],["javascript",AN],["request",f2],["wait",y2],["visualDiff",S2],["addFile",b2],["installApp",T2],["uninstallApp",A2],["toggleSettings",E2],["rotate",C2],["adb",v2],["appium",R2],["debugState",w2]]);Object.freeze([...x2.keys()]);var _2=z$1.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"v2 mobile commands must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"v2 mobile commands must have exactly one action key."});return}let r=x2.get(o)??(_i(o)?TN:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported v2 mobile command '${o}'.`});return}let i=r.safeParse(e);if(!i.success)for(let s of i.error.issues)t.addIssue({...s});}),P2=z$1.union([SN,bN,h2,AN,TN]);var hTe=z$1.preprocess(e=>typeof e=="number"?String(e):e,OM),gTe=z$1.looseObject({goal:z$1.string(),version:hTe.optional(),precondition:z$1.string().optional(),postcondition:z$1.string().optional(),...tt}),fTe=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:gTe})]),yTe=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),Sb).optional(),...tt}),STe=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:yTe})]),bTe=new Set(["then",...fb]),TTe=z$1.looseObject({then:z$1.lazy(()=>Ql.array()),...tt}).superRefine((e,t)=>{if("else"in e){t.addIssue({code:"custom",message:"v2 mobile conditionals do not support 'else'. Use a separate step instead.",path:["else"]});return}Object.entries(e).filter(([o,r])=>!bTe.has(o)&&P2.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),ATe=z$1.strictObject({if:TTe}),Ql=z$1.lazy(()=>z$1.union([I2,fTe,STe,ATe,_2]));z$1.object({before:Ql.array().optional(),steps:Ql.array(),after:Ql.array().optional()});var EN=["android","ios"],ETe=z$1.literal("android"),CTe=z$1.literal("ios");z$1.enum(EN);function rv(e){if(typeof e!="object"||e===null)return e;let t=e;if(typeof t.platform!="string")return e;let n=t.platform.toLowerCase();return n===t.platform?e:{...t,platform:n}}var O2=fg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:ETe,...ob.shape}),M2=yg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:CTe,...ob.shape}),vTe=z$1.discriminatedUnion("platform",[O2,M2]),N2=z$1.preprocess(rv,vTe),L2={before:Ql.array().optional(),steps:Ql.array(),after:Ql.array().optional()},k2=z$1.looseObject({fileType:z$1.literal(De.MOBILE_TEST_V2)}).extend(O2.shape).extend(L2);z$1.preprocess(rv,k2);var D2=z$1.looseObject({fileType:z$1.literal(De.MOBILE_TEST_V2)}).extend(M2.shape).extend(L2);z$1.preprocess(rv,D2);var RTe=z$1.discriminatedUnion("platform",[k2,D2]);z$1.preprocess(rv,RTe);var wTe=z$1.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z$1.enum(EN).optional().default("android")),iv=FC.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:mo,name:z$1.string().optional(),version:z$1.string().optional(),platform:wTe});z$1.looseObject(iv.extend({fileType:z$1.literal(De.MOBILE_MODULE_V2),steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).optional()}).shape);z$1.looseObject(iv.extend({fileType:z$1.literal(De.MOBILE_MODULE_V2),steps:Ql.array().optional()}).shape);var sv="x-momentic-cli-version",B2="x-momentic-client-mode",av="x-momentic-runner",U2="x-momentic-cli-type",H2="x-momentic-logger-tags",ITe="x-momentic-main-branch-name",xTe="x-momentic-branch-name",_Te="x-momentic-commit-timestamp",PTe="x-momentic-last-commit-on-main",OTe="x-momentic-last-commit-on-main-timestamp",MTe="x-momentic-merged-branch-name",G2="x-momentic-session-id",j2="x-momentic-parent-trace-id";O.object({error:O.boolean(),reason:O.string(),message:O.string()});rr.merge(cM);var $2=OE;rr.merge(cM);rr.merge(jV).extend({useConsensus:O.boolean().optional(),attemptNumber:O.number().optional()});var CN=lj;rr.merge($V);var V2=P$;rr.merge(BV);var z2=ZE;rr.merge(nj);rr.merge(UV);var W2=I$;rr.merge(HV);rr.merge(GV);rr.merge(qV);rr.merge(KV);O.object({testPaths:O.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:O.string().optional(),all:O.boolean().optional(),urlOverride:O.string().optional(),customHeaders:O.record(O.string(),O.string()).optional(),testInputMatrix:O.record(O.string(),O.string()).array().optional()});var q2=O.object({queuedTests:O.unknown().optional().array(),runIds:O.guid().array(),runGroupId:O.string().optional()});O.string().array();O.union([O.object({paths:O.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:O.boolean().describe("run all tests").optional()}),O.object({path:O.string().describe("deprecated; present for backcompat")})]);var NTe=O.object({tests:O.record(O.string().describe("Test name (keys correspond to entries in `tests`)"),O.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:O.record(O.string().describe("Module name (keys correspond to entries in `modules`)"),O.string().describe("Slash-separated folder name path that the module lives in."))}),K2=O.object({tests:O.record(O.string().describe("Test name"),O.string().describe("Test YAML")),modules:O.record(O.string().describe("Module name"),O.string().describe("Module YAML")),folderPaths:NTe.optional().describe("Optional map from exported entity name to its slash-separated cloud folder path. Used by the CLI to recreate folder structure on disk.")}),LTe=O.object({test:O.string().describe("test YAML"),modules:O.record(O.string().describe("moduleId"),O.string().describe("module YAML"))});LTe.array();O.object({testId:O.string(),schemaVersion:O.string()}).merge(Vc);function lv(e){let{gitMainBranch:t,gitBranchName:n,gitCommitTimestamp:o,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,s={};return t&&(s[ITe]=encodeURIComponent(t)),n&&(s[xTe]=encodeURIComponent(n)),o&&(s[_Te]=o.toISOString()),r&&(s[PTe]=encodeURIComponent(r)),i&&(s[OTe]=i.toISOString()),e.mergedGitBranchName&&(s[MTe]=encodeURIComponent(e.mergedGitBranchName)),s}O.object({entries:O.array(Jj)});O.object({platform:yN.optional(),entries:O.array(Vq)});O.object({testId:O.string(),environment:O.string().optional(),platform:yN.optional()});O.object({testId:O.string(),key:O.string(),environment:O.string().optional()});function Y2(e){return O.record(O.string(),O.unknown().optional()).transform(t=>{let n={};for(let[o,r]of Object.entries(t)){let i=e.safeParse(r);i.success&&(n[o]=i.data);}return n})}var J2=Y2(Xj),X2=zq.array();function F2(e){return Y2(Zy(e))}var Q2={ANDROID:e=>F2(HC).parse(e),IOS:e=>F2(GC).parse(e)},kTe=O.object({id:O.string(),completionType:O.string(),description:O.string().optional(),thoughts:O.string(),result:O.string(),sessionType:O.string(),timeCreated:O.string().optional(),citations:O.array(No).optional()}),DTe=O.object({id:O.string(),assertion:O.string().optional(),result:O.string(),thoughts:O.string(),sessionType:O.string(),timeCreated:O.string().optional(),citations:O.array(No).optional()});O.object({completionType:O.string(),traceIds:O.string().array()});var vN=O.union([kTe,DTe]).array(),Z2=O.object({trigger:O.nativeEnum(vs),status:O.nativeEnum(ht),startedAt:O.coerce.date().optional(),gitCommitSha:O.string().optional(),gitCommitShaShort:O.string().optional(),gitCommitTimestamp:O.coerce.date().optional(),gitBranchName:O.string().optional(),gitOriginUrl:O.string().optional(),gitCommitMessage:O.string().optional(),gitCommitAuthorName:O.string().optional(),githubRepository:O.string().optional(),gitlabProjectPath:O.string().optional(),pipelineId:O.string().optional(),cliVersion:O.string().optional()});O.object({id:O.string()});var eK=O.object({status:O.nativeEnum(ht),updatedAt:O.coerce.date().optional(),finishedAt:O.coerce.date().optional()});O.object({summary:zp,githubRepository:O.string().optional(),gitBranchName:O.string().optional()});O.object({updates:O.object({runId:O.string(),healStatus:NS,healDetails:OS.optional()}).array()});var tK=O.object({stepsSnapshot:O.array(O.record(O.string(),O.unknown().optional())).optional(),beforeStepsSnapshot:O.array(O.record(O.string(),O.unknown().optional())).optional(),afterStepsSnapshot:O.array(O.record(O.string(),O.unknown().optional())).optional(),runGroupId:O.string().optional(),testId:O.string(),testName:O.string(),resolvedBaseUrl:O.string().optional(),environmentName:O.string().optional(),labels:O.array(O.string()).optional(),cliVersion:O.string().optional(),trigger:O.nativeEnum(vs),schemaVersion:O.string().optional(),section:O.nativeEnum(bC).optional(),resolvedInputs:O.record(O.string(),O.string()).optional(),quarantined:O.boolean().optional().default(false),quarantinedReason:O.string().optional(),aiSettings:sa.optional()});O.object({id:O.string()});var FTe=sM.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),nK=FTe.array(),oK=sM.pick({startedAt:true,finishedAt:true,updatedAt:true,results:true,beforeResults:true,afterResults:true,status:true,healStatus:true,healDetails:true,failureDetails:true,failureReason:true,failureRecoveryDetails:true,resolvedBaseUrl:true,environmentName:true,labels:true,cliVersion:true,resolvedInputs:true,attempts:true,flake:true,aiSettings:true}).partial();O.object({id:O.string()});var rK=O.object({run:Qi.omit({runAttempts:true}),attemptZipUrls:O.array(O.string().url().nullish())}),iK=O.object({status:O.nativeEnum(ht),finishedAt:O.coerce.date().optional(),schemaVersion:O.string().optional().default("1.0.19"),results:O.record(O.string(),O.unknown().optional()).array().optional(),beforeResults:O.record(O.string(),O.unknown().optional()).array().optional(),afterResults:O.record(O.string(),O.unknown().optional()).array().optional()});O.object({screenshot:O.string(),contentType:O.enum(["image/jpeg","image/png"]).optional()});O.object({id:O.string(),screenshot:O.string(),contentType:O.enum(["image/jpeg","image/png"])});var sK=O.object({key:O.string()}),aK=O.object({orgId:O.string(),userId:O.string(),email:O.string().optional(),name:O.string().optional(),pylonEmailHash:O.string().optional(),selfServe:O.boolean().optional()}),lK=O.object({blocked:O.boolean()}),cK=O.array(z$);O.record(O.string(),O.union([O.string(),O.boolean()]));O.object({workosAccessToken:O.string().min(1),organizationId:O.string().optional(),clientName:O.string().min(1).max(80).optional()});var dK=O.object({apiKey:O.string(),apiKeyName:O.string(),organizationId:O.string(),user:O.object({id:O.string(),email:O.string().optional()}),selfServe:O.boolean().optional()}),uK=O.object({error:O.literal("multiple_organizations"),organizations:O.array(O.object({id:O.string(),name:O.string()}))}),BTe=["web","ios","android"];O.object({platforms:O.array(O.enum(BTe)),packageManager:O.enum(["npm","pnpm","yarn","bun"]),wizardVersion:O.string().min(1).max(40),cliVersions:O.object({momentic:O.string().max(40).optional(),momenticMobile:O.string().max(40).optional()}).optional(),firstRunIds:O.array(O.guid()).max(10).optional()});O.object({ok:O.literal(true)});O.object({paths:O.string().array(),env:O.string().optional(),urlOverride:O.string().optional(),customHeaders:O.record(O.string(),O.string()).optional()});var pK=O.object({suiteRunIds:O.string().array(),runGroupIds:O.string().array()});O.object({suiteRunIds:O.string().array()});NV.array();O.object({runGroupIds:O.string().array()});var cv=O.object({uploadUrl:O.string()});rr.merge(VV);rr.merge(WV);rr.merge(zV);var UTe=O.object({testId:O.string().optional().default(""),testName:O.string().optional().default(""),suiteId:O.string().optional().default(""),suiteName:O.string().optional().default(""),isInteractive:O.boolean().optional().default(false),runner:O.nativeEnum(Zi).optional(),creditsUsed:O.number().optional(),stepsExecuted:O.number().optional(),tokensUsed:O.number().optional(),hostedBrowserSecondsUsed:O.number().optional()}),HTe=O.object({transactionId:O.string(),timestamp:O.string(),event:O.nativeEnum(mg),properties:UTe});HTe.array();var mK=E1.omit({steps:true}).extend({steps:O.array(O.record(O.string(),O.unknown().optional())).describe("unparsed ResolvedStep[]")});O.object({limit:O.number().min(1).max(10).optional(),page:O.number().min(1).optional(),start:uo.optional(),end:uo.optional(),gitBranchName:O.string().optional(),status:O.nativeEnum(ht).optional()});var hK=AV.array(),GTe=O.object({testId:mo.optional(),gitBranchName:O.string().optional(),gitCommitSha:O.string().optional(),status:O.nativeEnum(ht).optional(),label:O.string().array().optional(),limit:O.number().min(1).max(100).optional(),page:O.number().min(1).optional(),start:uo.optional(),end:uo.optional(),quarantined:O.boolean().optional(),recovered:O.boolean().optional(),includeFailureDetails:O.boolean().optional()});GTe.extend({orgId:O.string().optional(),testId:or(mo),status:or(O.nativeEnum(ht)),gitBranchName:or(O.string()),label:or(O.string()),testName:O.string().optional(),trigger:or(O.nativeEnum(vs)),executionType:or(mu),cliVersion:or(O.string()),githubRepository:or(O.string()),gitlabProjectPath:or(O.string()),environment:or(O.string()),directory:or(O.string()),failureCategory:or(O.string()),exclude:or(O.string()),healed:O.boolean().optional()});var jTe=Qi.omit({test:true}),gK=O.object({runs:jTe.array(),page:O.number(),pageSize:O.number(),pageCount:O.number()});O.object({applied:O.boolean().optional(),appliedAt:O.coerce.date().optional()});var fK=cv.extend({id:O.string()});O.object({runGroupId:O.guid().optional(),persist:O.boolean().optional()});var yK=O.object({runGroupId:O.guid()}),SK=O.object({quarantined:O.object({testId:mo,quarantinedAt:O.coerce.date(),quarantinedBy:O.string().optional(),quarantinedReason:O.string()}).array()}),bK=O.object({gitLocalUsername:O.string().optional(),gitLocalEmail:O.string().optional(),gitLocalName:O.string().optional()});O.object({testId:mo,testName:O.string().optional(),reason:O.string()}).merge(bK);O.object({testName:O.string().optional(),reason:O.string().optional()}).merge(bK);rr.merge(eW);rr.merge(tW);rr.merge(nW);O.object({apkToInstall:O.object({channel:O.string(),tag:O.string().optional()}).optional(),hostname:O.string().optional(),region:qM.optional(),osVersion:O.nativeEnum(gg).optional(),sessionId:O.string().optional(),playwrightVersion:pW.optional()});var TK=O.object({name:O.string(),apiUrl:O.string(),webRtcUrl:O.string(),adbUrl:O.string(),token:O.string(),apkDownloadUrl:O.string().optional(),playwrightServerUrl:O.string().optional(),region:O.string().optional(),resolvedTag:O.string().optional()});O.object({appToInstall:O.object({channel:O.string(),tag:O.string().optional()}).optional(),hostname:O.string().optional(),region:qM.optional(),osVersion:O.nativeEnum(jC).optional(),sessionId:O.string().optional(),installAppOnClient:O.boolean().optional()});var AK=O.object({id:O.string(),apiUrl:O.string(),webRtcUrl:O.string(),wdaUrl:O.string(),token:O.string(),appDownloadUrl:O.string().optional(),appMd5:O.string().optional(),region:O.string().optional(),resolvedTag:O.string().optional()});O.object({channel:O.string().trim().min(1,"channel must be a non-empty string"),tag:O.string().trim().min(1,"tag must be a non-empty string"),md5:O.string()});var EK=O.object({id:O.string(),uploadUrl:O.string().optional(),downloadUrl:O.string(),md5:O.string().optional()}),$Te=O.object({channel:O.string(),tag:O.string(),md5:O.string(),platform:O.nativeEnum(ja).default("ANDROID"),createdAt:O.number().describe("Unix timestamp in milliseconds")}),CK=O.object({assets:O.array($Te)}),vK=O.object({downloadUrl:O.string()}),RN=(n=>(n.PLAYWRIGHT="PLAYWRIGHT",n.CDP="CDP",n))(RN||{}),VTe=O.nativeEnum(RN);O.object({testId:O.string().optional(),testName:O.string().optional(),runId:O.guid().optional(),attemptedProviders:O.array(rN).optional()});var RK=O.object({wsEndpoint:O.string(),accessToken:O.string().optional(),endpointType:VTe.optional(),provider:rN.optional()});z$1.object({repositoriesIndexed:z$1.boolean(),indexingInProgress:z$1.boolean(),indexesOutdated:z$1.boolean()});var wK=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(wK||{}),IK=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(IK||{});z$1.object({name:z$1.string(),status:z$1.enum(wK),conclusion:z$1.enum(IK).nullable()});var Tb=z$1.object({sha:z$1.string(),message:z$1.string(),author:z$1.object({name:z$1.string().optional(),email:z$1.string().optional(),date:z$1.coerce.date().optional()}),committer:z$1.object({name:z$1.string().optional(),email:z$1.string().optional(),date:z$1.coerce.date().optional()})}),wN=z$1.object({mergedBranch:z$1.string().optional()});var xK=z$1.object({orgId:z$1.string(),cacheKeys:z$1.string().array()});z$1.object({keyParams:xK,clientMetadata:z$1.string(),lockAcquisitionTimeoutMs:z$1.number().optional()});var _K=z$1.object({acquired:z$1.boolean(),acquiredByMetadata:z$1.string(),keyPrefix:z$1.string()});z$1.object({keyPrefix:z$1.string(),result:z$1.string(),ttlMs:z$1.number()});z$1.union([z$1.object({keyPrefix:z$1.string()}),xK]);var zTe=z$1.object({remainingTtlMs:z$1.number(),value:z$1.string().nullish()});z$1.object({results:z$1.record(z$1.string(),zTe),activeLocks:z$1.string().array()});var PK=0,OK=5*60*1e3;var MK=z$1.object({testId:z$1.string().min(1),stepId:z$1.string().min(1),baseTestFileHash:z$1.string().min(1),branchName:z$1.string().min(1).optional(),environment:z$1.string().min(1).optional(),classification:sO,healDetails:TV.optional()}),WTe=MK.extend({createdAt:z$1.coerce.date(),updatedAt:z$1.coerce.date()});z$1.object({branchName:z$1.string().min(1).optional(),mainBranchName:z$1.string().min(1).optional(),stepId:z$1.string().min(1),baseTestFileHash:z$1.string().min(1),environment:z$1.string().min(1).optional()});var NK=WTe.array();z$1.object({entries:MK.array()});var qTe=30*bg;function LK(){return new Date(Date.now()-qTe)}function vg(e){if(e.startsWith("https://api"))return e.replace("https://api","https://app");if(e.startsWith("http://localhost:8000"))return e.replace("http://localhost:8000","http://localhost:3000");throw new Error(`Unknown Momentic app server URL pattern: ${e}`)}var KTe=z$1.object({version:z$1.string(),json:z$1.record(z$1.string(),z$1.unknown().optional()),hash:z$1.string()}),kK=z$1.record(z$1.string(),z$1.unknown().optional());z$1.object({newSvgs:z$1.array(KTe),metadata:kK.optional()});var YTe=z$1.object({version:z$1.string(),json:z$1.record(z$1.string(),z$1.unknown().optional()).nullish(),hash:z$1.string(),description:z$1.string().nullish(),metadata:kK.nullish()}),DK=z$1.record(z$1.string().describe("icon hash"),YTe);var dv="heal-trace",xN=`${dv}/timeline.json`,_N=`${dv}/assets`,uv=(o=>(o.RECOVERY_ASSESSOR="recovery-assessor",o.ORCHESTRATOR="orchestrator",o.HEAL_SUBAGENT="heal-subagent",o))(uv||{}),PN=(o=>(o.REASONING="reasoning",o.TEXT="text",o.TOOL_CALL="tool-call",o))(PN||{}),JTe=z$1.object({asset:z$1.string(),startedAt:z$1.number()}),XTe=z$1.object({type:z$1.enum(PN),startedAt:z$1.number(),finishedAt:z$1.number().optional(),text:z$1.string().optional(),toolName:z$1.string().optional(),toolInput:z$1.string().optional(),toolInputJson:z$1.string().optional(),toolOutputJson:z$1.string().optional(),stepsAfterSplice:Gt.array().optional(),screenshotAsset:z$1.string().optional(),subagents:z$1.lazy(()=>IN.array()).optional()}),IN=z$1.object({agentId:z$1.string(),kind:z$1.enum(uv),label:z$1.string(),testId:z$1.string().optional(),runId:z$1.string().optional(),targetId:z$1.string().optional(),bucketId:z$1.string().optional(),startedAt:z$1.number(),finishedAt:z$1.number().optional(),spans:XTe.array(),videos:JTe.array().optional(),initialTestState:Gt.array().optional()}),QTe=z$1.object({testId:z$1.string(),appliedAt:z$1.number(),originRunId:z$1.string().optional()});z$1.object({cliVersion:z$1.string().optional(),healSessionId:z$1.string(),startedAt:z$1.number(),finishedAt:z$1.number().optional(),recoveryAssessors:IN.array(),orchestrator:IN.optional(),cachedHeals:QTe.array()});var ON="metadata.json",MN="test.yaml",FK=".snapshot.zip",NN=Zn.extend(Dl.shape),ZTe=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:CS.optional()}),BK=z$1.object({browser:Ga.optional(),ai:sa.optional(),advanced:PS.optional(),retries:z$1.number().optional()});z$1.object({momenticVersion:z$1.string(),schemaVersion:z$1.string(),createdAt:z$1.string(),relativeFilePath:z$1.string(),environment:ZTe,config:BK});var UK=z$1.object({variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:CS.optional()}),eAe=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),encryptedSecrets:z$1.string()}),HK=z$1.object({momenticVersion:z$1.string(),schemaVersion:z$1.string(),createdAt:z$1.string(),relativeFilePath:z$1.string(),environment:eAe,config:BK});function GK(e){let t;try{t=JSON.parse(e);}catch(n){return `The schema is not valid JSON. ${n}`}try{validator(t);}catch(n){return `The schema is not a valid JSON schema. ${n}`}}var jK=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,n])=>t.trim()&&n.trim())));};var pv=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function nAe(e){return e.map(t=>({...t,environment:void 0}))}function LN(e,t){return t?e:nAe(e)}var DN="browser-crash-dump.zip",kN=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new Ab}},Ab=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new kN}flushResults(t){}};var ct="metadata.json",Fr="assets",to="runs",oAe=z$1.object({step:Gt,status:z$1.enum(Mt),startedAt:z$1.coerce.date(),finishedAt:z$1.coerce.date().optional(),healMetadata:z$1.object({healType:z$1.enum(AS).or(z$1.literal("AI")),healedAt:z$1.coerce.date()}).optional(),beforeSnapshotId:z$1.guid().optional(),afterSnapshotId:z$1.guid().optional(),message:z$1.string().optional()}),rAe=oAe.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});rAe.extend({step:z$1.unknown().optional()});var FN=z$1.object({avdId:z$1.string().optional(),channel:z$1.string().optional(),tag:z$1.string().optional(),region:z$1.string().optional(),osVersion:mW.optional()}),VK="1.0.0",zK=iK.extend({id:z$1.guid().optional(),startedAt:z$1.coerce.date(),runAttemptSchemaVersion:z$1.string().optional(),schemaVersion:z$1.string().optional().default("1.0.19"),results:z$1.record(z$1.string(),z$1.unknown().optional()).array().optional(),beforeResults:z$1.record(z$1.string(),z$1.unknown().optional()).array().optional(),afterResults:z$1.record(z$1.string(),z$1.unknown().optional()).array().optional(),assetDetails:FN.optional(),viewport:Jc.optional(),activeVideos:z$1.array(z$1.object({videoName:z$1.string(),timestamp:z$1.coerce.date()})).optional()}),Eb=zK.extend({assetDetails:FN.optional(),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});zK.extend(YO.shape);var WK=Eb.extend(YO.shape),iAe=z$1.object({results:z$1.array(ws),beforeResults:z$1.array(ws).optional(),afterResults:z$1.array(ws).optional()});Eb.extend(iAe.shape);var sAe=z$1.object({results:z$1.array(Is),beforeResults:z$1.array(Is).optional(),afterResults:z$1.array(Is).optional()});Eb.extend(sAe.shape);var qK=oK.merge(tK).extend({executionType:mu.optional().default("WEB"),testId:mo,testDescription:z$1.string().optional(),directory:z$1.string().optional(),runGroupId:z$1.guid(),status:z$1.enum(ht),healStatus:NS,startedAt:z$1.coerce.date(),schemaVersion:z$1.string().nullish(),attempts:z$1.number(),failureRecoveryDetails:z$1.object({attempts:z$1.number()}).optional(),aiSettings:sa.optional(),avgCpuUsage:z$1.number().optional(),avgMemoryUsage:z$1.number().optional()}),aAe=qK.extend(FN.shape),tm=qK.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});aAe.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var $K=z$1.object({mode:z$1.enum(["SELECTED","RUN_ALL","RUN_NONE","SHADOW"]),baseRef:z$1.string().nullable(),headSha:z$1.string(),planId:z$1.string().nullable(),totalCandidates:z$1.number().int().nonnegative(),selectedCount:z$1.number().int().nonnegative(),anchorSegmentIds:z$1.array(z$1.string()),userSummary:z$1.string(),toolCallCount:z$1.number().int().nonnegative(),selectedTests:z$1.array(hC),forcedTests:z$1.array(z$1.object({name:z$1.string(),testPath:z$1.string(),status:z$1.enum(["A","M","R","C","T"])})).optional().default([]),runAllReason:z$1.string().nullable()}),lAe=Z2.merge(eK).extend({id:z$1.guid().optional(),startedAt:z$1.coerce.date(),cliVersion:z$1.string(),labels:z$1.string().array().optional().default([]),suiteName:z$1.string().optional(),ciProvider:z$1.string().optional(),gitMainBranch:z$1.string().optional(),ai:sa.optional(),browser:Ga.optional(),aiSelect:z$1.union([$K.transform(e=>[e]),z$1.array($K)]).optional()}),ua=lAe.extend({healRiskSummary:zp.optional(),updatedAt:z$1.coerce.date().optional().transform(e=>e??new Date),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var cAe=new Set(["AWAIT_LISTENER","REGISTER_REQUEST_LISTENER","GET_RECORDED_REQUESTS","MOCK_ROUTE","REMOVE_ROUTE_MOCK","SCROLL_DOWN","SCROLL_UP","SCROLL_LEFT","SCROLL_RIGHT","VISUAL_DIFF","WAIT","SET_HEADER","OFFLINE_MODE"]),dAe=new Set(["MODULE","RESOLVED_MODULE"]);function mv(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function hv(e){return dAe.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!cAe.has(e.command.type)}var KK="progress.json",YK="1.0.0",uAe=z$1.object({runId:z$1.string(),testId:z$1.string().optional(),testName:z$1.string().optional(),directory:z$1.string().optional(),status:z$1.nativeEnum(ht),completedSteps:z$1.number(),totalSteps:z$1.number(),startedAt:z$1.coerce.date(),updatedAt:z$1.coerce.date()});z$1.object({schemaVersion:z$1.string(),runGroupId:z$1.string(),status:z$1.nativeEnum(ht),totalRuns:z$1.number(),completedRuns:z$1.number(),completedSteps:z$1.number(),totalSteps:z$1.number(),startedAt:z$1.coerce.date(),updatedAt:z$1.coerce.date(),runs:uAe.array()});function JK(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return R.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var XK="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",Rg="https://us-west.metrics.momentic.ai",wg="c60c6a0f-60da-41a7-a61b-07969a0aa303",nm=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;var bAe=new Set(["exit","quit"]),eY=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})();async function sr(e){return nm||eY?true:(await R.flush(),await new Promise(n=>setTimeout(n,100)),await confirm({message:e}))}async function BN(e){let t=dirname(e);return JK(t)?existsSync(e)?sr(`File '${QK(e)}' already exists. Overwrite existing content?`):true:await sr(`Directory '${QK(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function QK(e){return e.replace(/(\s+)/g,"\\$1")}async function tY(e,t){return nm||eY?t:(await input({message:e,default:t})).trim()||t}async function nY(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){R.info("");return}throw t}if(!bAe.has(e.toLowerCase()))return e}var Ig=new Map,rY="Log throttle exceeded",PAe=100,OAe=5e3,MAe=vAe(global.fetch,{retries:2,retryOn:function(e,t,n){return !!(t!==null||n&&n.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}}),NAe=`${Rg}/logs/json`,UN=class{constructor(t,n){this.flushIntervalMs=t;this.maxBatchSize=n;}records=[];flushTimer;push(t){if(this.records.push(t),this.records.length>=this.maxBatchSize){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flush();return}this.scheduleFlush();}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush();},this.flushIntervalMs));}async flush(){if(this.records.length===0)return;let t=this.records;this.records=[];try{let n=await MAe(NAe,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":XK,"x-momentic-metrics-api-key":wg},body:Va(t),signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch{}}},HN=class e{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=false;lastWindowStart=Date.now();flushIntervalMs;maxBatchSize;buffer;constructor({bindings:t,hostname:n,disableConsoleLogs:o,flushIntervalMs:r,maxBatchSize:i,buffer:s}){this.hostname=n??sd.hostname(),this.disableConsoleLogs=o,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=s??new UN(this.flushIntervalMs,this.maxBatchSize);let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=oY(a);}child(t){return new e({bindings:{...this.bindingAttributes,...t},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize,buffer:this.buffer})}async flush(){await this.buffer.flush(),this.disableConsoleLogs||this.consoleLogger.flush();}shouldAllowLog(t){if(t===rY)return true;let n=Date.now();return n-this.lastWindowStart>OAe&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,rY),this.droppedLogsInWindow=false,this.lastWindowStart=n),this.logsInCurrentWindow<PAe?(this.logsInCurrentWindow++,true):(this.droppedLogsInWindow=true,false)}log(t,n,o,...r){try{this.logHelper(t,n,o,...r);}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`);}}logHelper(t,n,o,...r){if(_S[t]<this.minLevelValue||!this.shouldAllowLog(o))return;typeof n=="string"&&!o&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=xAe.err(n.err));let i={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...r.length>0?{args:r}:{}},s={host:this.hostname,env:this.bindingAttributes.env},a=LAe();this.disableConsoleLogs||this.consoleLogger[t]({...i,...a??{}},o,...r);let l={timestamp:Math.round(Date.now()*1e6),...a??{},severity_text:t.toUpperCase(),resources:s,attributes:{},body:dV({message:o||"",...i})};this.buffer.push(l);}setApp(t){let n=this.bindingAttributes.app;this.bindingAttributes.app=t,Ig.set("app",this),Ig.delete(n);}debug(t,n,...o){this.log("debug",t,n,...o);}info(t,n,...o){this.log("info",t,n,...o);}warn(t,n,...o){this.log("warn",t,n,...o);}error(t,n,...o){this.log("error",t,n,...o);}bindings(){return this.bindingAttributes}addBinding(t,n){this.bindingAttributes[t]=n;}setMinLevel(t){typeof t=="number"?(this.minLevelValue=t,this.consoleLogger.level=uV[t]):(this.minLevelValue=_S[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},xg=({app:e,hostname:t,disableConsoleLogs:n})=>(Ig.has(e)||Ig.set(e,new HN({bindings:{app:e},hostname:t,disableConsoleLogs:n})),Ig.get(e));function LAe(){let e=trace.getSpan(context.active());if(!e)return;let t=e.spanContext();if(isSpanContextValid(t))return {trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}async function gv(){await Promise.all([...Ig.values()].map(e=>e.flush()));}var vu=class extends Error{callSiteStack;constructor(t){super(t),this.name="TimeoutError";}};var iY=e=>{let t=e.reason===void 0?new DOMException("This operation was aborted.","AbortError"):e.reason;return t instanceof Error?t:new DOMException(t,"AbortError")};function _e(e,t){let{milliseconds:n,fallback:o,message:r,customTimers:i={setTimeout,clearTimeout}}=t,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);let a=new Error().stack;return new Promise((l,c)=>{let d;if(t.signal){let{signal:m}=t;if(m.aborted)return c(iY(m));d=()=>c(iY(m)),m.addEventListener("abort",d,{once:true});}let u=()=>{if(t.signal&&t.signal.removeEventListener("abort",d),o)try{l(o());}catch(m){c(m);}else {if(typeof e.cancel=="function"&&Promise.resolve().then(()=>e.cancel()).catch(()=>{}),r instanceof Error){c(r);return}let m=new vu(r??`Promise timed out after ${n}ms`);m.callSiteStack=a,c(m);}};n<1/0&&(s=i.setTimeout(u,n));let p=()=>{i.clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",d);};Promise.resolve(e).then(m=>{p(),l(m);}).catch(m=>{p(),c(m);});})}var fv="organization";function yv(e){let t=new PostHog(e.writeKey,{host:e.host,...e.flushImmediately?{flushAt:1,flushInterval:0}:{}}),n=e.platform,o=(l,c,d)=>{let{type:u,...p}=l;t.capture({distinctId:c??d??randomUUID(),event:u,...d&&{groups:{[fv]:d}},properties:{platform:n,user_id:c??void 0,org_id:d??void 0,...p,organizationId:d??void 0,...c==null&&d==null&&{$process_person_profile:false}}});},r=({orgId:l,properties:c})=>{t.groupIdentify({groupType:fv,groupKey:l,properties:c});},i=({userId:l,properties:c})=>{Object.values(c).some(u=>u!=null&&u!=="")&&t.identify({distinctId:l,properties:c});},s=()=>t.shutdown();if(e.identity==="stashed"){let l=null;return {shutdownAnalytics:s,groupIdentifyOrg:r,setAnalyticsIdentity:d=>{l=d,e.onIdentify?.(d),i({userId:d.userId,properties:{email:d.email,...d.selfServe!==void 0?{self_serve:d.selfServe}:{}}});},captureEvent:d=>o(d,l?.userId??null,l?.orgId??null)}}return {shutdownAnalytics:s,groupIdentifyOrg:r,identifyUser:i,captureEvent:(l,{userId:c,orgId:d})=>o(l,c,d),captureBillingEvent:(l,{userId:c,orgId:d})=>o(l,c,d)}}async function sY(e,t,n){let o,r=0,i=3,s,a;for(;r<i;)try{let l=await _e(e.getAllFlagsAndPayloads(n??t,{personProperties:{organizationId:t},groups:{[fv]:t}}),{milliseconds:5e3});s=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){o=l,r++,await new Promise(c=>setTimeout(c,100*r));}if(s&&a)return {flags:s,payloads:a};throw o}var Sv=class e extends cb{constructor(n,o,r,i,s){super(i,s);this.client=n;this.orgId=o;this.userId=r;}static async init(n,o){let r=new PostHog("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://p.momentic.ai"}),{flags:i,payloads:s}=await sY(r,n,o);return new e(r,n,o,i,s)}async refresh(){let{flags:n,payloads:o}=await sY(this.client,this.orgId,this.userId);this.flags=n,this.payloads=o;}};var HAe=2e3,om=e=>Number.parseInt(e,10),jN=e=>readFileSync(e,"utf8").trim(),_g=e=>om(jN(e)),aY,bv,Cb={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function dY(){return {...Cb}}var Av=sd.platform(),GAe=sd.cpus().map(e=>({model:e.model,speed:e.speed})).reduce((e,t)=>(e[t.model]={speed:t.speed},e.totalCores=(e.totalCores??0)+1,e),{});function GN(e=Date.now()){let t=sd.cpus(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;return n.total=n.user+n.nice+n.sys+n.idle+n.irq,n}function uY(e,t){let n={user:t.user-e.user,nice:t.nice-e.nice,sys:t.sys-e.sys,idle:t.idle-e.idle,irq:t.irq-e.irq,total:t.total-e.total};return n.total<=0?null:{measurementTime:t.measurementTime,intervalMs:t.measurementTime-e.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100}}function jAe(){let e=GN();return ()=>{let t=GN(),n=uY(e,t);return e=t,n}}function lY(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return om(t[1])}catch{}try{let e=_g("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function $Ae(){try{let t=jN("/sys/fs/cgroup/cpu.max").split(" "),n=t[0],o=t[1];return !n||!o||n==="max"?null:om(n)/om(o)}catch{}try{let e=_g("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=_g("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function VAe(){if(Av!=="linux")return null;let e=lY();if(e===null)return null;let t=$Ae()??sd.cpus().length,n=e,o=Date.now();return ()=>{let r=lY();if(r===null)return null;let i=Date.now(),s=i-o;if(s<=0)return null;let a=r-n,l=s*1e3,c=Math.max(0,Math.min(100,a/l/t*100));return n=r,o=i,{measurementTime:i,intervalMs:s,user:c,nice:0,sys:0,idle:Math.max(0,100-c),irq:0,total:c}}}function zAe(){let e=process.cpuUsage(),t=process.hrtime.bigint();return ()=>{let n=process.cpuUsage(),o=process.hrtime.bigint(),r=Number(o-t)/1e6,i=n.user-e.user,s=n.system-e.system;if(e=n,t=o,r<=0)return null;let a=Math.max(sd.cpus().length,1),l=c=>Math.max(0,c/1e3/r*100/a);return {total:l(i+s),user:l(i),sys:l(s),intervalMs:r}}}function pY({intervalMs:e=HAe,maxSamples:t=1e4,keepSamples:n=true,onSample:o}={}){let r=[],i=VAe()??jAe(),s=zAe(),a=()=>{let d=Date.now(),u=hY(),p=process.memoryUsage(),m=i(),h=s(),g={timestamp:d,system:{cpu:m,memory:{total:u.totalMemory,free:u.freeMemory,freePercentage:u.freePercentage}},process:{cpu:h,memory:{rss:p.rss,heapTotal:p.heapTotal,heapUsed:p.heapUsed,external:p.external,arrayBuffers:p.arrayBuffers}}};o?.(g),n&&(r.push(g),r.length>t&&r.shift());};a();let l=setInterval(a,e),c=d=>({samples:n?[...r]:[]});return {stop:()=>(clearInterval(l),c()),getSeries:()=>c()}}var Tv=e=>{try{let t={},n=!1,o=hY(),r=qAe();Cb.samples++,o.freePercentage<.05&&(Object.assign(t,process.memoryUsage()),n=!0,Cb.lowMemorySamples++),r&&r?.total>80&&(n=!0,Cb.highCpuSamples++);let i=UAe.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(n=!0,Cb.highHeapSamples++),n?e.warn({memory:o,cpu:r,heapStats:i,...t},"Critical resource usage metrics detected"):e.debug({memory:o,cpu:r},"Got machine resource usage metrics");}catch{}},mY=e=>{Tv(e),setTimeout(()=>Tv(e),5e3);};function Ev(e){return Tv(e),{interval:setInterval(()=>Tv(e),2e4),cpuMetadata:GAe,platform:Av}}function WAe(){if(Av!=="linux")return null;try{let e=jN("/sys/fs/cgroup/memory.max"),t=_g("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let n=om(e);if(isNaN(n))return null;let o=Math.max(0,n-t);return {totalMemory:n,freeMemory:o,freePercentage:o/n}}catch{}try{let e=_g("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=_g("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let n=sd.totalmem();if(e>=n)return null;let o=Math.max(0,e-t);return {totalMemory:e,freeMemory:o,freePercentage:o/e}}catch{return null}}function hY(){let e=WAe();if(e)return e;let t=sd.totalmem(),n=Av==="darwin"?KAe():(()=>{let r=sd.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),o=n.availableMemory/t;return {totalMemory:t,freeMemory:n.availableMemory,freePercentage:o}}function qAe(){let e=GN();if(!bv)return bv=e,null;let t=uY(bv,e);return bv=e,t?(aY=t,aY):null}function KAe(){try{let e=execSync("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),n=e.match(/page size of (\d+) bytes/)?.[1],o=n?om(n):4096,r=d=>{let p=e.match(new RegExp(`${d}:\\s+(\\d+)\\.`,"i"))?.[1];return p?om(p):0},i=r("Pages free"),s=r("Pages inactive"),a=r("Pages speculative"),l=i*o,c=(s+a)*o;return {availableMemory:l+c,rawFreeMemory:l,cachedMemory:c}}catch{let e=sd.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}process.env.APP||"unknown";var Cv="deployment.environment",vv="service.instance.id";function gY(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"}var Pg=false,Rv,vb,Rb,SY=[],wv;function Iv(){return Pg}function bY(e){SY.push(e);}async function aEe(){for(let e of SY)try{await e();}catch{}}function lEe(){return Iv()&&trace.getSpan(context.active())!==void 0}function cEe(){return gY()?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${Rg}/v1/traces`,headers:{"x-momentic-metrics-api-key":wg}})}function dEe(e){let t="production",n=v4$1(),o=cEe();return new NodeTracerProvider({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:e,[Cv]:t,[vv]:n,[ATTR_SERVICE_VERSION]:"3.16.2"}),spanProcessors:[new BatchSpanProcessor(o)]})}function uEe(e){wv=registerInstrumentations({tracerProvider:e,instrumentations:[new UndiciInstrumentation({requireParentforSpans:true})]});}function pEe(e){return !e&&!Rv?trace.getTracer("momentic-serverless"):Rb?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function Ru(e){if(!(!e.enabled||Pg))try{Rv=e.serviceName;let t=dEe(e.serviceName);Rb=t,vb=new AsyncLocalStorageContextManager,t.register({contextManager:vb.enable(),propagator:new W3CTraceContextPropagator}),uEe(t),Pg=!0;}catch{Pg=false,Rv=void 0,Rb=void 0,vb=void 0,wv=void 0;}}async function xv(){if(Pg)try{await aEe(),await Rb?.shutdown();}catch{}finally{wv?.();try{vb?.disable();}catch{}Pg=false,Rv=void 0,vb=void 0,Rb=void 0,wv=void 0;}}async function He(e){if(!Iv()||!e.root&&!lEe())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await pEe(e.serviceName).startActiveSpan(e.name,{attributes:t,kind:e.kind??SpanKind.CLIENT},async n=>{try{let o=await e.fn(n);return n.setStatus({code:SpanStatusCode.OK}),o}catch(o){throw n.setStatus({code:SpanStatusCode.ERROR,message:o instanceof Error?o.message.slice(0,300):void 0}),o instanceof Error&&n.recordException(o),o}finally{n.end();}})}var wb=class{increment(t,n,o){}gauge(t,n){}distribution(t,n,o){}async flush(){}async recordDuration(t){return await VN(t)}};async function VN({fn:e,name:t,timeoutMs:n,timeoutMessage:o,trace:r}){let i=r?()=>He({name:r.name,attributes:r.attributes,fn:e}):e,s=Promise.resolve(i());return n===void 0?await s:await _e(s,{milliseconds:n,message:o??`Timed out after ${n}ms recording duration for ${t}`})}function mEe(e){if(!e||e.length===0)return {};let t={};for(let n of e){let o=n.indexOf(":");if(o>-1){let r=n.slice(0,o).trim(),i=n.slice(o+1).trim();r&&(t[r]=i);continue}t[n]=true;}return t}function zN(e,t){let n=mEe(e);return !t||Object.keys(t).length===0?n:{...t,...n}}function vEe(){return new OTLPMetricExporter({url:`${Rg}/v1/metrics`,headers:{"x-momentic-metrics-api-key":wg},temporalityPreference:AggregationTemporalityPreference.DELTA})}var WN=[100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],_v=(e,t)=>({instrumentName:e,instrumentType:InstrumentType.HISTOGRAM,aggregation:{type:AggregationType.EXPLICIT_BUCKET_HISTOGRAM,options:{boundaries:t,recordMinMax:false}}}),REe=[_v("test_event_duration",WN),_v("test_step_duration",WN),_v("test_mobile_step_duration",WN),_v("web_agent_action_duration",[25,50,100,200,350,500,750,1e3,2e3,5e3,1e4,2e4])],Pv=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(t){let n=this.counterCache.get(t);if(n)return n;let o=this.meter.createCounter(t);return this.counterCache.set(t,o),o}getHistogram(t){let n=this.histogramCache.get(t);if(n)return n;let o=this.meter.createHistogram(t);return this.histogramCache.set(t,o),o}ensureObservableGauge(t){let n=this.observableGaugeCache.get(t);if(n)return n;let o=this.meter.createObservableGauge(t);return o.addCallback(r=>{let i=this.gaugeValues.get(t);i!==void 0&&r.observe(i,this.globalAttributes);}),this.observableGaugeCache.set(t,o),o}constructor(t){this.globalAttributes={...t.globalAttributes??{}};let n=typeof process<"u"?"production":"unknown",o=resourceFromAttributes({[ATTR_SERVICE_NAME]:t.serviceName,[Cv]:n,[vv]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1(),[ATTR_SERVICE_VERSION]:"3.16.2"}),r=vEe(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:o,readers:[i],views:REe}),metrics.setGlobalMeterProvider(this.provider),this.meter=metrics.getMeter("momentic-serverless");}increment(t,n,o){try{let r=zN(o,this.globalAttributes);this.getCounter(t).add(typeof n=="number"?n:1,r);}catch{}}gauge(t,n){try{this.ensureObservableGauge(t),this.gaugeValues.set(t,n);}catch{}}distribution(t,n,o){try{let r=zN(o,this.globalAttributes);this.getHistogram(t).record(n,r);}catch{}}async flush(){try{await this.provider.forceFlush();}catch{}}async recordDuration(t){let{name:n,tags:o}=t,r=Date.now();try{return await VN(t)}finally{this.distribution(n,Date.now()-r,o);}}};var At=new wb;function AY(e){if(!e.disabled)try{At=new Pv(e);}catch{At=new wb;}}var qN;function EY(e){qN=e;}function wu(e){IEe(e)&&qN&&qN(e);}var wEe=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function IEe(e){return e instanceof Error&&e.name==="AbortError"||VE(e,ke)?false:e instanceof te?wEe.has(e.reason):true}function xEe({usage:e,promptType:t,result:n="success"}){let o=[`type:${t}`,`result:${n}`],r=e.inputTokens??0,i=e.inputTokenDetails.cacheReadTokens??e.cachedInputTokens??0,s=e.outputTokens??0;At.distribution("ai_session_tokens",r,[...o,"category:input"]),At.distribution("ai_session_tokens",Math.max(0,Math.min(i,r)),[...o,"category:cached_input"]),At.distribution("ai_session_tokens",s,[...o,"category:output"]);}function Ov({usage:e,promptType:t,logger:n,message:o,result:r="success",attributes:i}){xEe({usage:e,promptType:t,result:r}),n.info({...i,promptType:t,result:r,usage:e},o);}function pa({usage:e,promptType:t,logger:n}){let o=Promise.resolve(e).catch(r=>{n.warn({err:r,promptType:t},"Failed to resolve AI session usage");});return ({message:r,result:i="success",attributes:s})=>{o.then(a=>{a&&Ov({usage:a,promptType:t,logger:n,result:i,message:r,attributes:s});});}}function kY(){return globalThis.crypto}function XN(e){let t=kY(),n=new Uint8Array(e);if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(n),n;for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);return n}function xu(){let e=kY();if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=XN(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return `${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function QN(e){let t=globalThis.Buffer;if(t)return t.from(e).toString("base64");let n="";for(let a=0;a<e.length;a++)n+=String.fromCharCode(e[a]);let o=globalThis.btoa;if(typeof o=="function")return o(n);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="",s=0;for(;s<n.length;){let a=n.charCodeAt(s++)&255,l=s<n.length?n.charCodeAt(s++)&255:NaN,c=s<n.length?n.charCodeAt(s++)&255:NaN,d=a>>2,u=(a&3)<<4|(Number.isNaN(l)?0:l>>4),p=Number.isNaN(l)?64:(l&15)<<2|(Number.isNaN(c)?0:c>>6),m=Number.isNaN(c)?64:c&63;i+=r.charAt(d),i+=r.charAt(u),i+=p===64?"=":r.charAt(p),i+=m===64?"=":r.charAt(m);}return i}function PEe(e){return new Promise(t=>setTimeout(t,e))}function xb(e){if(e)return e.endsWith("/")?e:`${e}/`}function OEe(e){var t;let n=(t=e.get("Retry-After"))!=null?t:e.get("retry-after");if(!n)return;let o=Number(n);if(n.trim()!==""&&!Number.isNaN(o))return o*1e3;let r=new Date(n).getTime();if(!Number.isNaN(r)){let i=r-Date.now();return i>0?i:0}}function MEe(e,t){if(t&&typeof t=="object"&&t!==null&&"retryAfterMs"in t){let r=t.retryAfterMs;if(typeof r=="number")return Math.max(0,r)}if(e<=1)return 0;let n=500,o=Math.pow(2,e-2);return n*o}async function NEe(e,t,n){let o=n.sdkName?`[raindrop-ai/${n.sdkName}]`:"[raindrop-ai/core]",r;for(let i=1;i<=n.maxAttempts;i++){if(i>1){let s=MEe(i,r);n.debug&&console.warn(`${o} ${t} retry ${i}/${n.maxAttempts} in ${s}ms`),s>0&&await PEe(s);}else n.debug&&console.log(`${o} ${t} attempt ${i}/${n.maxAttempts}`);try{return await e()}catch(s){if(r=s,n.debug){let a=s instanceof Error?s.message:String(s);console.warn(`${o} ${t} attempt ${i} failed: ${a}${i===n.maxAttempts?" (no more retries)":""}`);}if(r&&typeof r=="object"&&"retryable"in r&&!r.retryable||i===n.maxAttempts)break}}throw r instanceof Error?r:new Error(String(r))}async function rm(e,t,n,o){let r=`POST ${e}`;await NEe(async()=>{let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)});if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`HTTP ${i.status} ${i.statusText}${s?`: ${s}`:""}`),l=OEe(i.headers);throw typeof l=="number"&&(a.retryAfterMs=l),a.retryable=i.status===429||i.status>=500,a}},r,o);}var CY={UNSET:0,ERROR:2};function vY(e){let t=e?e.traceIdB64:QN(XN(16)),n=QN(XN(8));return {traceIdB64:t,spanIdB64:n,parentSpanIdB64:e?e.spanIdB64:void 0}}function _b(){return Date.now().toString()+"000000"}function RY(e){return String(Math.floor(e))+"000000"}function J(e,t){if(t!==void 0)return {key:e,value:{stringValue:t}}}function nt(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{intValue:String(Math.trunc(t))}}}function Mg(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{doubleValue:t}}}function LEe(e,t){if(t!==void 0)return {key:e,value:{boolValue:t}}}function ad(e,t){if(!(!t||t.length===0))return {key:e,value:{arrayValue:{values:t.filter(n=>typeof n=="string").map(n=>({stringValue:n}))}}}}function KN(e){let t=e.attributes.filter(o=>o!==void 0),n={traceId:e.ids.traceIdB64,spanId:e.ids.spanIdB64,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano};return e.ids.parentSpanIdB64&&(n.parentSpanId=e.ids.parentSpanIdB64),t.length&&(n.attributes=t),e.status&&(n.status=e.status),n}function wY(e,t="raindrop.core",n="0.0.0"){return {resourceSpans:[{resource:{attributes:[{key:"service.name",value:{stringValue:t}}]},scopeSpans:[{scope:{name:t,version:n},spans:e}]}]}}var kEe="RAINDROP_LOCAL_DEBUGGER",DEe="RAINDROP_WORKSHOP",IY="http://localhost:5899/v1/";function iL(e){var t;try{let n=(t=globalThis?.process)==null?void 0:t.env;if(n&&typeof n[e]=="string"&&n[e].length>0)return n[e]}catch{}}function FEe(){let e=iL(DEe);if(e===void 0)return;let t=e.trim();if(t.length!==0){if(/^https?:\/\//i.test(t))return {url:t};if(/^(1|true|yes|on)$/i.test(t))return "enable";if(/^(0|false|no|off)$/i.test(t))return "disable"}}function BEe(e){return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e.endsWith(".localhost")):false}function UEe(){try{let e=globalThis?.location;if(e&&typeof e.hostname=="string"&&e.hostname.length>0)return e.hostname}catch{}}function HEe(){return !!(BEe(UEe())||iL("NODE_ENV")==="development")}function sm(e){var t,n,o;if(e===null)return null;if(typeof e=="string"&&e.length>0)return (t=xb(e))!=null?t:null;let r=iL(kEe);if(r)return (n=xb(r))!=null?n:null;let i=FEe();return i==="disable"?null:i==="enable"?IY:i&&"url"in i?(o=xb(i.url))!=null?o:null:HEe()?IY:null}function Bv(e){return sm(e)!==null}function GEe(e,t={}){var n;let o=sm(t.baseUrl);o&&rm(`${o}traces`,e,{},{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function jEe(e,t={}){var n;let o=sm(t.baseUrl);if(!o)return;let r=t.writeKey?{Authorization:`Bearer ${t.writeKey}`}:{};rm(`${o}events/track_partial`,e,r,{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function Iu(e,t={}){var n,o;let r=sm(t.baseUrl);r&&rm(`${r}live`,{...e,type:e.type,timestamp:(n=e.timestamp)!=null?n:Date.now()},{},{maxAttempts:1,debug:(o=t.debug)!=null?o:false,sdkName:t.sdkName}).catch(()=>{});}function $Ee(e,t){var n,o,r,i;let s={...e,...t};return (e.properties||t.properties)&&(s.properties={...(n=e.properties)!=null?n:{},...(o=t.properties)!=null?o:{}}),(e.attachments||t.attachments)&&(s.attachments=[...(r=e.attachments)!=null?r:[],...(i=t.attachments)!=null?i:[]]),s}var VEe=class{constructor(e){this.buffers=new Map,this.sticky=new Map,this.timers=new Map,this.inFlight=new Set;var t,n,o,r,i,s,a,l;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=xb(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.partialFlushMs=(o=e.partialFlushMs)!=null?o:1e3,this.sdkName=(r=e.sdkName)!=null?r:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.defaultEventName=(i=e.defaultEventName)!=null?i:"ai_generation",this.localDebuggerUrl=(s=sm(e.localDebuggerUrl))!=null?s:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);let c=typeof process<"u"&&typeof process.version=="string";this.context={library:{name:(a=e.libraryName)!=null?a:"@raindrop-ai/core",version:(l=e.libraryVersion)!=null?l:"0.0.0"},metadata:{jsRuntime:c?"node":"web",...c?{nodeVersion:process.version}:{}}};}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}async patch(e,t){var n,o,r,i,s,a,l,c,d,u,p;if(!this.enabled||!e||!e.trim())return;this.debug&&console.log(`${this.prefix} queue patch`,{eventId:e,userId:t.userId,convoId:t.convoId,eventName:t.eventName,hasInput:typeof t.input=="string"&&t.input.length>0,hasOutput:typeof t.output=="string"&&t.output.length>0,attachments:(o=(n=t.attachments)==null?void 0:n.length)!=null?o:0,isPending:t.isPending});let m=(r=this.sticky.get(e))!=null?r:{},h=(i=this.buffers.get(e))!=null?i:{},g=$Ee(h,t);g.isPending=(l=(a=(s=t.isPending)!=null?s:h.isPending)!=null?a:m.isPending)!=null?l:true,this.buffers.set(e,g),this.sticky.set(e,{userId:(c=g.userId)!=null?c:m.userId,convoId:(d=g.convoId)!=null?d:m.convoId,eventName:(u=g.eventName)!=null?u:m.eventName,isPending:(p=g.isPending)!=null?p:m.isPending});let f=this.timers.get(e);if(f&&clearTimeout(f),g.isPending===false){await this.flushOne(e);return}let y=setTimeout(()=>{this.flushOne(e).catch(()=>{});},this.partialFlushMs);this.timers.set(e,y);}async finish(e,t){await this.patch(e,{...t,isPending:false});}async flush(){if(!this.enabled)return;let e=[...this.buffers.keys()];await Promise.all(e.map(t=>this.flushOne(t))),await Promise.all([...this.inFlight].map(t=>t.catch(()=>{})));}async shutdown(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),await this.flush();}async trackSignal(e){var t,n;if(!this.enabled)return;let o=[{event_id:e.eventId,signal_name:e.name,signal_type:(t=e.type)!=null?t:"default",timestamp:e.timestamp,sentiment:e.sentiment,attachment_id:e.attachmentId,properties:{...(n=e.properties)!=null?n:{},...e.comment?{comment:e.comment}:{},...e.after?{after:e.after}:{}}}];if(!this.writeKey)return;let r=`${this.baseUrl}signals/track`;try{await rm(r,o,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`${this.prefix} failed to send signal (dropping): ${s}`);}}async identify(e){if(!this.enabled)return;let n=(Array.isArray(e)?e:[e]).filter(r=>!r?.userId||!r.userId.trim()?(this.debug&&console.warn(`${this.prefix} skipping identify: missing userId`),false):true).map(r=>{var i;return {user_id:r.userId,traits:(i=r.traits)!=null?i:{}}});if(!this.writeKey||n.length===0)return;let o=`${this.baseUrl}users/identify`;try{await rm(o,n,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send identify (dropping): ${i}`);}}async flushOne(e){var t,n,o,r,i,s,a,l,c,d,u,p,m;if(!this.enabled)return;let h=this.timers.get(e);h&&(clearTimeout(h),this.timers.delete(e));let g=this.buffers.get(e);if(this.buffers.delete(e),!g)return;let f=(t=this.sticky.get(e))!=null?t:{},y=(o=(n=g.eventName)!=null?n:f.eventName)!=null?o:this.defaultEventName,S=(r=g.userId)!=null?r:f.userId;if(!S){this.debug&&console.warn(`${this.prefix} skipping track_partial for ${e}: missing userId`),this.sticky.delete(e);return}let{wizardSession:T,...E}=(i=g.properties)!=null?i:{},C=(s=g.convoId)!=null?s:f.convoId,w=(l=(a=g.isPending)!=null?a:f.isPending)!=null?l:true,x={event_id:e,user_id:S,event:y,timestamp:(c=g.timestamp)!=null?c:new Date().toISOString(),ai_data:{input:g.input,output:g.output,model:g.model,convo_id:C},properties:{...E,...T?{"raindrop.wizardSession":T}:{},$context:this.context},attachments:g.attachments,is_pending:w},I=`${this.baseUrl}events/track_partial`;if(this.debug&&console.log(`${this.prefix} sending track_partial`,{eventId:e,eventName:y,userId:S,convoId:C,isPending:w,inputPreview:typeof g.input=="string"?g.input.slice(0,120):void 0,outputPreview:typeof g.output=="string"?g.output.slice(0,120):void 0,attachments:(u=(d=g.attachments)==null?void 0:d.length)!=null?u:0,attachmentKinds:(m=(p=g.attachments)==null?void 0:p.map(_=>({type:_.type,role:_.role,name:_.name,valuePreview:_.value.slice(0,60)})))!=null?m:[],endpoint:I}),this.localDebuggerUrl&&jEe(x,{baseUrl:this.localDebuggerUrl,writeKey:this.writeKey,debug:this.debug,sdkName:this.sdkName}),!this.writeKey){w||this.sticky.delete(e);return}let v=rm(I,x,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(v);try{try{await v,this.debug&&console.log(`${this.prefix} sent track_partial ${e} (${y})`);}catch(_){let P=_ instanceof Error?_.message:String(_);console.warn(`${this.prefix} failed to send track_partial (dropping): ${P}`);}}finally{this.inFlight.delete(v);}w||this.sticky.delete(e);}},DY=["apikey","apisecret","apitoken","secretaccesskey","sessiontoken","privatekey","privatekeyid","clientsecret","accesstoken","refreshtoken","oauthtoken","bearertoken","authorization","password","passphrase"],FY="[REDACTED]";function BY(e){return e.toLowerCase().replace(/[-_.]/g,"")}function UY(e,t){var n,o;let r=zEe((n=t?.secretKeyNames)!=null?n:DY),i=(o=t?.placeholder)!=null?o:FY,s=new WeakSet,a=l=>{if(l===null||typeof l!="object")return l;if(s.has(l))return "[CIRCULAR]";if(s.add(l),Array.isArray(l))return l.map(d=>a(d));let c={};for(let[d,u]of Object.entries(l))r.has(BY(d))?c[d]=i:c[d]=a(u);return c};return a(e)}function zEe(e){let t=new Set;for(let n of e)t.add(BY(n));return t}var HY=["ai.request.providerOptions","ai.response.providerMetadata"];function GY(e){let t=e.attributes;if(!t||t.length===0)return e;let n;for(let o=0;o<t.length;o++){let r=t[o],i=jY(r.key,r.value);i!==void 0&&(n||(n=t.slice()),n[o]={key:r.key,value:i});}return n?{...e,attributes:n}:e}var WEe=new Set(HY);function jY(e,t){if(!WEe.has(e))return;let n=t.stringValue;if(typeof n!="string"||n.length===0)return;let o;try{o=JSON.parse(n);}catch{return}let r=UY(o),i;try{i=JSON.stringify(r);}catch{return}if(i!==n)return {stringValue:i}}var qEe=class{constructor(e){this.queue=[],this.inFlight=new Set;var t,n,o,r,i,s,a,l,c;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=xb(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.debugSpans=e.debugSpans===true,this.flushIntervalMs=(o=e.flushIntervalMs)!=null?o:1e3,this.maxBatchSize=(r=e.maxBatchSize)!=null?r:50,this.maxQueueSize=(i=e.maxQueueSize)!=null?i:5e3,this.sdkName=(s=e.sdkName)!=null?s:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.serviceName=(a=e.serviceName)!=null?a:"raindrop.core",this.serviceVersion=(l=e.serviceVersion)!=null?l:"0.0.0",this.localDebuggerUrl=(c=sm(e.localDebuggerUrl))!=null?c:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`),this.transformSpanHook=e.transformSpan,this.disableDefaultRedaction=e.disableDefaultRedaction===true;}redactSpan(e){let t=e;if(this.transformSpanHook)try{let n=this.transformSpanHook(t);if(n===null)return null;n!==void 0&&(t=n);}catch(n){if(this.debug){let o=n instanceof Error?n.message:String(n);console.warn(`${this.prefix} transformSpan hook threw: ${o}`);}return null}return this.disableDefaultRedaction||(t=GY(t)),t}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}startSpan(e){var t,n;let o=vY(e.parent),r=(t=e.startTimeUnixNano)!=null?t:_b(),i=[J("ai.telemetry.metadata.raindrop.eventId",e.eventId),J("ai.operationId",e.operationId)];(n=e.attributes)!=null&&n.length&&i.push(...e.attributes);let s={ids:o,name:e.name,startTimeUnixNano:r,attributes:i};return this.mirrorToLocalDebugger(KN({ids:s.ids,name:s.name,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:s.startTimeUnixNano,attributes:s.attributes,status:{code:CY.UNSET}})),s}mirrorToLocalDebugger(e){if(!this.localDebuggerUrl)return;let t=this.redactSpan(e);if(t===null)return;let n=wY([t],this.serviceName,this.serviceVersion);GEe(n,{baseUrl:this.localDebuggerUrl,debug:false,sdkName:this.sdkName});}endSpan(e,t){var n,o;if(e.endTimeUnixNano)return;e.endTimeUnixNano=(n=t?.endTimeUnixNano)!=null?n:_b(),(o=t?.attributes)!=null&&o.length&&e.attributes.push(...t.attributes);let r=t?.status;if(!r&&t?.error!==void 0){let s=t.error instanceof Error?t.error.message:String(t.error);r={code:CY.ERROR,message:s};}let i=KN({ids:e.ids,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:e.attributes,status:r});this.enqueue(i),this.mirrorToLocalDebugger(i);}createSpan(e){var t;let n=vY(e.parent),o=[J("ai.telemetry.metadata.raindrop.eventId",e.eventId)];(t=e.attributes)!=null&&t.length&&o.push(...e.attributes);let r=KN({ids:n,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:o,status:e.status});this.enqueue(r),this.mirrorToLocalDebugger(r);}enqueue(e){if(!this.enabled)return;if(this.debugSpans){let n=o=>o?o.slice(-8):"none";console.log(`${this.prefix}[span] name=${e.name} trace=${n(e.traceId)} span=${n(e.spanId)} parent=${n(e.parentSpanId)}`);}let t=this.redactSpan(e);if(t!==null){if(this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(t),this.queue.length>=this.maxBatchSize){this.flush().catch(()=>{});return}this.timer||(this.timer=setTimeout(()=>{this.timer=void 0,this.flush().catch(()=>{});},this.flushIntervalMs));}}async flush(){if(this.enabled)for(this.timer&&(clearTimeout(this.timer),this.timer=void 0);this.queue.length>0;){let e=this.queue.splice(0,this.maxBatchSize);if(!this.writeKey)continue;let t=wY(e,this.serviceName,this.serviceVersion),n=`${this.baseUrl}traces`;this.debug&&console.log(`${this.prefix} sending traces batch`,{spans:e.length,endpoint:n});let o=rm(n,t,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(o);try{try{await o,this.debug&&console.log(`${this.prefix} sent ${e.length} spans`);}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send ${e.length} spans: ${i}`);}}finally{this.inFlight.delete(o);}}}async shutdown(){this.timer&&(clearTimeout(this.timer),this.timer=void 0),await this.flush(),await Promise.all([...this.inFlight].map(e=>e.catch(()=>{})));}},KEe={};function xY(){return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE}var YEe=class{constructor(){this._stack=[];}isEmpty(){return this._stack.length===0}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},JEe=class{},XEe=class extends JEe{constructor(){super(),this._fallback=null;let e=xY();if(e){this._storage=new e;return}this._fallback=new YEe,this._storage=this._fallback;}maybeAdoptAsyncLocalStorage(){if(!this._fallback||!this._fallback.isEmpty())return;let e=xY();e&&(this._storage=new e,this._fallback=null);}isReady(){return true}getParentSpanIds(){this.maybeAdoptAsyncLocalStorage();let e=this._storage.getStore();if(!(!e||e===KEe))return {traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId}}runInContext(e,t){return this.maybeAdoptAsyncLocalStorage(),this._storage.run(e,t)}getCurrentSpan(){return this.maybeAdoptAsyncLocalStorage(),this._storage.getStore()}},YN=null;function _u(){return YN||(YN=globalThis.RAINDROP_CONTEXT_MANAGER?new globalThis.RAINDROP_CONTEXT_MANAGER:new XEe),YN}function $Y(e,t){return _u().runInContext(e,t)}async function im(){return _u().getParentSpanIds()}async function Pb(e,t){let n=_u(),o={traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId};return n.runInContext(o,t)}async function*QEe(e,t){let n;for(;;){let o=await $Y(e,async()=>{try{return await t.next(n)}catch(r){return {value:void 0,done:true,error:r}}});if("error"in o&&o.error!==void 0)throw o.error;if(o.done)return o.value;n=yield o.value;}}globalThis.RAINDROP_ASYNC_LOCAL_STORAGE=AsyncLocalStorage;function be(e){return typeof e=="object"&&e!==null}function ti(e){return typeof e=="function"}function _Y(e){var t;if(!e||typeof e!="object")return false;if(((t=e.constructor)==null?void 0:t.name)==="Module")return true;try{let o=Object.keys(e);if(o.length===0)return !1;let r=Object.getOwnPropertyDescriptor(e,o[0]);if(!r)return !1;let i="writable"in r?r.writable:!0;return !r.configurable&&!i}catch{return false}}function Dv(e){try{return JSON.stringify(e)}catch{return}}function dt(e){try{return JSON.stringify(e,(t,n)=>n instanceof Uint8Array?QN(n):n)}catch{return}}function $v(e){if(typeof e=="string"){let r=e.indexOf("/");return r>0&&r<e.length-1?{provider:e.slice(0,r),modelId:e.slice(r+1)}:{modelId:e}}if(!be(e))return {};let t=typeof e.provider=="string"?e.provider:void 0,n;if(typeof e.modelId=="string"?n=e.modelId:typeof e.model=="string"&&(n=e.model),!n)return {provider:t};let o=n.indexOf("/");return !t&&o>0&&o<n.length-1?{provider:n.slice(0,o),modelId:n.slice(o+1)}:{provider:t,modelId:n}}function sL(e){if(!be(e))return;let t=e.text;return typeof t=="string"?t:void 0}function ZEe(e){var t;if(!be(e))return;let n=e.object;if(n!==void 0)return (t=Dv(n))!=null?t:String(n)}function eCe(e){if(typeof e!="function")return false;let t=e.prototype;return be(t)?typeof t.generate=="function"&&typeof t.stream=="function":false}function aL(e){if(!be(e))return;let t=e.model;if(typeof t=="string"&&t.length)return t;let n=e.response;if(be(n)){let o=n.modelId;if(typeof o=="string"&&o.length)return o}}function Ob(e){if(be(e)){if(typeof e.finishReason=="string")return e.finishReason;if(be(e.finishReason)&&typeof e.finishReason.unified=="string")return e.finishReason.unified}}function PY(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return typeof btoa=="function"?btoa(t):""}function Fv(e,t){if(e instanceof URL)return e.toString();if(typeof e=="string")return e.startsWith("data:")||e.startsWith("http://")||e.startsWith("https://")?e:`data:${t};base64,${e}`;if(e instanceof Uint8Array){let n=PY(e);return n?`data:${t};base64,${n}`:void 0}if(e instanceof ArrayBuffer){let n=PY(new Uint8Array(e));return n?`data:${t};base64,${n}`:void 0}}function VY(e){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return `[binary:${e.byteLength} bytes]`;if(e instanceof ArrayBuffer)return `[binary:${e.byteLength} bytes]`}function OY(e){if(typeof e.mediaType=="string")return e.mediaType;if(typeof e.mimeType=="string")return e.mimeType;let t=e.file;if(be(t)){if(typeof t.mediaType=="string")return t.mediaType;if(typeof t.mimeType=="string")return t.mimeType}}function tCe(e){if(typeof e.filename=="string")return e.filename;if(typeof e.name=="string")return e.name;let t=e.file;if(be(t)){if(typeof t.filename=="string")return t.filename;if(typeof t.name=="string")return t.name}}function nCe(e){if("data"in e)return e.data;let t=e.file;if(be(t)){if("file_data"in t)return t.file_data;if("data"in t)return t.data}}function oCe(e,t){var n,o,r;let i=e.type;if(typeof i=="string"){if(i==="image"){let s=(n=OY(e))!=null?n:"image/png",a=Fv(e.image,s);return a?{type:"image",role:t,value:a}:void 0}if(i==="image_url"){let s=e.image_url,a=be(s)?s.url:s,l=Fv(a,"image/png");return l?{type:"image",role:t,value:l}:void 0}if(i==="file"){let s=OY(e),a=nCe(e),l=s?.startsWith("image/")===true,c=l&&s?Fv(a,s):VY(a);if(!c)return;let d=(r=(o=tCe(e))!=null?o:s)!=null?r:"file";return {type:l?"image":"text",role:t,name:d,value:c}}}}function ZN(e,t){if(!Array.isArray(e))return;let n=[];for(let o of e){if(!be(o))continue;let r=oCe(o,t);r&&n.push(r);}return n.length?n:void 0}function rCe(e){var t,n,o,r;let i=typeof e.mediaType=="string"?e.mediaType:typeof e.mimeType=="string"?e.mimeType:void 0,s=(r=(o=(n=(t=e.base64Data)!=null?t:e.base64)!=null?n:e.uint8ArrayData)!=null?o:e.uint8Array)!=null?r:e.data,a=i?.startsWith("image/")===true,l=a&&i?Fv(s,i):VY(s);if(!l)return;let c=typeof e.filename=="string"?e.filename:typeof e.name=="string"?e.name:i??"file";return {type:a?"image":"text",role:"output",name:c,value:l}}async function iCe(e){let t=e;if(t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function")try{t=await t;}catch{return}if(!Array.isArray(t))return;let n=[];for(let o of t){if(!be(o))continue;let r=rCe(o);r&&n.push(r);}return n.length?n:void 0}function zY(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t="";for(let n of e)!be(n)||n.type!=="text"||typeof n.text!="string"||(t+=n.text);return t.length?t:void 0}function lL(e){let t=e.messages;if(Array.isArray(t))return t;let n=e.prompt;if(Array.isArray(n))return n}function WY(e){let t=lL(e);if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(be(o)&&o.role==="user")return o}}function cL(e){var t;if(be(e))return ZN((t=WY(e))==null?void 0:t.content,"input")}async function dL(e){if(!be(e))return;let t=await iCe(e.files);if(t?.length)return t;let n=Vv(e);for(let o=n.length-1;o>=0;o--){let r=n[o];if(!(!be(r)||r.role!=="assistant"))return ZN(r.content,"output")}return ZN(e.content,"output")}function uL(e){var t,n;if(!be(e))return;let o=(t=WY(e))==null?void 0:t.content;if(o===void 0)return;let r=zY(o);return r!==void 0?r:(n=dt(o))!=null?n:String(o)}function pL(e){var t;if(!be(e))return;let n=e.prompt;if(typeof n=="string")return n;let o=lL(e);if(Array.isArray(o)&&o.length>0){let i=o[o.length-1];if(be(i)){let s=i.content,a=zY(s);if(a!==void 0)return a;let l=Dv(s);if(l)return l}return (t=Dv(o))!=null?t:void 0}let r=e.input;return typeof r=="string"?r:Dv(e)}function mL(e){if(!be(e))return [];let t=[];typeof e.system=="string"&&e.system&&t.push({role:"system",content:e.system});let n=lL(e);if(Array.isArray(n)){for(let o of n)be(o)&&typeof o.role=="string"&&t.push(o);return t}return typeof e.prompt=="string"&&e.prompt&&t.push({role:"user",content:e.prompt}),t}function Vv(e){if(!be(e))return [];let t=e.response;if(be(t)&&Array.isArray(t.messages))return t.messages.filter(o=>be(o)&&typeof o.role=="string"&&"content"in o).map(o=>o);let n=e.steps;if(Array.isArray(n)&&n.length>0){let o=n[n.length-1];if(be(o)&&be(o.response)){let r=o.response.messages;if(Array.isArray(r))return r.filter(i=>be(i)&&typeof i.role=="string"&&"content"in i).map(i=>i)}}return []}function Uv(e){if(typeof e.toolCallId=="string"&&e.toolCallId.length>0)return `id:${e.toolCallId}`;if(typeof e.toolName=="string"&&e.toolName.length>0){let t=dt(e.input);return t!==void 0?`name:${e.toolName}|input:${t}`:`name:${e.toolName}`}}function sCe(e,t){return e.isError===true||e.type==="tool-error"?true:be(t)&&typeof t.type=="string"?t.type.startsWith("error")||t.type==="execution-denied":false}function aCe(e){if(typeof e=="string"&&e.length>0)return e;if(be(e)){if(typeof e.value=="string"&&e.value.length>0)return e.value;if(typeof e.reason=="string"&&e.reason.length>0)return e.reason;if(typeof e.message=="string"&&e.message.length>0)return e.message}return dt(e)}function lCe(e){if(!be(e))return [];let t=e.content;return Array.isArray(t)?t.filter(be):be(t)?[t]:[]}function cCe(e){return "input"in e?e.input:"args"in e?e.args:void 0}function hL(e){let t=e.toolCallId;return typeof t=="string"&&t.length>0?t:void 0}function dCe(e){return "output"in e?e.output:"result"in e?e.result:e.error}function uCe(e,t,n){var o;if(!t)return;let r=(o=e.get(t))!=null?o:[];r.includes(n)||(r.push(n),e.set(t,r));}function pCe(e,t){if(!t)return;let n=e.get(t);if(!n||n.length===0)return;let o=n.shift();if(o!==void 0)return n.length===0&&e.delete(t),o}function mCe(e){var t,n,o,r;let{spans:i,pendingKeysByToolName:s,part:a}=e,l=hL(a),c=typeof a.toolName=="string"?a.toolName:void 0,d=cCe(a),u=Uv({toolCallId:l,toolName:c,input:d});if(!u)return;let p=l==null?Uv({toolCallId:void 0,toolName:c,input:void 0}):void 0,m=p&&p!==u?i.get(p):void 0,h=(t=i.get(u))!=null?t:m;i.set(u,{key:u,toolCallId:(n=h?.toolCallId)!=null?n:l,toolName:(o=h?.toolName)!=null?o:c,input:(r=h?.input)!=null?r:d,result:h?.result,status:h?.status,errorMessage:h?.errorMessage}),p&&p!==u&&i.delete(p),!l&&h?.result===void 0&&uCe(s,c,u);}function hCe(e){var t,n,o;let{spans:r,pendingKeysByToolName:i,part:s}=e,a=hL(s),l=typeof s.toolName=="string"?s.toolName:void 0,c=dCe(s),d=Uv({toolCallId:a,toolName:l,input:void 0}),u=a!=null?d:(t=pCe(i,l))!=null?t:d;if(!u)return;let p=r.get(u),m=sCe(s,c);r.set(u,{key:u,toolCallId:(n=p?.toolCallId)!=null?n:a,toolName:(o=p?.toolName)!=null?o:l,input:p?.input,result:c,status:m?"ERROR":"OK",errorMessage:m?aCe(c):void 0});}function qY(e){let t=new Map,n=new Map;for(let o of e)for(let r of lCe(o)){if(r.type==="tool-call"){mCe({spans:t,pendingKeysByToolName:n,part:r});continue}(r.type==="tool-result"||r.type==="tool-error")&&hCe({spans:t,pendingKeysByToolName:n,part:r});}return [...t.values()]}function gCe(e){if(!Array.isArray(e))return;let t="";for(let n of e)be(n)&&n.type==="text"&&typeof n.text=="string"&&(t+=n.text);return t.length?t:void 0}function fCe(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!be(n)||n.type!=="tool-call")continue;let o=hL(n),r=typeof n.toolName=="string"?n.toolName:void 0;(o||r)&&t.push({toolCallId:o,toolName:r,input:n.input});}return t.length?t:void 0}function Lg(e){if(!be(e))return;let t=e.experimental_telemetry;if(be(t))return {functionId:typeof t.functionId=="string"?t.functionId:void 0,isEnabled:typeof t.isEnabled=="boolean"?t.isEnabled:void 0,recordInputs:typeof t.recordInputs=="boolean"?t.recordInputs:void 0,recordOutputs:typeof t.recordOutputs=="boolean"?t.recordOutputs:void 0,metadata:be(t.metadata)?t.metadata:void 0}}function ma(e,t){return {operationName:`${e}${t?` ${t}`:""}`,resourceName:t}}function KY(e,t){if(t==null)return;if(typeof t=="string")return J(e,t);if(typeof t=="number")return Number.isInteger(t)?nt(e,t):Mg(e,t);if(typeof t=="boolean")return LEe(e,t);if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return ad(e,t);let n=dt(t);return n?J(e,n):void 0}function zv(e){return e?Object.entries(e).filter(([t])=>!t.startsWith("raindrop.internal.")).map(([t,n])=>KY(`ai.telemetry.metadata.${t==="raindrop.userId"?"raindrop.ai.userId":t}`,n)):[]}function gL(e){return be(e)?Object.entries(e).filter(([,t])=>typeof t=="string").map(([t,n])=>J(`ai.request.headers.${t}`,n)):[]}function fL(e){if(!be(e))return [];let t=[],n=["maxRetries","timeout","maxOutputTokens","temperature","topP","topK","presencePenalty","frequencyPenalty","seed","stopSequences"];for(let o of n){if(!(o in e))continue;let r=e[o];o==="stopSequences"&&Array.isArray(r)&&r.every(i=>typeof i=="string")?t.push(ad(`ai.settings.${o}`,r)):o==="timeout"&&typeof r=="number"?t.push(nt(`ai.settings.${o}`,r)):t.push(KY(`ai.settings.${o}`,r));}return t}function YY(e){return be(e)?[Mg("gen_ai.request.frequency_penalty",typeof e.frequencyPenalty=="number"?e.frequencyPenalty:void 0),nt("gen_ai.request.max_tokens",typeof e.maxOutputTokens=="number"?e.maxOutputTokens:void 0),Mg("gen_ai.request.presence_penalty",typeof e.presencePenalty=="number"?e.presencePenalty:void 0),...Array.isArray(e.stopSequences)&&e.stopSequences.every(t=>typeof t=="string")?[ad("gen_ai.request.stop_sequences",e.stopSequences)]:[],Mg("gen_ai.request.temperature",typeof e.temperature=="number"?e.temperature:void 0),nt("gen_ai.request.top_k",typeof e.topK=="number"?e.topK:void 0),Mg("gen_ai.request.top_p",typeof e.topP=="number"?e.topP:void 0)]:[]}function JY(e){if(!be(e)||!be(e.providerOptions))return;let t=dt(e.providerOptions);return t?J("ai.request.providerOptions",t):void 0}var yCe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},Mv=null;function XY(){if(Mv)return Mv;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return Mv=e?new e:new yCe,Mv}function yL(){return XY().getStore()}function eL(e,t){return XY().run(e,t)}function QY(e){var t;if(e.length===0)return;let n=e[0];if(!be(n))return;let o=be(n.metadata)?n.metadata:void 0,r=be(n.telemetry)?n.telemetry.metadata:void 0,i=be(r)?r:void 0,s=Lg(n),a=s?.metadata&&typeof s.metadata=="object"?s.metadata:void 0,l=(t=o??i)!=null?t:a;if(!l)return;let c={rawMetadata:l},d=l["raindrop.userId"];typeof d=="string"&&d&&(c.userId=d);let u=l["raindrop.eventId"];typeof u=="string"&&u&&(c.eventId=u);let p=l["raindrop.internal.eventIdGenerated"];(p===true||p==="true"||p==="1")&&(c.eventIdGenerated=true);let m=l["raindrop.convoId"];typeof m=="string"&&m&&(c.convoId=m);let h=l["raindrop.eventName"];typeof h=="string"&&h&&(c.eventName=h);let g=l["raindrop.properties"];if(typeof g=="string")try{let f=JSON.parse(g);f&&typeof f=="object"&&(c.properties=f);}catch{}else g&&typeof g=="object"&&(c.properties=g);return c}var SCe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},Nv=null;function SL(){if(Nv)return Nv;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return Nv=e?new e:new SCe,Nv}function tL(){return SL().getStore()}function nL(e){var t;let n=SL();(t=n.enterWith)==null||t.call(n,e);}function ZY(){var e;let t=SL();(e=t.enterWith)==null||e.call(t,void 0);}var bL=class{constructor(e){this.callStates=new Map,this.priorParentContexts=new Map,this.onStart=t=>{var n,o,r,i,s;if(t.isEnabled===false)return;let a=t.operationId==="ai.embed"||t.operationId==="ai.embedMany",l=t.recordInputs!==false,c=t.recordOutputs!==false,d=t.functionId,u=t.metadata,p=yL(),m=u??p?.rawMetadata,h=this.extractRaindropMetadata(m),g=_u().getParentSpanIds(),f=m?.["raindrop.internal.eventIdGenerated"]==="true"||m?.["raindrop.internal.eventIdGenerated"]===true||p?.eventIdGenerated===true,y=h.eventId&&!f?h.eventId:void 0,S=(i=(r=(o=y??((n=this.defaultContext)==null?void 0:n.eventId))!=null?o:g?.eventId)!=null?r:h.eventId)!=null?i:xu(),T=g&&g.eventId===S?{traceIdB64:g.traceIdB64,spanIdB64:g.spanIdB64}:void 0,{operationName:E,resourceName:C}=ma(t.operationId,d),w=!a&&this.subagentWrapping?tL():void 0,x=!a&&this.subagentWrapping&&w===void 0&&typeof m?.["ash.subagent.name"]=="string"?m["ash.subagent.name"]:void 0,I=(s=w?.toolName)!=null?s:x,v,_;if(I&&this.sendTraces){let L=w?[J("raindrop.parent.callId",w.parentCallId),J("raindrop.parent.toolCallId",w.toolCallId),J("raindrop.parent.toolName",w.toolName)]:[];v=this.traceShipper.startSpan({name:I,parent:T,eventId:S,operationId:"ai.toolCall",attributes:[J("operation.name","ai.toolCall"),J("resource.name",I),J("raindrop.span.kind","tool_call"),J("ai.toolCall.name",I),J("raindrop.subagent.name",I),J("raindrop.agent.role","subagent"),...L]});let k=this.spanParentRef(v),V=this.traceShipper.startSpan({name:"agent.subagent",parent:k,eventId:S,operationId:"agent.subagent",attributes:[J("operation.name","agent.subagent"),J("raindrop.span.kind","llm_call"),J("raindrop.subagent.name",I)]});this.traceShipper.endSpan(V),_=k;}let P;if(this.sendTraces){let L=!a&&l?[J("ai.prompt",dt({system:t.system,prompt:t.prompt,messages:t.messages}))]:[],k=a&&l?t.operationId==="ai.embedMany"?[J("ai.values",dt(t.value))]:[J("ai.value",dt(t.value))]:[];P=this.traceShipper.startSpan({name:t.operationId,parent:_??T,eventId:S,operationId:t.operationId,attributes:[J("operation.name",E),J("resource.name",C),J("ai.telemetry.functionId",d),J("ai.model.provider",t.provider),J("ai.model.id",t.modelId),...zv(m?Object.fromEntries(Object.entries(m).filter(([V])=>V!=="raindrop.eventId"&&V!=="raindrop.internal.eventIdGenerated")):void 0),...L,...k]});}this.callStates.set(t.callId,{operationId:t.operationId,eventId:S,rootSpan:P,rootParent:P?this.spanParentRef(P):_??T,stepSpan:void 0,stepParent:void 0,toolSpans:new Map,embedSpans:new Map,parentContextToolCallIds:new Set,recordInputs:l,recordOutputs:c,functionId:d,metadata:m,accumulatedText:"",inputText:a?void 0:this.extractInputText(t),toolCallCount:0,subagentName:I,subagentToolCallSpan:v});},this.onStepStart=t=>{let n=this.getState(t.callId);if(!n?.rootSpan||!n.rootParent)return;let r=n.operationId==="ai.streamText"||n.operationId==="ai.streamObject"?`${n.operationId}.doStream`:`${n.operationId}.doGenerate`,{operationName:i,resourceName:s}=ma(r,n.functionId),a=[];n.recordInputs&&(t.promptMessages&&a.push(J("ai.prompt.messages",dt(t.promptMessages))),t.stepTools&&a.push(ad("ai.prompt.tools",t.stepTools.map(c=>JSON.stringify(c)))),t.stepToolChoice!=null&&a.push(J("ai.prompt.toolChoice",JSON.stringify(t.stepToolChoice))));let l=this.traceShipper.startSpan({name:r,parent:n.rootParent,eventId:n.eventId,operationId:r,attributes:[J("operation.name",i),J("resource.name",s),J("ai.telemetry.functionId",n.functionId),J("ai.model.provider",t.provider),J("ai.model.id",t.modelId),J("gen_ai.system",t.provider),J("gen_ai.request.model",t.modelId),...a]});n.stepSpan=l,n.stepParent=this.spanParentRef(l);},this.onToolExecutionStart=t=>this.toolExecutionStart(t),this.onToolExecutionEnd=t=>this.toolExecutionEnd(t),this.onToolCallStart=t=>this.toolExecutionStart(t),this.onToolCallFinish=t=>this.toolExecutionEnd(t),this.onLanguageModelCallStart=t=>{},this.onLanguageModelCallEnd=t=>{},this.onChunk=t=>{var n,o,r,i,s;let a=(o=t.callId)!=null?o:(n=t.chunk)==null?void 0:n.callId;if(!a)return;let l=this.getState(a);if(!l)return;let c=t.chunk;if(!(!c||typeof c!="object")){if(c.type==="text-delta"){let d=(r=c.textDelta)!=null?r:c.delta;typeof d=="string"&&(l.accumulatedText+=d,this.emitLive(l,"text_delta",d));}else if(c.type==="reasoning"||c.type==="reasoning-delta"){let d=(s=(i=c.textDelta)!=null?i:c.text)!=null?s:c.delta;typeof d=="string"&&this.emitLive(l,"reasoning_delta",d);}}},this.onStepFinish=t=>{var n,o,r,i,s,a,l,c,d;let u=this.getState(t.callId);if(!u?.stepSpan)return;let p=[];if(u.recordOutputs&&(p.push(J("ai.response.finishReason",t.finishReason),J("ai.response.text",(n=t.text)!=null?n:void 0),J("ai.response.id",(o=t.response)==null?void 0:o.id),J("ai.response.model",(r=t.response)==null?void 0:r.modelId),J("ai.response.timestamp",((i=t.response)==null?void 0:i.timestamp)instanceof Date?t.response.timestamp.toISOString():(s=t.response)==null?void 0:s.timestamp),J("ai.response.providerMetadata",t.providerMetadata?dt(t.providerMetadata):void 0)),((a=t.toolCalls)==null?void 0:a.length)>0&&p.push(J("ai.response.toolCalls",JSON.stringify(t.toolCalls.map(h=>({toolCallId:h.toolCallId,toolName:h.toolName,input:h.input}))))),((l=t.reasoning)==null?void 0:l.length)>0)){let h=t.reasoning.filter(g=>"text"in g).map(g=>g.text).join(`
172
+ `)),i(" ",n(u));}}setMinLevel(t){typeof t=="string"?this.minLogLevel=_S[t]:this.minLogLevel=t;}setOutputStream(t){this.forcedStream=t;}log(...t){this.logWithLevel(30,$a.reset,...t);}info(...t){this.logWithLevel(30,$a.white,...t);}debug(...t){this.logWithLevel(20,$a.dim,...t);}warn(...t){this.logWithLevel(40,$a.yellow,...t);}error(...t){this.logWithLevel(50,$a.red,...t);}success(...t){this.logWithLevel(30,$a.green,...t);}dimmed(...t){this.logWithLevel(30,$a.dim,...t);}underline(...t){this.logWithLevel(30,$a.underline,...t);}bold(...t){this.logWithLevel(30,$a.bold,...t);}grey(...t){this.logWithLevel(30,$a.grey,...t);}child(t){let n=new e(this.minLogLevel,{...this.logBindings,...t});return n.forcedStream=this.forcedStream,n}async flush(){}bindings(){return this.logBindings}},R=tM._internalSingleton(),Dr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Dr,flush:async()=>{},bindings:()=>({})},gC={},oM=({logger:e,logKey:t,maxCount:n,intervalMs:o},r,i,...s)=>{let a=gC[t];a?clearTimeout(a.timer):(a={count:0,totalCount:0},gC[t]=a),a.totalCount++,a.count<n&&(a.count++,e.debug(r,i,...s)),a.timer=setTimeout(()=>{let l=gC[t];l?.totalCount!==l?.count&&e.debug({logKey:t,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${t}`),delete gC[t];},o);};var pV=1e4,mV=1,eg=Ga.extend({browserType:z$1.enum(jl).optional(),slowMoMs:z$1.number().optional().refine(e=>e===void 0||e<=pV&&e>=-1,{message:`Slow motion must be between 0 and ${pV} milliseconds`}),basicAuthorization:z$1.object({username:z$1.string().optional(),password:z$1.string().optional()}).optional(),geolocation:z$1.object({latitude:z$1.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:z$1.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:z$1.boolean().optional(),locale:z$1.string().optional(),timezone:z$1.enum(oC).optional(),colorScheme:z$1.enum(["light","dark"]).optional()}),hV=["extraHeaders","basicAuthorization","localChromeExtensionPaths","proxy"],rM=z$1.object({useMemory:z$1.boolean().optional(),failureRecovery:z$1.boolean().optional().describe("undefined means inherit org settings")}),iM=rM.extend({disableAICaching:z$1.boolean().optional(),failureRecoveryInstructions:z$1.string().optional()}),tfe=z$1.object({viewport:Jc.optional()}),Cs=tfe.extend(iM.shape).extend(eg.shape),fC=z$1.object({cron:z$1.string().refine(e=>isValidCron(e),{error:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:z$1.boolean().default(false),env:z$1.string().optional(),timeZone:z$1.string().default("America/Los_Angeles"),jobKey:z$1.string().optional()}),yC=z$1.object({onSuccess:z$1.boolean().default(false),failureMessage:z$1.string().optional(),onFailure:z$1.boolean().default(true),successMessage:z$1.string().optional()}),nfe=z$1.object({name:z$1.string(),required:z$1.boolean().optional(),defaultValue:z$1.string().describe("this is not optional because we need a value when the editor is first loaded")}),gV=nfe.array(),ofe=z$1.object({name:z$1.string(),value:z$1.string()}),SC=ofe.array(),fV=z$1.object({name:z$1.string(),default:z$1.boolean().optional(),fixtures:V$.array().optional()});var sa=rM.extend({agentConfig:z$1.record(z$1.string(),z$1.string()).optional(),aiFailureAnalysis:z$1.boolean().optional(),classification:XG.optional(),triage:JG.optional(),healing:EE.optional(),explore:vE.optional(),select:eV.optional()}),rfe=z$1.object({cliOnly:z$1.boolean().optional(),neverShowUsageBanner:z$1.boolean().optional(),hideInternalTraceInfo:z$1.boolean().optional(),bypassUsageLimits:z$1.boolean().optional()}),PS=z$1.object({fakerConstantSeed:z$1.boolean().optional(),isolateCachesByEnvironment:z$1.boolean().optional()}),ife=z$1.enum(["flaky_tests","low_test_coverage","frequent_bugs","fix_flaky_tests","migrate_tests","increase_test_coverage","catch_more_bugs"]),sfe=z$1.enum(["ios","android","web"]),afe=z$1.enum(["selenium","playwright","cypress","puppeteer","maestro","appium","detox","manual_qa","nothing_yet","other"]),lfe=z$1.enum(["advertisement","ai_search","google_search","hacker_news","linkedin","reddit","referral_from_customer","twitter_x","word_of_mouth","youtube","other"]),cfe=z$1.object({helpIntents:z$1.array(ife).optional(),helpIntentOtherText:z$1.string().optional(),deviceTypeIntent:sfe.optional(),currentTestingTool:afe.optional(),heardAboutSource:lfe.optional()}),dfe=z$1.object({discovery:cfe.optional(),needsToCompleteOnboarding:z$1.boolean().optional(),wizardCompletedAt:z$1.iso.datetime().optional()}),tg=z$1.object({ai:sa.optional(),githubAppInstallationId:z$1.number().nullish(),githubAppSummaryMessageEnabled:z$1.boolean().nullish(),githubReleaseAppInstallationId:z$1.number().nullish(),gitlabAppAccessToken:z$1.string().nullish(),gitlabAppBaseUrl:z$1.string().nullish(),browser:$O.optional(),internal:rfe.optional(),advanced:PS.optional(),onboarding:dfe.optional()});function yV(e){try{return tg.parse(e)}catch{return R.warn("Cloud settings contain values this version of the CLI does not support. Please upgrade. Falling back to defaults."),tg.parse({})}}z$1.object({globalOverrides:z$1.record(z$1.string(),z$1.string()).optional(),agentConfig:z$1.record(z$1.string(),z$1.string()).optional()});z$1.record(z$1.string(),z$1.string()).nullish();var Vl=(n=>(n.CANNOT_FIX_TEST="CANNOT_FIX_TEST",n.FIXED="FIXED",n))(Vl||{}),SV=z$1.object({index:z$1.int().nonnegative(),section:kO,step:Nt}),ufe=z$1.object({additions:SV.array(),deletions:SV.array()}),OS=z$1.object({subAgentStatus:z$1.enum(Vl).default("CANNOT_FIX_TEST"),rootCause:z$1.string(),solution:z$1.string(),verificationNotes:z$1.string().optional().default(""),diffs:ufe.optional(),pullRequestUrl:z$1.string().optional(),branchUrl:z$1.string().optional()}),bV=OS.optional().catch(void 0),TV=z$1.object({subAgentStatus:z$1.literal("FIXED").default("FIXED"),rootCause:z$1.string(),solution:z$1.string(),verificationNotes:z$1.string().optional().default(""),gitPatch:z$1.string().min(1)});var vs={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ht=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(ht||{});var MS=(r=>(r.NOT_ATTEMPTED="NOT_ATTEMPTED",r.PERM_HEAL_SUCCEEDED="PERM_HEAL_SUCCEEDED",r.PERM_HEAL_FAILED="PERM_HEAL_FAILED",r.PERM_HEAL_ON_SUCCESS_FAILED="PERM_HEAL_ON_SUCCESS_FAILED",r))(MS||{});var NS=z$1.enum(MS).default("NOT_ATTEMPTED"),bC=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(bC||{});var pfe=z$1.object({attempts:z$1.int().nonnegative()}),uo=z$1.string().pipe(z$1.coerce.date()).or(z$1.date()),Qi=z$1.object({id:z$1.string(),runKey:z$1.string(),organizationId:z$1.string(),executionType:mu.optional().default("WEB"),createdAt:uo,createdBy:z$1.string(),flake:z$1.boolean().nullish(),scheduledAt:uo.or(z$1.null()),startedAt:uo.or(z$1.null()),updatedAt:uo.nullish(),finishedAt:uo.or(z$1.null()),resolvedBaseUrl:z$1.string().nullish(),environmentName:z$1.string().nullish(),gitBranchName:z$1.string().nullish(),gitMainBranch:z$1.string().nullish(),githubRepository:z$1.string().nullish(),gitlabProjectPath:z$1.string().nullish(),labels:z$1.array(z$1.string()).optional(),gitOriginUrl:z$1.string().nullish(),gitCommitSha:z$1.string().nullish(),gitCommitShaShort:z$1.string().nullish(),gitCommitAuthorName:z$1.string().nullish(),gitCommitTimestamp:uo.nullish(),gitCommitMessage:z$1.string().nullish(),schemaVersion:z$1.string().nullish(),cliVersion:z$1.string().nullish(),section:z$1.enum(bC).nullish(),status:z$1.enum(ht),healStatus:NS,healDetails:bV.nullish(),trigger:z$1.enum(vs),attempts:z$1.number(),runAttempts:z$1.array(z$1.object({id:z$1.string(),status:z$1.enum(ht),startedAt:uo.or(z$1.null()),finishedAt:uo.or(z$1.null())})).optional(),videos:z$1.array(z$1.string()).optional(),failureReason:z$1.string().nullish(),failureDetails:Zj.nullish(),failureRecoveryDetails:pfe.nullish(),pipelineId:z$1.string().nullish(),resolvedInputs:z$1.record(z$1.string(),z$1.string()).nullish(),quarantined:z$1.boolean().nullish().default(false),quarantinedReason:z$1.string().nullish(),localTestId:z$1.string().nullish(),testId:z$1.string().nullish(),testName:z$1.string().nullish(),description:z$1.string().nullish(),directory:z$1.string().nullish(),test:z$1.object({name:z$1.string(),id:z$1.string()}).nullish().default(null),suiteId:z$1.string().nullish(),aiSettings:sa.nullish(),stepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),beforeStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),afterStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish()}),mfe={id:true,status:true,healStatus:true,healDetails:true,testName:true,localTestId:true,testId:true,test:{select:{name:true,id:true}},finishedAt:true,failureReason:true,failureDetails:true},TC=Qi.pick({...mfe,test:true}),AV=Qi.omit({failureReason:true,failureDetails:true,test:true}),sM=Qi.extend({stepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),beforeStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),afterStepsSnapshot:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).nullish(),resolvedInputs:z$1.record(z$1.string(),z$1.string()).nullish(),test:z$1.object({name:z$1.string(),id:z$1.string(),description:z$1.string().nullish(),baseUrl:z$1.string().nullish(),advanced:Cs.nullish()}).nullish()}).extend(KO.shape),EV=e=>e.includes("PASSED")&&e.includes("FAILED");var hfe=z$1.object({category:z$1.string(),reasoning:z$1.string(),citations:z$1.array(No).optional()}),gfe=z$1.object({testInputs:z$1.record(z$1.string(),z$1.string()).optional(),envName:z$1.string().optional(),urlOverride:z$1.string().optional()}),ffe=z$1.object({reason:z$1.string().optional(),message:z$1.string().optional()}),yfe=z$1.object({runId:z$1.string().optional(),testId:z$1.string(),testName:z$1.string(),filePath:z$1.string(),labels:z$1.array(z$1.string()).optional(),status:z$1.enum(ht),startedAt:z$1.string(),finishedAt:z$1.string(),durationMs:z$1.number(),attempts:z$1.number(),quarantined:z$1.boolean(),recovered:z$1.boolean(),parameters:gfe.optional(),failure:ffe.nullable(),classification:hfe.nullable()}),Sfe=z$1.object({testId:z$1.string(),testName:z$1.string(),filePath:z$1.string(),labels:z$1.array(z$1.string()).optional(),quarantined:z$1.boolean()}),bfe=z$1.object({total:z$1.number(),executed:z$1.number(),skipped:z$1.number(),passed:z$1.number(),failed:z$1.number(),cancelled:z$1.number(),quarantined:z$1.number(),recovered:z$1.number()}),CV=z$1.object({version:z$1.literal(1),runGroup:z$1.object({startedAt:z$1.string(),finishedAt:z$1.string(),durationMs:z$1.number()}),summary:bfe,runs:z$1.array(yfe),skipped:z$1.array(Sfe)});var vV=z$1.enum(["error","warning","passing"]);var RV=z$1.enum(["safe_to_merge","confirm_intended_change","investigate_regression","fix_test","resolve_infra","review_coverage"]);var wV=z$1.object({kind:RV,detail:z$1.string().min(1).max(280)}),zp=z$1.object({riskLevel:z$1.string(),headline:z$1.string().min(1).max(200).describe("One-sentence summary of what happened in this run. Plain text, no markdown."),overview:z$1.string().min(1).max(280).optional().describe("One plain-text sentence giving the bottom line of the run. No markdown."),summaryMarkdown:z$1.string().min(1).max(4e3).describe("Markdown body. Several short paragraphs or a tight list. No emojis, no top-level heading. Max 5 sentences."),recommendedAction:wV.optional()}),IV=zp.extend({riskLevel:vV.describe("Traffic-light validation signal. Use passing when validation is trustworthy with no real concern, warning when review or follow-up is needed, and error when the evidence shows the PR may hide or cause a product regression or another material concern that requires review."),headline:z$1.string().min(1).max(60).describe("Short, factual, title-case status of the validation signal, 6 words max, no punctuation. Describe the outcome only - never name the process or mode (no 'dry run', 'auto-heal', 'triage', 'pending'); those are shown separately. Examples: 'Review Required', 'Sign In Failing Across 5 Tests', 'All Tests Passed'."),overview:z$1.string().min(1).max(280).describe("The bottom-line verdict in one plain sentence: what the Momentic validation means for user-visible behavior and how trustworthy the signal is. This is the conclusion only, not the evidence. No markdown, headings, lists, or emojis. Do not prescribe a merge decision (use recommendedAction)."),summaryMarkdown:z$1.string().min(1).max(1e3).describe("The supporting evidence behind the overview, in GitHub-flavored markdown: a few short sentences or a tight list with the specific tests, errors, and signals that justify the verdict. Must carry information the overview does not - never paraphrase or restate the overview. Do not prescribe a merge decision or restate repair mechanics. Max 4 sentences. No emojis or top-level heading."),recommendedAction:wV.extend({kind:RV.describe("The kind of action a reviewer should take. safe_to_merge = signal is trustworthy and can be merged as-is; confirm_intended_change = a product or UI change was detected (or a heal relaxed an expectation) and a human must confirm it is intentional; investigate_regression = evidence points to a real product bug or regression to investigate before merging; fix_test = a broken or stale test or test setup needs repair; resolve_infra = an infrastructure or environment problem needs resolving and a re-run; review_coverage = quarantine has materially reduced coverage that should be reviewed."),detail:z$1.string().min(1).max(280).describe("One plain-text sentence naming the specific next step (e.g. 'Confirm the new success-indicator color is an intended design change'). No markdown.")}).describe("The single most important next step a reviewer should take. Omit entirely when the signal is clean and there is genuinely nothing to do.").optional()});var xV=z$1.object({id:z$1.string(),status:z$1.enum(ht),trigger:z$1.enum(vs),createdAt:uo,startedAt:uo.nullish(),finishedAt:uo.nullish(),gitCommitSha:z$1.string().nullish(),gitCommitShaShort:z$1.string().nullish(),gitCommitTimestamp:uo.nullish(),gitBranchName:z$1.string().nullish(),gitOriginUrl:z$1.string().nullish(),gitCommitMessage:z$1.string().nullish(),gitCommitAuthorName:z$1.string().nullish(),githubRepository:z$1.string().nullish(),gitlabProjectPath:z$1.string().nullish(),pipelineId:z$1.string().nullish(),ciProvider:z$1.string().nullish(),cliVersion:z$1.string().nullish(),labels:z$1.string().array().optional(),healRiskSummary:zp.optional(),localSuiteName:z$1.string().optional(),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:z$1.object({executionType:mu,status:z$1.enum(ht),environmentName:z$1.string().nullish()}).array()}),_V=xV.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true,localSuiteName:true}).extend({runs:TC.array()}),PV=xV.extend({runs:Qi.array()});var Afe=z$1.object({type:z$1.literal("TARGETING"),name:z$1.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:U$.array(),pageState:z$1.string().optional(),targetSource:z$1.enum(vl).optional(),targetUpdateTime:z$1.string().optional()}),Efe=z$1.object({type:z$1.literal("AI_LOCATION"),matched:z$1.boolean(),pageState:z$1.string().optional(),ragUsed:z$1.boolean().optional(),thoughts:z$1.string().optional()}),Cfe=z$1.object({type:z$1.literal("ASSERTION"),relevantElementsSerialized:z$1.string().array().optional(),pageState:z$1.string().optional(),ragUsed:z$1.boolean().optional()}),OV=z$1.discriminatedUnion("type",[Afe,Efe,Cfe]);var vfe=z$1.object({id:z$1.string(),name:z$1.string()});vfe.extend(z$1.object({createdAt:uo,createdBy:z$1.string(),schedule:fC,notification:yC,environment:z$1.object({name:z$1.string()}).nullish(),beforeTests:z$1.object({id:z$1.string()}).array().nullish(),afterTests:z$1.object({id:z$1.string()}).array().nullish()}).shape);var MV=z$1.object({id:z$1.guid(),orgId:z$1.string(),createdAt:uo,startedAt:uo.or(z$1.null()),finishedAt:uo.or(z$1.null()),status:z$1.enum(ht),trigger:z$1.enum(vs),suite:z$1.object({id:z$1.string(),name:z$1.string()}).nullish(),runs:Qi.array()});MV.pick({id:true,createdAt:true,startedAt:true,finishedAt:true,status:true,trigger:true,suite:true});var NV=MV.extend({runs:TC.array()});function LV({beforeStatus:e,mainStatus:t,afterStatus:n}){return e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":"PASSED"}function AC(e,t){return e.some(r=>t?.onlyQuarantined?r.status==="FAILED":!r.quarantined&&r.status==="FAILED")?"FAILED":e.some(r=>r.status==="CANCELLED")?"CANCELLED":"PASSED"}function kV(e){switch(e){case "PASSED":return "SUCCESS";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":case "PENDING":case "RETRYING":case "WAITING_FOR_USER":return "RUNNING"}}var aM=z$1.object({content:z$1.string(),ids:z$1.string().array(),tokenLength:z$1.number()}),Rfe=z$1.object({chunks:aM.array()});z$1.object({ids:z$1.string().array(),score:z$1.number(),tokenLength:z$1.number()});Rfe.extend({description:z$1.string().describe("Input to pass to RAG engine"),tokenLimit:z$1.number()});var DV=z$1.object({ids:z$1.number().array()}),FV=z$1.object({indices:z$1.number().array()});var zl=(n=>(n.Interactive="interactive",n.Runner="runner",n))(zl||{}),wfe=z$1.enum(zl),rr=z$1.object({disableCache:z$1.boolean().optional(),useMemory:z$1.boolean().optional(),clientMode:wfe.optional(),loggerTags:z$1.record(z$1.string(),z$1.string()).optional(),langfuseSessionId:z$1.string().optional(),agentConfigVersion:z$1.string().optional(),cacheBustReason:z$1.enum(Gy).optional()});rr.extend({chunks:aM.array(),description:z$1.string().describe("Input to pass to AI"),type:z$1.union([z$1.literal("locator"),z$1.literal("assertion"),z$1.literal("ai-action")]),softTokenLimit:z$1.number(),mediumTokenLimit:z$1.number().optional(),hardTokenLimit:z$1.number(),callId:z$1.string().optional()});var Ife=z$1.object({screenshotBase64AfterCommand:z$1.string(),urlAfterCommand:z$1.string(),serializedCommand:z$1.string(),elementInteracted:z$1.string().optional(),thoughts:z$1.string().optional()}),BV=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),source:B$.optional().catch(void 0),isTieBreakerCall:z$1.boolean().optional(),memory:z$1.discriminatedUnion("type",[ka,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),firstPassModelResults:ZE.array().optional(),knowledgeBaseSection:z$1.string().optional()}),UV=z$1.object({target:z$1.string().or(z$1.number()),browserState:z$1.string().optional(),screenshot:z$1.string().optional(),boundingBox:z$1.object({x:z$1.number(),y:z$1.number(),height:z$1.number(),width:z$1.number()}).optional()}),HV=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),GV=z$1.object({goal:z$1.string(),emulatorState:z$1.string(),screenshot:z$1.string().optional(),returnSchema:z$1.string().optional()}),lM=z$1.union([z$1.literal("NEGATED_CHECK"),z$1.literal("CONDITIONAL_CHECK")]),jV=z$1.object({goal:z$1.string(),browserState:z$1.string(),screenshot:z$1.string(),url:z$1.string(),contextChoice:kp.optional(),memory:z$1.discriminatedUnion("type",[Mp,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional(),source:lM.optional(),recoveryHint:z$1.string().optional(),knowledgeBaseSection:z$1.string().optional()}),$V=z$1.object({command:ru}),cM=z$1.object({goal:z$1.string(),browserState:z$1.string(),startingScreenshot:z$1.string().optional(),screenshot:z$1.string(),url:z$1.string(),history:Ife.array(),actionHint:z$1.string().optional(),lastError:z$1.string().optional()}),VV=z$1.object({results:lC.array(),errorMessage:z$1.string(),errorStack:z$1.string().optional()}),zV=z$1.object({results:lC.array(),goal:z$1.string(),errorMessage:z$1.string()}),WV=z$1.object({failedResults:lC.array(),nextStepsSerialized:z$1.string().array(),currentUrl:z$1.string(),currentPageState:z$1.string(),currentScreenshot:z$1.string(),customInstructions:z$1.string().optional(),testDescription:z$1.string().optional()});z$1.object({description:z$1.string(),type:z$1.union([z$1.literal("locator"),z$1.literal("assertion"),z$1.literal("ai-action")]),excerpt:z$1.string()});var qV=z$1.object({type:z$1.string(),browserContext:z$1.string(),currentStep:z$1.string(),screenshot:z$1.string()}),KV=z$1.object({description:z$1.string(),browserState:z$1.string().optional(),screenshot:z$1.string()}),xfe=z$1.enum(["locator","assertion"]);z$1.object({completionType:xfe,currentGoal:z$1.string(),pastGoal:z$1.string().optional(),currentScreenshot:z$1.string(),pastScreenshot:z$1.string(),pastResult:z$1.union([z$1.boolean(),z$1.number()])});z$1.object({goal:z$1.string()});var YV=z$1.object({keywords:z$1.array(z$1.string())});var EC=(i=>(i.LOCATOR="locator",i.ASSERTION="assertion",i.VISUAL_ASSERTION="visual-assertion",i.TEXT_EXTRACTION="text-extraction",i.FAILURE_RECOVERY="failure-recovery",i))(EC||{}),_fe=["locator","assertion","visual-assertion","text-extraction","failure-recovery"];z$1.enum(EC);var Pfe=new Set(_fe);function Ofe(e){return Pfe.has(e)}var Mfe=z$1.enum(["v1","v2","v3","v4"]),Nfe=z$1.string().regex(/^v\d+\.\d+$/).describe("pinned sub-version like v3.1");z$1.union([Mfe,Nfe,z$1.string().describe("for people with special configurations")]);var og={locator:"v4.2",assertion:"v4.1","visual-assertion":"v4.0","text-extraction":"v3.0","failure-recovery":"v2.1"},JV={locator:{v4:["v4.2","v4.1","v4.0"],v3:["v3.3","v3.2","v3.1","v3.0"],v2:["v2.2","v2.1","v2.0"],v1:["v1.0"]},assertion:{v4:["v4.1","v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.3","v2.2","v2.1","v2.0"],v1:["v1.0"]},"visual-assertion":{v4:["v4.0"],v3:["v3.2","v3.1","v3.0"],v2:["v2.0"],v1:["v1.0"]},"text-extraction":{v3:["v3.0"],v2:["v2.0"],v1:["v1.0"]},"failure-recovery":{v2:["v2.1","v2.0"],v1:["v1.0"]}},XV=(s=>(s.ANDROID_LOCATOR="android-locator",s.IOS_LOCATOR="ios-locator",s.ANDROID_ASSERTION="android-assertion",s.IOS_ASSERTION="ios-assertion",s.ANDROID_TEXT_EXTRACTION="android-text-extraction",s.IOS_TEXT_EXTRACTION="ios-text-extraction",s))(XV||{});z$1.enum(XV);var Lfe={locator:["v1"],assertion:["v1"],"visual-assertion":["v1"],"text-extraction":["v1"]};function kfe(e){let t=Lfe[e];if(!t)return new Set;let n=JV[e],o=new Set;for(let r of t){o.add(r);for(let i of n[r]??[])o.add(i);}return o}function CC(e){for(let[t,n]of Object.entries(e)){if(!Ofe(t))continue;let o=JV[t];if(!o)continue;let r=new Set;for(let[i,s]of Object.entries(o)){r.add(i);for(let a of s)r.add(a);}if(!r.has(n)){let i=[...r].sort();throw new te("UserConfigurationError",`Invalid agent config: "${n}" is not a valid version for "${t}". Valid versions: ${i.join(", ")}`)}if(kfe(t).has(n))throw new te("UserConfigurationError",`Agent config "${n}" for "${t}" is no longer supported because it relies on a legacy model. Upgrade to a newer version.`)}}var Xc=O__default.object({id:O__default.guid(),envKey:O__default.string().optional(),skipped:O__default.boolean().optional(),retries:O__default.number().optional()});var gu=(r=>(r.PRESET="MOBILE_PRESET_STEP",r.MODULE="MOBILE_MODULE_STEP",r.AI_ACTION="MOBILE_AI_ACTION_STEP",r.CONDITIONAL="MOBILE_CONDITIONAL_STEP",r))(gu||{});var rg=Xc.extend({type:O__default.literal("MOBILE_CONDITIONAL_STEP")});var Zr=z$1.object({id:z$1.string(),name:qE,baseUrl:KE,description:z$1.string().optional().nullish(),schemaVersion:z$1.string(),advanced:Cs,retries:z$1.number().optional().nullish(),envs:z$1.array(fV).nullish(),parameters:gV.nullish(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional().catch([])}),QV=z$1.enum(["INHERIT","ENABLED","DISABLED"]);var Ffe=Cs.extend({failureRecovery:QV.optional(),useMemory:QV.optional()});Zr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,parameters:true}).extend({advanced:Ffe});Zr.pick({name:true,description:true,baseUrl:true,retries:true,disabled:true,advanced:true,parameters:true});var Bfe=z$1.object({labels:z$1.array(z$1.string()).optional(),outputs:SC.nullish()}),Zn=Zr.extend(Bfe.shape),Ufe=z$1.object({createdAt:z$1.coerce.date(),updatedAt:z$1.coerce.date(),updatedBy:z$1.string().nullable(),schedule:fC,notification:yC,createdBy:z$1.string(),organizationId:z$1.string(),folderId:z$1.string().nullable().optional()}),Hfe=Zr.extend(Ufe.shape);Hfe.extend(Dl.shape);var dM=Zr.extend(Dl.shape);Zr.extend(Vc.shape);var Gfe="test",jfe="module",$fe="mobile-test",Vfe="mobile-module",zfe="test/v2",Wfe="module/v2",qfe="mobile-test/v2",Kfe="mobile-module/v2";var De=(l=>(l.TEST=`momentic/${Gfe}`,l.MODULE=`momentic/${jfe}`,l.TEST_V2=`momentic/${zfe}`,l.MODULE_V2=`momentic/${Wfe}`,l.MOBILE_TEST=`momentic/${$fe}`,l.MOBILE_MODULE=`momentic/${Vfe}`,l.MOBILE_TEST_V2=`momentic/${qfe}`,l.MOBILE_MODULE_V2=`momentic/${Kfe}`,l))(De||{});Zr.merge(Vc);var Yfe=Xn.extend({steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())),schemaVersion:z$1.string()}),DS=Yfe.extend({fileType:z$1.literal(De.MODULE)});z$1.object({test:z$1.string().describe("YAML for the test, including metadata and steps"),modules:z$1.record(z$1.string(),z$1.string()).describe("Map of module name to YAML for the module")});function vC(e){if(e===void 0)return "__undefined__";if(e===null)return null;if(typeof e!="object")return e;if(Array.isArray(e))return e.map(vC);let t={};for(let[n,o]of Object.entries(e))t[n]=vC(o);return t}var Jfe=/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/,ZV=36,mo=z$1.union([z$1.guid().max(ZV,"V2 IDs must be 36 characters or fewer"),z$1.string().max(ZV,"V2 IDs must be 36 characters or fewer").regex(Jfe,"V2 IDs must be lowercase kebab-case with at least three words, e.g. silver-river-lantern")],{error:"ID must be a UUID or lowercase kebab-case with at least three words, e.g. silver-river-lantern (36 characters max)"});var RC=O.discriminatedUnion("type",[O.object({type:O.literal("SCREEN")}),O.object({type:O.literal("OPEN_APP")}),O.object({type:O.literal("OPEN_WEBVIEW")})]),Qc=O.object({type:O.literal("description"),description:O.string()}),pM=O.object({type:O.literal("CUSTOM_COORDINATES"),startX:O.number().describe("Starting X coordinate in pixels"),startY:O.number().describe("Starting Y coordinate in pixels"),deltaPixels:O.number().describe("Number of pixels to scroll in the specified direction")}),wC=O.discriminatedUnion("type",[...RC.options,O.object({type:O.literal("CUSTOM"),target:Qc}),pM]);function Xfe(e){return e.toLowerCase().replaceAll("_"," ")}function mM(e){switch(e.type){case "CUSTOM":return e.target.description;case "CUSTOM_COORDINATES":return `custom coordinates (x: ${Math.round(e.startX)}, y: ${Math.round(e.startY)}, delta: ${Math.round(e.deltaPixels)}px)`;case "SCREEN":case "OPEN_APP":case "OPEN_WEBVIEW":return Xfe(e.type);default:{throw new Error("Unreachable")}}}var Qfe=O.object({type:O.literal("coordinates"),xPercent:O.number(),yPercent:O.number()}),Zfe=O.object({type:O.literal("absolute_percent"),x:O.number(),y:O.number()}),ig=O.discriminatedUnion("type",[Qc,Qfe,Zfe]);var eye=O.object({x1:O.number(),y1:O.number(),x2:O.number(),y2:O.number(),tolerance:O.nativeEnum(Ki),preciseTolerance:O.boolean().optional()}),tye=O.object({width:O.number(),height:O.number(),tolerance:O.nativeEnum(Ki),preciseTolerance:O.boolean().optional()}),hM=O.object({requiredText:O.string().optional(),requiredAttributes:O.record(O.string(),O.string()).optional(),requiredBounds:O.boolean().optional(),position:eye.optional(),shape:tye.optional()}),ez=O.object({xPath:O.string(),requirements:hM.optional()}),nye=O.object({type:O.literal("CUSTOM"),target:Qc,cache:O.lazy(()=>tz).optional()}),oye=O.object({pixelDelta:O.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:O.union([RC,nye,pM]),direction:O.enum(["up","down"])}),tz=O.object({type:O.literal("NATIVE"),bounds:O.number().array().optional(),resolvedDescription:O.string().optional(),xPath:O.string().optional(),elementOnlySerializedXml:O.string().optional(),scrollDetails:oye.optional(),requirements:hM.optional(),requiredRelatedElements:ez.array().optional(),memory:ka.optional()}),rye=O.object({type:O.literal("WEBVIEW"),resolvedDescription:O.string().optional(),xPath:O.string().optional(),browserCache:Rl.optional(),memory:ka.optional()}),IC=O.union([tz,rye]);var iye=O.object({left:O.number(),top:O.number(),right:O.number(),bottom:O.number()});O.object({newViewportBounds:iye});var sye=O.object({type:O.literal("CUSTOM"),target:Qc,cache:O.lazy(()=>iz).optional()}),nz=O.object({pixelDelta:O.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:O.union([RC,sye,pM]),direction:O.enum(["up","down"])}),oz=(n=>(n.Native="native",n.Appium="appium",n))(oz||{}),gM=O.tuple([O.number(),O.number(),O.number(),O.number()]),rz=ez.extend({bounds:gM.optional(),browserCache:Rl.optional()}),iz=O.object({type:O.literal("NATIVE"),bounds:gM.optional(),resolvedDescription:O.string().optional(),sourceTree:O.nativeEnum(oz).optional(),xPath:O.string().optional(),elementOnlySerializedXml:O.string().optional(),scrollDetails:nz.optional(),requirements:hM.optional(),requiredRelatedElements:rz.array().optional(),memory:ka.optional()}),aye=O.object({type:O.literal("WEBVIEW"),bounds:gM.optional(),resolvedDescription:O.string().optional(),xPath:O.string().optional(),scrollDetails:nz.optional(),browserCache:Rl.optional(),requiredRelatedElements:rz.array().optional(),memory:ka.optional()}),xC=O.discriminatedUnion("type",[iz,aye]);var zt=(_=>(_.AI_CHECK="AI_CHECK",_.AI_EXTRACT="AI_EXTRACT",_.TAP="TAP",_.TYPE="TYPE",_.PRESS="PRESS",_.PRESS_KEYBOARD="PRESS_KEYBOARD",_.OPEN_APP="OPEN_APP",_.KILL_APP="KILL_APP",_.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",_.SWIPE="SWIPE",_.SCROLL_TO="SCROLL_TO",_.SCREEN_CHECK="SCREEN_CHECK",_.ELEMENT_CHECK="ELEMENT_CHECK",_.VISUAL_DIFF="VISUAL_DIFF",_.DRAG_AND_DROP="DRAG_AND_DROP",_.JAVASCRIPT="JAVASCRIPT",_.REQUEST="REQUEST",_.WAIT="WAIT",_.ADD_FILE="ADD_FILE",_.INSTALL_APP="INSTALL_APP",_.UNINSTALL_APP="UNINSTALL_APP",_.TOGGLE_SETTINGS="TOGGLE_SETTINGS",_.ROTATE_ORIENTATION="ROTATE_ORIENTATION",_.ADB_COMMAND="ADB_COMMAND",_.APPIUM_EXECUTE="APPIUM_EXECUTE",_.STATE="STATE",_))(zt||{}),Xe=O__default.object({id:O__default.guid(),disableCache:O__default.boolean().optional()}),sg=O__default.object({updatedAt:O__default.coerce.date().optional(),updatedAtLoggerTags:O__default.record(O__default.string(),O__default.string()).optional()}),la=sg.extend({target:IC}),_C=sg.extend({fromTarget:IC,toTarget:IC}),Wl=sg.extend({target:xC}),sz=sg.extend({fromTarget:xC,toTarget:xC}),Zc=e=>{switch(e.type){case "description":return e.description;case "coordinates":return `${Math.round(e.xPercent*100)}%, ${Math.round(e.yPercent*100)}%`;case "absolute_percent":return `x: ${e.x}%, y: ${e.y}%`}};var az=Xe.extend({type:O__default.literal("ADB_COMMAND"),command:O__default.string(),jsonArgs:O__default.string().optional()});var lye=O__default.string().trim(),cz=Xe.extend({type:O__default.literal("INSTALL_APP"),uri:lye});var dz=Xe.extend({type:O__default.literal("OPEN_NOTIFICATION_DRAWER")});var FS=(r=>(r.AIRPLANE_MODE="AIRPLANE_MODE",r.DATA="DATA",r.WIFI="WIFI",r.LOCATION="LOCATION",r))(FS||{}),pz=Xe.extend({type:O__default.literal("TOGGLE_SETTINGS"),settingsType:O__default.nativeEnum(FS)});var hz=Xe.extend({type:O__default.literal("UNINSTALL_APP"),packageName:O__default.string()});var PC=Xe.extend({type:O__default.literal("APPIUM_EXECUTE"),command:O__default.string(),jsonArgs:O__default.string().optional()});var gz=Xe.extend({type:O__default.literal("ADD_FILE"),file:O__default.string(),storageLocation:O__default.string()});var ed=Xe.extend({type:O__default.literal("AI_CHECK"),assertion:O__default.string(),timeoutSecs:O__default.number().optional(),contextChoice:kp.optional(),cache:sg.extend({memory:Mp.optional()}).optional()});var fz=Xe.extend({type:O__default.literal("AI_EXTRACT"),goal:O__default.string(),schema:O__default.string().optional()});var ag=Xe.extend({type:O__default.literal("JAVASCRIPT"),code:O__default.string(),timeout:O__default.number().int().max(600).optional().describe("Max seconds for the code to complete")});var yz=Xe.extend({type:O__default.literal("KILL_APP")});var US=(n=>(n.HOME="HOME",n.POWER="POWER",n))(US||{}),OC=(s=>(s.BACK="BACK",s.APP_SWITCHER="APP_SWITCHER",s.SEARCH="SEARCH",s.VOLUME_UP="VOLUME_UP",s.VOLUME_DOWN="VOLUME_DOWN",s.VOLUME_MUTE="VOLUME_MUTE",s))(OC||{}),MC=Xe.extend({type:O__default.literal("PRESS"),key:O__default.nativeEnum(US),longPress:O__default.boolean().optional()}),Sz=MC.extend({key:O__default.nativeEnum(OC).or(O__default.nativeEnum(US))}),bz=MC;var Tz=Xe.extend({type:O__default.literal("REQUEST")}).merge(Vy);var EM=(n=>(n.PORTRAIT="PORTRAIT",n.LANDSCAPE="LANDSCAPE",n))(EM||{}),Ez=Xe.extend({type:O__default.literal("ROTATE_ORIENTATION"),orientation:O__default.nativeEnum(EM)});var pye=O__default.object({type:O__default.literal("CONTENT"),negated:O__default.boolean().optional(),value:O__default.string()}),cg=Xe.extend({type:O__default.literal("SCREEN_CHECK"),assertion:pye,timeout:O__default.number().int().min(0).max(Ih).optional().describe("max seconds to wait for the assertion to be true")});var Cz=Xe.extend({type:O__default.literal("STATE")});var vz=Xe.extend({type:O__default.literal("VISUAL_DIFF"),path:O__default.string().describe("path to the golden screenshot to compare against"),threshold:O__default.number().min(0).max(1).optional().describe("max allowed fraction of differing pixels before the diff fails (default 0.1)")});O__default.object({created:O__default.boolean(),goldenPath:O__default.string(),threshold:O__default.number(),goldenScreenshotBase64:O__default.string().optional(),currentScreenshotBase64:O__default.string().optional(),diffScreenshotBase64:O__default.string().optional(),goldenScreenshotSnapshotId:O__default.string().optional(),currentScreenshotSnapshotId:O__default.string().optional(),diffScreenshotSnapshotId:O__default.string().optional(),diffPercent:O__default.number().optional(),pass:O__default.boolean().optional(),dimensionMismatch:O__default.boolean().optional()});var wz=Xe.extend({type:O__default.literal("WAIT"),timeoutSecs:O__default.number()});var HS=O__default.discriminatedUnion("type",[Cz,ed,fz,ag,wz,Tz,Ez,cg,vz,gz,yz]);O__default.discriminatedUnion("type",[...HS.options,MC]);var vM=Xe.extend({type:O__default.literal("DRAG_AND_DROP"),fromTarget:Qc,toTarget:Qc,hoverDuration:O__default.number().optional(),dragDuration:O__default.number().optional()}),GS=vM.extend({cache:_C.optional()}),jS=vM.extend({cache:sz.optional()});var RM=Xe.extend({type:O__default.literal("ELEMENT_CHECK"),target:ig,assertion:xE,timeout:O__default.number().int().min(0).max(Ih).optional().describe("max seconds to wait for the assertion to be true")}),Wp=RM.extend({cache:la.optional()}),qp=RM.extend({cache:Wl.optional()});var $S=(n=>(n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))($S||{}),NC=(t=>(t.CLOSE_KEYBOARD="CLOSE_KEYBOARD",t))(NC||{}),_z={repeat:O__default.number().int().min(1).optional(),keyPressDelayMs:O__default.number().min(0).optional()},Pz=Xe.extend({type:O__default.literal("PRESS_KEYBOARD"),key:O__default.nativeEnum($S),..._z}),Oz=Xe.extend({type:O__default.literal("PRESS_KEYBOARD"),key:O__default.nativeEnum(NC).or(O__default.nativeEnum($S)),..._z});var Mz=Xe.extend({type:O__default.literal("OPEN_APP"),packageName:O__default.string(),activityName:O__default.string().optional(),intentExtras:O__default.string().optional()}),Nz=Xe.extend({type:O__default.literal("OPEN_APP"),packageName:O__default.string(),intentExtras:O__default.string().optional()});var wM=Xe.extend({type:O__default.literal("SCROLL_TO"),target:Qc,direction:O__default.enum(["down","up"]),scrollableElement:wC,scrollStepPercent:O__default.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.9 (90%)."),maxScrollAttempts:O__default.number().int().min(1).max(50).optional().describe("Maximum number of scroll attempts before giving up. Default is 20.")}),VS=wM.extend({cache:la.optional()}),zS=wM.extend({cache:Wl.optional()});var IM=Xe.extend({type:O__default.literal("SWIPE"),direction:O__default.enum(["up","down","left","right"]),scrollableElement:wC,viewportPercent:O__default.number().optional(),durationMs:O__default.number().optional(),relativePosition:wE.optional()}),WS=IM.extend({cache:la.optional()}),qS=IM.extend({cache:Wl.optional()});var xM=Xe.extend({type:O__default.literal("TAP"),target:ig,longPress:O__default.boolean().optional(),longPressDurationMs:O__default.number().optional(),iterations:O__default.number().optional(),tapDelayMs:O__default.number().optional(),relativePosition:wE.optional(),doubleTap:O__default.boolean().optional(),doubleTapDelayMs:O__default.number().optional()}),KS=xM.extend({cache:la.optional()}),YS=xM.extend({cache:Wl.optional()});var JS=(r=>(r.AUTO="auto",r.PROGRAMMATIC="programmatic",r.LONG_PRESS="long-press",r.BACKSPACE="backspace",r))(JS||{});var _M=Xe.extend({type:O__default.literal("TYPE"),target:ig.optional(),keyPressDelayMs:O__default.number().optional(),text:O__default.string(),clearContent:O__default.boolean().optional(),forceClearContent:O__default.boolean().optional(),replaceStrategy:O__default.nativeEnum(JS).optional()});var XS=_M.extend({cache:la.optional()}),QS=_M.extend({cache:Wl.optional()});var ZS=O__default.discriminatedUnion("type",[...HS.options,KS,XS,Sz,Oz,hz,cz,az,PC,GS,dz,VS,WS,pz,Wp,Mz]);var eb=O__default.discriminatedUnion("type",[...HS.options,YS,QS,bz,Pz,Nz,qS,jS,zS,qp,PC]);var Dz=O__default.union([O__default.string(),O__default.record(O__default.string(),O__default.unknown().optional())]),DC=Xc.extend({type:O__default.literal("MOBILE_PRESET_STEP"),keyPressDelayMs:O__default.number().optional()}),yu=DC.extend({command:ZS}),Su=DC.extend({command:eb}),ug=O__default.object({moduleId:O__default.string(),inputs:O__default.record(O__default.string(),O__default.string()).optional()}),tb=Xc.merge(ug.extend({type:O__default.literal("MOBILE_MODULE_STEP")}));ug.extend({steps:O__default.lazy(()=>ql.array())});ug.extend({steps:O__default.lazy(()=>td.array())});var PM=(n=>(n.V2="2",n.V3="3",n))(PM||{});var OM=O__default.nativeEnum(PM),yye=Cl.extend({platform:O__default.literal("ANDROID"),resolvedGoal:O__default.string(),steps:O__default.lazy(()=>yu.array()),autoGeneratedPostcondition:O__default.string().optional()}),Sye=Cl.extend({platform:O__default.literal("IOS"),resolvedGoal:O__default.string(),steps:O__default.lazy(()=>Su.array()),autoGeneratedPostcondition:O__default.string().optional()}),MM=O__default.discriminatedUnion("platform",[yye,Sye]),bu=Xc.extend({type:O__default.literal("MOBILE_AI_ACTION_STEP"),text:O__default.string(),version:OM.optional(),cache:MM.optional(),precondition:O__default.string().optional(),postcondition:O__default.string().optional()});var Tye=O__default.discriminatedUnion("type",[ed,cg,Wp,ag]),NM=DC.extend({command:Tye}),Aye=O__default.discriminatedUnion("type",[ed,cg,qp,ag]),LM=DC.extend({command:Aye}),Eye=O__default.object({assertion:NM,steps:O__default.lazy(()=>ql.array())}),Cye=O__default.object({assertion:LM,steps:O__default.lazy(()=>td.array())}),vye=rg.extend({blocks:O__default.lazy(()=>Eye.array()),elseSteps:O__default.lazy(()=>ql.array()).optional()}),Rye=rg.extend({blocks:O__default.lazy(()=>Cye.array()),elseSteps:O__default.lazy(()=>td.array()).optional()}),ql=O__default.discriminatedUnion("type",[yu,tb,bu,vye]),td=O__default.discriminatedUnion("type",[Su,tb,bu,Rye]);O__default.union([ql.array(),td.array()]);var kM=O__default.object({parameterNames:O__default.string().array(),defaultParameters:O__default.record(O__default.string(),O__default.string()).optional(),parameterEnums:O__default.record(O__default.string(),O__default.string().array()).optional()}),FC=O__default.object({moduleId:mo,name:O__default.string(),description:O__default.string().nullish(),platform:O__default.nativeEnum(ja).optional().default("ANDROID"),parameters:kM.optional(),enabled:O__default.boolean().nullish(),schemaVersion:O__default.string()}),DM=FC.omit({name:true}),wye=DM.extend({steps:Dz.array()});O__default.object({fileType:O__default.literal(De.MOBILE_MODULE)}).merge(wye);var Fz=FC.omit({platform:true,schemaVersion:true});({ANDROID:Fz.extend({platform:O__default.literal("ANDROID"),steps:ql.array()}),IOS:Fz.extend({platform:O__default.literal("IOS"),steps:td.array()})});var pg=(t=>(t.MODULE="RESOLVED_MOBILE_MODULE",t))(pg||{}),Bz=O__default.object({description:O__default.string().optional(),name:O__default.string().describe("name of the module"),parameters:kM.optional()}),Uz=ug.merge(Bz).extend({platform:O__default.literal("ANDROID"),get steps(){return Wa.array()}}),Hz=ug.merge(Bz).extend({platform:O__default.literal("IOS"),get steps(){return qa.array()}});O__default.discriminatedUnion("platform",[Uz,Hz]);var FM=Xc.merge(Uz).extend({type:O__default.literal("RESOLVED_MOBILE_MODULE")}),BM=Xc.merge(Hz).extend({type:O__default.literal("RESOLVED_MOBILE_MODULE")});O__default.discriminatedUnion("platform",[FM,BM]);var Iye=O__default.object({assertion:NM,get steps(){return Wa.array()}}),UM=rg.extend({get blocks(){return Iye.array()},get elseSteps(){return Wa.array().optional()}}),xye=O__default.object({assertion:LM,get steps(){return qa.array()}}),HM=rg.extend({get blocks(){return xye.array()},get elseSteps(){return qa.array().optional()}}),Wa=O__default.discriminatedUnion("type",[FM,yu,bu,UM]),qa=O__default.discriminatedUnion("type",[BM,Su,bu,HM]);function Gz(e){return Object.values(pg).includes(e)||Object.values(gu).includes(e)}var jz=(i=>(i.PRECONDITION="PRECONDITION",i.REPLAY="REPLAY",i.GENERATE="GENERATE",i.AUTOHEAL="AUTOHEAL",i.POSTCONDITION="POSTCONDITION",i))(jz||{}),$z=z$1.enum(["pending","running","success","failed"]),Vz=z$1.object({type:z$1.literal("THOUGHT"),text:z$1.string(),blockId:z$1.string().optional()}),zz=z$1.object({type:z$1.literal("TOOL_CALL"),toolName:z$1.string()}),Wz=z$1.object({type:z$1.literal("PHASE"),phase:z$1.nativeEnum(jz),failureMessage:z$1.string().optional()}),_ye=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:Wa,status:$z,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),Pye=z$1.object({type:z$1.literal("STEP_UPDATE"),stepIndex:z$1.number(),step:qa,status:$z,message:z$1.string().optional(),afterSnapshotId:z$1.string().optional()}),qz=z$1.object({type:z$1.literal("POSTCONDITION_AUTOGENERATED"),postcondition:z$1.string()}),Oye=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:yu.array(),resolvedGoal:z$1.string()}),Mye=z$1.object({type:z$1.literal("CACHED_STEPS_GENERATED"),cachedSteps:Su.array(),resolvedGoal:z$1.string()}),Kz=z$1.discriminatedUnion("type",[Vz,zz,Wz,_ye,Oye,qz]),Yz=z$1.discriminatedUnion("type",[Vz,zz,Wz,Pye,Mye,qz]);var Kl=O__default.object({message:O__default.string().optional(),startTime:O__default.number(),endTime:O__default.number(),status:O__default.nativeEnum(Mt),trace:O__default.unknown().optional().optional(),beforeSnapshot:O__default.string().optional(),afterSnapshot:O__default.string().optional(),data:O__default.unknown().optional().optional().describe("output data from the step"),aiSuggested:O__default.boolean().optional(),beforeTestContext:Jh.optional(),afterTestContext:Jh.optional()}),Jz=Kl.merge(yu).extend({previousAttempts:O__default.lazy(()=>ws.array()).optional()}),Nye=Kl.merge(tb).extend({steps:O__default.lazy(()=>ws.array()),name:O__default.string().optional(),previousAttempts:O__default.lazy(()=>ws.array()).optional()}),Lye=Kl.merge(bu).extend({steps:O__default.lazy(()=>ws.array()),previousAttempts:O__default.lazy(()=>ws.array()).optional(),failureRecoveryReason:O__default.string().optional(),trajectory:Kz.array().optional()}),kye=Kl.merge(UM).extend({assertionResult:Jz.optional(),steps:O__default.lazy(()=>ws.array()),previousAttempts:O__default.lazy(()=>ws.array()).optional()}),ws=O__default.discriminatedUnion("type",[Jz,Nye,Lye,kye]),Xz=Kl.merge(Su).extend({previousAttempts:O__default.lazy(()=>Is.array()).optional()}),Dye=Kl.merge(tb).extend({steps:O__default.lazy(()=>Is.array()),name:O__default.string().optional(),previousAttempts:O__default.lazy(()=>Is.array()).optional()}),Fye=Kl.merge(bu).extend({steps:O__default.lazy(()=>Is.array()),previousAttempts:O__default.lazy(()=>Is.array()).optional(),failureRecoveryReason:O__default.string().optional(),trajectory:Yz.array().optional()}),Bye=Kl.merge(HM).extend({assertionResult:Xz.optional(),steps:O__default.lazy(()=>Is.array()),previousAttempts:O__default.lazy(()=>Is.array()).optional()}),Is=O__default.discriminatedUnion("type",[Xz,Dye,Fye,Bye]);var Uye=Kl.extend({index:O__default.number().optional(),userFacingStepReference:O__default.string().optional(),description:O__default.string()}),Qz=Uye.extend({beforeScreenshot:O__default.string().optional(),afterScreenshot:O__default.string().optional()});var Zz=z$1.object({attributesRequired:z$1.array(z$1.string()).optional(),textRequired:z$1.boolean().optional(),boundsRequired:z$1.boolean().optional(),positionSpecificity:z$1.enum(Ki).optional(),shapeSpecificity:z$1.enum(Ki).optional()}),Hye=z$1.object({id:z$1.number(),requirements:Zz}).array();z$1.object({thoughts:z$1.string(),id:z$1.number(),updatedMemory:Uy.optional(),inWebview:z$1.boolean().optional(),requirements:Zz.optional(),additionalElements:Hye.optional()});var Gye=z$1.literal("SCROLL_TO"),eW=z$1.object({description:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),source:Gye.optional(),memory:z$1.discriminatedUnion("type",[ka,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional()}),tW=z$1.object({assertion:z$1.string(),screenXml:z$1.string(),screenshot:z$1.string(),contextChoice:kp.optional(),memory:z$1.discriminatedUnion("type",[Mp,z$1.object({type:z$1.literal("RESOLVED_TRACES"),traces:z$1.unknown().optional().array()})]).optional()});z$1.object({thoughts:z$1.string(),result:z$1.boolean(),relevantElements:z$1.array(z$1.number()).optional(),updatedMemory:Hy.optional()});var nW=z$1.object({failedResults:Qz.array(),nextStepsSerialized:z$1.string().array(),currentScreenXml:z$1.string(),currentScreenshot:z$1.string(),customInstructions:z$1.string().optional(),testDescription:z$1.string()}),oW=(o=>(o.LEGITIMATE="LEGITIMATE",o.RECOVERABLE="RECOVERABLE",o.INELIGIBLE="INELIGIBLE",o))(oW||{});z$1.object({thoughts:z$1.string(),scenario:z$1.enum(oW),instructions:z$1.string().nullish(),reasonSummary:z$1.string().nullish()});z$1.looseObject({type:z$1.literal("response.create")});var rW=z$1.union([z$1.looseObject({response:z$1.looseObject({id:z$1.string()}),sequence_number:z$1.number(),type:z$1.literal("response.completed")}),z$1.looseObject({code:z$1.string().nullable(),message:z$1.string(),sequence_number:z$1.number(),type:z$1.literal("error")})]);var iW="ui_states.jsonl";z$1.object({stepId:z$1.string(),parentStepIdChain:z$1.array(z$1.string()),fingerprintHash:z$1.string(),minhash:z$1.array(z$1.number().int()),canonicalUrl:z$1.string(),capturedAt:z$1.number().describe("Unix timestamp in milliseconds")});var mg=(a=>(a.TestRun="test-run",a.MobileTestRun="mobile-test-run",a.CreditsUsed="credits-used",a.CreditsUsedV2="credits-used-v2",a.StepsExecuted="steps-executed",a.LLMTokensUsed="llm-tokens-used",a.HostedBrowserSecondsUsed="hosted-browser-seconds-used",a))(mg||{}),Zi=(c=>(c.TestRunner="test-runner",c.Editor="editor",c.Mcp="mcp",c.Explore="explore",c.Heal="heal",c.ResultClassification="result-classification",c.GithubPrSummary="github-pr-summary",c.AppGraph="app-graph",c.RunViewer="run-viewer",c))(Zi||{}),jye=3;function $ye(e){return e==="MODULE"||e==="CONDITIONAL"||e==="WHILE_LOOP"||e==="SECTION"||e==="RESOLVED_MODULE"}function sW(e){if(!$ye(e))switch(e){case "PRESET_ACTION":return 0;case "AI_ACTION":return 3;case "AI_ACTION_DYNAMIC":return 5;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}function aW(e){switch(e.type){case "AI_EXTRACT":case "AI_ASSERTION":return jye;case "CAPTCHA":return 3;case "CLICK":case "TYPE":case "SELECT_OPTION":case "HOVER":case "ELEMENT_CHECK":case "FOCUS":case "BLUR":case "SCROLL_DOWN":case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_UP":case "MOUSE_DRAG":return e.useSelector||!e.target||e.target.type!=="description"?0:1;case "DRAG":return e.useSelector?0:1;case "VISUAL_DIFF":case "TAB":case "JAVASCRIPT":case "NAVIGATE":case "WAIT":case "SUCCESS":case "AUTH_LOAD":case "AUTH_SAVE":case "COOKIE":case "DIALOG":case "FILE_UPLOAD":case "GO_BACK":case "GO_FORWARD":case "LOCAL_STORAGE":case "NEW_TAB":case "CLOSE_TAB":case "PAGE_CHECK":case "PRESS":case "KEY_DOWN":case "KEY_UP":case "COPY":case "PASTE":case "REFRESH":case "REQUEST":case "GRAPHQL_REQUEST":case "WAIT_FOR_URL":case "REGISTER_REQUEST_LISTENER":case "AWAIT_LISTENER":case "RECORD_REQUESTS":case "GET_RECORDED_REQUESTS":case "SET_HEADER":case "MOCK_ROUTE":case "REMOVE_ROUTE_MOCK":case "OFFLINE_MODE":return 0;default:(n=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})();}}var GM=z$1.object({name:z$1.string(),value:z$1.string(),url:z$1.string().optional(),domain:z$1.string().optional(),path:z$1.string().optional(),expires:z$1.number().default(Date.now()/1e3+60*60*24*365),httpOnly:z$1.boolean().optional(),secure:z$1.boolean().default(true),sameSite:z$1.union([z$1.literal("Strict"),z$1.literal("Lax"),z$1.literal("None")]).default("None")});function BC(e,t){let n=[],o=splitCookiesString(e);for(let r of o){let i=parseString(r,{decodeValues:false});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let s;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")s="Strict";else if(d==="lax")s="Lax";else if(d==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=false),!i.path&&i.domain&&(i.path="/"),!i.domain&&t&&(i.domain=t);let a=GM.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:s});n.push(a);let l=[a.name,...Object.keys(a)].map(d=>d.toLowerCase()),c=r.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,p]=d.split("=");if(!u||!p)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||n.push({...a,name:u,value:p});}}return n}var Wye=z$1.object({origin:z$1.string(),localStorage:z$1.array(z$1.object({name:z$1.string(),value:z$1.string()})),sessionStorage:z$1.array(z$1.object({name:z$1.string(),value:z$1.string()})).optional()}),qye=z$1.object({entries:z$1.record(z$1.string(),z$1.array(z$1.tuple([z$1.unknown().optional(),z$1.unknown().optional()]))),version:z$1.number().optional()}),UC=z$1.object({cookies:GM.array().optional(),origins:Wye.array().optional(),idb:z$1.record(z$1.string(),qye).optional().describe("key is db name")});function lW(e,t){let n=[];return e.cloneSync()?.serializeSync()?.cookies.forEach(o=>{let r=GM.safeParse({name:o.key,...o});if(!r.success)return;let i=r.data;!i.domain&&!i.url&&(i.domain=t),n.push(i);}),n}var es={type:true,cache:true},cW=[ed.pick(es),Wp.pick(es),KS.pick(es),XS.pick(es),WS.pick(es),VS.pick(es),GS.pick(es)],jM=O__default.discriminatedUnion("type",cW),dW=[ed.pick(es),qp.pick(es),YS.pick(es),QS.pick(es),qS.pick(es),jS.pick(es),zS.pick(es)],$M=O__default.discriminatedUnion("type",dW);Object.values(zt).filter(e=>cW.some(t=>t.shape.type.safeParse(e).success));Object.values(zt).filter(e=>dW.some(t=>t.shape.type.safeParse(e).success));var VM=O__default.object({type:O__default.literal("MOBILE_AI_ACTION_STEP"),cache:MM}),HC=O__default.union([jM,VM]),GC=O__default.union([$M,VM]);var zM=(s=>(s.US_EAST_1="us-east1",s.US_EAST_2="us-east2",s.US_WEST_1="us-west1",s.US_WEST_2="us-west2",s.EU_NORTH_1="eu-north1",s.AS_SOUTH_1="as-south1",s))(zM||{}),WM=(o=>(o.US="us",o.EU="eu",o.AS="as",o))(WM||{}),uW=(t=>(t.LOCAL="local",t))(uW||{}),qM=O__default.nativeEnum(zM).or(O__default.nativeEnum(WM)),KM=O__default.nativeEnum(zM).or(O__default.nativeEnum(WM)).or(O__default.nativeEnum(uW)),Yye="closest";KM.or(O__default.literal(Yye));var gg=(n=>(n.ANDROID_14="14",n.ANDROID_15="15",n))(gg||{});var jC=(t=>(t.IOS_26="26",t))(jC||{});var Jye=["1.56.1-lim.1","1.60.0-lim.1"],pW=O__default.enum(Jye);var mW=O__default.nativeEnum(gg).or(O__default.nativeEnum(jC));var Xye=O__default.object({disableMomenticAccessibilityTree:O__default.boolean().optional(),autoGrantPermissions:O__default.boolean().optional().describe("Automatically grant app permission prompts during the run. Android only."),autoAcceptAlerts:O__default.boolean().optional().describe("Automatically accept native alert dialogs. iOS only."),autoDismissAlerts:O__default.boolean().optional().describe("Automatically dismiss native alert dialogs. iOS only."),disableXmlSnapshots:O__default.boolean().optional().describe("Skip collecting XML snapshots during test runs. This can speed up test runs, but will cause the run viewer to show less information."),browserSettings:eg.optional(),locale:O__default.string().optional().describe("Device locale code (e.g. 'fr', 'en-us'). Sets the device language and region. iOS and Android.")}),Qye="avdId",Zye="iosDeviceType",eSe="iosVersion",YM=Xye.extend({region:KM.optional().describe('Where the emulator runs: "local" for an emulator on your machine, or a region for hosted emulators. Defaults to hosted emulators.'),remoteEmulatorSettings:O__default.object({androidVersion:O__default.nativeEnum(gg).optional()}).optional(),localEmulatorSettings:O__default.object({[Qye]:Qh,[Zye]:Qh,[eSe]:Qh}).optional(),geolocation:O__default.object({latitude:O__default.number().refine(e=>e>=-90&&e<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:O__default.number().refine(e=>e>=-180&&e<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),waitForStability:O__default.boolean().optional().describe("wait for stability before every targeting action")});var ob=O__default.object({retries:O__default.number().optional().describe("number of retries to run"),defaultChannel:O__default.string().optional().describe("Default app release channel to use when installing from managed mobile artifacts."),defaultTag:O__default.string().optional().describe("Default app artifact tag to use. If not set, the latest available tag is used."),defaultEnv:O__default.string().optional().describe("Default mobile environment name to load variables from at runtime."),defaultApkFilePath:Qh.describe("APK to install when using the emulator in the local region."),defaultAppFilePath:Qh.describe("App file (e.g. .app or .ipa) to install when using the emulator in the local region."),emulator:YM.optional().describe("Emulator configuration for local or remote mobile execution, including region and local emulator overrides."),ai:iM.optional().describe("AI behavior overrides for this mobile test, such as memory and failure recovery settings.")}),hW=O__default.object({id:mo,description:O__default.string(),schemaVersion:O__default.string(),settings:ob.optional(),disabled:O__default.boolean().optional(),labels:O__default.array(O__default.string()).optional()}),fg=hW.extend({platform:O__default.literal("ANDROID").optional().default("ANDROID")}),yg=hW.extend({platform:O__default.literal("IOS")}),gW=O__default.discriminatedUnion("platform",[fg,yg]),fW=O__default.object({fileType:O__default.literal(De.MOBILE_TEST)}),yW=fW.merge(fg),SW=fW.merge(yg);O__default.discriminatedUnion("platform",[yW,SW]);var bW=fg.merge(O__default.object({steps:O__default.array(ql)})),TW=yg.merge(O__default.object({steps:O__default.array(td)}));O__default.discriminatedUnion("platform",[bW,TW]);var tSe=yW.merge(bW),nSe=SW.merge(TW);O__default.discriminatedUnion("platform",[tSe,nSe]);O__default.object({name:O__default.string(),steps:O__default.array(ql).optional(),settings:ob.optional()});var AW=fg.extend({steps:Wa.array(),beforeSteps:Wa.array().optional(),afterSteps:Wa.array().optional()}),EW=yg.extend({steps:qa.array(),beforeSteps:qa.array().optional(),afterSteps:qa.array().optional()});O__default.discriminatedUnion("platform",[AW,EW]);var oSe=AW.extend({name:O__default.string()}),rSe=EW.extend({name:O__default.string()});O__default.discriminatedUnion("platform",[oSe,rSe]);var Er=O__default.object({startTime:O__default.number(),endTime:O__default.number().optional(),durationMs:O__default.number().optional(),error:O__default.string().optional(),result:O__default.unknown().optional().optional(),attributes:O__default.record(O__default.string(),O__default.unknown().optional()),subSpans:O__default.lazy(()=>ESe.array())});var JM=Er.extend({type:O__default.literal("SECTION"),name:O__default.string()}),iSe=Er.extend({type:O__default.literal("GET_PAGE_STATE")}),sSe=Er.extend({type:O__default.literal("GET_PAGE_SCREENSHOT")}),aSe=Er.extend({type:O__default.literal("SMART_WAITING")}),lSe=Er.extend({type:O__default.literal("SCROLL_ELEMENT_INTO_VIEW")}),cSe=Er.extend({type:O__default.literal("AI_LOCATOR_CALL"),screenshotSnapshotId:O__default.string().optional(),result:O__default.object({id:O__default.number(),thoughts:O__default.string(),citations:No.array().optional()}).optional()}),dSe=Er.extend({type:O__default.literal("AI_ASSERTION_CALL"),screenshotSnapshotId:O__default.string().optional(),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({thoughts:O__default.string(),result:O__default.boolean(),citations:No.array().optional()}).optional()}),uSe=Er.extend({type:O__default.literal("AI_EXTRACTION_CALL"),screenshotSnapshotId:O__default.string().optional(),browserStateSnapshotId:O__default.string().optional(),result:O__default.object({thoughts:O__default.string().optional(),result:O__default.unknown().optional().optional()}).optional()}),pSe=Er.extend({type:O__default.literal("ELEMENT_ASSERTION"),name:O__default.string(),result:O__default.object({success:O__default.boolean(),message:O__default.string().optional()}).optional()}),mSe=Er.extend({type:O__default.literal("BROWSER_INTERACTION"),name:O__default.string(),coordinates:O__default.object({x:O__default.number(),y:O__default.number()}).optional(),value:O__default.string().optional(),selector:O__default.string().optional()}),hSe=Er.extend({type:O__default.literal("CACHE_RESOLUTION"),resolutionMethod:O__default.string().optional(),cacheMissReason:O__default.nativeEnum(bh).optional(),targetSource:O__default.string().optional(),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({serializedElement:O__default.string()}).optional()}),gSe=Er.extend({type:O__default.literal("TARGET_RESOLUTION"),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({serializedElement:O__default.string()}).optional()}),fSe=Er.extend({type:O__default.literal("LOCATOR_REDIRECT"),elementScreenshotSnapshotId:O__default.string().optional(),result:O__default.object({outcome:O__default.string(),logs:O__default.string().array().optional(),serializedElement:O__default.string().optional(),relativeClickPoint:O__default.object({x:O__default.number(),y:O__default.number()}).optional(),force:O__default.boolean().optional()}).optional()}),ySe=Er.extend({type:O__default.literal("WAIT_FOR_STABILITY")}),SSe=Er.extend({type:O__default.literal("GENERIC"),name:O__default.string()}),bSe=Er.extend({type:O__default.literal("PAGE_ASSERTION"),name:O__default.string(),result:O__default.object({success:O__default.boolean(),message:O__default.string().optional()}).optional()}),TSe=Er.extend({type:O__default.literal("AUTO_FOLLOW_NEW_TABS"),result:O__default.object({followed:O__default.boolean()}).optional()}),ASe=Er.extend({type:O__default.literal("VISUAL_DIFF"),name:O__default.string(),result:O__default.object({success:O__default.boolean(),message:O__default.string().optional()}).optional()});function CW(e){return e.type==="CACHE_RESOLUTION"||e.type==="TARGET_RESOLUTION"}var ESe=O__default.discriminatedUnion("type",[JM,iSe,sSe,aSe,lSe,cSe,dSe,uSe,pSe,mSe,gSe,hSe,fSe,ySe,bSe,ASe,SSe,TSe]);z$1.object({testId:z$1.string(),sessionId:z$1.string()});var vW=z$1.object({uploadUrl:z$1.string(),id:z$1.string()});new Set(Object.values(Vn));var bn={AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of a conditional check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",BLUR:"Remove focus from an element on the page.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",CLOSE_TAB:"Close a specified open tab or current tab if none specified.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock."};var CSe=z$1.string().refine(e=>Ld.valid(e),{error:"must be a valid semver string"});function XM(e){return Ld.parse(e)||void 0}function rb(e){if(e!==void 0)return e===true||e==="true"||e==="1"}var wW="on-fail";function IW(e){return e==="on-fail"?"on-fail":e==="false"?false:!!e}var xW=(n=>(n.CLI="cli",n.MobileCLI="mobile-cli",n))(xW||{}),vSe=z$1.nativeEnum(xW),_W=(o=>(o.Error="error",o.Warn="warn",o.Info="info",o))(_W||{}),RSe=z$1.nativeEnum(_W),wSe=z$1.object({id:z$1.string(),level:RSe,versionRange:z$1.string(),announcement:z$1.string()});z$1.object({cliType:vSe,version:CSe});var PW=z$1.object({announcements:z$1.array(wSe)});var ib=55555,$C="momentic-code-eval.js";z$1.object({body:z$1.string(),to:z$1.string(),from:z$1.string()});z$1.object({from:z$1.string().optional(),to:z$1.string(),timeout:z$1.number().optional(),beforeDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional(),afterDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional()});z$1.object({timeoutMs:z$1.number().nonnegative().optional()}).optional();z$1.object({phoneNumber:z$1.string(),leaseToken:z$1.string()});var ISe=z$1.union([z$1.string(),z$1.date()]).transform(e=>e instanceof Date?e:new Date(e)),OW=z$1.object({phoneNumber:z$1.string(),expiresAt:ISe,leaseToken:z$1.string()});z$1.object({to:z$1.email(),from:z$1.string(),subject:z$1.string(),body:z$1.string(),html:z$1.string().optional()});z$1.object({inbox:z$1.string().transform(e=>e.toLowerCase()),afterDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional(),timeout:z$1.number().optional(),trimWhitespace:z$1.boolean().optional()});z$1.object({inbox:z$1.string(),limit:z$1.number().optional(),afterDate:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()).optional(),trimWhitespace:z$1.boolean().optional()});var MW=z$1.object({email:z$1.string(),prefix:z$1.string(),expiresAt:z$1.coerce.date()}),VC=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(VC||{}),NW=z$1.object({body:z$1.string().nullish(),status:z$1.number().optional(),headers:z$1.array(z$1.tuple([z$1.string(),z$1.string()])).optional()}),xSe=z$1.object({url:z$1.string(),options:z$1.object({method:z$1.string(),body:z$1.string().nullish(),headers:z$1.array(z$1.tuple([z$1.string(),z$1.string()])).optional()}).optional()}).optional(),_Se=z$1.object({body:z$1.string().nullish(),options:z$1.object({status:z$1.number(),statusText:z$1.string().optional(),headers:z$1.array(z$1.tuple([z$1.string(),z$1.string()])).optional()}).optional()}).optional(),LW=z$1.object({result:z$1.unknown().optional(),variableUpdates:z$1.record(z$1.string(),z$1.unknown().optional()).optional(),persistentVariableUpdates:z$1.record(z$1.string(),z$1.unknown().optional()).optional(),error:z$1.string().optional(),success:z$1.boolean()});z$1.object({id:z$1.string().optional(),orgId:z$1.string(),momenticLambdaAuthHash:z$1.string(),code:z$1.string(),fragment:z$1.boolean(),state:z$1.object({env:z$1.record(z$1.string(),z$1.unknown().optional()),request:xSe,response:_Se,additionalBindings:z$1.record(z$1.string(),z$1.unknown().optional()).optional()}),timeoutMs:z$1.number().optional(),disallowVariableUpdates:z$1.boolean().optional(),responseSerialization:z$1.enum(VC).optional()});var Tu=9e4;var PSe=O.object({url:O.string(),lineNumber:O.number(),columnNumber:O.number()}),kW=O.object({timestamp:O.number(),text:O.string(),type:O.string(),tabIndex:O.number(),args:O.unknown().optional().array().optional(),url:O.string().optional(),location:PSe.optional()}),DW=kW.array(),QM=DW.array();var sb=class{async getConsoleLogsForRunAttempt(t,n,o){}async getNetworkLogsForRunAttempt(t,n,o){}async getHtmlSnapshot(t,n){}async getA11yTreeSnapshot(t,n){}async getScreenshot(t,n){}async storeConsoleLogsForRunAttempt(t,n,o,r){}async storeNetworkLogsForRunAttempt(t,n,o,r){}listVideoAssetPaths(){return []}close(){}async storeScreenshot(t,n,o){}async storeOnDemandScreenshotById(t,n,o,r){}async storeHtmlSnapshot(t,n,o){}};var OSe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),MSe=z$1.object({name:z$1.string(),version:z$1.string(),comment:z$1.string().optional()}),NSe=z$1.object({onContentLoad:z$1.number().optional(),onLoad:z$1.number().optional(),comment:z$1.string().optional()}),ab=z$1.object({startedDateTime:z$1.string(),id:z$1.string(),title:z$1.string().optional(),pageTimings:NSe,comment:z$1.string().optional()}),LSe=z$1.array(ab),kSe=z$1.object({name:z$1.string(),value:z$1.string(),path:z$1.string().optional(),domain:z$1.string().optional(),expires:z$1.string().optional(),httpOnly:z$1.boolean().optional(),secure:z$1.boolean().optional(),comment:z$1.string().optional()}),BW=z$1.array(kSe),DSe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),UW=z$1.array(DSe),FSe=z$1.object({name:z$1.string(),value:z$1.string(),comment:z$1.string().optional()}),BSe=z$1.array(FSe),USe=z$1.object({name:z$1.string(),value:z$1.string().optional(),fileName:z$1.string().optional(),contentType:z$1.string().optional(),comment:z$1.string().optional()}),HSe=z$1.array(USe),GSe=z$1.object({mimeType:z$1.string(),params:HSe,text:z$1.string(),comment:z$1.string().optional(),_redactedReason:z$1.string().optional()}),jSe=z$1.object({method:z$1.string(),url:z$1.string(),httpVersion:z$1.string().optional(),cookies:BW,headers:UW,queryString:BSe,postData:GSe.optional(),headersSize:z$1.number().optional(),bodySize:z$1.number().optional(),comment:z$1.string().optional()}),$Se=z$1.object({size:z$1.number().optional(),compression:z$1.number().optional(),mimeType:z$1.string().optional(),text:z$1.string().optional(),encoding:z$1.string().optional(),comment:z$1.string().optional(),_redactedReason:z$1.string().optional()}),VSe=z$1.object({status:z$1.number(),statusText:z$1.string(),httpVersion:z$1.string().optional(),cookies:BW,headers:UW,content:$Se,redirectURL:z$1.string().optional(),headersSize:z$1.number().optional(),bodySize:z$1.number().optional(),comment:z$1.string().optional(),_mocked:z$1.boolean().optional()}),FW=z$1.object({expires:z$1.string().optional(),lastAccess:z$1.string(),eTag:z$1.string(),hitCount:z$1.number(),comment:z$1.string().optional()}),zSe=z$1.object({beforeRequest:FW.optional(),afterRequest:FW.optional(),comment:z$1.string().optional()}),WSe=z$1.object({blocked:z$1.number().optional(),dns:z$1.number().optional(),connect:z$1.number().optional(),send:z$1.number(),wait:z$1.number(),receive:z$1.number(),ssl:z$1.number().optional(),comment:z$1.string().optional()}),lb=z$1.object({pageref:z$1.string().optional(),startedDateTime:z$1.string(),time:z$1.number().optional(),request:jSe,response:VSe.optional(),cache:zSe.optional(),timings:WSe,serverIPAddress:z$1.string().optional(),connection:z$1.string().optional(),comment:z$1.string().optional(),_resourceType:z$1.string().optional()}),qSe=z$1.array(lb),KSe=z$1.object({version:z$1.string().default("1.1"),creator:OSe.optional(),browser:MSe.optional(),pages:LSe.optional(),entries:qSe,comment:z$1.string().optional()});z$1.object({log:KSe});z$1.record(z$1.string(),ab);z$1.record(z$1.string(),lb);function ZM(e,t){return {log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(e).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime()),entries:Object.values(t).sort((n,o)=>new Date(n.startedDateTime).getTime()-new Date(o.startedDateTime).getTime())}}}var eN=(E=>(E.DisableClickhouseCaches="disable_clickhouse_caches",E.ShowZeroOpacityElements="show_zero_opacity_elements",E.VisualActions="visual_actions",E.RagV2="rag_v2",E.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",E.GlobalLocatorRedirect="global_locator_redirect",E.FakerConstantSeed="faker_constant_seed",E.AutoExpandIframes="auto_expand_iframes",E.MobileNewAiActionStepsUseV3="mobile_new_ai_action_steps_use_v3",E.PerformanceInsights="performance_insights",E.ShowKnowledgeBase="show_knowledge_base",E.AppGraphBackend="app_graph_backend",E.AppGraphUI="app_graph_ui",E.ClassificationUI="classification_ui",E.HealingUI="healing_ui",E.ExploreUI="explore_ui",E.SlackNotifications="slack_notifications",E.SlackNotificationDms="slack_notification_dms",E.ResultClassificationCache="result_classification_cache",E.HealTraceUI="heal_trace_ui",E))(eN||{});var Au=z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null(),z$1.record(z$1.string(),z$1.lazy(()=>Au)),z$1.array(z$1.lazy(()=>Au))]),cb=class{flags;payloads;constructor(t,n){this.flags=t,this.payloads=n;}isBooleanFlagEnabled(t){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="true"?true:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${t.toUpperCase()}`]==="false"?false:this.flags[t]===true}getAllFlags(){let t=cloneDeep(this.flags);return Object.entries(t).forEach(([n,o])=>{typeof o=="boolean"&&Object.values(eN).includes(n)&&(t[n]=this.isBooleanFlagEnabled(n));}),t}getFlagPayload(t){let n=this.payloads[t];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}};var db={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},HW=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var GW=z$1.discriminatedUnion("operation",[z$1.object({operation:z$1.literal("upsert"),path:z$1.string().min(1),content:z$1.string()}),z$1.object({operation:z$1.literal("delete"),path:z$1.string().min(1)})]),XSe=z$1.object({githubLogin:z$1.string().optional(),email:z$1.string().optional()}),QSe=z$1.object({baseSha:z$1.string().min(1),headSha:z$1.string().min(1)}),ZSe=z$1.object({baseBranch:z$1.string().min(1).max(255),baseCommitSha:z$1.string().min(1),headBranch:z$1.string().min(1).max(255).optional(),branchPrefix:z$1.string().min(1).max(255).optional(),idempotencyKey:z$1.string().min(1).optional()}),ebe=z$1.object({commitMessage:z$1.string().min(1),title:z$1.string().min(1),body:z$1.string(),reviewers:z$1.array(z$1.string().min(1)).optional(),draft:z$1.boolean().optional()});ZSe.extend(ebe.shape).extend({changes:z$1.array(GW).min(1),coAuthorRange:QSe.optional(),requestCommitAuthorsAsReviewers:z$1.boolean().optional()}).superRefine((e,t)=>{e.headBranch||(!e.branchPrefix||!e.idempotencyKey)&&t.addIssue({code:"custom",message:"branchPrefix and idempotencyKey are required when headBranch is omitted",path:["idempotencyKey"]});});var jW=z$1.object({pullRequestUrl:z$1.url(),pullRequestNumber:z$1.number(),headBranch:z$1.string(),commitSha:z$1.string(),created:z$1.boolean(),authors:z$1.array(XSe).optional()});z$1.object({branch:z$1.string().min(1).max(255),commitMessage:z$1.string().min(1),changes:z$1.array(GW).min(1)});var $W=z$1.object({branch:z$1.string(),commitSha:z$1.string(),committed:z$1.boolean()}),VW=z$1.object({issueNumber:z$1.number(),htmlUrl:z$1.url(),headBranch:z$1.string().min(1),baseBranch:z$1.string().min(1),latestCommitSha:z$1.string().min(1),draft:z$1.boolean().optional(),title:z$1.string().optional(),body:z$1.string().optional()});z$1.object({number:z$1.number(),htmlUrl:z$1.url()});var tbe=z$1.object({path:z$1.string().min(1),status:z$1.string().min(1),additions:z$1.number(),deletions:z$1.number(),previousPath:z$1.string().optional(),patch:z$1.string().optional()}),nbe=z$1.object({sha:z$1.string().min(1),author:z$1.string().optional(),email:z$1.string().optional(),date:z$1.string().optional(),message:z$1.string()}),zW=z$1.object({mergeBaseSha:z$1.string().min(1),totalCommits:z$1.number(),commits:z$1.array(nbe),files:z$1.array(tbe)}),WW=z$1.object({content:z$1.string().nullable()}),qW=z$1.object({name:z$1.string().min(1),protected:z$1.boolean()}),KW=z$1.object({iid:z$1.number(),webUrl:z$1.url(),sourceBranch:z$1.string().min(1),targetBranch:z$1.string().min(1),latestCommitSha:z$1.string().min(1)}),obe=z$1.object({name:z$1.string(),path:z$1.string(),body:z$1.string()}),YW=z$1.object({template:obe});function ir(e){let[t,n,...o]=e.split("/");if(!(!t||!n||o.length>0))return {owner:t,repo:n}}function JW(e){let t=ir(e);if(t)return t;throw new mt(`Invalid GitHub repository string: ${e}. Expected format "owner/repo".`)}var rbe=/^co-authored-by:\s*.*?<([^>]+)>\s*$/gim,ibe=/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i;function zC(e){return e.match(ibe)?.[1]}function XW(e){let t=[];for(let n of e.matchAll(rbe)){let o=n[1]?.trim();o&&t.push({email:o,githubLogin:zC(o)});}return t}function sbe(e){return (e.githubLogin??(e.email?zC(e.email):void 0))?.toLowerCase().endsWith("[bot]")??false}function QW(e){return e.filter(t=>!sbe(t))}var ZW="https://static.momentic.ai";function ub(e,t){return {light:`${ZW}/${e}.svg`,dark:`${ZW}/${e}-dark.svg`,alt:t}}var pb={runGroup:ub("run-group-button","View run group"),basePr:ub("view-base-pr-button","View base PR"),branch:ub("view-branch-button","View branch"),commit:ub("view-commit-button","View commit")};function mb({href:e,button:t}){return `<a href="${e}"><picture><source media="(prefers-color-scheme: dark)" srcset="${t.dark}" /><img src="${t.light}" alt="${t.alt}" /></picture></a>`}var tN=O__default.object({platformSep:O__default.string(),fullPathSegments:O__default.string().array(),relativePathSegments:O__default.string().array(),relativePath:O__default.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:O__default.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:O__default.coerce.date(),createdAt:O__default.coerce.date()});var abe=z$1.array(tN.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),labels:z$1.string().array().optional()})),lbe=tN.extend({id:z$1.string(),name:z$1.string(),description:z$1.string().optional(),content:WE}),cbe=z$1.array(lbe);z$1.object({tests:abe,modules:cbe,labels:z$1.string().array()});z$1.string().array();var e1=z$1.object({pathSegments:z$1.string().array()});dM.merge(Zn);var t1=z$1.object({schemaVersion:z$1.string(),stepLists:Dl}),n1=Zn.partial().merge(Zr.pick({id:true})),Xp="1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID.",nN={name:z$1.string().min(1).max(255).describe(Xp),description:z$1.string().optional(),baseUrl:z$1.url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:z$1.string().optional().describe("For LLM: Do not include the variable unless the user explicitly asks for it and use the environment lookup tool to get the correct one before passing here."),browserType:z$1.enum(jl).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Jc.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:z$1.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder. Paths are relative to the project root.")},o1=z$1.object(nN);dM.extend(z$1.object({relativeFilePath:z$1.string().describe("relative to project root")}).shape);var r1=z$1.object({name:z$1.string()});z$1.object({relativeFilePath:z$1.string()});var i1=z$1.object({name:z$1.string(),sourceModuleContent:WE});z$1.object({relativeFilePath:z$1.string()});var s1=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean(),steps:z$1.lazy(()=>Gt.array()),testFilePath:z$1.string().describe("relative to the project root"),folderPath:z$1.string().optional().describe("user selected folder path")}),a1=z$1.object({name:z$1.string(),description:z$1.string(),enabled:z$1.boolean()}).partial(),l1=z$1.object({folderPath:z$1.string()}),c1=z$1.object({folderPath:z$1.string()});z$1.array(CS);var d1=z$1.object({defaultEnv:z$1.string().optional().describe("name of the default env, or undefined to unset")}),u1=z$1.object({configFilePath:z$1.string().describe("full path on disk")});z$1.string().array();z$1.object({message:z$1.string(),newRelativeTestPath:z$1.string().optional()});var oN=z$1.object({name:z$1.string(),absolutePath:z$1.string(),relativePath:z$1.string(),pathSegments:z$1.array(z$1.string()),isDirectory:z$1.boolean(),size:z$1.number(),createdAt:z$1.coerce.date(),modifiedAt:z$1.coerce.date(),accessedAt:z$1.coerce.date()}),p1=z$1.object({pathSegments:z$1.array(z$1.string())});z$1.object({absolutePath:z$1.string(),pathSegments:z$1.array(z$1.string()),contents:z$1.array(oN)});var m1=z$1.object({sourceDirectoryPath:z$1.string().optional(),value:z$1.string(),allowedExtensions:z$1.array(z$1.string()).optional()}),dbe=z$1.object({name:z$1.string(),value:z$1.string(),isDirectory:z$1.boolean()});z$1.object({suggestions:z$1.array(dbe)});var h1=z$1.object({pathSegments:z$1.array(z$1.string())}),g1=z$1.object({pathSegments:z$1.array(z$1.string()),newPathSegments:z$1.array(z$1.string())}),f1=z$1.object({pathSegments:z$1.array(z$1.string()),recursive:z$1.boolean().optional()});z$1.object({success:z$1.boolean(),message:z$1.string(),pathSegments:z$1.array(z$1.string()).optional()});z$1.object({gitBranch:z$1.string(),fileMtime:z$1.coerce.date(),gitCommitSha:z$1.string()});var y1=typeof process<"u"&&true&&true,WC=58889,bg=24*60*60*1e3;var S1=z$1.object({id:z$1.string(),createdAt:z$1.coerce.date(),createdBy:z$1.string(),organizationId:z$1.string(),name:z$1.string(),description:z$1.string().nullish(),enabled:z$1.boolean(),schemaVersion:z$1.string().describe("Schema version for steps"),parameters:z$1.string().array().nullish().describe("Parameter list"),parameterEnums:z$1.record(z$1.string(),z$1.string().array()).nullish(),defaultParameters:z$1.record(z$1.string(),z$1.string()).nullish(),defaultCacheKey:z$1.string().nullish(),defaultCacheTtl:z$1.number().nullish(),defaultCacheAllInvocations:z$1.boolean().nullish(),autoAuth:z$1.boolean().nullish(),defaultRetries:z$1.int().min(0).nullish(),advanced:OO.nullish()});S1.extend({steps:z$1.lazy(()=>Nt.array())});var b1=5*60*1e3,hb=Xn.extend(S1.omit({id:true,createdAt:true,createdBy:true,organizationId:true,enabled:true}).shape);var ube="org_01HMJTX4GT1KG94KZRCT8MZ6YB",pbe="org_01HMSCJQBCCG51M2ZF65YC5B8W",mbe="org_01JPR6MGFQSHF3W234R3XJDPMB",hbe=[ube,pbe,mbe];function T1(e){return hbe.includes(e)}var A1=(o=>(o.AZURE="AZURE",o.KERNEL="KERNEL",o.BROWSERBASE="BROWSERBASE",o))(A1||{}),rN=z$1.enum(A1);z$1.object({azureRegion:z$1.string().optional(),azureWorkspaceId:z$1.string().optional()});z$1.object({});var gbe=z$1.enum(["us-west-2","us-east-1","eu-central-1","ap-southeast-1"]);z$1.object({region:gbe.optional()});var iN=(t=>(t.TEST_REVIEW="TEST_REVIEW",t))(iN||{});var fbe=z$1.object({type:z$1.literal("DESCRIPTION_UPDATE"),thoughts:z$1.string()}),qC=z$1.discriminatedUnion("type",[fbe]),ybe=z$1.object({testId:z$1.string(),name:z$1.string(),orgId:z$1.string(),runId:z$1.string(),steps:Gt.array(),purpose:z$1.enum(iN),details:qC.or(qC.array()).optional()});ybe.pick({name:true,orgId:true});var Sbe=z$1.object({id:z$1.string(),name:z$1.string().nullish(),createdAt:z$1.string().pipe(z$1.coerce.date()).or(z$1.date()),organizationId:z$1.string(),schemaVersion:z$1.string(),runId:z$1.string().nullish(),purpose:z$1.enum(iN),details:qC.or(qC.array()).optional(),applied:z$1.boolean().nullish(),appliedAt:z$1.coerce.date().nullish()}),E1=Sbe.extend({steps:Gt.array()});var C1=z$1.enum(["v1","v2"]);var Tbe=z$1.enum(["element","content","attribute","tag_name","style"]),KC=z$1.enum(["exists","visible","enabled","editable","focused","contains","equals","starts_with"]);[...dj,...cj].forEach(e=>{if(!KC.options.includes(e.toLowerCase()))throw new Error(`V2CheckConditionSchema is missing option: ${e}`)});var sN={element:{aliasPrefix:"",assertionType:"ELEMENT_EXISTENCE",requiresName:false},content:{aliasPrefix:"Content",assertionType:"ELEMENT_CONTENT",requiresName:false},attribute:{aliasPrefix:"Attribute",assertionType:"ELEMENT_ATTRIBUTE",requiresName:true},tag_name:{aliasPrefix:"Name",assertionType:"ELEMENT_NAME",requiresName:false},style:{aliasPrefix:"Style",assertionType:"ELEMENT_STYLE",requiresName:true}},w1={exists:{positiveAliasSuffix:"Exists",negativeAliasSuffix:"DoesNotExist",elementCondition:"EXISTS",contentOperation:"EXISTS"},visible:{positiveAliasSuffix:"Visible",negativeAliasSuffix:"NotVisible",elementCondition:"VISIBLE"},enabled:{positiveAliasSuffix:"Enabled",negativeAliasSuffix:"NotEnabled",elementCondition:"ENABLED"},editable:{positiveAliasSuffix:"Editable",negativeAliasSuffix:"NotEditable",elementCondition:"EDITABLE"},focused:{positiveAliasSuffix:"Focused",negativeAliasSuffix:"NotFocused",elementCondition:"FOCUSED"},contains:{positiveAliasSuffix:"Contains",negativeAliasSuffix:"DoesNotContain",contentOperation:"CONTAINS"},equals:{positiveAliasSuffix:"Equals",negativeAliasSuffix:"DoesNotEqual",contentOperation:"EQUALS"},starts_with:{positiveAliasSuffix:"StartsWith",negativeAliasSuffix:"DoesNotStartWith",contentOperation:"STARTS_WITH"}},I1={ELEMENT_EXISTENCE:"element",ELEMENT_CONTENT:"content",ELEMENT_ATTRIBUTE:"attribute",ELEMENT_NAME:"tag_name",ELEMENT_STYLE:"style"};function v1(e){return {alias:aN(e),subject:e.subject,condition:e.condition,negated:e.negated,assertionType:sN[e.subject].assertionType,requiresName:sN[e.subject].requiresName,requiresValue:e.subject!=="element"&&e.condition!=="exists"}}function aN(e){let t=sN[e.subject],n=w1[e.condition];if(!x1(e.subject,e.condition))throw new Error(`Unsupported element check alias for subject '${e.subject}' and condition '${e.condition}'.`);let o=e.negated?n.negativeAliasSuffix:n.positiveAliasSuffix;return `checkElement${t.aliasPrefix}${o}`}function x1(e,t){let n=w1[t],o=n.elementCondition,r=n.contentOperation;return e==="element"?o!==void 0:r!==void 0}var Abe=Tbe.options.flatMap(e=>KC.options.flatMap(t=>x1(e,t)?[v1({subject:e,condition:t,negated:false}),v1({subject:e,condition:t,negated:true})]:[])),_1=new Map(Abe.map(e=>[e.alias,e]));var Ebe=z$1.enum(_l),Cbe=z$1.enum(fs);function _i(e){return _1.get(e)}function O1(e){let t=I1[e.type],n=e.type==="ELEMENT_EXISTENCE"?e.condition:e.operation;return aN({subject:t,condition:vbe(n),negated:e.negated})}function M1(e){return Ebe.parse(e.toUpperCase())}function gb(e){return Cbe.parse(e.toUpperCase())}function vbe(e){return KC.parse(e.toLowerCase())}var tt={saveAs:z$1.string().optional(),retries:z$1.number().optional(),skipped:z$1.boolean().optional(),comment:z$1.string().optional()};z$1.object(tt);var fb=Object.keys(tt);function qe(e){return z$1.union([z$1.strictObject({[e.key]:e.simplified}),z$1.strictObject({[e.key]:e.detailed})])}function qn(e){return z$1.strictObject({[e.key]:e.detailed})}var N1='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Tg=z$1.union([wl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,N1)],{error:N1});z$1.union([z$1.string(),wl]);var Ps={css:z$1.string().optional(),coords:Tg.optional(),x:z$1.union([z$1.number(),z$1.string()]).optional(),y:z$1.union([z$1.number(),z$1.string()]).optional()},cN={on:z$1.string().optional(),...Ps},Os={...tt,useSelector:z$1.boolean().optional(),force:z$1.boolean().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional()},yb={...Os,offset:Tg.optional()};function Pi({schema:e,descriptionKey:t,required:n=true}){return e.superRefine((o,r)=>{let s=[t in o?Object.entries(o).find(([a])=>a===t)?.[1]:void 0,"css"in o?o.css:void 0,"coords"in o?o.coords:void 0,"x"in o||"y"in o?true:void 0].filter(a=>a!==void 0).length;n&&s!==1&&r.addIssue({code:"custom",message:`Use exactly one target: ${t}, css, coords, or x/y.`}),!n&&s>1&&r.addIssue({code:"custom",message:`Use at most one target: ${t}, css, coords, or x/y.`}),("x"in o||"y"in o)&&(!("x"in o)||o.x===void 0||!("y"in o)||o.y===void 0)&&r.addIssue({code:"custom",message:"x and y must be provided together."});})}var Rbe=Pi({descriptionKey:"on",schema:z$1.strictObject({...cN,...yb,times:z$1.int().min(1).optional(),rightClick:z$1.boolean().optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),wbe=Pi({descriptionKey:"on",schema:z$1.strictObject({...cN,...yb,rightClick:z$1.boolean().optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),Ibe=Pi({descriptionKey:"on",schema:z$1.strictObject({...cN,...yb,times:z$1.int().min(1).optional(),waitForDownload:z$1.boolean().optional(),delay:z$1.number().optional(),downloadTimeout:z$1.number().optional()})}),L1=qe({key:"click",simplified:z$1.string(),detailed:Rbe}),k1=qe({key:"doubleClick",simplified:z$1.string(),detailed:wbe}),D1=qe({key:"rightClick",simplified:z$1.string(),detailed:Ibe}),xbe=Pi({descriptionKey:"into",required:false,schema:z$1.strictObject({text:z$1.string(),into:z$1.string().optional(),...Ps,...yb,pressEnter:z$1.boolean().optional(),clear:z$1.union([z$1.literal("inputs"),z$1.literal("always"),z$1.literal("never"),z$1.boolean()]).optional(),delay:z$1.number().optional()})}),F1=qe({key:"type",simplified:z$1.string(),detailed:xbe}),B1=qn({key:"select",detailed:Pi({descriptionKey:"from",schema:z$1.strictObject({from:z$1.string().optional(),...Ps,label:z$1.string().optional(),value:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),...Os})}).superRefine((e,t)=>{[e.label,e.value,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"select requires exactly one of label, value, or index"});})}),U1=qe({key:"hover",simplified:z$1.string(),detailed:Pi({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...Ps,...yb})})}),H1=qn({key:"blur",detailed:Pi({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...Ps,...Os})})}),G1=qe({key:"focus",simplified:z$1.string(),detailed:Pi({descriptionKey:"on",schema:z$1.strictObject({on:z$1.string().optional(),...Ps,...Os})})}),j1=qn({key:"dragAndDrop",detailed:z$1.strictObject({from:z$1.string().optional(),to:z$1.string().optional(),fromCss:z$1.string().optional(),toCss:z$1.string().optional(),fromCoords:Tg.optional(),toCoords:Tg.optional(),fromX:z$1.union([z$1.number(),z$1.string()]).optional(),fromY:z$1.union([z$1.number(),z$1.string()]).optional(),toX:z$1.union([z$1.number(),z$1.string()]).optional(),toY:z$1.union([z$1.number(),z$1.string()]).optional(),steps:z$1.number().optional(),hover:z$1.number().optional(),...Os}).superRefine((e,t)=>{let n=[e.from,e.fromCss,e.fromCoords,e.fromX!==void 0||e.fromY!==void 0?true:void 0].filter(r=>r!==void 0).length,o=[e.to,e.toCss,e.toCoords,e.toX!==void 0||e.toY!==void 0?true:void 0].filter(r=>r!==void 0).length;n!==1&&t.addIssue({code:"custom",message:"Use exactly one from target."}),o!==1&&t.addIssue({code:"custom",message:"Use exactly one to target."}),(e.fromX!==void 0||e.fromY!==void 0)&&(e.fromX===void 0||e.fromY===void 0)&&t.addIssue({code:"custom",message:"fromX and fromY must be provided together."}),(e.toX!==void 0||e.toY!==void 0)&&(e.toX===void 0||e.toY===void 0)&&t.addIssue({code:"custom",message:"toX and toY must be provided together."});})}),$1=z$1.union([z$1.strictObject({mouseDrag:Tg}),z$1.strictObject({mouseDrag:Pi({descriptionKey:"from",required:false,schema:z$1.strictObject({from:z$1.string().optional(),...Ps,delta:Tg,steps:z$1.number().optional(),...Os})})})]),V1=qe({key:"press",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),repeat:z$1.number().optional(),delay:z$1.number().optional(),convertMeta:z$1.boolean().optional(),...tt})}),z1=qe({key:"keyDown",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...tt})}),W1=qe({key:"keyUp",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),convertMeta:z$1.boolean().optional(),...tt})}),q1=qe({key:"navigate",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:z$1.number().optional(),...tt})}),K1=qe({key:"newTab",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),timeout:z$1.number().optional(),...tt})}),Y1=qe({key:"switchTab",simplified:z$1.union([z$1.number(),z$1.string()]),detailed:z$1.strictObject({substring:z$1.string().optional(),regex:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length!==1&&t.addIssue({code:"custom",message:"switchTab requires exactly one of substring, regex, or index"});})}),J1=qn({key:"closeTab",detailed:z$1.strictObject({substring:z$1.string().optional(),regex:z$1.string().optional(),index:z$1.union([z$1.string(),z$1.number()]).optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{[e.substring,e.regex,e.index].filter(o=>o!==void 0).length<=1||t.addIssue({code:"custom",message:"closeTab accepts at most one of substring, regex, or index"});})}),X1=qn({key:"goBack",detailed:z$1.strictObject(tt)}),Q1=qn({key:"goForward",detailed:z$1.strictObject(tt)}),Z1=qn({key:"refresh",detailed:z$1.strictObject({timeout:z$1.number().optional(),...tt})}),YC=z$1.enum(["goBack","goForward","refresh","paste","authSave","offline","online","blur","visualDiff","captcha","closeTab"]),eq=qe({key:"scrollUp",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),tq=qe({key:"scrollDown",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),nq=qe({key:"scrollLeft",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),oq=qe({key:"scrollRight",simplified:z$1.number().nonnegative(),detailed:Pi({descriptionKey:"in",required:false,schema:z$1.strictObject({pixels:z$1.number().nonnegative().optional(),in:z$1.string().optional(),...Ps,...Os})})}),rq=qe({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...tt})}),_be=qe({key:"assert",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),source:z$1.string().optional(),...tt})}),Pbe=qe({key:"assertVisually",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),source:z$1.string().optional(),...tt})}),JC=_be,XC=Pbe,iq=qe({key:"checkPageContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...tt})}),sq=qe({key:"checkPageDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),iframe:z$1.string().optional(),...tt})}),dN=z$1.union([iq,sq]),Obe=z$1.record(z$1.string(),z$1.unknown().optional()),QC=Obe.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=_i(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=Pi({descriptionKey:"element",schema:z$1.looseObject({element:z$1.string().optional(),...Ps,...Os,timeout:z$1.number().optional(),name:z$1.string().optional(),value:z$1.string().optional()})}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),aq=qe({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:Au.optional(),DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional(),iframe:z$1.string().optional(),...tt})}),lq=qe({key:"cookie",simplified:z$1.string(),detailed:z$1.strictObject({value:z$1.string(),...tt})}),cq=qn({key:"localStorage",detailed:z$1.strictObject({key:z$1.string(),value:z$1.string(),...tt})}),dq=qe({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:Gc.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),params:z$1.record(z$1.string(),z$1.string()).optional(),body:Au.optional(),contentType:z$1.enum(Pl).optional(),timeout:z$1.number().optional(),...tt})}),uq=qn({key:"graphqlRequest",detailed:z$1.strictObject({url:z$1.string(),query:z$1.string(),variables:Au.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),timeout:z$1.number().optional(),...tt})}),ZC=qe({key:"javascript",simplified:z$1.string(),detailed:z$1.strictObject({code:z$1.string(),environment:z$1.enum(["node","browser","NODE","BROWSER"]).optional(),fragment:z$1.boolean().optional(),timeout:z$1.number().optional(),...tt})}),Ag={substring:z$1.string().optional(),glob:z$1.string().optional(),regex:z$1.string().optional(),domain:z$1.string().optional()};function Mbe(e){return [e.substring,e.glob,e.regex,e.domain].filter(t=>t!==void 0).length}function Eg(e){let t=Mbe(e.payload);if(e.required&&t!==1||!e.required&&t>1){e.ctx.addIssue({code:"custom",message:e.required?"requires exactly one of substring, glob, regex, or domain":"requires at most one of substring, glob, regex, or domain"});return}!e.required&&t===0&&e.payload.method&&e.ctx.addIssue({code:"custom",message:"method requires a URL matcher"});}var pq=qn({key:"header",detailed:z$1.strictObject({name:z$1.string(),value:z$1.string(),...Ag,method:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:false});})}),mq=qn({key:"mock",detailed:z$1.strictObject({...Ag,method:z$1.string().optional(),responseGenerator:z$1.string(),fetchOriginalResponse:z$1.boolean().optional(),key:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),hq=qe({key:"removeRouteMock",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string().optional(),...tt})}),gq=qe({key:"waitForUrl",simplified:z$1.string(),detailed:z$1.strictObject({...Ag,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),fq=qe({key:"waitForUrlNotToMatch",simplified:z$1.string(),detailed:z$1.strictObject({...Ag,caseInsensitive:z$1.boolean().optional(),timeout:z$1.number().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),Nbe=z$1.union([gq,fq]),yq=qe({key:"dialog",simplified:z$1.enum(["ACCEPT","DISMISS"]),detailed:z$1.strictObject({action:z$1.enum(["ACCEPT","DISMISS"]),...tt})}),Sq=qe({key:"fileUpload",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),name:z$1.string().optional(),...tt})}),bq=qe({key:"copy",simplified:z$1.union([z$1.string(),z$1.boolean(),z$1.null()]),detailed:z$1.strictObject({value:z$1.union([z$1.string(),z$1.boolean(),z$1.null()]),...tt})}),Tq=qn({key:"paste",detailed:z$1.strictObject(tt)}),Aq=qn({key:"captcha",detailed:z$1.strictObject({...Os})}),Lbe=z$1.strictObject({data:z$1.union([z$1.string(),La]),width:z$1.number(),height:z$1.number()}),Eq=qe({key:"visualDiff",simplified:z$1.string(),detailed:Pi({descriptionKey:"on",required:false,schema:z$1.strictObject({on:z$1.string().optional(),...Ps,threshold:z$1.number().optional(),screenshot:Lbe.optional(),...Os})})}),Cq=qn({key:"offline",detailed:z$1.strictObject(tt)}),vq=qn({key:"online",detailed:z$1.strictObject(tt)}),Rq=qn({key:"registerRequestListener",detailed:z$1.strictObject({...Ag,key:z$1.string(),method:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),wq=qe({key:"awaitListener",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),timeout:z$1.number().optional(),...tt})}),Iq=qn({key:"recordRequests",detailed:z$1.strictObject({...Ag,key:z$1.string(),method:z$1.string().optional(),...tt}).superRefine((e,t)=>{Eg({payload:e,ctx:t,required:true});})}),xq=qe({key:"getRecordedRequests",simplified:z$1.string(),detailed:z$1.strictObject({key:z$1.string(),...tt})}),_q=qe({key:"authLoad",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...tt})}),Pq=qe({key:"authSave",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string().optional(),...tt})});z$1.union([L1,k1,D1,Y1,J1,F1,B1,U1,H1,G1,j1,$1,V1,z1,W1,q1,K1,X1,Q1,Z1,eq,tq,nq,oq,rq,JC,XC,dN,aq,lq,cq,dq,uq,ZC,pq,mq,hq,Nbe,yq,Sq,bq,Tq,Aq,Eq,Cq,vq,Rq,wq,Iq,xq,_q,Pq,QC]);var Oq=new Map([["click",L1],["doubleClick",k1],["rightClick",D1],["switchTab",Y1],["closeTab",J1],["type",F1],["select",B1],["hover",U1],["blur",H1],["focus",G1],["dragAndDrop",j1],["mouseDrag",$1],["press",V1],["keyDown",z1],["keyUp",W1],["navigate",q1],["newTab",K1],["goBack",X1],["goForward",Q1],["refresh",Z1],["scrollUp",eq],["scrollDown",tq],["scrollLeft",nq],["scrollRight",oq],["wait",rq],["assert",JC],["assertVisually",XC],["checkPageContains",iq],["checkPageDoesNotContain",sq],["extract",aq],["cookie",lq],["localStorage",cq],["request",dq],["graphqlRequest",uq],["javascript",ZC],["header",pq],["mock",mq],["removeRouteMock",hq],["waitForUrl",gq],["waitForUrlNotToMatch",fq],["dialog",yq],["fileUpload",Sq],["copy",bq],["paste",Tq],["captcha",Aq],["visualDiff",Eq],["offline",Cq],["online",vq],["registerRequestListener",Rq],["awaitListener",wq],["recordRequests",Iq],["getRecordedRequests",xq],["authLoad",_q],["authSave",Pq]]),Mq=Object.freeze([...Oq.keys()]),Xl=z$1.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"Steps must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"Steps must have exactly one action key."});return}let r=Oq.get(o)??(_i(o)?QC:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported step type '${o}'.`});return}let i=r.safeParse(e);if(!i.success){let s=kbe(i.error.issues,o);s.length>0&&Nq(t,s);}});function kbe(e,t){return Dbe(e).filter(n=>!Fbe(n,t))}function Nq(e,t){for(let n of t){if(n.code==="invalid_union"){Nq(e,uN(n));continue}e.addIssue({...n});}}function Dbe(e){let t=[];for(let n of e){if(n.code==="invalid_union"){t.push(...uN(n));continue}t.push(n);}return t}function Fbe(e,t){return e.code!=="unrecognized_keys"?false:t===void 0?e.path.length===0:e.path.length===1&&e.path[0]===t}function uN(e){let t=e.errors[0]??[],n=lN(t);for(let o of e.errors.slice(1)){let r=lN(o);r>n&&(t=o,n=r);}return t}function lN(e){return e.reduce((t,n)=>{let o=n.code==="invalid_union"?lN(uN(n)):0;return t+n.path.length+o},0)}var Lq=z$1.strictObject({string:z$1.string()}),Bbe=z$1.strictObject({javascript:z$1.string()}),kq=z$1.union([Lq,Bbe]),Ube=z$1.union([z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),default:Lq.optional()}),z$1.strictObject({name:z$1.string(),required:z$1.boolean().optional(),defaultValue:z$1.string()})]),Dq=Ube.array(),Hbe=z$1.strictObject({name:z$1.string(),default:kq.optional(),enum:z$1.array(z$1.string()).optional()}),Fq=Hbe.array(),Sb=z$1.union([kq,z$1.string()]),Bq=z$1.record(z$1.string(),Sb);var Gbe=z$1.preprocess(e=>typeof e=="number"?String(e):e,bO),ev=z$1.looseObject({goal:z$1.string(),version:Gbe.optional(),...tt}),jbe=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:ev})]),pN=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),Sb).optional(),...tt}),$be=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:pN})]),id=z$1.union([JC,XC,dN,ZC,QC]),Vbe=new Set(["then",...fb]),zbe=z$1.looseObject({then:z$1.lazy(()=>Ka.array()),...tt}).superRefine((e,t)=>{Object.entries(e).filter(([o,r])=>!Vbe.has(o)&&id.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"Conditional steps require exactly one assertion condition at the top level."});}),Wbe=z$1.strictObject({if:zbe}),qbe=new Set(["do","maxIterations",...fb]),Kbe=z$1.looseObject({do:z$1.lazy(()=>Ka.array()),maxIterations:z$1.number().int().positive().optional(),...tt}).superRefine((e,t)=>{let n=Object.entries(e).filter(([o,r])=>!qbe.has(o)&&id.safeParse({[o]:r}).success).length;if(n>1){t.addIssue({code:"custom",message:"While loops accept at most one condition at the top level."});return}n===0&&e.maxIterations===void 0&&t.addIssue({code:"custom",message:"While loops require a condition or a maximum number of iterations."});}),Ybe=z$1.strictObject({while:Kbe}),Ka=z$1.lazy(()=>z$1.union([YC,jbe,$be,Wbe,Ybe,Xl]));z$1.object({before:Ka.array().optional(),steps:Ka.array(),after:Ka.array().optional()});var Jbe=z$1.union([Jc,z$1.string().refine(e=>{let t=e.match(/^\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*$/);if(!t)return false;let[,n,o]=t;return Jc.safeParse({width:Number(n),height:Number(o)}).success},"Viewport must be two numeric values, e.g. 1920, 1080")]),Xbe=Cs.omit({viewport:true}).extend({viewport:Jbe.optional()}),mN=z$1.object({id:mo,version:z$1.string().optional(),url:KE.optional(),description:z$1.string().optional(),retries:z$1.number().optional(),defaultEnv:z$1.string().optional(),parameters:Dq.optional(),outputs:SC.optional(),disabled:z$1.boolean().optional(),labels:z$1.array(z$1.string()).optional()}).extend(Xbe.shape),Cu=z$1.looseObject({fileType:z$1.literal(De.TEST_V2)}).extend(mN.shape).extend({before:Ka.array().optional(),steps:Ka.array(),after:Ka.array().optional()});var Qbe=z$1.array(z$1.string()),Zbe=z$1.union([z$1.string(),z$1.record(z$1.string(),z$1.unknown().optional())]),tv=Xn.omit({moduleId:true,name:true,parameters:true,defaultParameters:true,parameterEnums:true}).extend({id:mo,version:z$1.string().optional(),name:z$1.string().optional(),parameters:z$1.union([Fq,Qbe]).optional(),defaultParameters:z$1.record(z$1.string(),z$1.string()).optional(),parameterEnums:z$1.record(z$1.string(),z$1.array(z$1.string())).optional()}),nv=z$1.looseObject(tv.extend({fileType:z$1.literal(De.MODULE_V2),steps:Zbe.array().optional()}).shape).superRefine(Hq),ov=z$1.looseObject(tv.extend({fileType:z$1.literal(De.MODULE_V2),steps:Ka.array().optional()}).shape).superRefine(Hq);function Uq(e){return e.steps??[]}function Hq(e,t){"main"in e&&t.addIssue({code:"custom",message:"v2 modules must use steps, not main",path:["main"]});}var hN=(n=>(n.TEST="TEST",n.MODULE="MODULE",n))(hN||{}),eTe=z$1.enum(hN),Gq=z$1.object({orgId:z$1.string(),entityType:eTe,entityId:z$1.string()}),gN=Gq.extend({entityType:z$1.literal("TEST"),stepLists:Da}),fN=Gq.extend({entityType:z$1.literal("MODULE"),steps:Nt.array()});z$1.discriminatedUnion("entityType",[gN,fN]);var jq=(o=>(o.WEB="web",o.ANDROID="android",o.IOS="ios",o))(jq||{}),yN=z$1.nativeEnum(jq);var $q=z$1.object({entity_type:z$1.string(),value:z$1.string(),schema_version:z$1.string().optional()}),Vq=Qy($q),zq=$q.extend({cache_key:z$1.string()});function bb({entityType:e,entityId:t}){return `${e}:${t}`}var em=z$1.string();var Wq='Coordinates must be "x, y" pixel values, e.g. "100, 200"',Jq=z$1.union([wl,z$1.string().regex(/^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$/,Wq)],{error:Wq}),qq='Percent must be a number or a percent string, e.g. 90 or "90%"',Xq=z$1.union([z$1.number(),z$1.string().regex(/^-?\d+(?:\.\d+)?%$/,qq)],{error:qq}).transform(e=>typeof e=="number"?e:Number(e.slice(0,-1))).pipe(z$1.number().min(0,{message:"Percent must be >= 0"}).max(100,{message:"Percent must be <= 100"})),tTe=z$1.strictObject({x:z$1.number(),y:z$1.number(),delta:z$1.number()}),Qq=z$1.union([z$1.string(),tTe]),Pn={...tt,DANGEROUS_FORCE_DYNAMIC:z$1.boolean().optional()},nTe=["home","power","back","app_switcher","search","volume_up","volume_down","volume_mute"],oTe=["enter","backspace","close_keyboard"],Kq=["airplane_mode","data","wifi","location"],Yq=["portrait","landscape"],rTe=z$1.strictObject({on:em.optional(),longPress:z$1.boolean().optional(),longPressDuration:z$1.number().optional(),iterations:z$1.number().optional(),tapDelay:z$1.number().optional(),offset:Jq.optional(),...Pn}),Zq=qe({key:"tap",simplified:em,detailed:rTe}),iTe=z$1.strictObject({text:z$1.string(),into:em.optional(),clearContent:z$1.boolean().optional(),forceClearContent:z$1.boolean().optional(),delay:z$1.number().optional(),replaceStrategy:z$1.nativeEnum(JS).optional(),keyPressDelay:z$1.number().optional(),...Pn}),e2=qe({key:"type",simplified:z$1.string(),detailed:iTe}),t2=z$1.enum(nTe),sTe=z$1.strictObject({key:t2,longPress:z$1.boolean().optional(),...Pn}),n2=qe({key:"press",simplified:t2,detailed:sTe}),o2=z$1.enum(oTe),aTe=z$1.strictObject({key:o2,repeat:z$1.number().optional(),delay:z$1.number().optional(),keyPressDelay:z$1.number().optional(),...Pn}),r2=qe({key:"pressKey",simplified:o2,detailed:aTe}),lTe=z$1.strictObject({package:z$1.string(),activity:z$1.string().optional(),intentExtras:z$1.string().optional(),...Pn}),i2=qe({key:"openApp",simplified:z$1.string(),detailed:lTe}),s2=qn({key:"killApp",detailed:z$1.strictObject(Pn)}),a2=qn({key:"openNotifications",detailed:z$1.strictObject(Pn)}),l2=z$1.enum(["up","down","left","right"]),cTe=z$1.strictObject({direction:l2,in:Qq.optional(),viewportPercent:Xq.optional(),duration:z$1.number().optional(),offset:Jq.optional(),...Pn}),c2=qe({key:"swipe",simplified:l2,detailed:cTe}),dTe=z$1.enum(["up","down"]),uTe=z$1.strictObject({on:em,direction:dTe.optional(),in:Qq.optional(),scrollStepPercent:Xq.optional(),maxScrollAttempts:z$1.number().optional(),...Pn}),d2=qe({key:"scrollTo",simplified:z$1.string(),detailed:uTe}),SN=qe({key:"assert",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Pn})}),bN=qe({key:"assertVisually",simplified:z$1.string(),detailed:z$1.strictObject({that:z$1.string(),timeout:z$1.number().optional(),...Pn})}),u2=qe({key:"extract",simplified:z$1.string(),detailed:z$1.strictObject({goal:z$1.string(),schema:Au.optional(),...Pn})}),p2=qe({key:"checkScreenContains",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Pn})}),m2=qe({key:"checkScreenDoesNotContain",simplified:z$1.string(),detailed:z$1.strictObject({text:z$1.string(),timeout:z$1.number().optional(),...Pn})}),h2=z$1.union([p2,m2]),pTe=z$1.record(z$1.string(),z$1.unknown().optional()),TN=pTe.superRefine((e,t)=>{let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}let r=_i(o);if(r===void 0){t.addIssue({code:"custom",message:"element checks require exactly one checkElement... key"});return}if(typeof e[r.alias]=="string")return;let i=z$1.looseObject({on:em.optional(),timeout:z$1.number().optional(),name:z$1.string().optional(),value:z$1.string().optional(),...Pn}).safeParse(e[r.alias]);if(!i.success){t.addIssue({code:"custom",message:`element check alias '${r.alias}' must be a string target or detailed object`,path:[r.alias]});return}i.data.on===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a target via 'on'`,path:[r.alias,"on"]}),r.requiresName&&i.data.name===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a name`,path:[r.alias,"name"]}),r.requiresValue&&i.data.value===void 0&&t.addIssue({code:"custom",message:`element check alias '${r.alias}' requires a value`,path:[r.alias,"value"]});}),mTe=z$1.strictObject({from:em,to:em,hoverDuration:z$1.number().optional(),dragDuration:z$1.number().optional(),...Pn}),g2=qn({key:"dragAndDrop",detailed:mTe}),AN=qe({key:"javascript",simplified:z$1.string(),detailed:z$1.strictObject({code:z$1.string(),timeout:z$1.number().optional(),...Pn})}),f2=qe({key:"request",simplified:z$1.string(),detailed:z$1.strictObject({url:z$1.string(),method:Gc.optional(),headers:z$1.record(z$1.string(),z$1.string()).optional(),params:z$1.record(z$1.string(),z$1.string()).optional(),body:z$1.string().optional(),bodyType:z$1.nativeEnum(Pl).optional(),timeout:z$1.number().optional(),...Pn})}),y2=qe({key:"wait",simplified:z$1.number(),detailed:z$1.strictObject({ms:z$1.number(),...Pn})}),S2=qe({key:"visualDiff",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),threshold:z$1.number().min(0).max(1).optional(),...Pn})}),b2=qn({key:"addFile",detailed:z$1.strictObject({path:z$1.string(),location:z$1.string(),...Pn})}),T2=qe({key:"installApp",simplified:z$1.string(),detailed:z$1.strictObject({path:z$1.string(),...Pn})}),A2=qe({key:"uninstallApp",simplified:z$1.string(),detailed:z$1.strictObject({package:z$1.string(),...Pn})}),E2=qe({key:"toggleSettings",simplified:z$1.enum(Kq),detailed:z$1.strictObject({setting:z$1.enum(Kq),...Pn})}),C2=qe({key:"rotate",simplified:z$1.enum(Yq),detailed:z$1.strictObject({orientation:z$1.enum(Yq),...Pn})}),v2=qe({key:"adb",simplified:z$1.string(),detailed:z$1.strictObject({command:z$1.string(),args:z$1.string().optional(),...Pn})}),R2=qn({key:"appium",detailed:z$1.strictObject({script:z$1.string(),args:z$1.string().optional(),...Pn})}),w2=qn({key:"debugState",detailed:z$1.strictObject(Pn)}),I2=z$1.enum(["killApp","openNotifications","debugState"]);z$1.union([Zq,e2,n2,r2,i2,s2,a2,c2,d2,SN,bN,u2,h2,g2,AN,f2,y2,S2,b2,T2,A2,E2,C2,v2,R2,w2,TN]);var x2=new Map([["tap",Zq],["type",e2],["press",n2],["pressKey",r2],["openApp",i2],["killApp",s2],["openNotifications",a2],["swipe",c2],["scrollTo",d2],["assert",SN],["assertVisually",bN],["extract",u2],["checkScreenContains",p2],["checkScreenDoesNotContain",m2],["dragAndDrop",g2],["javascript",AN],["request",f2],["wait",y2],["visualDiff",S2],["addFile",b2],["installApp",T2],["uninstallApp",A2],["toggleSettings",E2],["rotate",C2],["adb",v2],["appium",R2],["debugState",w2]]);Object.freeze([...x2.keys()]);var _2=z$1.custom().superRefine((e,t)=>{if(typeof e!="object"||e===null){t.addIssue({code:"custom",message:"v2 mobile commands must be objects with exactly one action key."});return}let n=Object.keys(e),o=n[0];if(n.length!==1||o===void 0){t.addIssue({code:"custom",message:"v2 mobile commands must have exactly one action key."});return}let r=x2.get(o)??(_i(o)?TN:void 0);if(!r){t.addIssue({code:"custom",message:`Unsupported v2 mobile command '${o}'.`});return}let i=r.safeParse(e);if(!i.success)for(let s of i.error.issues)t.addIssue({...s});}),P2=z$1.union([SN,bN,h2,AN,TN]);var hTe=z$1.preprocess(e=>typeof e=="number"?String(e):e,OM),gTe=z$1.looseObject({goal:z$1.string(),version:hTe.optional(),precondition:z$1.string().optional(),postcondition:z$1.string().optional(),...tt}),fTe=z$1.union([z$1.strictObject({act:z$1.string()}),z$1.strictObject({act:gTe})]),yTe=z$1.looseObject({path:z$1.string(),inputs:z$1.record(z$1.string(),Sb).optional(),...tt}),STe=z$1.union([z$1.strictObject({module:z$1.string()}),z$1.strictObject({module:yTe})]),bTe=new Set(["then",...fb]),TTe=z$1.looseObject({then:z$1.lazy(()=>Ql.array()),...tt}).superRefine((e,t)=>{if("else"in e){t.addIssue({code:"custom",message:"v2 mobile conditionals do not support 'else'. Use a separate step instead.",path:["else"]});return}Object.entries(e).filter(([o,r])=>!bTe.has(o)&&P2.safeParse({[o]:r}).success).length!==1&&t.addIssue({code:"custom",message:"v2 mobile conditional steps require exactly one assertion condition at the top level."});}),ATe=z$1.strictObject({if:TTe}),Ql=z$1.lazy(()=>z$1.union([I2,fTe,STe,ATe,_2]));z$1.object({before:Ql.array().optional(),steps:Ql.array(),after:Ql.array().optional()});var EN=["android","ios"],ETe=z$1.literal("android"),CTe=z$1.literal("ios");z$1.enum(EN);function rv(e){if(typeof e!="object"||e===null)return e;let t=e;if(typeof t.platform!="string")return e;let n=t.platform.toLowerCase();return n===t.platform?e:{...t,platform:n}}var O2=fg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:ETe,...ob.shape}),M2=yg.omit({schemaVersion:true,settings:true,platform:true}).extend({version:z$1.string().optional(),platform:CTe,...ob.shape}),vTe=z$1.discriminatedUnion("platform",[O2,M2]),N2=z$1.preprocess(rv,vTe),L2={before:Ql.array().optional(),steps:Ql.array(),after:Ql.array().optional()},k2=z$1.looseObject({fileType:z$1.literal(De.MOBILE_TEST_V2)}).extend(O2.shape).extend(L2);z$1.preprocess(rv,k2);var D2=z$1.looseObject({fileType:z$1.literal(De.MOBILE_TEST_V2)}).extend(M2.shape).extend(L2);z$1.preprocess(rv,D2);var RTe=z$1.discriminatedUnion("platform",[k2,D2]);z$1.preprocess(rv,RTe);var wTe=z$1.preprocess(e=>typeof e=="string"?e.toLowerCase():e,z$1.enum(EN).optional().default("android")),iv=FC.omit({moduleId:true,name:true,schemaVersion:true,platform:true}).extend({id:mo,name:z$1.string().optional(),version:z$1.string().optional(),platform:wTe});z$1.looseObject(iv.extend({fileType:z$1.literal(De.MOBILE_MODULE_V2),steps:z$1.array(z$1.record(z$1.string(),z$1.unknown().optional())).optional()}).shape);z$1.looseObject(iv.extend({fileType:z$1.literal(De.MOBILE_MODULE_V2),steps:Ql.array().optional()}).shape);var sv="x-momentic-cli-version",B2="x-momentic-client-mode",av="x-momentic-runner",U2="x-momentic-cli-type",H2="x-momentic-logger-tags",ITe="x-momentic-main-branch-name",xTe="x-momentic-branch-name",_Te="x-momentic-commit-timestamp",PTe="x-momentic-last-commit-on-main",OTe="x-momentic-last-commit-on-main-timestamp",MTe="x-momentic-merged-branch-name",G2="x-momentic-session-id",j2="x-momentic-parent-trace-id";O.object({error:O.boolean(),reason:O.string(),message:O.string()});rr.merge(cM);var $2=OE;rr.merge(cM);rr.merge(jV).extend({useConsensus:O.boolean().optional(),attemptNumber:O.number().optional()});var CN=lj;rr.merge($V);var V2=P$;rr.merge(BV);var z2=ZE;rr.merge(nj);rr.merge(UV);var W2=I$;rr.merge(HV);rr.merge(GV);rr.merge(qV);rr.merge(KV);O.object({testPaths:O.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:O.string().optional(),all:O.boolean().optional(),urlOverride:O.string().optional(),customHeaders:O.record(O.string(),O.string()).optional(),testInputMatrix:O.record(O.string(),O.string()).array().optional()});var q2=O.object({queuedTests:O.unknown().optional().array(),runIds:O.guid().array(),runGroupId:O.string().optional()});O.string().array();O.union([O.object({paths:O.string().array().describe("Export specific test paths or folder paths (e.g. todo-test, auth/onboarding)"),all:O.boolean().describe("run all tests").optional()}),O.object({path:O.string().describe("deprecated; present for backcompat")})]);var NTe=O.object({tests:O.record(O.string().describe("Test name (keys correspond to entries in `tests`)"),O.string().describe("Slash-separated folder name path that the test lives in (e.g. 'Auth/Login'). Top-level entities are omitted.")),modules:O.record(O.string().describe("Module name (keys correspond to entries in `modules`)"),O.string().describe("Slash-separated folder name path that the module lives in."))}),K2=O.object({tests:O.record(O.string().describe("Test name"),O.string().describe("Test YAML")),modules:O.record(O.string().describe("Module name"),O.string().describe("Module YAML")),folderPaths:NTe.optional().describe("Optional map from exported entity name to its slash-separated cloud folder path. Used by the CLI to recreate folder structure on disk.")}),LTe=O.object({test:O.string().describe("test YAML"),modules:O.record(O.string().describe("moduleId"),O.string().describe("module YAML"))});LTe.array();O.object({testId:O.string(),schemaVersion:O.string()}).merge(Vc);function lv(e){let{gitMainBranch:t,gitBranchName:n,gitCommitTimestamp:o,lastCommitOnMainSha:r,lastCommitOnMainTimestamp:i}=e,s={};return t&&(s[ITe]=encodeURIComponent(t)),n&&(s[xTe]=encodeURIComponent(n)),o&&(s[_Te]=o.toISOString()),r&&(s[PTe]=encodeURIComponent(r)),i&&(s[OTe]=i.toISOString()),e.mergedGitBranchName&&(s[MTe]=encodeURIComponent(e.mergedGitBranchName)),s}O.object({entries:O.array(Jj)});O.object({platform:yN.optional(),entries:O.array(Vq)});O.object({testId:O.string(),environment:O.string().optional(),platform:yN.optional()});O.object({testId:O.string(),key:O.string(),environment:O.string().optional()});function Y2(e){return O.record(O.string(),O.unknown().optional()).transform(t=>{let n={};for(let[o,r]of Object.entries(t)){let i=e.safeParse(r);i.success&&(n[o]=i.data);}return n})}var J2=Y2(Xj),X2=zq.array();function F2(e){return Y2(Zy(e))}var Q2={ANDROID:e=>F2(HC).parse(e),IOS:e=>F2(GC).parse(e)},kTe=O.object({id:O.string(),completionType:O.string(),description:O.string().optional(),thoughts:O.string(),result:O.string(),sessionType:O.string(),timeCreated:O.string().optional(),citations:O.array(No).optional()}),DTe=O.object({id:O.string(),assertion:O.string().optional(),result:O.string(),thoughts:O.string(),sessionType:O.string(),timeCreated:O.string().optional(),citations:O.array(No).optional()});O.object({completionType:O.string(),traceIds:O.string().array()});var vN=O.union([kTe,DTe]).array(),Z2=O.object({trigger:O.nativeEnum(vs),status:O.nativeEnum(ht),startedAt:O.coerce.date().optional(),gitCommitSha:O.string().optional(),gitCommitShaShort:O.string().optional(),gitCommitTimestamp:O.coerce.date().optional(),gitBranchName:O.string().optional(),gitOriginUrl:O.string().optional(),gitCommitMessage:O.string().optional(),gitCommitAuthorName:O.string().optional(),githubRepository:O.string().optional(),gitlabProjectPath:O.string().optional(),pipelineId:O.string().optional(),cliVersion:O.string().optional()});O.object({id:O.string()});var eK=O.object({status:O.nativeEnum(ht),updatedAt:O.coerce.date().optional(),finishedAt:O.coerce.date().optional()});O.object({summary:zp,githubRepository:O.string().optional(),gitBranchName:O.string().optional()});O.object({updates:O.object({runId:O.string(),healStatus:NS,healDetails:OS.optional()}).array()});var tK=O.object({stepsSnapshot:O.array(O.record(O.string(),O.unknown().optional())).optional(),beforeStepsSnapshot:O.array(O.record(O.string(),O.unknown().optional())).optional(),afterStepsSnapshot:O.array(O.record(O.string(),O.unknown().optional())).optional(),runGroupId:O.string().optional(),testId:O.string(),testName:O.string(),resolvedBaseUrl:O.string().optional(),environmentName:O.string().optional(),labels:O.array(O.string()).optional(),cliVersion:O.string().optional(),trigger:O.nativeEnum(vs),schemaVersion:O.string().optional(),section:O.nativeEnum(bC).optional(),resolvedInputs:O.record(O.string(),O.string()).optional(),quarantined:O.boolean().optional().default(false),quarantinedReason:O.string().optional(),aiSettings:sa.optional()});O.object({id:O.string()});var FTe=sM.pick({id:true,status:true,healStatus:true,healDetails:true,testName:true,testId:true,test:true,failureReason:true,failureDetails:true}),nK=FTe.array(),oK=sM.pick({startedAt:true,finishedAt:true,updatedAt:true,results:true,beforeResults:true,afterResults:true,status:true,healStatus:true,healDetails:true,failureDetails:true,failureReason:true,failureRecoveryDetails:true,resolvedBaseUrl:true,environmentName:true,labels:true,cliVersion:true,resolvedInputs:true,attempts:true,flake:true,aiSettings:true}).partial();O.object({id:O.string()});var rK=O.object({run:Qi.omit({runAttempts:true}),attemptZipUrls:O.array(O.string().url().nullish())}),iK=O.object({status:O.nativeEnum(ht),finishedAt:O.coerce.date().optional(),schemaVersion:O.string().optional().default("1.0.19"),results:O.record(O.string(),O.unknown().optional()).array().optional(),beforeResults:O.record(O.string(),O.unknown().optional()).array().optional(),afterResults:O.record(O.string(),O.unknown().optional()).array().optional()});O.object({screenshot:O.string(),contentType:O.enum(["image/jpeg","image/png"]).optional()});O.object({id:O.string(),screenshot:O.string(),contentType:O.enum(["image/jpeg","image/png"])});var sK=O.object({key:O.string()}),aK=O.object({orgId:O.string(),userId:O.string(),email:O.string().optional(),name:O.string().optional(),pylonEmailHash:O.string().optional(),selfServe:O.boolean().optional()}),lK=O.object({blocked:O.boolean()}),cK=O.array(z$);O.record(O.string(),O.union([O.string(),O.boolean()]));O.object({workosAccessToken:O.string().min(1),organizationId:O.string().optional(),clientName:O.string().min(1).max(80).optional()});var dK=O.object({apiKey:O.string(),apiKeyName:O.string(),organizationId:O.string(),user:O.object({id:O.string(),email:O.string().optional()}),selfServe:O.boolean().optional()}),uK=O.object({error:O.literal("multiple_organizations"),organizations:O.array(O.object({id:O.string(),name:O.string()}))}),BTe=["web","ios","android"];O.object({platforms:O.array(O.enum(BTe)),packageManager:O.enum(["npm","pnpm","yarn","bun"]),wizardVersion:O.string().min(1).max(40),cliVersions:O.object({momentic:O.string().max(40).optional(),momenticMobile:O.string().max(40).optional()}).optional(),firstRunIds:O.array(O.guid()).max(10).optional()});O.object({ok:O.literal(true)});O.object({paths:O.string().array(),env:O.string().optional(),urlOverride:O.string().optional(),customHeaders:O.record(O.string(),O.string()).optional()});var pK=O.object({suiteRunIds:O.string().array(),runGroupIds:O.string().array()});O.object({suiteRunIds:O.string().array()});NV.array();O.object({runGroupIds:O.string().array()});var cv=O.object({uploadUrl:O.string()});rr.merge(VV);rr.merge(WV);rr.merge(zV);var UTe=O.object({testId:O.string().optional().default(""),testName:O.string().optional().default(""),suiteId:O.string().optional().default(""),suiteName:O.string().optional().default(""),isInteractive:O.boolean().optional().default(false),runner:O.nativeEnum(Zi).optional(),creditsUsed:O.number().optional(),stepsExecuted:O.number().optional(),tokensUsed:O.number().optional(),hostedBrowserSecondsUsed:O.number().optional()}),HTe=O.object({transactionId:O.string(),timestamp:O.string(),event:O.nativeEnum(mg),properties:UTe});HTe.array();var mK=E1.omit({steps:true}).extend({steps:O.array(O.record(O.string(),O.unknown().optional())).describe("unparsed ResolvedStep[]")});O.object({limit:O.number().min(1).max(10).optional(),page:O.number().min(1).optional(),start:uo.optional(),end:uo.optional(),gitBranchName:O.string().optional(),status:O.nativeEnum(ht).optional()});var hK=AV.array(),GTe=O.object({testId:mo.optional(),gitBranchName:O.string().optional(),gitCommitSha:O.string().optional(),status:O.nativeEnum(ht).optional(),label:O.string().array().optional(),limit:O.number().min(1).max(100).optional(),page:O.number().min(1).optional(),start:uo.optional(),end:uo.optional(),quarantined:O.boolean().optional(),recovered:O.boolean().optional(),includeFailureDetails:O.boolean().optional()});GTe.extend({orgId:O.string().optional(),testId:or(mo),status:or(O.nativeEnum(ht)),gitBranchName:or(O.string()),label:or(O.string()),testName:O.string().optional(),trigger:or(O.nativeEnum(vs)),executionType:or(mu),cliVersion:or(O.string()),githubRepository:or(O.string()),gitlabProjectPath:or(O.string()),environment:or(O.string()),directory:or(O.string()),failureCategory:or(O.string()),exclude:or(O.string()),healed:O.boolean().optional()});var jTe=Qi.omit({test:true}),gK=O.object({runs:jTe.array(),page:O.number(),pageSize:O.number(),pageCount:O.number()});O.object({applied:O.boolean().optional(),appliedAt:O.coerce.date().optional()});var fK=cv.extend({id:O.string()});O.object({runGroupId:O.guid().optional(),persist:O.boolean().optional()});var yK=O.object({runGroupId:O.guid()}),SK=O.object({quarantined:O.object({testId:mo,quarantinedAt:O.coerce.date(),quarantinedBy:O.string().optional(),quarantinedReason:O.string()}).array()}),bK=O.object({gitLocalUsername:O.string().optional(),gitLocalEmail:O.string().optional(),gitLocalName:O.string().optional()});O.object({testId:mo,testName:O.string().optional(),reason:O.string()}).merge(bK);O.object({testName:O.string().optional(),reason:O.string().optional()}).merge(bK);rr.merge(eW);rr.merge(tW);rr.merge(nW);O.object({apkToInstall:O.object({channel:O.string(),tag:O.string().optional()}).optional(),hostname:O.string().optional(),region:qM.optional(),osVersion:O.nativeEnum(gg).optional(),sessionId:O.string().optional(),playwrightVersion:pW.optional()});var TK=O.object({name:O.string(),apiUrl:O.string(),webRtcUrl:O.string(),adbUrl:O.string(),token:O.string(),apkDownloadUrl:O.string().optional(),playwrightServerUrl:O.string().optional(),region:O.string().optional(),resolvedTag:O.string().optional()});O.object({appToInstall:O.object({channel:O.string(),tag:O.string().optional()}).optional(),hostname:O.string().optional(),region:qM.optional(),osVersion:O.nativeEnum(jC).optional(),sessionId:O.string().optional(),installAppOnClient:O.boolean().optional()});var AK=O.object({id:O.string(),apiUrl:O.string(),webRtcUrl:O.string(),wdaUrl:O.string(),token:O.string(),appDownloadUrl:O.string().optional(),appMd5:O.string().optional(),region:O.string().optional(),resolvedTag:O.string().optional()});O.object({channel:O.string().trim().min(1,"channel must be a non-empty string"),tag:O.string().trim().min(1,"tag must be a non-empty string"),md5:O.string()});var EK=O.object({id:O.string(),uploadUrl:O.string().optional(),downloadUrl:O.string(),md5:O.string().optional()}),$Te=O.object({channel:O.string(),tag:O.string(),md5:O.string(),platform:O.nativeEnum(ja).default("ANDROID"),createdAt:O.number().describe("Unix timestamp in milliseconds")}),CK=O.object({assets:O.array($Te)}),vK=O.object({downloadUrl:O.string()}),RN=(n=>(n.PLAYWRIGHT="PLAYWRIGHT",n.CDP="CDP",n))(RN||{}),VTe=O.nativeEnum(RN);O.object({testId:O.string().optional(),testName:O.string().optional(),runId:O.guid().optional(),attemptedProviders:O.array(rN).optional()});var RK=O.object({wsEndpoint:O.string(),accessToken:O.string().optional(),endpointType:VTe.optional(),provider:rN.optional()});z$1.object({repositoriesIndexed:z$1.boolean(),indexingInProgress:z$1.boolean(),indexesOutdated:z$1.boolean()});var wK=(s=>(s.Queued="queued",s.InProgress="in_progress",s.Completed="completed",s.Waiting="waiting",s.Requested="requested",s.Pending="pending",s))(wK||{}),IK=(a=>(a.Success="success",a.Failure="failure",a.Neutral="neutral",a.Cancelled="cancelled",a.Skipped="skipped",a.TimedOut="timed_out",a.ActionRequired="action_required",a))(IK||{});z$1.object({name:z$1.string(),status:z$1.enum(wK),conclusion:z$1.enum(IK).nullable()});var Tb=z$1.object({sha:z$1.string(),message:z$1.string(),author:z$1.object({name:z$1.string().optional(),email:z$1.string().optional(),date:z$1.coerce.date().optional()}),committer:z$1.object({name:z$1.string().optional(),email:z$1.string().optional(),date:z$1.coerce.date().optional()})}),wN=z$1.object({mergedBranch:z$1.string().optional()});var xK=z$1.object({orgId:z$1.string(),cacheKeys:z$1.string().array()});z$1.object({keyParams:xK,clientMetadata:z$1.string(),lockAcquisitionTimeoutMs:z$1.number().optional()});var _K=z$1.object({acquired:z$1.boolean(),acquiredByMetadata:z$1.string(),keyPrefix:z$1.string()});z$1.object({keyPrefix:z$1.string(),result:z$1.string(),ttlMs:z$1.number()});z$1.union([z$1.object({keyPrefix:z$1.string()}),xK]);var zTe=z$1.object({remainingTtlMs:z$1.number(),value:z$1.string().nullish()});z$1.object({results:z$1.record(z$1.string(),zTe),activeLocks:z$1.string().array()});var PK=0,OK=5*60*1e3;var MK=z$1.object({testId:z$1.string().min(1),stepId:z$1.string().min(1),baseTestFileHash:z$1.string().min(1),branchName:z$1.string().min(1).optional(),environment:z$1.string().min(1).optional(),classification:sO,healDetails:TV.optional()}),WTe=MK.extend({createdAt:z$1.coerce.date(),updatedAt:z$1.coerce.date()});z$1.object({branchName:z$1.string().min(1).optional(),mainBranchName:z$1.string().min(1).optional(),stepId:z$1.string().min(1),baseTestFileHash:z$1.string().min(1),environment:z$1.string().min(1).optional()});var NK=WTe.array();z$1.object({entries:MK.array()});var qTe=30*bg;function LK(){return new Date(Date.now()-qTe)}function vg(e){if(e.startsWith("https://api"))return e.replace("https://api","https://app");if(e.startsWith("http://localhost:8000"))return e.replace("http://localhost:8000","http://localhost:3000");throw new Error(`Unknown Momentic app server URL pattern: ${e}`)}var KTe=z$1.object({version:z$1.string(),json:z$1.record(z$1.string(),z$1.unknown().optional()),hash:z$1.string()}),kK=z$1.record(z$1.string(),z$1.unknown().optional());z$1.object({newSvgs:z$1.array(KTe),metadata:kK.optional()});var YTe=z$1.object({version:z$1.string(),json:z$1.record(z$1.string(),z$1.unknown().optional()).nullish(),hash:z$1.string(),description:z$1.string().nullish(),metadata:kK.nullish()}),DK=z$1.record(z$1.string().describe("icon hash"),YTe);var dv="heal-trace",xN=`${dv}/timeline.json`,_N=`${dv}/assets`,uv=(o=>(o.RECOVERY_ASSESSOR="recovery-assessor",o.ORCHESTRATOR="orchestrator",o.HEAL_SUBAGENT="heal-subagent",o))(uv||{}),PN=(o=>(o.REASONING="reasoning",o.TEXT="text",o.TOOL_CALL="tool-call",o))(PN||{}),JTe=z$1.object({asset:z$1.string(),startedAt:z$1.number()}),XTe=z$1.object({type:z$1.enum(PN),startedAt:z$1.number(),finishedAt:z$1.number().optional(),text:z$1.string().optional(),toolName:z$1.string().optional(),toolInput:z$1.string().optional(),toolInputJson:z$1.string().optional(),toolOutputJson:z$1.string().optional(),stepsAfterSplice:Gt.array().optional(),screenshotAsset:z$1.string().optional(),subagents:z$1.lazy(()=>IN.array()).optional()}),IN=z$1.object({agentId:z$1.string(),kind:z$1.enum(uv),label:z$1.string(),testId:z$1.string().optional(),runId:z$1.string().optional(),targetId:z$1.string().optional(),bucketId:z$1.string().optional(),startedAt:z$1.number(),finishedAt:z$1.number().optional(),spans:XTe.array(),videos:JTe.array().optional(),initialTestState:Gt.array().optional()}),QTe=z$1.object({testId:z$1.string(),appliedAt:z$1.number(),originRunId:z$1.string().optional()});z$1.object({cliVersion:z$1.string().optional(),healSessionId:z$1.string(),startedAt:z$1.number(),finishedAt:z$1.number().optional(),recoveryAssessors:IN.array(),orchestrator:IN.optional(),cachedHeals:QTe.array()});var ON="metadata.json",MN="test.yaml",FK=".snapshot.zip",NN=Zn.extend(Dl.shape),ZTe=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:CS.optional()}),BK=z$1.object({browser:Ga.optional(),ai:sa.optional(),advanced:PS.optional(),retries:z$1.number().optional()});z$1.object({momenticVersion:z$1.string(),schemaVersion:z$1.string(),createdAt:z$1.string(),relativeFilePath:z$1.string(),environment:ZTe,config:BK});var UK=z$1.object({variables:z$1.record(z$1.string(),z$1.unknown().optional()),resolvedEnv:CS.optional()}),eAe=z$1.object({envName:z$1.string().optional(),baseUrl:z$1.string(),encryptedSecrets:z$1.string()}),HK=z$1.object({momenticVersion:z$1.string(),schemaVersion:z$1.string(),createdAt:z$1.string(),relativeFilePath:z$1.string(),environment:eAe,config:BK});function GK(e){let t;try{t=JSON.parse(e);}catch(n){return `The schema is not valid JSON. ${n}`}try{validator(t);}catch(n){return `The schema is not a valid JSON schema. ${n}`}}var jK=e=>{e.extraHeaders&&(e.extraHeaders=Object.fromEntries(Object.entries(e.extraHeaders).filter(([t,n])=>t.trim()&&n.trim())));};var pv=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}async saveSnapshotCacheEntries(){}async deleteStepCacheEntry(){}};function nAe(e){return e.map(t=>({...t,environment:void 0}))}function LN(e,t){return t?e:nAe(e)}var DN="browser-crash-dump.zip",kN=class{loggerBindings;attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}recordTargetAutoHeal(){}storeTraceAsset(){}async finish(){}async startSubSteps(){return new Ab}},Ab=class{async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new kN}flushResults(t){}};var ct="metadata.json",Fr="assets",to="runs",oAe=z$1.object({step:Gt,status:z$1.enum(Mt),startedAt:z$1.coerce.date(),finishedAt:z$1.coerce.date().optional(),healMetadata:z$1.object({healType:z$1.enum(AS).or(z$1.literal("AI")),healedAt:z$1.coerce.date()}).optional(),beforeSnapshotId:z$1.guid().optional(),afterSnapshotId:z$1.guid().optional(),message:z$1.string().optional()}),rAe=oAe.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});rAe.extend({step:z$1.unknown().optional()});var FN=z$1.object({avdId:z$1.string().optional(),channel:z$1.string().optional(),tag:z$1.string().optional(),region:z$1.string().optional(),osVersion:mW.optional()}),VK="1.0.0",zK=iK.extend({id:z$1.guid().optional(),startedAt:z$1.coerce.date(),runAttemptSchemaVersion:z$1.string().optional(),schemaVersion:z$1.string().optional().default("1.0.19"),results:z$1.record(z$1.string(),z$1.unknown().optional()).array().optional(),beforeResults:z$1.record(z$1.string(),z$1.unknown().optional()).array().optional(),afterResults:z$1.record(z$1.string(),z$1.unknown().optional()).array().optional(),assetDetails:FN.optional(),viewport:Jc.optional(),activeVideos:z$1.array(z$1.object({videoName:z$1.string(),timestamp:z$1.coerce.date()})).optional()}),Eb=zK.extend({assetDetails:FN.optional(),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});zK.extend(YO.shape);var WK=Eb.extend(YO.shape),iAe=z$1.object({results:z$1.array(ws),beforeResults:z$1.array(ws).optional(),afterResults:z$1.array(ws).optional()});Eb.extend(iAe.shape);var sAe=z$1.object({results:z$1.array(Is),beforeResults:z$1.array(Is).optional(),afterResults:z$1.array(Is).optional()});Eb.extend(sAe.shape);var qK=oK.merge(tK).extend({executionType:mu.optional().default("WEB"),testId:mo,testDescription:z$1.string().optional(),directory:z$1.string().optional(),runGroupId:z$1.guid(),status:z$1.enum(ht),healStatus:NS,startedAt:z$1.coerce.date(),schemaVersion:z$1.string().nullish(),attempts:z$1.number(),failureRecoveryDetails:z$1.object({attempts:z$1.number()}).optional(),aiSettings:sa.optional(),avgCpuUsage:z$1.number().optional(),avgMemoryUsage:z$1.number().optional()}),aAe=qK.extend(FN.shape),tm=qK.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});aAe.extend({finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var $K=z$1.object({mode:z$1.enum(["SELECTED","RUN_ALL","RUN_NONE","SHADOW"]),baseRef:z$1.string().nullable(),headSha:z$1.string(),planId:z$1.string().nullable(),totalCandidates:z$1.number().int().nonnegative(),selectedCount:z$1.number().int().nonnegative(),anchorSegmentIds:z$1.array(z$1.string()),userSummary:z$1.string(),toolCallCount:z$1.number().int().nonnegative(),selectedTests:z$1.array(hC),forcedTests:z$1.array(z$1.object({name:z$1.string(),testPath:z$1.string(),status:z$1.enum(["A","M","R","C","T"])})).optional().default([]),runAllReason:z$1.string().nullable()}),lAe=Z2.merge(eK).extend({id:z$1.guid().optional(),startedAt:z$1.coerce.date(),cliVersion:z$1.string(),labels:z$1.string().array().optional().default([]),suiteName:z$1.string().optional(),ciProvider:z$1.string().optional(),gitMainBranch:z$1.string().optional(),ai:sa.optional(),browser:Ga.optional(),aiSelect:z$1.union([$K.transform(e=>[e]),z$1.array($K)]).optional()}),ua=lAe.extend({healRiskSummary:zp.optional(),updatedAt:z$1.coerce.date().optional().transform(e=>e??new Date),finishedAt:z$1.coerce.date().optional().transform(e=>e??new Date)});var cAe=new Set(["AWAIT_LISTENER","REGISTER_REQUEST_LISTENER","GET_RECORDED_REQUESTS","MOCK_ROUTE","REMOVE_ROUTE_MOCK","SCROLL_DOWN","SCROLL_UP","SCROLL_LEFT","SCROLL_RIGHT","VISUAL_DIFF","WAIT","SET_HEADER","OFFLINE_MODE"]),dAe=new Set(["MODULE","RESOLVED_MODULE"]);function mv(e){return e.type!=="PRESET_ACTION"?e.type:e.command.type}function hv(e){return dAe.has(e.type)?false:e.type!=="PRESET_ACTION"?true:!cAe.has(e.command.type)}var KK="progress.json",YK="1.0.0",uAe=z$1.object({runId:z$1.string(),testId:z$1.string().optional(),testName:z$1.string().optional(),directory:z$1.string().optional(),status:z$1.nativeEnum(ht),completedSteps:z$1.number(),totalSteps:z$1.number(),startedAt:z$1.coerce.date(),updatedAt:z$1.coerce.date()});z$1.object({schemaVersion:z$1.string(),runGroupId:z$1.string(),status:z$1.nativeEnum(ht),totalRuns:z$1.number(),completedRuns:z$1.number(),completedSteps:z$1.number(),totalSteps:z$1.number(),startedAt:z$1.coerce.date(),updatedAt:z$1.coerce.date(),runs:uAe.array()});function JK(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch(t){return R.error({err:t},`Error reading path ${e} during directory existence check.`),false}}var XK="CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih",Rg="https://us-west.metrics.momentic.ai",wg="c60c6a0f-60da-41a7-a61b-07969a0aa303",nm=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;var bAe=new Set(["exit","quit"]),eY=(()=>{try{return statSync("/.dockerenv"),!0}catch{return false}})();async function sr(e){return nm||eY?true:(await R.flush(),await new Promise(n=>setTimeout(n,100)),await confirm({message:e}))}async function BN(e){let t=dirname(e);return JK(t)?existsSync(e)?sr(`File '${QK(e)}' already exists. Overwrite existing content?`):true:await sr(`Directory '${QK(t)}' doesn't exist. Create it now?`)?(mkdirSync(t,{recursive:true}),true):false}function QK(e){return e.replace(/(\s+)/g,"\\$1")}async function tY(e,t){return nm||eY?t:(await input({message:e,default:t})).trim()||t}async function nY(){let e;try{e=(await input({message:"ask"})).trim();}catch(t){if(t instanceof Error&&t.name==="ExitPromptError"){R.info("");return}throw t}if(!bAe.has(e.toLowerCase()))return e}var Ig=new Map,rY="Log throttle exceeded",PAe=100,OAe=5e3,MAe=vAe(global.fetch,{retries:2,retryOn:function(e,t,n){return !!(t!==null||n&&n.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}}),NAe=`${Rg}/logs/json`,UN=class{constructor(t,n){this.flushIntervalMs=t;this.maxBatchSize=n;}records=[];flushTimer;push(t){if(this.records.push(t),this.records.length>=this.maxBatchSize){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flush();return}this.scheduleFlush();}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush();},this.flushIntervalMs));}async flush(){if(this.records.length===0)return;let t=this.records;this.records=[];try{let n=await MAe(NAe,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":XK,"x-momentic-metrics-api-key":wg},body:Va(t),signal:AbortSignal.timeout(5e3)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch{}}},HN=class e{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=false;lastWindowStart=Date.now();flushIntervalMs;maxBatchSize;buffer;constructor({bindings:t,hostname:n,disableConsoleLogs:o,flushIntervalMs:r,maxBatchSize:i,buffer:s}){this.hostname=n??sd.hostname(),this.disableConsoleLogs=o,this.bindingAttributes={...t,env:"production"},this.flushIntervalMs=r??5e3,this.maxBatchSize=i??10,this.buffer=s??new UN(this.flushIntervalMs,this.maxBatchSize);let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=oY(a);}child(t){return new e({bindings:{...this.bindingAttributes,...t},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize,buffer:this.buffer})}async flush(){await this.buffer.flush(),this.disableConsoleLogs||this.consoleLogger.flush();}shouldAllowLog(t){if(t===rY)return true;let n=Date.now();return n-this.lastWindowStart>OAe&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,rY),this.droppedLogsInWindow=false,this.lastWindowStart=n),this.logsInCurrentWindow<PAe?(this.logsInCurrentWindow++,true):(this.droppedLogsInWindow=true,false)}log(t,n,o,...r){try{this.logHelper(t,n,o,...r);}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`);}}logHelper(t,n,o,...r){if(_S[t]<this.minLevelValue||!this.shouldAllowLog(o))return;typeof n=="string"&&!o&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=xAe.err(n.err));let i={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...r.length>0?{args:r}:{}},s={host:this.hostname,env:this.bindingAttributes.env},a=LAe();this.disableConsoleLogs||this.consoleLogger[t]({...i,...a??{}},o,...r);let l={timestamp:Math.round(Date.now()*1e6),...a??{},severity_text:t.toUpperCase(),resources:s,attributes:{},body:dV({message:o||"",...i})};this.buffer.push(l);}setApp(t){let n=this.bindingAttributes.app;this.bindingAttributes.app=t,Ig.set("app",this),Ig.delete(n);}debug(t,n,...o){this.log("debug",t,n,...o);}info(t,n,...o){this.log("info",t,n,...o);}warn(t,n,...o){this.log("warn",t,n,...o);}error(t,n,...o){this.log("error",t,n,...o);}bindings(){return this.bindingAttributes}addBinding(t,n){this.bindingAttributes[t]=n;}setMinLevel(t){typeof t=="number"?(this.minLevelValue=t,this.consoleLogger.level=uV[t]):(this.minLevelValue=_S[t],this.consoleLogger.level=t);}enableConsoleLogs(){this.disableConsoleLogs=false;}},xg=({app:e,hostname:t,disableConsoleLogs:n})=>(Ig.has(e)||Ig.set(e,new HN({bindings:{app:e},hostname:t,disableConsoleLogs:n})),Ig.get(e));function LAe(){let e=trace.getSpan(context.active());if(!e)return;let t=e.spanContext();if(isSpanContextValid(t))return {trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}async function gv(){await Promise.all([...Ig.values()].map(e=>e.flush()));}var vu=class extends Error{callSiteStack;constructor(t){super(t),this.name="TimeoutError";}};var iY=e=>{let t=e.reason===void 0?new DOMException("This operation was aborted.","AbortError"):e.reason;return t instanceof Error?t:new DOMException(t,"AbortError")};function _e(e,t){let{milliseconds:n,fallback:o,message:r,customTimers:i={setTimeout,clearTimeout}}=t,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);let a=new Error().stack;return new Promise((l,c)=>{let d;if(t.signal){let{signal:m}=t;if(m.aborted)return c(iY(m));d=()=>c(iY(m)),m.addEventListener("abort",d,{once:true});}let u=()=>{if(t.signal&&t.signal.removeEventListener("abort",d),o)try{l(o());}catch(m){c(m);}else {if(typeof e.cancel=="function"&&Promise.resolve().then(()=>e.cancel()).catch(()=>{}),r instanceof Error){c(r);return}let m=new vu(r??`Promise timed out after ${n}ms`);m.callSiteStack=a,c(m);}};n<1/0&&(s=i.setTimeout(u,n));let p=()=>{i.clearTimeout(s),t.signal&&t.signal.removeEventListener("abort",d);};Promise.resolve(e).then(m=>{p(),l(m);}).catch(m=>{p(),c(m);});})}var fv="organization";function yv(e){let t=new PostHog(e.writeKey,{host:e.host,...e.flushImmediately?{flushAt:1,flushInterval:0}:{}}),n=e.platform,o=(l,c,d)=>{let{type:u,...p}=l;t.capture({distinctId:c??d??randomUUID(),event:u,...d&&{groups:{[fv]:d}},properties:{platform:n,user_id:c??void 0,org_id:d??void 0,...p,organizationId:d??void 0,...c==null&&d==null&&{$process_person_profile:false}}});},r=({orgId:l,properties:c})=>{t.groupIdentify({groupType:fv,groupKey:l,properties:c});},i=({userId:l,properties:c})=>{Object.values(c).some(u=>u!=null&&u!=="")&&t.identify({distinctId:l,properties:c});},s=()=>t.shutdown();if(e.identity==="stashed"){let l=null;return {shutdownAnalytics:s,groupIdentifyOrg:r,setAnalyticsIdentity:d=>{l=d,e.onIdentify?.(d),i({userId:d.userId,properties:{email:d.email,...d.selfServe!==void 0?{self_serve:d.selfServe}:{}}});},captureEvent:d=>o(d,l?.userId??null,l?.orgId??null)}}return {shutdownAnalytics:s,groupIdentifyOrg:r,identifyUser:i,captureEvent:(l,{userId:c,orgId:d})=>o(l,c,d),captureBillingEvent:(l,{userId:c,orgId:d})=>o(l,c,d)}}async function sY(e,t,n){let o,r=0,i=3,s,a;for(;r<i;)try{let l=await _e(e.getAllFlagsAndPayloads(n??t,{personProperties:{organizationId:t},groups:{[fv]:t}}),{milliseconds:5e3});s=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){o=l,r++,await new Promise(c=>setTimeout(c,100*r));}if(s&&a)return {flags:s,payloads:a};throw o}var Sv=class e extends cb{constructor(n,o,r,i,s){super(i,s);this.client=n;this.orgId=o;this.userId=r;}static async init(n,o){let r=new PostHog("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://p.momentic.ai"}),{flags:i,payloads:s}=await sY(r,n,o);return new e(r,n,o,i,s)}async refresh(){let{flags:n,payloads:o}=await sY(this.client,this.orgId,this.userId);this.flags=n,this.payloads=o;}};var HAe=2e3,om=e=>Number.parseInt(e,10),jN=e=>readFileSync(e,"utf8").trim(),_g=e=>om(jN(e)),aY,bv,Cb={samples:0,lowMemorySamples:0,highCpuSamples:0,highHeapSamples:0};function dY(){return {...Cb}}var Av=sd.platform(),GAe=sd.cpus().map(e=>({model:e.model,speed:e.speed})).reduce((e,t)=>(e[t.model]={speed:t.speed},e.totalCores=(e.totalCores??0)+1,e),{});function GN(e=Date.now()){let t=sd.cpus(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;return n.total=n.user+n.nice+n.sys+n.idle+n.irq,n}function uY(e,t){let n={user:t.user-e.user,nice:t.nice-e.nice,sys:t.sys-e.sys,idle:t.idle-e.idle,irq:t.irq-e.irq,total:t.total-e.total};return n.total<=0?null:{measurementTime:t.measurementTime,intervalMs:t.measurementTime-e.measurementTime,user:n.user/n.total*100,nice:n.nice/n.total*100,sys:n.sys/n.total*100,idle:n.idle/n.total*100,irq:n.irq/n.total*100,total:100-n.idle/n.total*100}}function jAe(){let e=GN();return ()=>{let t=GN(),n=uY(e,t);return e=t,n}}function lY(){try{let t=readFileSync("/sys/fs/cgroup/cpu.stat","utf8").match(/^usage_usec\s+(\d+)/m);if(t?.[1])return om(t[1])}catch{}try{let e=_g("/sys/fs/cgroup/cpuacct/cpuacct.usage");if(!isNaN(e))return e/1e3}catch{}return null}function $Ae(){try{let t=jN("/sys/fs/cgroup/cpu.max").split(" "),n=t[0],o=t[1];return !n||!o||n==="max"?null:om(n)/om(o)}catch{}try{let e=_g("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"),t=_g("/sys/fs/cgroup/cpu/cpu.cfs_period_us");return e===-1||isNaN(t)?null:e/t}catch{return null}}function VAe(){if(Av!=="linux")return null;let e=lY();if(e===null)return null;let t=$Ae()??sd.cpus().length,n=e,o=Date.now();return ()=>{let r=lY();if(r===null)return null;let i=Date.now(),s=i-o;if(s<=0)return null;let a=r-n,l=s*1e3,c=Math.max(0,Math.min(100,a/l/t*100));return n=r,o=i,{measurementTime:i,intervalMs:s,user:c,nice:0,sys:0,idle:Math.max(0,100-c),irq:0,total:c}}}function zAe(){let e=process.cpuUsage(),t=process.hrtime.bigint();return ()=>{let n=process.cpuUsage(),o=process.hrtime.bigint(),r=Number(o-t)/1e6,i=n.user-e.user,s=n.system-e.system;if(e=n,t=o,r<=0)return null;let a=Math.max(sd.cpus().length,1),l=c=>Math.max(0,c/1e3/r*100/a);return {total:l(i+s),user:l(i),sys:l(s),intervalMs:r}}}function pY({intervalMs:e=HAe,maxSamples:t=1e4,keepSamples:n=true,onSample:o}={}){let r=[],i=VAe()??jAe(),s=zAe(),a=()=>{let d=Date.now(),u=hY(),p=process.memoryUsage(),m=i(),h=s(),g={timestamp:d,system:{cpu:m,memory:{total:u.totalMemory,free:u.freeMemory,freePercentage:u.freePercentage}},process:{cpu:h,memory:{rss:p.rss,heapTotal:p.heapTotal,heapUsed:p.heapUsed,external:p.external,arrayBuffers:p.arrayBuffers}}};o?.(g),n&&(r.push(g),r.length>t&&r.shift());};a();let l=setInterval(a,e),c=d=>({samples:n?[...r]:[]});return {stop:()=>(clearInterval(l),c()),getSeries:()=>c()}}var Tv=e=>{try{let t={},n=!1,o=hY(),r=qAe();Cb.samples++,o.freePercentage<.05&&(Object.assign(t,process.memoryUsage()),n=!0,Cb.lowMemorySamples++),r&&r?.total>80&&(n=!0,Cb.highCpuSamples++);let i=UAe.getHeapStatistics(),s=i.used_heap_size,a=i.heap_size_limit;s/a>.9&&(n=!0,Cb.highHeapSamples++),n?e.warn({memory:o,cpu:r,heapStats:i,...t},"Critical resource usage metrics detected"):e.debug({memory:o,cpu:r},"Got machine resource usage metrics");}catch{}},mY=e=>{Tv(e),setTimeout(()=>Tv(e),5e3);};function Ev(e){return Tv(e),{interval:setInterval(()=>Tv(e),2e4),cpuMetadata:GAe,platform:Av}}function WAe(){if(Av!=="linux")return null;try{let e=jN("/sys/fs/cgroup/memory.max"),t=_g("/sys/fs/cgroup/memory.current");if(e==="max"||isNaN(t))return null;let n=om(e);if(isNaN(n))return null;let o=Math.max(0,n-t);return {totalMemory:n,freeMemory:o,freePercentage:o/n}}catch{}try{let e=_g("/sys/fs/cgroup/memory/memory.limit_in_bytes"),t=_g("/sys/fs/cgroup/memory/memory.usage_in_bytes");if(isNaN(e)||isNaN(t))return null;let n=sd.totalmem();if(e>=n)return null;let o=Math.max(0,e-t);return {totalMemory:e,freeMemory:o,freePercentage:o/e}}catch{return null}}function hY(){let e=WAe();if(e)return e;let t=sd.totalmem(),n=Av==="darwin"?KAe():(()=>{let r=sd.freemem();return {availableMemory:r,rawFreeMemory:r,cachedMemory:0}})(),o=n.availableMemory/t;return {totalMemory:t,freeMemory:n.availableMemory,freePercentage:o}}function qAe(){let e=GN();if(!bv)return bv=e,null;let t=uY(bv,e);return bv=e,t?(aY=t,aY):null}function KAe(){try{let e=execSync("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),n=e.match(/page size of (\d+) bytes/)?.[1],o=n?om(n):4096,r=d=>{let p=e.match(new RegExp(`${d}:\\s+(\\d+)\\.`,"i"))?.[1];return p?om(p):0},i=r("Pages free"),s=r("Pages inactive"),a=r("Pages speculative"),l=i*o,c=(s+a)*o;return {availableMemory:l+c,rawFreeMemory:l,cachedMemory:c}}catch{let e=sd.freemem();return {availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}process.env.APP||"unknown";var Cv="deployment.environment",vv="service.instance.id";function gY(){return process.env.MOMENTIC_LOCAL_DEV==="1"&&process.env.LOCAL_SIGNOZ==="true"}var Pg=false,Rv,vb,Rb,SY=[],wv;function Iv(){return Pg}function bY(e){SY.push(e);}async function aEe(){for(let e of SY)try{await e();}catch{}}function lEe(){return Iv()&&trace.getSpan(context.active())!==void 0}function cEe(){return gY()?new OTLPTraceExporter({url:"http://localhost:4318/v1/traces"}):new OTLPTraceExporter({url:`${Rg}/v1/traces`,headers:{"x-momentic-metrics-api-key":wg}})}function dEe(e){let t="production",n=v4$1(),o=cEe();return new NodeTracerProvider({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:e,[Cv]:t,[vv]:n,[ATTR_SERVICE_VERSION]:"3.16.3"}),spanProcessors:[new BatchSpanProcessor(o)]})}function uEe(e){wv=registerInstrumentations({tracerProvider:e,instrumentations:[new UndiciInstrumentation({requireParentforSpans:true})]});}function pEe(e){return !e&&!Rv?trace.getTracer("momentic-serverless"):Rb?.getTracer("momentic-serverless")??trace.getTracer("momentic-serverless")}async function Ru(e){if(!(!e.enabled||Pg))try{Rv=e.serviceName;let t=dEe(e.serviceName);Rb=t,vb=new AsyncLocalStorageContextManager,t.register({contextManager:vb.enable(),propagator:new W3CTraceContextPropagator}),uEe(t),Pg=!0;}catch{Pg=false,Rv=void 0,Rb=void 0,vb=void 0,wv=void 0;}}async function xv(){if(Pg)try{await aEe(),await Rb?.shutdown();}catch{}finally{wv?.();try{vb?.disable();}catch{}Pg=false,Rv=void 0,vb=void 0,Rb=void 0,wv=void 0;}}async function He(e){if(!Iv()||!e.root&&!lEe())return e.fn(void 0);let t=e.serviceName===void 0?e.attributes:{...e.attributes??{},"momentic.span_service_name":e.serviceName};return await pEe(e.serviceName).startActiveSpan(e.name,{attributes:t,kind:e.kind??SpanKind.CLIENT},async n=>{try{let o=await e.fn(n);return n.setStatus({code:SpanStatusCode.OK}),o}catch(o){throw n.setStatus({code:SpanStatusCode.ERROR,message:o instanceof Error?o.message.slice(0,300):void 0}),o instanceof Error&&n.recordException(o),o}finally{n.end();}})}var wb=class{increment(t,n,o){}gauge(t,n){}distribution(t,n,o){}async flush(){}async recordDuration(t){return await VN(t)}};async function VN({fn:e,name:t,timeoutMs:n,timeoutMessage:o,trace:r}){let i=r?()=>He({name:r.name,attributes:r.attributes,fn:e}):e,s=Promise.resolve(i());return n===void 0?await s:await _e(s,{milliseconds:n,message:o??`Timed out after ${n}ms recording duration for ${t}`})}function mEe(e){if(!e||e.length===0)return {};let t={};for(let n of e){let o=n.indexOf(":");if(o>-1){let r=n.slice(0,o).trim(),i=n.slice(o+1).trim();r&&(t[r]=i);continue}t[n]=true;}return t}function zN(e,t){let n=mEe(e);return !t||Object.keys(t).length===0?n:{...t,...n}}function vEe(){return new OTLPMetricExporter({url:`${Rg}/v1/metrics`,headers:{"x-momentic-metrics-api-key":wg},temporalityPreference:AggregationTemporalityPreference.DELTA})}var WN=[100,500,1e3,2e3,3e3,4e3,5e3,7500,1e4,15e3,2e4],_v=(e,t)=>({instrumentName:e,instrumentType:InstrumentType.HISTOGRAM,aggregation:{type:AggregationType.EXPLICIT_BUCKET_HISTOGRAM,options:{boundaries:t,recordMinMax:false}}}),REe=[_v("test_event_duration",WN),_v("test_step_duration",WN),_v("test_mobile_step_duration",WN),_v("web_agent_action_duration",[25,50,100,200,350,500,750,1e3,2e3,5e3,1e4,2e4])],Pv=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(t){let n=this.counterCache.get(t);if(n)return n;let o=this.meter.createCounter(t);return this.counterCache.set(t,o),o}getHistogram(t){let n=this.histogramCache.get(t);if(n)return n;let o=this.meter.createHistogram(t);return this.histogramCache.set(t,o),o}ensureObservableGauge(t){let n=this.observableGaugeCache.get(t);if(n)return n;let o=this.meter.createObservableGauge(t);return o.addCallback(r=>{let i=this.gaugeValues.get(t);i!==void 0&&r.observe(i,this.globalAttributes);}),this.observableGaugeCache.set(t,o),o}constructor(t){this.globalAttributes={...t.globalAttributes??{}};let n=typeof process<"u"?"production":"unknown",o=resourceFromAttributes({[ATTR_SERVICE_NAME]:t.serviceName,[Cv]:n,[vv]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:v4$1(),[ATTR_SERVICE_VERSION]:"3.16.3"}),r=vEe(),i=new PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:t.exportIntervalMs??6e4});this.provider=new MeterProvider({resource:o,readers:[i],views:REe}),metrics.setGlobalMeterProvider(this.provider),this.meter=metrics.getMeter("momentic-serverless");}increment(t,n,o){try{let r=zN(o,this.globalAttributes);this.getCounter(t).add(typeof n=="number"?n:1,r);}catch{}}gauge(t,n){try{this.ensureObservableGauge(t),this.gaugeValues.set(t,n);}catch{}}distribution(t,n,o){try{let r=zN(o,this.globalAttributes);this.getHistogram(t).record(n,r);}catch{}}async flush(){try{await this.provider.forceFlush();}catch{}}async recordDuration(t){let{name:n,tags:o}=t,r=Date.now();try{return await VN(t)}finally{this.distribution(n,Date.now()-r,o);}}};var At=new wb;function AY(e){if(!e.disabled)try{At=new Pv(e);}catch{At=new wb;}}var qN;function EY(e){qN=e;}function wu(e){IEe(e)&&qN&&qN(e);}var wEe=new Set(["InternalWebAgentError","InternalPlatformError","UnknownError"]);function IEe(e){return e instanceof Error&&e.name==="AbortError"||VE(e,ke)?false:e instanceof te?wEe.has(e.reason):true}function xEe({usage:e,promptType:t,result:n="success"}){let o=[`type:${t}`,`result:${n}`],r=e.inputTokens??0,i=e.inputTokenDetails.cacheReadTokens??e.cachedInputTokens??0,s=e.outputTokens??0;At.distribution("ai_session_tokens",r,[...o,"category:input"]),At.distribution("ai_session_tokens",Math.max(0,Math.min(i,r)),[...o,"category:cached_input"]),At.distribution("ai_session_tokens",s,[...o,"category:output"]);}function Ov({usage:e,promptType:t,logger:n,message:o,result:r="success",attributes:i}){xEe({usage:e,promptType:t,result:r}),n.info({...i,promptType:t,result:r,usage:e},o);}function pa({usage:e,promptType:t,logger:n}){let o=Promise.resolve(e).catch(r=>{n.warn({err:r,promptType:t},"Failed to resolve AI session usage");});return ({message:r,result:i="success",attributes:s})=>{o.then(a=>{a&&Ov({usage:a,promptType:t,logger:n,result:i,message:r,attributes:s});});}}function kY(){return globalThis.crypto}function XN(e){let t=kY(),n=new Uint8Array(e);if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(n),n;for(let o=0;o<n.length;o++)n[o]=Math.floor(Math.random()*256);return n}function xu(){let e=kY();if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=XN(16);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return `${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function QN(e){let t=globalThis.Buffer;if(t)return t.from(e).toString("base64");let n="";for(let a=0;a<e.length;a++)n+=String.fromCharCode(e[a]);let o=globalThis.btoa;if(typeof o=="function")return o(n);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="",s=0;for(;s<n.length;){let a=n.charCodeAt(s++)&255,l=s<n.length?n.charCodeAt(s++)&255:NaN,c=s<n.length?n.charCodeAt(s++)&255:NaN,d=a>>2,u=(a&3)<<4|(Number.isNaN(l)?0:l>>4),p=Number.isNaN(l)?64:(l&15)<<2|(Number.isNaN(c)?0:c>>6),m=Number.isNaN(c)?64:c&63;i+=r.charAt(d),i+=r.charAt(u),i+=p===64?"=":r.charAt(p),i+=m===64?"=":r.charAt(m);}return i}function PEe(e){return new Promise(t=>setTimeout(t,e))}function xb(e){if(e)return e.endsWith("/")?e:`${e}/`}function OEe(e){var t;let n=(t=e.get("Retry-After"))!=null?t:e.get("retry-after");if(!n)return;let o=Number(n);if(n.trim()!==""&&!Number.isNaN(o))return o*1e3;let r=new Date(n).getTime();if(!Number.isNaN(r)){let i=r-Date.now();return i>0?i:0}}function MEe(e,t){if(t&&typeof t=="object"&&t!==null&&"retryAfterMs"in t){let r=t.retryAfterMs;if(typeof r=="number")return Math.max(0,r)}if(e<=1)return 0;let n=500,o=Math.pow(2,e-2);return n*o}async function NEe(e,t,n){let o=n.sdkName?`[raindrop-ai/${n.sdkName}]`:"[raindrop-ai/core]",r;for(let i=1;i<=n.maxAttempts;i++){if(i>1){let s=MEe(i,r);n.debug&&console.warn(`${o} ${t} retry ${i}/${n.maxAttempts} in ${s}ms`),s>0&&await PEe(s);}else n.debug&&console.log(`${o} ${t} attempt ${i}/${n.maxAttempts}`);try{return await e()}catch(s){if(r=s,n.debug){let a=s instanceof Error?s.message:String(s);console.warn(`${o} ${t} attempt ${i} failed: ${a}${i===n.maxAttempts?" (no more retries)":""}`);}if(r&&typeof r=="object"&&"retryable"in r&&!r.retryable||i===n.maxAttempts)break}}throw r instanceof Error?r:new Error(String(r))}async function rm(e,t,n,o){let r=`POST ${e}`;await NEe(async()=>{let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(t)});if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`HTTP ${i.status} ${i.statusText}${s?`: ${s}`:""}`),l=OEe(i.headers);throw typeof l=="number"&&(a.retryAfterMs=l),a.retryable=i.status===429||i.status>=500,a}},r,o);}var CY={UNSET:0,ERROR:2};function vY(e){let t=e?e.traceIdB64:QN(XN(16)),n=QN(XN(8));return {traceIdB64:t,spanIdB64:n,parentSpanIdB64:e?e.spanIdB64:void 0}}function _b(){return Date.now().toString()+"000000"}function RY(e){return String(Math.floor(e))+"000000"}function J(e,t){if(t!==void 0)return {key:e,value:{stringValue:t}}}function nt(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{intValue:String(Math.trunc(t))}}}function Mg(e,t){if(t!==void 0&&Number.isFinite(t))return {key:e,value:{doubleValue:t}}}function LEe(e,t){if(t!==void 0)return {key:e,value:{boolValue:t}}}function ad(e,t){if(!(!t||t.length===0))return {key:e,value:{arrayValue:{values:t.filter(n=>typeof n=="string").map(n=>({stringValue:n}))}}}}function KN(e){let t=e.attributes.filter(o=>o!==void 0),n={traceId:e.ids.traceIdB64,spanId:e.ids.spanIdB64,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano};return e.ids.parentSpanIdB64&&(n.parentSpanId=e.ids.parentSpanIdB64),t.length&&(n.attributes=t),e.status&&(n.status=e.status),n}function wY(e,t="raindrop.core",n="0.0.0"){return {resourceSpans:[{resource:{attributes:[{key:"service.name",value:{stringValue:t}}]},scopeSpans:[{scope:{name:t,version:n},spans:e}]}]}}var kEe="RAINDROP_LOCAL_DEBUGGER",DEe="RAINDROP_WORKSHOP",IY="http://localhost:5899/v1/";function iL(e){var t;try{let n=(t=globalThis?.process)==null?void 0:t.env;if(n&&typeof n[e]=="string"&&n[e].length>0)return n[e]}catch{}}function FEe(){let e=iL(DEe);if(e===void 0)return;let t=e.trim();if(t.length!==0){if(/^https?:\/\//i.test(t))return {url:t};if(/^(1|true|yes|on)$/i.test(t))return "enable";if(/^(0|false|no|off)$/i.test(t))return "disable"}}function BEe(e){return e?!!(e==="localhost"||e==="127.0.0.1"||e==="0.0.0.0"||e==="::1"||e.endsWith(".localhost")):false}function UEe(){try{let e=globalThis?.location;if(e&&typeof e.hostname=="string"&&e.hostname.length>0)return e.hostname}catch{}}function HEe(){return !!(BEe(UEe())||iL("NODE_ENV")==="development")}function sm(e){var t,n,o;if(e===null)return null;if(typeof e=="string"&&e.length>0)return (t=xb(e))!=null?t:null;let r=iL(kEe);if(r)return (n=xb(r))!=null?n:null;let i=FEe();return i==="disable"?null:i==="enable"?IY:i&&"url"in i?(o=xb(i.url))!=null?o:null:HEe()?IY:null}function Bv(e){return sm(e)!==null}function GEe(e,t={}){var n;let o=sm(t.baseUrl);o&&rm(`${o}traces`,e,{},{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function jEe(e,t={}){var n;let o=sm(t.baseUrl);if(!o)return;let r=t.writeKey?{Authorization:`Bearer ${t.writeKey}`}:{};rm(`${o}events/track_partial`,e,r,{maxAttempts:1,debug:(n=t.debug)!=null?n:false,sdkName:t.sdkName}).catch(()=>{});}function Iu(e,t={}){var n,o;let r=sm(t.baseUrl);r&&rm(`${r}live`,{...e,type:e.type,timestamp:(n=e.timestamp)!=null?n:Date.now()},{},{maxAttempts:1,debug:(o=t.debug)!=null?o:false,sdkName:t.sdkName}).catch(()=>{});}function $Ee(e,t){var n,o,r,i;let s={...e,...t};return (e.properties||t.properties)&&(s.properties={...(n=e.properties)!=null?n:{},...(o=t.properties)!=null?o:{}}),(e.attachments||t.attachments)&&(s.attachments=[...(r=e.attachments)!=null?r:[],...(i=t.attachments)!=null?i:[]]),s}var VEe=class{constructor(e){this.buffers=new Map,this.sticky=new Map,this.timers=new Map,this.inFlight=new Set;var t,n,o,r,i,s,a,l;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=xb(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.partialFlushMs=(o=e.partialFlushMs)!=null?o:1e3,this.sdkName=(r=e.sdkName)!=null?r:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.defaultEventName=(i=e.defaultEventName)!=null?i:"ai_generation",this.localDebuggerUrl=(s=sm(e.localDebuggerUrl))!=null?s:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);let c=typeof process<"u"&&typeof process.version=="string";this.context={library:{name:(a=e.libraryName)!=null?a:"@raindrop-ai/core",version:(l=e.libraryVersion)!=null?l:"0.0.0"},metadata:{jsRuntime:c?"node":"web",...c?{nodeVersion:process.version}:{}}};}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}async patch(e,t){var n,o,r,i,s,a,l,c,d,u,p;if(!this.enabled||!e||!e.trim())return;this.debug&&console.log(`${this.prefix} queue patch`,{eventId:e,userId:t.userId,convoId:t.convoId,eventName:t.eventName,hasInput:typeof t.input=="string"&&t.input.length>0,hasOutput:typeof t.output=="string"&&t.output.length>0,attachments:(o=(n=t.attachments)==null?void 0:n.length)!=null?o:0,isPending:t.isPending});let m=(r=this.sticky.get(e))!=null?r:{},h=(i=this.buffers.get(e))!=null?i:{},g=$Ee(h,t);g.isPending=(l=(a=(s=t.isPending)!=null?s:h.isPending)!=null?a:m.isPending)!=null?l:true,this.buffers.set(e,g),this.sticky.set(e,{userId:(c=g.userId)!=null?c:m.userId,convoId:(d=g.convoId)!=null?d:m.convoId,eventName:(u=g.eventName)!=null?u:m.eventName,isPending:(p=g.isPending)!=null?p:m.isPending});let f=this.timers.get(e);if(f&&clearTimeout(f),g.isPending===false){await this.flushOne(e);return}let y=setTimeout(()=>{this.flushOne(e).catch(()=>{});},this.partialFlushMs);this.timers.set(e,y);}async finish(e,t){await this.patch(e,{...t,isPending:false});}async flush(){if(!this.enabled)return;let e=[...this.buffers.keys()];await Promise.all(e.map(t=>this.flushOne(t))),await Promise.all([...this.inFlight].map(t=>t.catch(()=>{})));}async shutdown(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),await this.flush();}async trackSignal(e){var t,n;if(!this.enabled)return;let o=[{event_id:e.eventId,signal_name:e.name,signal_type:(t=e.type)!=null?t:"default",timestamp:e.timestamp,sentiment:e.sentiment,attachment_id:e.attachmentId,properties:{...(n=e.properties)!=null?n:{},...e.comment?{comment:e.comment}:{},...e.after?{after:e.after}:{}}}];if(!this.writeKey)return;let r=`${this.baseUrl}signals/track`;try{await rm(r,o,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`${this.prefix} failed to send signal (dropping): ${s}`);}}async identify(e){if(!this.enabled)return;let n=(Array.isArray(e)?e:[e]).filter(r=>!r?.userId||!r.userId.trim()?(this.debug&&console.warn(`${this.prefix} skipping identify: missing userId`),false):true).map(r=>{var i;return {user_id:r.userId,traits:(i=r.traits)!=null?i:{}}});if(!this.writeKey||n.length===0)return;let o=`${this.baseUrl}users/identify`;try{await rm(o,n,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send identify (dropping): ${i}`);}}async flushOne(e){var t,n,o,r,i,s,a,l,c,d,u,p,m;if(!this.enabled)return;let h=this.timers.get(e);h&&(clearTimeout(h),this.timers.delete(e));let g=this.buffers.get(e);if(this.buffers.delete(e),!g)return;let f=(t=this.sticky.get(e))!=null?t:{},y=(o=(n=g.eventName)!=null?n:f.eventName)!=null?o:this.defaultEventName,S=(r=g.userId)!=null?r:f.userId;if(!S){this.debug&&console.warn(`${this.prefix} skipping track_partial for ${e}: missing userId`),this.sticky.delete(e);return}let{wizardSession:T,...E}=(i=g.properties)!=null?i:{},C=(s=g.convoId)!=null?s:f.convoId,w=(l=(a=g.isPending)!=null?a:f.isPending)!=null?l:true,x={event_id:e,user_id:S,event:y,timestamp:(c=g.timestamp)!=null?c:new Date().toISOString(),ai_data:{input:g.input,output:g.output,model:g.model,convo_id:C},properties:{...E,...T?{"raindrop.wizardSession":T}:{},$context:this.context},attachments:g.attachments,is_pending:w},I=`${this.baseUrl}events/track_partial`;if(this.debug&&console.log(`${this.prefix} sending track_partial`,{eventId:e,eventName:y,userId:S,convoId:C,isPending:w,inputPreview:typeof g.input=="string"?g.input.slice(0,120):void 0,outputPreview:typeof g.output=="string"?g.output.slice(0,120):void 0,attachments:(u=(d=g.attachments)==null?void 0:d.length)!=null?u:0,attachmentKinds:(m=(p=g.attachments)==null?void 0:p.map(_=>({type:_.type,role:_.role,name:_.name,valuePreview:_.value.slice(0,60)})))!=null?m:[],endpoint:I}),this.localDebuggerUrl&&jEe(x,{baseUrl:this.localDebuggerUrl,writeKey:this.writeKey,debug:this.debug,sdkName:this.sdkName}),!this.writeKey){w||this.sticky.delete(e);return}let v=rm(I,x,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(v);try{try{await v,this.debug&&console.log(`${this.prefix} sent track_partial ${e} (${y})`);}catch(_){let P=_ instanceof Error?_.message:String(_);console.warn(`${this.prefix} failed to send track_partial (dropping): ${P}`);}}finally{this.inFlight.delete(v);}w||this.sticky.delete(e);}},DY=["apikey","apisecret","apitoken","secretaccesskey","sessiontoken","privatekey","privatekeyid","clientsecret","accesstoken","refreshtoken","oauthtoken","bearertoken","authorization","password","passphrase"],FY="[REDACTED]";function BY(e){return e.toLowerCase().replace(/[-_.]/g,"")}function UY(e,t){var n,o;let r=zEe((n=t?.secretKeyNames)!=null?n:DY),i=(o=t?.placeholder)!=null?o:FY,s=new WeakSet,a=l=>{if(l===null||typeof l!="object")return l;if(s.has(l))return "[CIRCULAR]";if(s.add(l),Array.isArray(l))return l.map(d=>a(d));let c={};for(let[d,u]of Object.entries(l))r.has(BY(d))?c[d]=i:c[d]=a(u);return c};return a(e)}function zEe(e){let t=new Set;for(let n of e)t.add(BY(n));return t}var HY=["ai.request.providerOptions","ai.response.providerMetadata"];function GY(e){let t=e.attributes;if(!t||t.length===0)return e;let n;for(let o=0;o<t.length;o++){let r=t[o],i=jY(r.key,r.value);i!==void 0&&(n||(n=t.slice()),n[o]={key:r.key,value:i});}return n?{...e,attributes:n}:e}var WEe=new Set(HY);function jY(e,t){if(!WEe.has(e))return;let n=t.stringValue;if(typeof n!="string"||n.length===0)return;let o;try{o=JSON.parse(n);}catch{return}let r=UY(o),i;try{i=JSON.stringify(r);}catch{return}if(i!==n)return {stringValue:i}}var qEe=class{constructor(e){this.queue=[],this.inFlight=new Set;var t,n,o,r,i,s,a,l,c;this.writeKey=(t=e.writeKey)==null?void 0:t.trim(),this.baseUrl=(n=xb(e.endpoint))!=null?n:"https://api.raindrop.ai/v1/",this.enabled=e.enabled!==false,this.debug=e.debug,this.debugSpans=e.debugSpans===true,this.flushIntervalMs=(o=e.flushIntervalMs)!=null?o:1e3,this.maxBatchSize=(r=e.maxBatchSize)!=null?r:50,this.maxQueueSize=(i=e.maxQueueSize)!=null?i:5e3,this.sdkName=(s=e.sdkName)!=null?s:"core",this.prefix=`[raindrop-ai/${this.sdkName}]`,this.serviceName=(a=e.serviceName)!=null?a:"raindrop.core",this.serviceVersion=(l=e.serviceVersion)!=null?l:"0.0.0",this.localDebuggerUrl=(c=sm(e.localDebuggerUrl))!=null?c:void 0,this.debug&&this.localDebuggerUrl&&console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`),this.transformSpanHook=e.transformSpan,this.disableDefaultRedaction=e.disableDefaultRedaction===true;}redactSpan(e){let t=e;if(this.transformSpanHook)try{let n=this.transformSpanHook(t);if(n===null)return null;n!==void 0&&(t=n);}catch(n){if(this.debug){let o=n instanceof Error?n.message:String(n);console.warn(`${this.prefix} transformSpan hook threw: ${o}`);}return null}return this.disableDefaultRedaction||(t=GY(t)),t}isDebugEnabled(){return this.debug}authHeaders(){return this.writeKey?{Authorization:`Bearer ${this.writeKey}`}:{}}startSpan(e){var t,n;let o=vY(e.parent),r=(t=e.startTimeUnixNano)!=null?t:_b(),i=[J("ai.telemetry.metadata.raindrop.eventId",e.eventId),J("ai.operationId",e.operationId)];(n=e.attributes)!=null&&n.length&&i.push(...e.attributes);let s={ids:o,name:e.name,startTimeUnixNano:r,attributes:i};return this.mirrorToLocalDebugger(KN({ids:s.ids,name:s.name,startTimeUnixNano:s.startTimeUnixNano,endTimeUnixNano:s.startTimeUnixNano,attributes:s.attributes,status:{code:CY.UNSET}})),s}mirrorToLocalDebugger(e){if(!this.localDebuggerUrl)return;let t=this.redactSpan(e);if(t===null)return;let n=wY([t],this.serviceName,this.serviceVersion);GEe(n,{baseUrl:this.localDebuggerUrl,debug:false,sdkName:this.sdkName});}endSpan(e,t){var n,o;if(e.endTimeUnixNano)return;e.endTimeUnixNano=(n=t?.endTimeUnixNano)!=null?n:_b(),(o=t?.attributes)!=null&&o.length&&e.attributes.push(...t.attributes);let r=t?.status;if(!r&&t?.error!==void 0){let s=t.error instanceof Error?t.error.message:String(t.error);r={code:CY.ERROR,message:s};}let i=KN({ids:e.ids,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:e.attributes,status:r});this.enqueue(i),this.mirrorToLocalDebugger(i);}createSpan(e){var t;let n=vY(e.parent),o=[J("ai.telemetry.metadata.raindrop.eventId",e.eventId)];(t=e.attributes)!=null&&t.length&&o.push(...e.attributes);let r=KN({ids:n,name:e.name,startTimeUnixNano:e.startTimeUnixNano,endTimeUnixNano:e.endTimeUnixNano,attributes:o,status:e.status});this.enqueue(r),this.mirrorToLocalDebugger(r);}enqueue(e){if(!this.enabled)return;if(this.debugSpans){let n=o=>o?o.slice(-8):"none";console.log(`${this.prefix}[span] name=${e.name} trace=${n(e.traceId)} span=${n(e.spanId)} parent=${n(e.parentSpanId)}`);}let t=this.redactSpan(e);if(t!==null){if(this.queue.length>=this.maxQueueSize&&this.queue.shift(),this.queue.push(t),this.queue.length>=this.maxBatchSize){this.flush().catch(()=>{});return}this.timer||(this.timer=setTimeout(()=>{this.timer=void 0,this.flush().catch(()=>{});},this.flushIntervalMs));}}async flush(){if(this.enabled)for(this.timer&&(clearTimeout(this.timer),this.timer=void 0);this.queue.length>0;){let e=this.queue.splice(0,this.maxBatchSize);if(!this.writeKey)continue;let t=wY(e,this.serviceName,this.serviceVersion),n=`${this.baseUrl}traces`;this.debug&&console.log(`${this.prefix} sending traces batch`,{spans:e.length,endpoint:n});let o=rm(n,t,this.authHeaders(),{maxAttempts:3,debug:this.debug,sdkName:this.sdkName});this.inFlight.add(o);try{try{await o,this.debug&&console.log(`${this.prefix} sent ${e.length} spans`);}catch(r){let i=r instanceof Error?r.message:String(r);console.warn(`${this.prefix} failed to send ${e.length} spans: ${i}`);}}finally{this.inFlight.delete(o);}}}async shutdown(){this.timer&&(clearTimeout(this.timer),this.timer=void 0),await this.flush(),await Promise.all([...this.inFlight].map(e=>e.catch(()=>{})));}},KEe={};function xY(){return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE}var YEe=class{constructor(){this._stack=[];}isEmpty(){return this._stack.length===0}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},JEe=class{},XEe=class extends JEe{constructor(){super(),this._fallback=null;let e=xY();if(e){this._storage=new e;return}this._fallback=new YEe,this._storage=this._fallback;}maybeAdoptAsyncLocalStorage(){if(!this._fallback||!this._fallback.isEmpty())return;let e=xY();e&&(this._storage=new e,this._fallback=null);}isReady(){return true}getParentSpanIds(){this.maybeAdoptAsyncLocalStorage();let e=this._storage.getStore();if(!(!e||e===KEe))return {traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId}}runInContext(e,t){return this.maybeAdoptAsyncLocalStorage(),this._storage.run(e,t)}getCurrentSpan(){return this.maybeAdoptAsyncLocalStorage(),this._storage.getStore()}},YN=null;function _u(){return YN||(YN=globalThis.RAINDROP_CONTEXT_MANAGER?new globalThis.RAINDROP_CONTEXT_MANAGER:new XEe),YN}function $Y(e,t){return _u().runInContext(e,t)}async function im(){return _u().getParentSpanIds()}async function Pb(e,t){let n=_u(),o={traceIdB64:e.traceIdB64,spanIdB64:e.spanIdB64,eventId:e.eventId};return n.runInContext(o,t)}async function*QEe(e,t){let n;for(;;){let o=await $Y(e,async()=>{try{return await t.next(n)}catch(r){return {value:void 0,done:true,error:r}}});if("error"in o&&o.error!==void 0)throw o.error;if(o.done)return o.value;n=yield o.value;}}globalThis.RAINDROP_ASYNC_LOCAL_STORAGE=AsyncLocalStorage;function be(e){return typeof e=="object"&&e!==null}function ti(e){return typeof e=="function"}function _Y(e){var t;if(!e||typeof e!="object")return false;if(((t=e.constructor)==null?void 0:t.name)==="Module")return true;try{let o=Object.keys(e);if(o.length===0)return !1;let r=Object.getOwnPropertyDescriptor(e,o[0]);if(!r)return !1;let i="writable"in r?r.writable:!0;return !r.configurable&&!i}catch{return false}}function Dv(e){try{return JSON.stringify(e)}catch{return}}function dt(e){try{return JSON.stringify(e,(t,n)=>n instanceof Uint8Array?QN(n):n)}catch{return}}function $v(e){if(typeof e=="string"){let r=e.indexOf("/");return r>0&&r<e.length-1?{provider:e.slice(0,r),modelId:e.slice(r+1)}:{modelId:e}}if(!be(e))return {};let t=typeof e.provider=="string"?e.provider:void 0,n;if(typeof e.modelId=="string"?n=e.modelId:typeof e.model=="string"&&(n=e.model),!n)return {provider:t};let o=n.indexOf("/");return !t&&o>0&&o<n.length-1?{provider:n.slice(0,o),modelId:n.slice(o+1)}:{provider:t,modelId:n}}function sL(e){if(!be(e))return;let t=e.text;return typeof t=="string"?t:void 0}function ZEe(e){var t;if(!be(e))return;let n=e.object;if(n!==void 0)return (t=Dv(n))!=null?t:String(n)}function eCe(e){if(typeof e!="function")return false;let t=e.prototype;return be(t)?typeof t.generate=="function"&&typeof t.stream=="function":false}function aL(e){if(!be(e))return;let t=e.model;if(typeof t=="string"&&t.length)return t;let n=e.response;if(be(n)){let o=n.modelId;if(typeof o=="string"&&o.length)return o}}function Ob(e){if(be(e)){if(typeof e.finishReason=="string")return e.finishReason;if(be(e.finishReason)&&typeof e.finishReason.unified=="string")return e.finishReason.unified}}function PY(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return typeof btoa=="function"?btoa(t):""}function Fv(e,t){if(e instanceof URL)return e.toString();if(typeof e=="string")return e.startsWith("data:")||e.startsWith("http://")||e.startsWith("https://")?e:`data:${t};base64,${e}`;if(e instanceof Uint8Array){let n=PY(e);return n?`data:${t};base64,${n}`:void 0}if(e instanceof ArrayBuffer){let n=PY(new Uint8Array(e));return n?`data:${t};base64,${n}`:void 0}}function VY(e){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return `[binary:${e.byteLength} bytes]`;if(e instanceof ArrayBuffer)return `[binary:${e.byteLength} bytes]`}function OY(e){if(typeof e.mediaType=="string")return e.mediaType;if(typeof e.mimeType=="string")return e.mimeType;let t=e.file;if(be(t)){if(typeof t.mediaType=="string")return t.mediaType;if(typeof t.mimeType=="string")return t.mimeType}}function tCe(e){if(typeof e.filename=="string")return e.filename;if(typeof e.name=="string")return e.name;let t=e.file;if(be(t)){if(typeof t.filename=="string")return t.filename;if(typeof t.name=="string")return t.name}}function nCe(e){if("data"in e)return e.data;let t=e.file;if(be(t)){if("file_data"in t)return t.file_data;if("data"in t)return t.data}}function oCe(e,t){var n,o,r;let i=e.type;if(typeof i=="string"){if(i==="image"){let s=(n=OY(e))!=null?n:"image/png",a=Fv(e.image,s);return a?{type:"image",role:t,value:a}:void 0}if(i==="image_url"){let s=e.image_url,a=be(s)?s.url:s,l=Fv(a,"image/png");return l?{type:"image",role:t,value:l}:void 0}if(i==="file"){let s=OY(e),a=nCe(e),l=s?.startsWith("image/")===true,c=l&&s?Fv(a,s):VY(a);if(!c)return;let d=(r=(o=tCe(e))!=null?o:s)!=null?r:"file";return {type:l?"image":"text",role:t,name:d,value:c}}}}function ZN(e,t){if(!Array.isArray(e))return;let n=[];for(let o of e){if(!be(o))continue;let r=oCe(o,t);r&&n.push(r);}return n.length?n:void 0}function rCe(e){var t,n,o,r;let i=typeof e.mediaType=="string"?e.mediaType:typeof e.mimeType=="string"?e.mimeType:void 0,s=(r=(o=(n=(t=e.base64Data)!=null?t:e.base64)!=null?n:e.uint8ArrayData)!=null?o:e.uint8Array)!=null?r:e.data,a=i?.startsWith("image/")===true,l=a&&i?Fv(s,i):VY(s);if(!l)return;let c=typeof e.filename=="string"?e.filename:typeof e.name=="string"?e.name:i??"file";return {type:a?"image":"text",role:"output",name:c,value:l}}async function iCe(e){let t=e;if(t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function")try{t=await t;}catch{return}if(!Array.isArray(t))return;let n=[];for(let o of t){if(!be(o))continue;let r=rCe(o);r&&n.push(r);}return n.length?n:void 0}function zY(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let t="";for(let n of e)!be(n)||n.type!=="text"||typeof n.text!="string"||(t+=n.text);return t.length?t:void 0}function lL(e){let t=e.messages;if(Array.isArray(t))return t;let n=e.prompt;if(Array.isArray(n))return n}function WY(e){let t=lL(e);if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(be(o)&&o.role==="user")return o}}function cL(e){var t;if(be(e))return ZN((t=WY(e))==null?void 0:t.content,"input")}async function dL(e){if(!be(e))return;let t=await iCe(e.files);if(t?.length)return t;let n=Vv(e);for(let o=n.length-1;o>=0;o--){let r=n[o];if(!(!be(r)||r.role!=="assistant"))return ZN(r.content,"output")}return ZN(e.content,"output")}function uL(e){var t,n;if(!be(e))return;let o=(t=WY(e))==null?void 0:t.content;if(o===void 0)return;let r=zY(o);return r!==void 0?r:(n=dt(o))!=null?n:String(o)}function pL(e){var t;if(!be(e))return;let n=e.prompt;if(typeof n=="string")return n;let o=lL(e);if(Array.isArray(o)&&o.length>0){let i=o[o.length-1];if(be(i)){let s=i.content,a=zY(s);if(a!==void 0)return a;let l=Dv(s);if(l)return l}return (t=Dv(o))!=null?t:void 0}let r=e.input;return typeof r=="string"?r:Dv(e)}function mL(e){if(!be(e))return [];let t=[];typeof e.system=="string"&&e.system&&t.push({role:"system",content:e.system});let n=lL(e);if(Array.isArray(n)){for(let o of n)be(o)&&typeof o.role=="string"&&t.push(o);return t}return typeof e.prompt=="string"&&e.prompt&&t.push({role:"user",content:e.prompt}),t}function Vv(e){if(!be(e))return [];let t=e.response;if(be(t)&&Array.isArray(t.messages))return t.messages.filter(o=>be(o)&&typeof o.role=="string"&&"content"in o).map(o=>o);let n=e.steps;if(Array.isArray(n)&&n.length>0){let o=n[n.length-1];if(be(o)&&be(o.response)){let r=o.response.messages;if(Array.isArray(r))return r.filter(i=>be(i)&&typeof i.role=="string"&&"content"in i).map(i=>i)}}return []}function Uv(e){if(typeof e.toolCallId=="string"&&e.toolCallId.length>0)return `id:${e.toolCallId}`;if(typeof e.toolName=="string"&&e.toolName.length>0){let t=dt(e.input);return t!==void 0?`name:${e.toolName}|input:${t}`:`name:${e.toolName}`}}function sCe(e,t){return e.isError===true||e.type==="tool-error"?true:be(t)&&typeof t.type=="string"?t.type.startsWith("error")||t.type==="execution-denied":false}function aCe(e){if(typeof e=="string"&&e.length>0)return e;if(be(e)){if(typeof e.value=="string"&&e.value.length>0)return e.value;if(typeof e.reason=="string"&&e.reason.length>0)return e.reason;if(typeof e.message=="string"&&e.message.length>0)return e.message}return dt(e)}function lCe(e){if(!be(e))return [];let t=e.content;return Array.isArray(t)?t.filter(be):be(t)?[t]:[]}function cCe(e){return "input"in e?e.input:"args"in e?e.args:void 0}function hL(e){let t=e.toolCallId;return typeof t=="string"&&t.length>0?t:void 0}function dCe(e){return "output"in e?e.output:"result"in e?e.result:e.error}function uCe(e,t,n){var o;if(!t)return;let r=(o=e.get(t))!=null?o:[];r.includes(n)||(r.push(n),e.set(t,r));}function pCe(e,t){if(!t)return;let n=e.get(t);if(!n||n.length===0)return;let o=n.shift();if(o!==void 0)return n.length===0&&e.delete(t),o}function mCe(e){var t,n,o,r;let{spans:i,pendingKeysByToolName:s,part:a}=e,l=hL(a),c=typeof a.toolName=="string"?a.toolName:void 0,d=cCe(a),u=Uv({toolCallId:l,toolName:c,input:d});if(!u)return;let p=l==null?Uv({toolCallId:void 0,toolName:c,input:void 0}):void 0,m=p&&p!==u?i.get(p):void 0,h=(t=i.get(u))!=null?t:m;i.set(u,{key:u,toolCallId:(n=h?.toolCallId)!=null?n:l,toolName:(o=h?.toolName)!=null?o:c,input:(r=h?.input)!=null?r:d,result:h?.result,status:h?.status,errorMessage:h?.errorMessage}),p&&p!==u&&i.delete(p),!l&&h?.result===void 0&&uCe(s,c,u);}function hCe(e){var t,n,o;let{spans:r,pendingKeysByToolName:i,part:s}=e,a=hL(s),l=typeof s.toolName=="string"?s.toolName:void 0,c=dCe(s),d=Uv({toolCallId:a,toolName:l,input:void 0}),u=a!=null?d:(t=pCe(i,l))!=null?t:d;if(!u)return;let p=r.get(u),m=sCe(s,c);r.set(u,{key:u,toolCallId:(n=p?.toolCallId)!=null?n:a,toolName:(o=p?.toolName)!=null?o:l,input:p?.input,result:c,status:m?"ERROR":"OK",errorMessage:m?aCe(c):void 0});}function qY(e){let t=new Map,n=new Map;for(let o of e)for(let r of lCe(o)){if(r.type==="tool-call"){mCe({spans:t,pendingKeysByToolName:n,part:r});continue}(r.type==="tool-result"||r.type==="tool-error")&&hCe({spans:t,pendingKeysByToolName:n,part:r});}return [...t.values()]}function gCe(e){if(!Array.isArray(e))return;let t="";for(let n of e)be(n)&&n.type==="text"&&typeof n.text=="string"&&(t+=n.text);return t.length?t:void 0}function fCe(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!be(n)||n.type!=="tool-call")continue;let o=hL(n),r=typeof n.toolName=="string"?n.toolName:void 0;(o||r)&&t.push({toolCallId:o,toolName:r,input:n.input});}return t.length?t:void 0}function Lg(e){if(!be(e))return;let t=e.experimental_telemetry;if(be(t))return {functionId:typeof t.functionId=="string"?t.functionId:void 0,isEnabled:typeof t.isEnabled=="boolean"?t.isEnabled:void 0,recordInputs:typeof t.recordInputs=="boolean"?t.recordInputs:void 0,recordOutputs:typeof t.recordOutputs=="boolean"?t.recordOutputs:void 0,metadata:be(t.metadata)?t.metadata:void 0}}function ma(e,t){return {operationName:`${e}${t?` ${t}`:""}`,resourceName:t}}function KY(e,t){if(t==null)return;if(typeof t=="string")return J(e,t);if(typeof t=="number")return Number.isInteger(t)?nt(e,t):Mg(e,t);if(typeof t=="boolean")return LEe(e,t);if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return ad(e,t);let n=dt(t);return n?J(e,n):void 0}function zv(e){return e?Object.entries(e).filter(([t])=>!t.startsWith("raindrop.internal.")).map(([t,n])=>KY(`ai.telemetry.metadata.${t==="raindrop.userId"?"raindrop.ai.userId":t}`,n)):[]}function gL(e){return be(e)?Object.entries(e).filter(([,t])=>typeof t=="string").map(([t,n])=>J(`ai.request.headers.${t}`,n)):[]}function fL(e){if(!be(e))return [];let t=[],n=["maxRetries","timeout","maxOutputTokens","temperature","topP","topK","presencePenalty","frequencyPenalty","seed","stopSequences"];for(let o of n){if(!(o in e))continue;let r=e[o];o==="stopSequences"&&Array.isArray(r)&&r.every(i=>typeof i=="string")?t.push(ad(`ai.settings.${o}`,r)):o==="timeout"&&typeof r=="number"?t.push(nt(`ai.settings.${o}`,r)):t.push(KY(`ai.settings.${o}`,r));}return t}function YY(e){return be(e)?[Mg("gen_ai.request.frequency_penalty",typeof e.frequencyPenalty=="number"?e.frequencyPenalty:void 0),nt("gen_ai.request.max_tokens",typeof e.maxOutputTokens=="number"?e.maxOutputTokens:void 0),Mg("gen_ai.request.presence_penalty",typeof e.presencePenalty=="number"?e.presencePenalty:void 0),...Array.isArray(e.stopSequences)&&e.stopSequences.every(t=>typeof t=="string")?[ad("gen_ai.request.stop_sequences",e.stopSequences)]:[],Mg("gen_ai.request.temperature",typeof e.temperature=="number"?e.temperature:void 0),nt("gen_ai.request.top_k",typeof e.topK=="number"?e.topK:void 0),Mg("gen_ai.request.top_p",typeof e.topP=="number"?e.topP:void 0)]:[]}function JY(e){if(!be(e)||!be(e.providerOptions))return;let t=dt(e.providerOptions);return t?J("ai.request.providerOptions",t):void 0}var yCe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},Mv=null;function XY(){if(Mv)return Mv;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return Mv=e?new e:new yCe,Mv}function yL(){return XY().getStore()}function eL(e,t){return XY().run(e,t)}function QY(e){var t;if(e.length===0)return;let n=e[0];if(!be(n))return;let o=be(n.metadata)?n.metadata:void 0,r=be(n.telemetry)?n.telemetry.metadata:void 0,i=be(r)?r:void 0,s=Lg(n),a=s?.metadata&&typeof s.metadata=="object"?s.metadata:void 0,l=(t=o??i)!=null?t:a;if(!l)return;let c={rawMetadata:l},d=l["raindrop.userId"];typeof d=="string"&&d&&(c.userId=d);let u=l["raindrop.eventId"];typeof u=="string"&&u&&(c.eventId=u);let p=l["raindrop.internal.eventIdGenerated"];(p===true||p==="true"||p==="1")&&(c.eventIdGenerated=true);let m=l["raindrop.convoId"];typeof m=="string"&&m&&(c.convoId=m);let h=l["raindrop.eventName"];typeof h=="string"&&h&&(c.eventName=h);let g=l["raindrop.properties"];if(typeof g=="string")try{let f=JSON.parse(g);f&&typeof f=="object"&&(c.properties=f);}catch{}else g&&typeof g=="object"&&(c.properties=g);return c}var SCe=class{constructor(){this._stack=[];}getStore(){return this._stack[this._stack.length-1]}run(e,t){this._stack.push(e);try{return t()}finally{this._stack.pop();}}},Nv=null;function SL(){if(Nv)return Nv;let e=globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;return Nv=e?new e:new SCe,Nv}function tL(){return SL().getStore()}function nL(e){var t;let n=SL();(t=n.enterWith)==null||t.call(n,e);}function ZY(){var e;let t=SL();(e=t.enterWith)==null||e.call(t,void 0);}var bL=class{constructor(e){this.callStates=new Map,this.priorParentContexts=new Map,this.onStart=t=>{var n,o,r,i,s;if(t.isEnabled===false)return;let a=t.operationId==="ai.embed"||t.operationId==="ai.embedMany",l=t.recordInputs!==false,c=t.recordOutputs!==false,d=t.functionId,u=t.metadata,p=yL(),m=u??p?.rawMetadata,h=this.extractRaindropMetadata(m),g=_u().getParentSpanIds(),f=m?.["raindrop.internal.eventIdGenerated"]==="true"||m?.["raindrop.internal.eventIdGenerated"]===true||p?.eventIdGenerated===true,y=h.eventId&&!f?h.eventId:void 0,S=(i=(r=(o=y??((n=this.defaultContext)==null?void 0:n.eventId))!=null?o:g?.eventId)!=null?r:h.eventId)!=null?i:xu(),T=g&&g.eventId===S?{traceIdB64:g.traceIdB64,spanIdB64:g.spanIdB64}:void 0,{operationName:E,resourceName:C}=ma(t.operationId,d),w=!a&&this.subagentWrapping?tL():void 0,x=!a&&this.subagentWrapping&&w===void 0&&typeof m?.["ash.subagent.name"]=="string"?m["ash.subagent.name"]:void 0,I=(s=w?.toolName)!=null?s:x,v,_;if(I&&this.sendTraces){let L=w?[J("raindrop.parent.callId",w.parentCallId),J("raindrop.parent.toolCallId",w.toolCallId),J("raindrop.parent.toolName",w.toolName)]:[];v=this.traceShipper.startSpan({name:I,parent:T,eventId:S,operationId:"ai.toolCall",attributes:[J("operation.name","ai.toolCall"),J("resource.name",I),J("raindrop.span.kind","tool_call"),J("ai.toolCall.name",I),J("raindrop.subagent.name",I),J("raindrop.agent.role","subagent"),...L]});let k=this.spanParentRef(v),V=this.traceShipper.startSpan({name:"agent.subagent",parent:k,eventId:S,operationId:"agent.subagent",attributes:[J("operation.name","agent.subagent"),J("raindrop.span.kind","llm_call"),J("raindrop.subagent.name",I)]});this.traceShipper.endSpan(V),_=k;}let P;if(this.sendTraces){let L=!a&&l?[J("ai.prompt",dt({system:t.system,prompt:t.prompt,messages:t.messages}))]:[],k=a&&l?t.operationId==="ai.embedMany"?[J("ai.values",dt(t.value))]:[J("ai.value",dt(t.value))]:[];P=this.traceShipper.startSpan({name:t.operationId,parent:_??T,eventId:S,operationId:t.operationId,attributes:[J("operation.name",E),J("resource.name",C),J("ai.telemetry.functionId",d),J("ai.model.provider",t.provider),J("ai.model.id",t.modelId),...zv(m?Object.fromEntries(Object.entries(m).filter(([V])=>V!=="raindrop.eventId"&&V!=="raindrop.internal.eventIdGenerated")):void 0),...L,...k]});}this.callStates.set(t.callId,{operationId:t.operationId,eventId:S,rootSpan:P,rootParent:P?this.spanParentRef(P):_??T,stepSpan:void 0,stepParent:void 0,toolSpans:new Map,embedSpans:new Map,parentContextToolCallIds:new Set,recordInputs:l,recordOutputs:c,functionId:d,metadata:m,accumulatedText:"",inputText:a?void 0:this.extractInputText(t),toolCallCount:0,subagentName:I,subagentToolCallSpan:v});},this.onStepStart=t=>{let n=this.getState(t.callId);if(!n?.rootSpan||!n.rootParent)return;let r=n.operationId==="ai.streamText"||n.operationId==="ai.streamObject"?`${n.operationId}.doStream`:`${n.operationId}.doGenerate`,{operationName:i,resourceName:s}=ma(r,n.functionId),a=[];n.recordInputs&&(t.promptMessages&&a.push(J("ai.prompt.messages",dt(t.promptMessages))),t.stepTools&&a.push(ad("ai.prompt.tools",t.stepTools.map(c=>JSON.stringify(c)))),t.stepToolChoice!=null&&a.push(J("ai.prompt.toolChoice",JSON.stringify(t.stepToolChoice))));let l=this.traceShipper.startSpan({name:r,parent:n.rootParent,eventId:n.eventId,operationId:r,attributes:[J("operation.name",i),J("resource.name",s),J("ai.telemetry.functionId",n.functionId),J("ai.model.provider",t.provider),J("ai.model.id",t.modelId),J("gen_ai.system",t.provider),J("gen_ai.request.model",t.modelId),...a]});n.stepSpan=l,n.stepParent=this.spanParentRef(l);},this.onToolExecutionStart=t=>this.toolExecutionStart(t),this.onToolExecutionEnd=t=>this.toolExecutionEnd(t),this.onToolCallStart=t=>this.toolExecutionStart(t),this.onToolCallFinish=t=>this.toolExecutionEnd(t),this.onLanguageModelCallStart=t=>{},this.onLanguageModelCallEnd=t=>{},this.onChunk=t=>{var n,o,r,i,s;let a=(o=t.callId)!=null?o:(n=t.chunk)==null?void 0:n.callId;if(!a)return;let l=this.getState(a);if(!l)return;let c=t.chunk;if(!(!c||typeof c!="object")){if(c.type==="text-delta"){let d=(r=c.textDelta)!=null?r:c.delta;typeof d=="string"&&(l.accumulatedText+=d,this.emitLive(l,"text_delta",d));}else if(c.type==="reasoning"||c.type==="reasoning-delta"){let d=(s=(i=c.textDelta)!=null?i:c.text)!=null?s:c.delta;typeof d=="string"&&this.emitLive(l,"reasoning_delta",d);}}},this.onStepFinish=t=>{var n,o,r,i,s,a,l,c,d;let u=this.getState(t.callId);if(!u?.stepSpan)return;let p=[];if(u.recordOutputs&&(p.push(J("ai.response.finishReason",t.finishReason),J("ai.response.text",(n=t.text)!=null?n:void 0),J("ai.response.id",(o=t.response)==null?void 0:o.id),J("ai.response.model",(r=t.response)==null?void 0:r.modelId),J("ai.response.timestamp",((i=t.response)==null?void 0:i.timestamp)instanceof Date?t.response.timestamp.toISOString():(s=t.response)==null?void 0:s.timestamp),J("ai.response.providerMetadata",t.providerMetadata?dt(t.providerMetadata):void 0)),((a=t.toolCalls)==null?void 0:a.length)>0&&p.push(J("ai.response.toolCalls",JSON.stringify(t.toolCalls.map(h=>({toolCallId:h.toolCallId,toolName:h.toolName,input:h.input}))))),((l=t.reasoning)==null?void 0:l.length)>0)){let h=t.reasoning.filter(g=>"text"in g).map(g=>g.text).join(`
173
173
  `);h&&p.push(J("ai.response.reasoning",h));}p.push(ad("gen_ai.response.finish_reasons",[t.finishReason]),J("gen_ai.response.id",(c=t.response)==null?void 0:c.id),J("gen_ai.response.model",(d=t.response)==null?void 0:d.modelId));let m=t.usage;m&&p.push(nt("ai.usage.inputTokens",m.inputTokens),nt("ai.usage.outputTokens",m.outputTokens),nt("ai.usage.totalTokens",m.totalTokens),nt("ai.usage.reasoningTokens",m.reasoningTokens),nt("ai.usage.cachedInputTokens",m.cachedInputTokens),nt("gen_ai.usage.input_tokens",m.inputTokens),nt("gen_ai.usage.output_tokens",m.outputTokens)),this.emitProviderExecutedToolSpans(t,u),this.traceShipper.endSpan(u.stepSpan,{attributes:p}),u.stepSpan=void 0,u.stepParent=void 0;},this.onEmbedStart=t=>{let n=this.getState(t.callId);if(!n?.rootSpan||!n.rootParent)return;let{operationName:o,resourceName:r}=ma(t.operationId,n.functionId),i=n.recordInputs?[J("ai.values",dt(t.values))]:[],s=this.traceShipper.startSpan({name:t.operationId,parent:n.rootParent,eventId:n.eventId,operationId:t.operationId,attributes:[J("operation.name",o),J("resource.name",r),J("ai.telemetry.functionId",n.functionId),...i]});n.embedSpans.set(t.embedCallId,s);},this.onEmbedFinish=t=>{var n;let o=this.getState(t.callId);if(!o)return;let r=o.embedSpans.get(t.embedCallId);if(!r)return;let i=[];o.recordOutputs&&i.push(J("ai.embeddings",dt(t.embeddings))),((n=t.usage)==null?void 0:n.tokens)!=null&&i.push(nt("ai.usage.tokens",t.usage.tokens)),this.traceShipper.endSpan(r,{attributes:i}),o.embedSpans.delete(t.embedCallId);},this.onEmbedEnd=t=>this.onEmbedFinish(t),this.onFinish=t=>{let n=this.getState(t.callId);if(!n)return;n.operationId==="ai.embed"||n.operationId==="ai.embedMany"?this.finishEmbed(t,n):this.finishGenerate(t,n),n.subagentToolCallSpan&&this.traceShipper.endSpan(n.subagentToolCallSpan),this.cleanup(t.callId);},this.onEnd=t=>this.onFinish(t),this.onError=t=>{var n;let o=t;if(!o?.callId)return;let r=this.getState(o.callId);if(!r)return;let i=(n=o.error)!=null?n:t;r.stepSpan&&this.traceShipper.endSpan(r.stepSpan,{error:i});for(let s of r.embedSpans.values())this.traceShipper.endSpan(s,{error:i});r.embedSpans.clear();for(let s of r.parentContextToolCallIds)this.priorParentContexts.delete(s);r.parentContextToolCallIds.clear();for(let s of r.toolSpans.values())this.traceShipper.endSpan(s,{error:i});r.toolSpans.clear(),r.rootSpan&&this.traceShipper.endSpan(r.rootSpan,{error:i}),r.subagentToolCallSpan&&this.traceShipper.endSpan(r.subagentToolCallSpan,{error:i}),this.cleanup(o.callId);},this.executeTool=async({callId:t,toolCallId:n,execute:o})=>{let r=this.getState(t),i=r?.toolSpans.get(n);return i?Pb({traceIdB64:i.ids.traceIdB64,spanIdB64:i.ids.spanIdB64,eventId:r.eventId},()=>o()):o()},this.traceShipper=e.traceShipper,this.eventShipper=e.eventShipper,this.sendTraces=e.sendTraces!==false,this.sendEvents=e.sendEvents!==false,this.subagentWrapping=e.subagentWrapping!==false,this.debug=e.debug===true,this.defaultContext=e.context;}getState(e){return this.callStates.get(e)}cleanup(e){this.callStates.delete(e);}spanParentRef(e){return {traceIdB64:e.ids.traceIdB64,spanIdB64:e.ids.spanIdB64}}emitLive(e,t,n,o){var r,i,s,a,l,c;if(!Bv()||!e.rootSpan)return;let d=this.extractRaindropMetadata(e.metadata);Iu({traceId:e.rootSpan.ids.traceIdB64,type:t,content:n,metadata:{userId:(i=d.userId)!=null?i:(r=this.defaultContext)==null?void 0:r.userId,convoId:(a=d.convoId)!=null?a:(s=this.defaultContext)==null?void 0:s.convoId,eventName:(c=d.eventName)!=null?c:(l=this.defaultContext)==null?void 0:l.eventName,eventId:e.eventId,...o}});}extractRaindropMetadata(e){if(!e)return {};let t={},n=e["raindrop.userId"];typeof n=="string"&&n&&(t.userId=n);let o=e["raindrop.eventId"];typeof o=="string"&&o&&(t.eventId=o);let r=e["raindrop.convoId"];typeof r=="string"&&r&&(t.convoId=r);let i=e["raindrop.eventName"];typeof i=="string"&&i&&(t.eventName=i);let s=e["raindrop.properties"];if(typeof s=="string")try{t.properties=JSON.parse(s);}catch{}else s&&typeof s=="object"&&(t.properties=s);return t}extractInputText(e){if(typeof e.prompt=="string")return e.prompt;if(Array.isArray(e.messages))for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(n?.role==="user"){if(typeof n.content=="string")return n.content;if(Array.isArray(n.content)){let o=n.content.find(r=>r?.type==="text"&&typeof r.text=="string");if(o)return o.text}}}}toolExecutionStart(e){let{toolCall:t}=e,n=tL();this.priorParentContexts.set(t.toolCallId,n??null),nL({parentCallId:e.callId,toolCallId:t.toolCallId,toolName:t.toolName});let o=this.getState(e.callId);if(o?.parentContextToolCallIds.add(t.toolCallId),!o?.stepParent)return;let{operationName:r,resourceName:i}=ma("ai.toolCall",o.functionId),s=o.recordInputs?[J("ai.toolCall.args",dt(t.input))]:[],a=this.traceShipper.startSpan({name:"ai.toolCall",parent:o.stepParent,eventId:o.eventId,operationId:"ai.toolCall",attributes:[J("operation.name",r),J("resource.name",i),J("ai.telemetry.functionId",o.functionId),J("ai.toolCall.name",t.toolName),J("ai.toolCall.id",t.toolCallId),...s]});o.toolSpans.set(t.toolCallId,a),this.emitLive(o,"tool_start",t.toolName,{args:t.input});}toolExecutionEnd(e){var t;let n=(t=e.toolCall)==null?void 0:t.toolCallId;if(n&&this.priorParentContexts.has(n)){let i=this.priorParentContexts.get(n);this.priorParentContexts.delete(n),i?nL(i):ZY();}let o=this.getState(e.callId);if(!o)return;let r=o.toolSpans.get(e.toolCall.toolCallId);if(r){if(o.toolCallCount+=1,e.success){let i=o.recordOutputs?[J("ai.toolCall.result",dt(e.output))]:[];this.traceShipper.endSpan(r,{attributes:i});}else this.traceShipper.endSpan(r,{error:e.error});this.emitLive(o,"tool_result",e.toolCall.toolName),o.toolSpans.delete(e.toolCall.toolCallId);}}emitProviderExecutedToolSpans(e,t){if(!t.stepParent)return;let n=Array.isArray(e.content)?e.content:[],o=n.filter(i=>i?.type==="tool-call"&&i.providerExecuted===true);if(o.length===0)return;let r=new Map;for(let i of n)(i?.type==="tool-result"||i?.type==="tool-error")&&typeof i.toolCallId=="string"&&r.set(i.toolCallId,i);for(let i of o){let{operationName:s,resourceName:a}=ma("ai.toolCall",t.functionId),l=t.recordInputs?[J("ai.toolCall.args",dt(i.input))]:[],c=this.traceShipper.startSpan({name:"ai.toolCall",parent:t.stepParent,eventId:t.eventId,operationId:"ai.toolCall",attributes:[J("operation.name",s),J("resource.name",a),J("ai.telemetry.functionId",t.functionId),J("ai.toolCall.name",i.toolName),J("ai.toolCall.id",i.toolCallId),J("ai.toolCall.providerExecuted","true"),...l]});t.toolCallCount+=1,this.emitLive(t,"tool_start",i.toolName,{args:i.input});let d=r.get(i.toolCallId);if(d?.type==="tool-error")this.traceShipper.endSpan(c,{error:d.error});else {let u=t.recordOutputs&&d&&"output"in d?[J("ai.toolCall.result",dt(d.output))]:[];this.traceShipper.endSpan(c,{attributes:u});}this.emitLive(t,"tool_result",i.toolName);}}finishGenerate(e,t){var n,o,r,i,s,a,l,c,d,u,p,m,h,g;if(t.rootSpan){let y=[];if(t.recordOutputs&&(y.push(J("ai.response.finishReason",e.finishReason),J("ai.response.text",(n=e.text)!=null?n:void 0),J("ai.response.providerMetadata",e.providerMetadata?dt(e.providerMetadata):void 0)),((o=e.toolCalls)==null?void 0:o.length)>0&&y.push(J("ai.response.toolCalls",JSON.stringify(e.toolCalls.map(T=>({toolCallId:T.toolCallId,toolName:T.toolName,input:T.input}))))),((r=e.reasoning)==null?void 0:r.length)>0)){let T=e.reasoning.filter(E=>"text"in E).map(E=>E.text).join(`
174
174
  `);T&&y.push(J("ai.response.reasoning",T));}let S=(i=e.totalUsage)!=null?i:e.usage;S&&y.push(nt("ai.usage.inputTokens",S.inputTokens),nt("ai.usage.outputTokens",S.outputTokens),nt("ai.usage.totalTokens",S.totalTokens),nt("ai.usage.reasoningTokens",S.reasoningTokens),nt("ai.usage.cachedInputTokens",S.cachedInputTokens)),y.push(nt("ai.toolCall.count",t.toolCallCount)),this.traceShipper.endSpan(t.rootSpan,{attributes:y});}let f=t.subagentName!==void 0&&t.subagentToolCallSpan!==void 0;if(this.sendEvents&&!f){let y=this.extractRaindropMetadata(t.metadata),S=(a=y.userId)!=null?a:(s=this.defaultContext)==null?void 0:s.userId;if(S){let T=(d=(c=y.eventName)!=null?c:(l=this.defaultContext)==null?void 0:l.eventName)!=null?d:t.operationId,E=(u=e.text)!=null?u:t.accumulatedText||void 0,C=t.inputText,w=(p=e.response)==null?void 0:p.modelId,x={...(m=this.defaultContext)==null?void 0:m.properties,...y.properties},I=(g=y.convoId)!=null?g:(h=this.defaultContext)==null?void 0:h.convoId;this.eventShipper.patch(t.eventId,{eventName:T,userId:S,convoId:I,input:C,output:E,model:w,properties:Object.keys(x).length>0?x:void 0,isPending:false}).catch(v=>{this.debug&&console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${v instanceof Error?v.message:v}`);});}}}finishEmbed(e,t){var n;if(!t.rootSpan)return;let o=[],r=t.operationId==="ai.embedMany";t.recordOutputs&&(r?o.push(J("ai.embeddings",dt(e.embedding))):o.push(J("ai.embedding",dt(e.embedding)))),((n=e.usage)==null?void 0:n.tokens)!=null&&o.push(nt("ai.usage.tokens",e.usage.tokens)),this.traceShipper.endSpan(t.rootSpan,{attributes:o});}},bCe="__raindrop_report",MY={missing_context:{description:"You cannot complete the task because critical information, credentials, or access is missing and the user cannot provide it. Do NOT report this for normal clarifying questions \u2014 only when you are blocked.",sentiment:"NEGATIVE"},repeatedly_broken_tool:{description:"A tool has failed or not returned the expected response on multiple distinct attempts in this conversation, preventing task completion. A single tool error is NOT enough \u2014 the tool must be persistently broken or aberrantly behaving across retries.",sentiment:"NEGATIVE"},capability_gap:{description:"The task requires a tool, permission, or capability that you do not have. For example, the user asks you to perform an action but no suitable tool exists, or you lack the necessary access. Do NOT report this if you simply need more information from the user \u2014 only when the gap is in your own capabilities.",sentiment:"NEGATIVE"},complete_task_failure:{description:"You were unable to accomplish what the user asked despite making genuine attempts. This might be things like, you genuinely do not have the capabilities the user is asking for. You have tried but run into a persistent bug in the environment etc. This is NOT a refusal or policy block \u2014 you tried and failed to deliver the result.",sentiment:"NEGATIVE"}},TCe="You have a diagnostic tool for flagging serious failures for developer review. Only call this when you hit a significant, unrecoverable problem \u2014 not for minor hiccups or routine clarifications. If you can still help the user, do that instead of calling this tool. This tool is invisible to the user \u2014 never mention it or its output.";function Ng(e){return typeof e!="string"?void 0:e.trim()||void 0}function ACe(e){if(!e)return MY;let t=Object.entries(e).map(([n,o])=>{var r;let i=n.trim();if(!i||!o||typeof o!="object")return;let s=(r=o.description)==null?void 0:r.trim();if(!s)return;let a=o.sentiment;return [i,{description:s,...a==="POSITIVE"||a==="NEGATIVE"?{sentiment:a}:{}}]}).filter(n=>n!==void 0);return t.length===0?MY:Object.fromEntries(t)}function eJ(e){var t,n;let o=ACe(e.signals),r=Object.keys(o),i={},s={};for(let p of r){let m=o[p];m&&(i[p]=m.description,s[p]=m.sentiment);}let a=((t=e.guidance)==null?void 0:t.trim())||"",l=((n=e.toolName)==null?void 0:n.trim())||bCe,c=r.map(p=>{let m=s[p],h=m?` [${m.toLowerCase()}]`:"";return `- ${p}: ${i[p]}${h}`}).join(`
175
175
  `),d=a?`
@@ -201,7 +201,7 @@ Categories:
201
201
  `);if(n<1||n>o.length)return;let r=Math.max(1,n-bJ),i=Math.min(o.length,n+bJ),s=String(i).length,a=[];for(let l=r;l<=i;l++){let c=l===n?cve:lve;a.push(`${c}${String(l).padStart(s)} | ${o[l-1]??""}`);}return a.join(`
202
202
  `)}var EJ="\r",CJ="\x1B[1A",vJ="\x1B[J",mve="\u28CB\u28D9\u28F9\u28F8\u28FC\u28F4\u28E6\u28E7\u28C7\u28CF",hve="|/-\\",gve="\u2736\u2738\u2739\u273A\u2739\u2737",fve="*",yve="#0891b2",Sve={pass:{glyph:"\u2713",ascii:"v",paint:$a.green},fail:{glyph:"\u2718",ascii:"x",paint:$a.red},skip:{glyph:"\u2212",ascii:"-",paint:$a.dim},cancel:{glyph:"\u2298",ascii:"o",paint:$a.yellow},retry:{glyph:"\u21BB",ascii:"~",paint:$a.yellow}};function zo(e){let t=e.colorLevel>0&&e.isTTY,n=(o,r)=>t?r(o):o;return {unicode:e.unicode,color:t,bold:o=>n(o,$a.bold),dim:o=>n(o,$a.gray),code:o=>n(o,$a.hex(yve)),spinner:o=>{let r=e.unicode?mve:hve,i=(o%r.length+r.length)%r.length;return n(r.charAt(i),$a.cyan)},classifySpinner:o=>{let r=e.unicode?gve:fve,i=(o%r.length+r.length)%r.length;return n(r.charAt(i),$a.cyan)},statusGlyph:o=>{let r=Sve[o],i=e.unicode?r.glyph:r.ascii;return t?r.paint(i):i},separator:e.unicode?" \xB7 ":" | "}}function RJ(e,t=""){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-t.length,20),r=[];for(let i of e.split(`
203
203
  `)){let s="";for(let a of i.split(" ")){if(!s.length){s=a;continue}let l=`${s} ${a}`;if(l.length<=o){s=l;continue}r.push(t+s),s=a;}r.push(t+s);}return r.join(`
204
- `)}var Tve={PASS:{glyph:"pass",isTerminal:true},FAIL:{glyph:"fail",isTerminal:true},SKIP:{glyph:"skip",isTerminal:true},CANCEL:{glyph:"cancel",isTerminal:true},RETRY:{glyph:"retry",isTerminal:false}},Ave={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function wJ(e,t,n=0){let o=Ave[e];if(!o)return;let r=zo(t);if(o==="RUNNING")return {badge:r.spinner(n),isTerminal:false};let{glyph:i,isTerminal:s}=Tve[o];return {badge:r.statusGlyph(i),isTerminal:s}}function ld(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function IJ({parallel:e,remoteBrowser:t}){let n=cpus$1().length;if(t){if(e<=n*4)return;let o=Math.max(1,n*4-2);R.warn(`Running ${e} workers on a ${n}-core machine with a remote browser. We recommend at most ~${o} workers ((cores \xD7 4) \u2212 2) to avoid local saturation.`);return}n>=e*2||R.warn(`Running ${e} workers on a ${n}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function xJ(){let e=dY(),t=[];e.lowMemorySamples>0&&t.push(`memory low ${e.lowMemorySamples}x`),e.highCpuSamples>0&&t.push(`CPU saturated ${e.highCpuSamples}x`),e.highHeapSamples>0&&t.push(`heap near limit ${e.highHeapSamples}x`),t.length!==0&&(R.log(""),R.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var Ee=xg({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"3.16.2"});var Cve=5,am=" ";async function Yv({getResults:e,checkDone:t,name:n,timeoutMs:o=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<o;){let s;i>Cve&&(R.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{s=await e(),i=0;}catch(c){i++,Ee.warn({err:c},"Failed to fetch run status; retrying."),R.warn({err:c},"Failed to fetch run status; retrying."),await new Promise(d=>setTimeout(d,1500*i));continue}if(t(s))return s;let l=Math.max(1e4,Math.floor(o/100));await new Promise(c=>setTimeout(c,l));}R.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(o/1e3)}s).`),process.exit(1);}function _J(e){let t={passed:[],failed:[],cancelled:[],quarantinedPassed:[],quarantinedFailed:[]};for(let n of e)switch(n.status){case "PASSED":(n.quarantined?t.quarantinedPassed:t.passed).push(n);break;case "FAILED":(n.quarantined?t.quarantinedFailed:t.failed).push(n);break;case "CANCELLED":t.cancelled.push(n);break}return t}function BL(e){let t=_J(e),n=t.failed.filter(r=>r.failureDetails?.classification?.action==="heal"),o=t.failed.filter(r=>r.failureDetails?.classification?.action==="warn");return {passed:t.passed.length,failed:t.failed.length,cancelled:t.cancelled.length,quarantinedPassed:t.quarantinedPassed.length,quarantinedFailed:t.quarantinedFailed.length,healElectedFailures:n.length,warnElectedFailures:o.length}}function kg(e,{onlyQuarantined:t=false,overrideExitCode:n=false}={}){let o=n?e.healElectedFailures+e.warnElectedFailures:0,r=e.failed-o,i=t?e.quarantinedFailed:0;return r+i>0||e.cancelled>0}function UL({results:e,startTime:t,getPath:n,getUrl:o,printFailureBody:r,getCancellationReason:i,recoveredCount:s,skippedCount:a,videoRecordingActive:l}){let{passed:c,failed:d,cancelled:u,quarantinedPassed:p,quarantinedFailed:m}=_J(e),h=Ct(),g=h.unicode?"\u2500":"-",f=process.stdout?.columns||80,y=(S,T,E,C)=>{let w=` ${T+1}) ${n(S)} `,x=Math.max(3,f-w.length-2);R.log(""),R.log(E(`${w}${g.repeat(x)}`)),R.log(""),C();let I=o(S);I&&(R.log(""),R.log(`${am}${ld(I,h)}`));};yJ(()=>{d.forEach((I,v)=>{y(I,v,$a.red.bold,()=>r?.(I));}),u.forEach((I,v)=>{y(I,d.length+v,$a.yellow.bold,()=>{let _=i?.(I)??"Cancelled";R.log(`${am}${$a.yellow.bold(_)}`);});});let S=(I,v,_)=>{I.length!==0&&(R.log(""),R.log(` ${_(`${I.length} ${v}`)}`),I.forEach(P=>{R.dimmed(`${am}${n(P)}`);}));};S(d,"failed",$a.red.bold),S(m,"failed",I=>$a.red.bold(`${I} (quarantined)`)),S(u,"cancelled",$a.yellow.bold),a&&(R.log(""),R.log(` ${$a.yellow.bold(`${a} skipped`)}`));let T=c.length+p.length,E=Math.max(1,Math.round((Date.now()-t)/1e3)),C=[];p.length>0&&C.push(`${p.length} quarantined`),s&&s>0&&C.push(`${s} recovered`);let w=C.length>0?` (${C.join(", ")})`:"",x=vve(e,h,l);R.log(""),R.log(` ${$a.green.bold(`${T} passed${w} (${E}s)`)}${x}`),xJ();});}function Jv(e){return UL(e),BL(e.results)}function vve(e,t,n=false){let o=e.length;if(o===0)return "";let r=e.filter(a=>a.usedRemoteBrowser).length;return r===0?"":`${t.unicode?" \xB7 ":" | "}${r}/${o} ran on remote browser${n?" (video saved async)":""}`}function Xv(e){if(!e.failureDetails||!e.failureReason)return;let t=Nl({failureReason:e.failureReason,classification:e.failureDetails.classification,manualClassification:e.failureDetails.manualClassification}),n=t.title??e.failureReason,o=e.failureDetails.classification?.rootCause??t.description??t.title??e.failureReason;R.log(`${am}${$a.red.bold(n)}`),o&&o!==n&&(R.log(""),R.log(RJ(o,am)));let r=TJ({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});r&&(R.log(""),R.log(r));let i=e.failureDetails.classification?.citations;if(i&&i.length>0){R.log(""),R.log(`${am}${$a.bold("Sources:")}`);for(let s of i)R.log(`${am} [${s.refId}] ${s.title}`);}}var Dg=" ".repeat(6);var Rve=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let r=Object.getOwnPropertyDescriptor(e,n),i=Object.getOwnPropertyDescriptor(t,n);!wve(r,i)&&o||Object.defineProperty(e,n,i);},wve=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Ive=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n);},xve=(e,t)=>`/* Wrapped ${e}*/
204
+ `)}var Tve={PASS:{glyph:"pass",isTerminal:true},FAIL:{glyph:"fail",isTerminal:true},SKIP:{glyph:"skip",isTerminal:true},CANCEL:{glyph:"cancel",isTerminal:true},RETRY:{glyph:"retry",isTerminal:false}},Ave={PASSED:"PASS",FAILED:"FAIL",CANCELLED:"CANCEL",RETRYING:"RETRY",RUNNING:"RUNNING",SKIP:"SKIP",RUN:"RUNNING",RETRY:"RETRY"};function wJ(e,t,n=0){let o=Ave[e];if(!o)return;let r=zo(t);if(o==="RUNNING")return {badge:r.spinner(n),isTerminal:false};let{glyph:i,isTerminal:s}=Tve[o];return {badge:r.statusGlyph(i),isTerminal:s}}function ld(e,t){return !t.isTTY||t.colorLevel===0?e:`\x1B]8;;${e}\x07${e}\x1B]8;;\x07`}function IJ({parallel:e,remoteBrowser:t}){let n=cpus$1().length;if(t){if(e<=n*4)return;let o=Math.max(1,n*4-2);R.warn(`Running ${e} workers on a ${n}-core machine with a remote browser. We recommend at most ~${o} workers ((cores \xD7 4) \u2212 2) to avoid local saturation.`);return}n>=e*2||R.warn(`Running ${e} workers on a ${n}-core machine. Chrome needs ~2 cores per worker; expect slowdowns.`);}function xJ(){let e=dY(),t=[];e.lowMemorySamples>0&&t.push(`memory low ${e.lowMemorySamples}x`),e.highCpuSamples>0&&t.push(`CPU saturated ${e.highCpuSamples}x`),e.highHeapSamples>0&&t.push(`heap near limit ${e.highHeapSamples}x`),t.length!==0&&(R.log(""),R.warn(`Machine was under pressure during this run (${t.join(", ")}). Slowdowns and timeouts may be related.`));}var Ee=xg({app:"cli",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:"3.16.3"});var Cve=5,am=" ";async function Yv({getResults:e,checkDone:t,name:n,timeoutMs:o=18e5}){let r=Date.now(),i=0;for(;Date.now()-r<o;){let s;i>Cve&&(R.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{s=await e(),i=0;}catch(c){i++,Ee.warn({err:c},"Failed to fetch run status; retrying."),R.warn({err:c},"Failed to fetch run status; retrying."),await new Promise(d=>setTimeout(d,1500*i));continue}if(t(s))return s;let l=Math.max(1e4,Math.floor(o/100));await new Promise(c=>setTimeout(c,l));}R.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(o/1e3)}s).`),process.exit(1);}function _J(e){let t={passed:[],failed:[],cancelled:[],quarantinedPassed:[],quarantinedFailed:[]};for(let n of e)switch(n.status){case "PASSED":(n.quarantined?t.quarantinedPassed:t.passed).push(n);break;case "FAILED":(n.quarantined?t.quarantinedFailed:t.failed).push(n);break;case "CANCELLED":t.cancelled.push(n);break}return t}function BL(e){let t=_J(e),n=t.failed.filter(r=>r.failureDetails?.classification?.action==="heal"),o=t.failed.filter(r=>r.failureDetails?.classification?.action==="warn");return {passed:t.passed.length,failed:t.failed.length,cancelled:t.cancelled.length,quarantinedPassed:t.quarantinedPassed.length,quarantinedFailed:t.quarantinedFailed.length,healElectedFailures:n.length,warnElectedFailures:o.length}}function kg(e,{onlyQuarantined:t=false,overrideExitCode:n=false}={}){let o=n?e.healElectedFailures+e.warnElectedFailures:0,r=e.failed-o,i=t?e.quarantinedFailed:0;return r+i>0||e.cancelled>0}function UL({results:e,startTime:t,getPath:n,getUrl:o,printFailureBody:r,getCancellationReason:i,recoveredCount:s,skippedCount:a,videoRecordingActive:l}){let{passed:c,failed:d,cancelled:u,quarantinedPassed:p,quarantinedFailed:m}=_J(e),h=Ct(),g=h.unicode?"\u2500":"-",f=process.stdout?.columns||80,y=(S,T,E,C)=>{let w=` ${T+1}) ${n(S)} `,x=Math.max(3,f-w.length-2);R.log(""),R.log(E(`${w}${g.repeat(x)}`)),R.log(""),C();let I=o(S);I&&(R.log(""),R.log(`${am}${ld(I,h)}`));};yJ(()=>{d.forEach((I,v)=>{y(I,v,$a.red.bold,()=>r?.(I));}),u.forEach((I,v)=>{y(I,d.length+v,$a.yellow.bold,()=>{let _=i?.(I)??"Cancelled";R.log(`${am}${$a.yellow.bold(_)}`);});});let S=(I,v,_)=>{I.length!==0&&(R.log(""),R.log(` ${_(`${I.length} ${v}`)}`),I.forEach(P=>{R.dimmed(`${am}${n(P)}`);}));};S(d,"failed",$a.red.bold),S(m,"failed",I=>$a.red.bold(`${I} (quarantined)`)),S(u,"cancelled",$a.yellow.bold),a&&(R.log(""),R.log(` ${$a.yellow.bold(`${a} skipped`)}`));let T=c.length+p.length,E=Math.max(1,Math.round((Date.now()-t)/1e3)),C=[];p.length>0&&C.push(`${p.length} quarantined`),s&&s>0&&C.push(`${s} recovered`);let w=C.length>0?` (${C.join(", ")})`:"",x=vve(e,h,l);R.log(""),R.log(` ${$a.green.bold(`${T} passed${w} (${E}s)`)}${x}`),xJ();});}function Jv(e){return UL(e),BL(e.results)}function vve(e,t,n=false){let o=e.length;if(o===0)return "";let r=e.filter(a=>a.usedRemoteBrowser).length;return r===0?"":`${t.unicode?" \xB7 ":" | "}${r}/${o} ran on remote browser${n?" (video saved async)":""}`}function Xv(e){if(!e.failureDetails||!e.failureReason)return;let t=Nl({failureReason:e.failureReason,classification:e.failureDetails.classification,manualClassification:e.failureDetails.manualClassification}),n=t.title??e.failureReason,o=e.failureDetails.classification?.rootCause??t.description??t.title??e.failureReason;R.log(`${am}${$a.red.bold(n)}`),o&&o!==n&&(R.log(""),R.log(RJ(o,am)));let r=TJ({failureDetails:e.failureDetails,filePath:e.filePath,results:e.results,beforeResults:e.beforeResults,afterResults:e.afterResults});r&&(R.log(""),R.log(r));let i=e.failureDetails.classification?.citations;if(i&&i.length>0){R.log(""),R.log(`${am}${$a.bold("Sources:")}`);for(let s of i)R.log(`${am} [${s.refId}] ${s.title}`);}}var Dg=" ".repeat(6);var Rve=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let r=Object.getOwnPropertyDescriptor(e,n),i=Object.getOwnPropertyDescriptor(t,n);!wve(r,i)&&o||Object.defineProperty(e,n,i);},wve=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Ive=(e,t)=>{let n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n);},xve=(e,t)=>`/* Wrapped ${e}*/
205
205
  ${t}`,_ve=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Pve=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Ove=(e,t,n)=>{let o=n===""?"":`with ${n.trim()}() `,r=xve.bind(null,o,t.toString());Object.defineProperty(r,"name",Pve);let{writable:i,enumerable:s,configurable:a}=_ve;Object.defineProperty(e,"toString",{value:r,writable:i,enumerable:s,configurable:a});};function HL(e,t,{ignoreNonConfigurable:n=false}={}){let{name:o}=e;for(let r of Reflect.ownKeys(t))Rve(e,t,r,n);return Ive(e,t),Ove(e,t,o),e}var Qv=new WeakMap,PJ=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0,r=e.displayName||e.name||"<anonymous>",i=function(...s){if(Qv.set(i,++o),o===1)n=e.apply(this,s),e=void 0;else if(t.throw===true)throw new Error(`Function \`${r}\` can only be called once`);return n};return HL(i,e),Qv.set(i,o),i};PJ.callCount=e=>{if(!Qv.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Qv.get(e)};var OJ=PJ;var lm=[];lm.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&lm.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&lm.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Zv=e=>!!e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function",GL=Symbol.for("signal-exit emitter"),jL=globalThis,Mve=Object.defineProperty.bind(Object),$L=class{emitted={afterExit:false,exit:false};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(jL[GL])return jL[GL];Mve(jL,GL,{value:this,writable:false,enumerable:false,configurable:false});}on(t,n){this.listeners[t].push(n);}removeListener(t,n){let o=this.listeners[t],r=o.indexOf(n);r!==-1&&(r===0&&o.length===1?o.length=0:o.splice(r,1));}emit(t,n,o){if(this.emitted[t])return false;this.emitted[t]=true;let r=false;for(let i of this.listeners[t])r=i(n,o)===true||r;return t==="exit"&&(r=this.emit("afterExit",n,o)||r),r}},eR=class{},Nve=e=>({onExit(t,n){return e.onExit(t,n)},load(){return e.load()},unload(){return e.unload()}}),VL=class extends eR{onExit(){return ()=>{}}load(){}unload(){}},zL=class extends eR{#s=WL.platform==="win32"?"SIGINT":"SIGHUP";#n=new $L;#e;#r;#p;#t={};#i=false;constructor(t){super(),this.#e=t,this.#t={};for(let n of lm)this.#t[n]=()=>{let o=this.#e.listeners(n),{count:r}=this.#n,i=t;if(typeof i.__signal_exit_emitter__=="object"&&typeof i.__signal_exit_emitter__.count=="number"&&(r+=i.__signal_exit_emitter__.count),o.length===r){this.unload();let s=this.#n.emit("exit",null,n),a=n==="SIGHUP"?this.#s:n;s||t.kill(t.pid,a);}};this.#p=t.reallyExit,this.#r=t.emit;}onExit(t,n){if(!Zv(this.#e))return ()=>{};this.#i===false&&this.load();let o=n?.alwaysLast?"afterExit":"exit";return this.#n.on(o,t),()=>{this.#n.removeListener(o,t),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload();}}load(){if(!this.#i){this.#i=true,this.#n.count+=1;for(let t of lm)try{let n=this.#t[t];n&&this.#e.on(t,n);}catch{}this.#e.emit=(t,...n)=>this.#m(t,...n),this.#e.reallyExit=t=>this.#o(t);}}unload(){this.#i&&(this.#i=false,lm.forEach(t=>{let n=this.#t[t];if(!n)throw new Error("Listener not defined for signal: "+t);try{this.#e.removeListener(t,n);}catch{}}),this.#e.emit=this.#r,this.#e.reallyExit=this.#p,this.#n.count-=1);}#o(t){return Zv(this.#e)?(this.#e.exitCode=t||0,this.#n.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(t,...n){let o=this.#r;if(t==="exit"&&Zv(this.#e)){typeof n[0]=="number"&&(this.#e.exitCode=n[0]);let r=o.call(this.#e,t,...n);return this.#n.emit("exit",this.#e.exitCode,null),r}else return o.call(this.#e,t,...n)}},WL=globalThis.process,{onExit:MJ}=Nve(Zv(WL)?new zL(WL):new VL);var NJ=Ya.stderr.isTTY?Ya.stderr:Ya.stdout.isTTY?Ya.stdout:void 0,Lve=NJ?OJ(()=>{MJ(()=>{NJ.write("\x1B[?25h");},{alwaysLast:true});}):()=>{},LJ=Lve;var nR=false,Fg={};Fg.show=(e=Ya.stderr)=>{e.isTTY&&(nR=false,e.write("\x1B[?25h"));};Fg.hide=(e=Ya.stderr)=>{e.isTTY&&(LJ(),nR=true,e.write("\x1B[?25l"));};Fg.toggle=(e,t)=>{e!==void 0&&(nR=e),nR?Fg.show(t):Fg.hide(t);};var qL=Fg;var kb=iO(KL());function YL(){return Ya.platform!=="win32"?Ya.env.TERM!=="linux":!!Ya.env.CI||!!Ya.env.WT_SESSION||!!Ya.env.TERMINUS_SUBLIME||Ya.env.ConEmuTask==="{cmd::Cmder}"||Ya.env.TERM_PROGRAM==="Terminus-Sublime"||Ya.env.TERM_PROGRAM==="vscode"||Ya.env.TERM==="xterm-256color"||Ya.env.TERM==="alacritty"||Ya.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Dve={info:$a.blue("\u2139"),success:$a.green("\u2714"),warning:$a.yellow("\u26A0"),error:$a.red("\u2716")},Fve={info:$a.blue("i"),success:$a.green("\u221A"),warning:$a.yellow("\u203C"),error:$a.red("\xD7")},Bve=YL()?Dve:Fve,Lb=Bve;function JL({onlyFirst:e=false}={}){let r="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(r,e?void 0:"g")}var Uve=JL();function XL(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return !e.includes("\x1B")&&!e.includes("\x9B")?e:e.replace(Uve,"")}function QL({stream:e=process.stdout}={}){return !!(e&&e.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function ZL(){let{env:e}=Ya,{TERM:t,TERM_PROGRAM:n}=e;return Ya.platform!=="win32"?t!=="linux":!!e.WT_SESSION||!!e.TERMINUS_SUBLIME||e.ConEmuTask==="{cmd::Cmder}"||n==="Terminus-Sublime"||n==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Hve=3,ek=class{#s=0;start(){this.#s++,this.#s===1&&this.#n();}stop(){if(this.#s<=0)throw new Error("`stop` called more times than `start`");this.#s--,this.#s===0&&this.#e();}#n(){Ya.platform==="win32"||!Ya.stdin.isTTY||(Ya.stdin.setRawMode(true),Ya.stdin.on("data",this.#r),Ya.stdin.resume());}#e(){Ya.stdin.isTTY&&(Ya.stdin.off("data",this.#r),Ya.stdin.pause(),Ya.stdin.setRawMode(false));}#r(t){t[0]===Hve&&Ya.emit("SIGINT");}},Gve=new ek,tk=Gve;iO(KL());var nk=class{#s=0;#n=false;#e=0;#r=-1;#p=0;#t;#i;#o;#m;#g;#c;#d;#u;#f;#a;#l;color;constructor(t){typeof t=="string"&&(t={text:t}),this.#t={color:"cyan",stream:Ya.stderr,discardStdin:true,hideCursor:true,...t},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#o=this.#t.stream,this.#c=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:QL({stream:this.#o}),this.#d=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:false,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Ya.env.NODE_ENV==="test"&&(this._stream=this.#o,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#s},set(n){this.#s=n;}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#r}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}));}get indent(){return this.#u}set indent(t=0){if(!(t>=0&&Number.isInteger(t)))throw new Error("The `indent` option must be an integer from 0 and up");this.#u=t,this.#h();}get interval(){return this.#g??this.#i.interval??100}get spinner(){return this.#i}set spinner(t){if(this.#r=-1,this.#g=void 0,typeof t=="object"){if(t.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#i=t;}else if(!ZL())this.#i=kb.default.line;else if(t===void 0)this.#i=kb.default.dots;else if(t!=="default"&&kb.default[t])this.#i=kb.default[t];else throw new Error(`There is no built-in spinner named '${t}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#f}set text(t=""){this.#f=t,this.#h();}get prefixText(){return this.#a}set prefixText(t=""){this.#a=t,this.#h();}get suffixText(){return this.#l}set suffixText(t=""){this.#l=t,this.#h();}get isSpinning(){return this.#m!==void 0}#y(t=this.#a,n=" "){return typeof t=="string"&&t!==""?t+n:typeof t=="function"?t()+n:""}#S(t=this.#l,n=" "){return typeof t=="string"&&t!==""?n+t:typeof t=="function"?n+t():""}#h(){let t=this.#o.columns??80,n=this.#y(this.#a,"-"),o=this.#S(this.#l,"-"),r=" ".repeat(this.#u)+n+"--"+this.#f+"--"+o;this.#e=0;for(let i of XL(r).split(`
206
206
  `))this.#e+=Math.max(1,Math.ceil(m6(i,{countAnsiEscapeCodes:true})/t));}get isEnabled(){return this.#c&&!this.#d}set isEnabled(t){if(typeof t!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#c=t;}get isSilent(){return this.#d}set isSilent(t){if(typeof t!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#d=t;}frame(){let t=Date.now();(this.#r===-1||t-this.#p>=this.interval)&&(this.#r=++this.#r%this.#i.frames.length,this.#p=t);let{frames:n}=this.#i,o=n[this.#r];this.color&&(o=$a[this.color](o));let r=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",i=typeof this.text=="string"?" "+this.text:"",s=typeof this.#l=="string"&&this.#l!==""?" "+this.#l:"";return r+o+i+s}clear(){if(!this.#c||!this.#o.isTTY)return this;this.#o.cursorTo(0);for(let t=0;t<this.#s;t++)t>0&&this.#o.moveCursor(0,-1),this.#o.clearLine(1);return (this.#u||this.lastIndent!==this.#u)&&this.#o.cursorTo(this.#u),this.lastIndent=this.#u,this.#s=0,this}render(){return this.#d?this:(this.clear(),this.#o.write(this.frame()),this.#s=this.#e,this)}start(t){return t&&(this.text=t),this.#d?this:this.#c?this.isSpinning?this:(this.#t.hideCursor&&qL.hide(this.#o),this.#t.discardStdin&&Ya.stdin.isTTY&&(this.#n=true,tk.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#o.write(`- ${this.text}
207
207
  `),this)}stop(){return this.#c?(clearInterval(this.#m),this.#m=void 0,this.#r=0,this.clear(),this.#t.hideCursor&&qL.show(this.#o),this.#t.discardStdin&&Ya.stdin.isTTY&&this.#n&&(tk.stop(),this.#n=false),this):this}succeed(t){return this.stopAndPersist({symbol:Lb.success,text:t})}fail(t){return this.stopAndPersist({symbol:Lb.error,text:t})}warn(t){return this.stopAndPersist({symbol:Lb.warning,text:t})}info(t){return this.stopAndPersist({symbol:Lb.info,text:t})}stopAndPersist(t={}){if(this.#d)return this;let n=t.prefixText??this.#a,o=this.#y(n," "),r=t.symbol??" ",i=t.text??this.text,a=typeof i=="string"?(r?" ":"")+i:"",l=t.suffixText??this.#l,c=this.#S(l," "),d=o+r+a+c+`
@@ -257,7 +257,7 @@ ${u}`,{cause:d})}i=mT({testV2:l,testName:Jn__default.basename(e,".test.yaml")});
257
257
  ${z$1.prettifyError(s)}`:`: ${X(s)}`;R.warn(`Project config at ${e} does not match the required schema${a}`);return}let o=deletedDiff(t,n),r=RQ(o,"");r.length>0&&R.warn(`Momentic config file at ${e} contains unrecognized keys: ${r.join(", ")}. These keys will be ignored.`);let i=t_e(n);return o_e(t)&&i.push("ai.classification.categories"),i.length>0&&R.warn(`Momentic config file at ${e} sets cloud-managed AI settings (${i.join(", ")}) that are configured in the Momentic dashboard and ignored locally. Remove them from this file.`),n}function r_e(e){let t=vQ(e,"workspace configuration");if(t!==void 0)try{return Kxe.parse(t)}catch(n){R.warn(`Possible Momentic workspace configuration file at ${e} does not adhere to the required schema: ${X(n)}`);return}}function i_e(){let e=[],t=cwd(),n=Jn__default.parse(t).root,o=15,r=0;for(;r<o;){r++;let i=Jn__default.basename(t);if(Yk.includes(i))return R.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),e;for(let s of readdirSync(t))if(s.endsWith(pc)){let a=Jn__default.join(t,s),l=iD(a);l&&e.push({configFilePath:a,config:l,rootDir:dirname(a)});}if(e.length)return e;if(t=Jn__default.dirname(t),t===n)break}return e}async function sn(e={}){let{configFilePath:t,nameFilter:n,skipExitOnError:o}=e,r=await sD(t,o);if(n&&(r=r.filter(i=>i.config.name===n)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
258
258
  ${r.map(i=>i.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return R.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}async function s_e(e){let t=r_e(e);if(!t||!t.projects||!t.projects.length)return;let n=t.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${pc}`)),o=AbortSignal.timeout(2e3),r;try{r=await Sd(n,{cwd:cwd(),maxDepth:gT,ignore:[],nodir:!0,signal:o});}catch(s){throw R.error({err:s},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${yT} is misconfigured.`),s}let i=[];for(let s of r){let a=Jn__default.join(cwd(),s),l=iD(a);l&&i.push({configFilePath:a,config:l,rootDir:dirname(a)});}return i}async function sD(e,t){if(e){e=Jn__default.resolve(e);let o=iD(e);return o?[{config:o,configFilePath:e,rootDir:Jn__default.dirname(e)}]:(console.error(`No valid Momentic project file found at ${e}.`),t||process.exit(1),[])}if(existsSync(yT)){let o=await s_e(yT);if(o)return o}return i_e()}function Ad(e,t){let n=Nb.stringify(e);writeFileSync(t,n);}async function Fs({project:e,apiClient:t,classificationOverrides:n}){let{classification:o,healing:r,explore:i}=(await t.getOrgSettings()).ai??{},s=l_e({flags:n,config:e.config.ai?.classification,cloudConfig:o}),a=a_e({config:e.config.ai?.triage,cloudConfig:r}),l={...e.config.ai};return delete l.healing,delete l.triage,n?.disabled&&(l.aiFailureAnalysis=false),{...e,config:{...e.config,ai:{...l,classification:s,triage:a,explore:i}}}}function a_e({config:e,cloudConfig:t}){if(!(!e&&!t))return {onHealFail:e?.onHealFail??t?.onFail??lO,onHealSuccess:e?.onHealSuccess??t?.onSuccess??cO,remoteBrowser:e?.remoteBrowser,requestCommitAuthorsAsReviewers:e?.requestCommitAuthorsAsReviewers??t?.requestCommitAuthorsAsReviewers}}function l_e({flags:e,config:t,cloudConfig:n}){if(!(!t&&!n))return {enabled:e?.disabled?false:t?.enabled??n?.enabled??false,overrideExitCode:e?.overrideExitCode??t?.overrideExitCode??n?.overrideExitCode??QG,categories:n?.categories??qi}}var wQ="golden/visual-diff",IQ="reports",el="test-results";var c_e=z$1.object({width:z$1.number(),height:z$1.number()}),hf=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;apiClient;constructor(t,n,o){let r=Jn__default.join(t.rootDir,t.config.goldenFileDir??wQ);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=o,this.apiClient=n;}async prepareGoldenScreenshotForComparison(t,n,o){if(Hj(n.screenshot?.data))return {buffer:(await this.apiClient.fetchOnDemandScreenshot(n.screenshot.data.id)).data,width:n.screenshot.width,height:n.screenshot.height};if(n.screenshot?.data?.startsWith("https://")){let s=await fetch(n.screenshot.data);return {buffer:Buffer.from(await s.arrayBuffer()),width:n.screenshot.width,height:n.screenshot.height}}let r=n.screenshot?.data;r||(r=Jn__default.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let i=`${r}.metadata.json`;if(this.regenerateGoldenFiles)return Oo__default.mkdirSync(Jn__default.dirname(r),{recursive:true}),Oo__default.writeFileSync(r,o.buffer),Oo__default.writeFileSync(i,JSON.stringify({width:o.width,height:o.height})),{buffer:Buffer.from(o.buffer),width:o.width,height:o.height};if(Oo__default.existsSync(r)){let s=Oo__default.readFileSync(r),a=c_e.parse(JSON.parse(Oo__default.readFileSync(i,"utf-8")));return {buffer:s,width:a.width,height:a.height}}else throw new te("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${r}`)}};var xQ=3e3,pn=ST(),p_e=promisify(execFile);async function dD(e,t){try{return await ST(e).revparse(t)}catch(n){if(OQ(n))return;throw n}}async function Ed(e){return dD(e,["--show-toplevel"])}async function _Q(e){return dD(e,["HEAD"])}async function PQ(e){return dD(e,["--abbrev-ref","HEAD"])}async function cw({cwd:e,base:t,head:n,logger:o}){try{let r=(await ST(e).raw(["merge-base",t,n])).trim();if(r.length>0)return r;o.warn({base:t,head:n},"git merge-base returned empty");}catch(r){o.warn({err:r,base:t,head:n},"git merge-base failed");}}function uD(){return process.env.GITHUB_BASE_REF||process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH||process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME||void 0}async function bT({client:e,repository:t,base:n,head:o,logger:r}){let i=ir(t);if(i)try{let s=await e.compareCommitsFromGithub({owner:i.owner,repo:i.repo,base:n,head:o});return s.commits.length===0?void 0:s}catch(s){r.warn({err:s,repository:t,base:n,head:o},"remote commit compare failed");return}}async function ba(e){let{logger:t,operation:n,fn:o,context:r}=e,i=Date.now();try{return await o()}finally{let s=Date.now()-i;s>xQ&&!process.env.CI&&t.warn({operation:n,durationMs:s,thresholdMs:xQ,...r??{}},"[timing] slow git metadata operation");}}function mc(e){if(e)try{let t=new Date(e);return isNaN(t.getTime())?void 0:t}catch{return}}async function m_e(e){let t=await gn(e,pn.raw(["config","--list"])),n={};if(!t)return n;for(let o of t.split(`
259
259
  `)){let r=o.indexOf("=");if(r===-1)continue;let i=o.slice(0,r),s=o.slice(r+1).trim();n[i]=s;}return n}async function h_e(e,t,n){try{let r=n["github.user"]||void 0;if(r)return r}catch{}let o;try{if(t?.startsWith("http://")||t?.startsWith("https://"))o=new URL(t).host;else if(t?.startsWith("git@")){let r=t.indexOf("@"),i=t.indexOf(":",r+1);r!==-1&&i!==-1&&(o=t.slice(r+1,i));}}catch{}if(o=o?.toLowerCase(),!!o&&t?.startsWith("git@")&&o.includes("github"))try{let{stdout:r,stderr:i}=await p_e("ssh",["-T","-o","BatchMode=yes",`git@${o}`],{timeout:5e3}),a=`${r??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(a?.[1])return a[1]}catch{return}}async function g_e(e,t,n){let o=t?.includes("github.com"),r=t?.includes("gitlab.com");try{if(o)return h_e(e,t,n);if(r)return}catch{}}function TT(e){if(e.startsWith("git@")){let t=e.split(":");if(t.length===2){let n=t[1].replace(".git","").split("/");if(n.length===2){let o=n[0],r=n[1];return `${o}/${r}`}}}else if(e.startsWith("http")||e.startsWith("https")){let n=new URL(e).pathname.split("/").filter(Boolean);if(n.length>=2){let o=n[0],r=n[1].replace(".git","");return `${o}/${r}`}}}function OQ(e){if(!(e instanceof Error))return false;let t=e.message;return t.includes("not a git repository")||t.includes("ENOENT")||t.includes("detected dubious ownership")}async function gn(e,t){try{return (await t).trim()}catch(n){if(OQ(n))return;e.error({err:n},"Failed to run git command");return}}async function Ta(e,t){if(e)try{return (await ST(t).revparse([e]))?.trim()||void 0}catch{return}}async function AT(e){let t=await Ta(e);return t||await Ta(`origin/${e}`)}function f_e(){if(process.env.GITHUB_ACTION)return "GithubActions";if(process.env.GITLAB_CI)return "GitlabCI";if(process.env.CIRCLECI)return "CircleCI";if(process.env.BUILDKITE)return "Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return "AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return "GCPCloudBuild";if(process.env.BITRISE_BUILD_SLUG)return "Bitrise";if(process.env.MOMENTIC_GIT_OVERRIDE)return "Custom"}async function y_e(e){let[t,n,o]=await Promise.all([gn(e,pn.show(["--no-patch","--format=%ci"])),gn(e,pn.show(["-s","--pretty=%B"])),gn(e,pn.show(["-s","--pretty=%an"]))]),r=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return {ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:t?mc(t):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:r,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function S_e(e){let[t,n,o]=await Promise.all([gn(e,pn.listRemote(["--get-url","origin"])),gn(e,pn.show(["-s","--pretty=%B"])),gn(e,pn.show(["-s","--pretty=%an"]))]);return {ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?mc(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:t,gitCommitMessage:n,gitCommitAuthorName:o,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function b_e(e){let[t,n,o,r]=await Promise.all([gn(e,pn.show(["--no-patch","--format=%ci"])),gn(e,pn.listRemote(["--get-url","origin"])),gn(e,pn.show(["-s","--pretty=%B"])),gn(e,pn.show(["-s","--pretty=%an"]))]),s=process.env.CIRCLE_REPOSITORY_URL?.trim()||void 0||n||void 0,a=s?.includes("github.com")??false,l=s?.includes("gitlab.com")??false,c=s?TT(s):void 0;return {ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:t?mc(t):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:s,gitCommitMessage:o,gitCommitAuthorName:r,githubRepository:a?c:void 0,gitlabProjectPath:l?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function T_e(e){let[t,n,o]=await Promise.all([gn(e,pn.show(["--no-patch","--format=%ci"])),gn(e,pn.show(["-s","--pretty=%B"])),gn(e,pn.show(["-s","--pretty=%an"]))]),r=process.env.BUILDKITE_REPO,i=r?.includes("github.com"),s=r?.includes("gitlab.com"),a=r?TT(r):void 0;return {ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:t?mc(t):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:r,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?a:void 0,gitlabProjectPath:s?a:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function A_e(e){let[t,n,o]=await Promise.all([gn(e,pn.show(["--no-patch","--format=%ci"])),gn(e,pn.show(["-s","--pretty=%B"])),gn(e,pn.show(["-s","--pretty=%an"]))]),r=process.env["Build.Repository.Uri"],i=r?.includes("github.com"),s=r?.includes("gitlab.com"),a=r?TT(r):void 0;return {ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:t?mc(t):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:r,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?a:void 0,gitlabProjectPath:s?a:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function E_e(e,t,n){let[o,r,i,s,a,l,c,d,u]=await Promise.all([gn(e,pn.revparse(["HEAD"])),gn(e,pn.revparse(["--short","HEAD"])),gn(e,pn.revparse(["--abbrev-ref","HEAD"])),gn(e,pn.listRemote(["--get-url","origin"])),gn(e,pn.show(["--no-patch","--format=%ci"])),gn(e,pn.show(["-s","--pretty=%B"])),gn(e,pn.show(["-s","--pretty=%an"])),t?gn(e,pn.raw(["merge-base","--fork-point",t])):Promise.resolve(void 0),m_e(e)]),p=d||(t?await gn(e,pn.raw(["merge-base",t,"HEAD"])):void 0),m=p?await gn(e,pn.show(["--no-patch","--format=%ci",p])):void 0,h=s?.includes("github.com"),g=s?.includes("gitlab.com"),f=s?TT(s):void 0,y=u["user.email"]||void 0,S=u["user.name"]||void 0,T=u["user.username"]||void 0,E=u["github.user"]||void 0,x=(n?.includeHostingUsername??true?await g_e(e,s,u):void 0)??T??E??void 0;return {ciProvider:"none",gitCommitSha:o,gitCommitShaShort:r,gitBranchName:i,gitOriginUrl:s,gitCommitTimestamp:a?mc(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:x,gitLocalEmail:y,gitLocalName:S,lastCommitOnMainSha:p,lastCommitOnMainTimestamp:m?mc(m):void 0,githubRepository:h?f:void 0,gitlabProjectPath:g?f:void 0,pipelineId:void 0}}async function C_e(e){let[t,n]=await Promise.all([gn(e,pn.show(["--no-patch","--format=%ci"])),gn(e,pn.show(["-s","--pretty=%an"]))]),o=process.env.GIT_REPOSITORY_URL,r=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?TT(o):void 0;return {ciProvider:"Bitrise",gitCommitSha:process.env.BITRISE_GIT_COMMIT,gitCommitShaShort:process.env.BITRISE_GIT_COMMIT?.slice(0,6),gitCommitTimestamp:t?mc(t):void 0,gitBranchName:process.env.BITRISE_GIT_BRANCH,gitOriginUrl:o,gitCommitMessage:process.env.BITRISE_GIT_MESSAGE,gitCommitAuthorName:n,githubRepository:r?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BITRISE_APP_SLUG}:${process.env.BITRISE_BUILD_SLUG}`}}async function v_e(){let e=process.env._HEAD_REPO_URL;return {ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:e?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:e?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}function R_e(){return {ciProvider:"Custom",gitCommitSha:process.env.GIT_COMMIT_SHA,gitCommitShaShort:process.env.GIT_COMMIT_SHA_SHORT??process.env.GIT_COMMIT_SHA?.slice(0,6),gitCommitTimestamp:mc(process.env.GIT_COMMIT_TIMESTAMP),gitBranchName:process.env.GIT_BRANCH_NAME,gitOriginUrl:process.env.GIT_ORIGIN_URL,gitCommitAuthorName:process.env.GIT_COMMIT_AUTHOR_NAME,gitCommitMessage:process.env.GIT_COMMIT_MESSAGE,lastCommitOnMainSha:process.env.LAST_COMMIT_ON_MAIN_SHA,lastCommitOnMainTimestamp:mc(process.env.LAST_COMMIT_ON_MAIN_TIMESTAMP),mergedGitBranchName:process.env.MERGED_GIT_BRANCH_NAME,githubRepository:process.env.GITHUB_REPOSITORY,gitlabProjectPath:process.env.GITLAB_PROJECT_PATH,gitLocalUsername:process.env.GIT_USERNAME,gitLocalEmail:process.env.GIT_EMAIL,gitLocalName:process.env.GIT_NAME}}async function w_e(e){let t=[...e.config.gitProtectedBranches??[]];return e.config.gitMainBranch&&t.push(e.config.gitMainBranch),{gitMainBranch:e.config.gitMainBranch,gitProtectedBranches:t}}async function Aa(e,t,n){let o=f_e();if(!o)return E_e(e,t,n);switch(o){case "GithubActions":return y_e(e);case "GitlabCI":return S_e(e);case "CircleCI":return b_e(e);case "Buildkite":return T_e(e);case "AzureDevOps":return A_e(e);case "GCPCloudBuild":return v_e();case "Bitrise":return C_e(e);case "Custom":return R_e()}}async function I_e(e,t,n,o){let r=o,i=o.gitCommitSha;if(!i)return r;let s=o.gitMainBranch;if(s&&(!r.lastCommitOnMainSha||!r.lastCommitOnMainTimestamp))try{let a=await ba({logger:e,operation:"getRemoteMetadataFromGitlab.getMergeBaseCommitFromGitlab",fn:()=>t.getMergeBaseCommitFromGitlab(n,s,i),context:{projectPath:n,mainBranch:s}});r={...r,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date};}catch(a){e.warn({err:a},"Failed to get merge base commit from Gitlab");}if(!r.gitCommitTimestamp||!r.gitCommitAuthorName||!r.gitCommitMessage||!r.gitCommitAuthorName)try{let a=await ba({logger:e,operation:"getRemoteMetadataFromGitlab.getCommitFromGitlab",fn:()=>t.getCommitFromGitlab(n,i),context:{projectPath:n,gitCommitSha:i}});a&&(r={...r,gitCommitTimestamp:r.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:r.gitCommitAuthorName??a.author.name,gitCommitMessage:r.gitCommitMessage??a.message});}catch(a){e.warn({err:a},"Failed to get commit from Gitlab");}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!r.mergedGitBranchName){let a=o.gitBranchName;try{let l=await ba({logger:e,operation:"getRemoteMetadataFromGitlab.getMergedBranchFromGitlab",fn:()=>t.getMergedBranchFromGitlab(n,a,i),context:{projectPath:n,branchName:a,gitCommitSha:i}});l.mergedBranch&&(r={...r,mergedGitBranchName:l.mergedBranch});}catch(l){e.warn({err:l},"Failed to get merged branch from Gitlab");}}return r}async function x_e(e,t,n,o,r){let i=r,s=r.gitCommitSha;if(!s)return i;let a=r.gitMainBranch;if(a&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let l=await ba({logger:e,operation:"getRemoteMetadataFromGitHub.getMergeBaseCommitFromGithub",fn:()=>t.getMergeBaseCommitFromGithub(n,o,a,s),context:{owner:n,repo:o,mainBranch:a}});i={...i,lastCommitOnMainSha:l.sha,lastCommitOnMainTimestamp:l.committer.date};}catch(l){e.warn({err:l},"Failed to get merge base commit from GitHub");}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName)try{let l=await ba({logger:e,operation:"getRemoteMetadataFromGitHub.getCommitFromGithub",fn:()=>t.getCommitFromGithub(n,o,s),context:{owner:n,repo:o,gitCommitSha:s}});l&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??l.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??l.author.name,gitCommitMessage:i.gitCommitMessage??l.message});}catch(l){e.warn({err:l},"Failed to get commit from GitHub");}if(r.gitBranchName&&r.gitBranchName===r.gitMainBranch&&!i.mergedGitBranchName){let l=r.gitBranchName;try{let c=await ba({logger:e,operation:"getRemoteMetadataFromGitHub.getMergedBranchFromGithub",fn:()=>t.getMergedBranchFromGithub(n,o,l,s),context:{owner:n,repo:o,branchName:l,gitCommitSha:s}});c.mergedBranch&&(i={...i,mergedGitBranchName:c.mergedBranch});}catch(c){e.warn({err:c},"Failed to get merged branch from GitHub");}}return i}async function __e(e,t,n){try{if(n.githubRepository){let{owner:o,repo:r}=JW(n.githubRepository);return await ba({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitHub",fn:()=>x_e(e,t,o,r,n),context:{githubRepository:n.githubRepository}})}else if(n.gitlabProjectPath){let o=n.gitlabProjectPath;return await ba({logger:e,operation:"getRemoteMetadataIfNeeded.getRemoteMetadataFromGitlab",fn:()=>I_e(e,t,o,n),context:{gitlabProjectPath:o}})}}catch(o){e.warn({err:o},"Failed to get remote git metadata");}return n}async function P_e(e,t,n,o){let r={},i={gitMainBranch:n.config.gitMainBranch};return ba({logger:e,operation:"getGitMetadata.total",fn:async()=>{let[s,a]=await Promise.all([ba({logger:e,operation:"getGitMetadata.getConfiguredGitMetadata",fn:()=>w_e(n),context:{projectConfigPath:n.configFilePath}}),ba({logger:e,operation:"getGitMetadata.getEnvironmentGitMetadata",fn:async()=>{let d=await Aa(e,n.config.gitMainBranch,o);return i.ciProvider=d.ciProvider,d},context:i})]),l={...s,...a};r.gitBranchName=l.gitBranchName,r.githubRepository=l.githubRepository,r.gitlabProjectPath=l.gitlabProjectPath,(!l.lastCommitOnMainSha||!l.lastCommitOnMainTimestamp)&&l.gitBranchName===s.gitMainBranch&&(l.lastCommitOnMainSha=l.gitCommitSha,l.lastCommitOnMainTimestamp=l.gitCommitTimestamp);let c=await ba({logger:e,operation:"getGitMetadata.getRemoteMetadataIfNeeded",fn:()=>__e(e,t,l),context:{githubRepository:l.githubRepository,gitlabProjectPath:l.gitlabProjectPath,gitBranchName:l.gitBranchName}});return {...s,...a,...c}},context:r})}async function MQ(e){try{let t=await ST(e).remote(["show","origin"]);return t?t.match(/HEAD branch: (.*)$/m)?.[1]?.trim():void 0}catch{return}}async function NQ(){try{return (await pn.revparse(["--is-inside-work-tree"])).trim()==="true"}catch{return false}}var cD=new Map;async function O_e(e,t,n){let o,r;try{[o,r]=await Promise.all([gn(e,pn.raw(["symbolic-ref","--short","-q","HEAD"]).then(a=>a.trim())),gn(e,pn.revparse(["--verify","HEAD"]).then(a=>a.trim()))]);}catch{return}if(!o||!r)return;let i=`${t.configFilePath}:${t.config.gitMainBranch}:${t.config.gitProtectedBranches?.join(",")}`,s=`${n?.includeHostingUsername}`;return `${o}:${r}:${i}:${s}`}async function ri(e,t,n,o){let r=await O_e(e,n,o);if(r&&cD.has(r))return e.debug("Using cached git metadata"),cD.get(r);let i=await P_e(e,t,n,o);return r&&cD.set(r,i),i}var M_e=1024*1024;async function uw({cwd:e,baseRef:t="HEAD"}){let n=ST(await ff(e)),[o,r]=await Promise.all([n.diff(["--name-only","--diff-filter=ACDMRTUXB",t,"--"]),n.raw(["ls-files","--others","--exclude-standard"])]);return N_e(mw([...LQ(o),...LQ(r)]))}function N_e(e){return e.filter(mD)}function mD(e){let t=tl.basename(e);return e.endsWith(".test.yaml")||e.endsWith(".module.yaml")||t===pc||t===yT}async function pw({cwd:e,paths:t,maxFileSizeBytes:n=M_e}){let o=await ff(e),r=[];for(let i of mw(t)){let s=BQ({repoRoot:o,relativePath:i});if(!mD(i))throw new Error(`Pull request path is not a Momentic file: ${i}`);let a=await promises.stat(s).catch(()=>{});if(!a){r.push({operation:"delete",path:i});continue}if(!a.isFile())throw new Error(`Cannot create pull request change for non-file path: ${i}`);if(a.size>n)throw new Error(`Cannot create pull request change for oversized file: ${i}`);let l=await promises.readFile(s,"utf8");if(l.includes("\0"))throw new Error(`Cannot create pull request change for binary file: ${i}`);r.push({operation:"upsert",path:i,content:l});}return r}async function kQ({cwd:e}){let t=await ff(e),n=await promises.mkdtemp(tl.join(pD.tmpdir(),"momentic-git-snapshot-"));try{let o=ST(t).env("GIT_INDEX_FILE",tl.join(n,"index"));return await o.raw(["read-tree","HEAD"]),await o.raw(["add","-A","--"]),(await o.raw(["write-tree"])).trim()}finally{await promises.rm(n,{recursive:true,force:true});}}async function gf({cwd:e,paths:t,baseRef:n="HEAD",maxFileSizeBytes:o}){let r=await ff(e),i=mw(t??await uw({cwd:r,baseRef:n}));if(i.length===0)return "";let a=(await pw({cwd:r,paths:i,maxFileSizeBytes:o})).filter(c=>c.operation==="upsert").map(c=>c.path),l=await promises.mkdtemp(tl.join(pD.tmpdir(),"momentic-git-patch-"));try{let c=ST(r).env("GIT_INDEX_FILE",tl.join(l,"index"));return await c.raw(["read-tree",n]),a.length>0&&await c.raw(["add","--intent-to-add","--",...a]),await c.raw(["diff","--binary","--",...i])}finally{await promises.rm(l,{recursive:true,force:true});}}async function DQ({cwd:e,patch:t}){let n=await ff(e),o=await promises.mkdtemp(tl.join(pD.tmpdir(),"momentic-git-apply-")),r=tl.join(o,"heal.patch");try{await promises.writeFile(r,t,"utf8");let i=ST(n),s=L_e(await i.raw(["apply","--numstat","-z","--",r]));if(s.length===0)throw new Error("Cannot apply an empty heal patch.");for(let a of s)if(BQ({repoRoot:n,relativePath:a}),!mD(a))throw new Error(`Heal patch path is not a Momentic file: ${a}`);return await i.raw(["apply","--check","--",r]),await i.raw(["apply","--",r]),s}finally{await promises.rm(o,{recursive:true,force:true});}}async function FQ({cwd:e,paths:t,baseBranch:n,baseCommitSha:o,headBranch:r,branchPrefix:i,idempotencyKey:s,commitMessage:a,title:l,body:c,reviewers:d,draft:u,coAuthorRange:p,requestCommitAuthorsAsReviewers:m,maxFileSizeBytes:h}){let g=await ff(e),f=await pw({cwd:g,paths:t??await uw({cwd:g,baseRef:o}),maxFileSizeBytes:h}),y=n??await PQ(g);if(!y)throw new ke(`Cannot determine base branch because git is not usable in '${g}'.`);let S=o??await _Q(g);if(!S)throw new ke(`Cannot determine base commit SHA because git is not usable in '${g}'.`);return {baseBranch:y,baseCommitSha:S,headBranch:r,branchPrefix:i,idempotencyKey:s,commitMessage:a,title:l,body:c,changes:f,reviewers:d,draft:u,coAuthorRange:p,requestCommitAuthorsAsReviewers:m}}function LQ(e){return e?e.split(`
260
- `).filter(t=>t.length>0):[]}function mw(e){return [...new Set(e)]}function L_e(e){let t=e.split("\0"),n=[];for(let o=0;o<t.length;o++){let r=t[o];if(!r)continue;let i=r.split(" ");if(i.length<3)throw new Error("Cannot determine files touched by heal patch.");let s=i.slice(2).join(" ");if(s){n.push(s);continue}let a=t[++o],l=t[++o];if(!a||!l)throw new Error("Cannot determine renamed files touched by heal patch.");n.push(a,l);}return mw(n)}async function ff(e){let t=await Ed(e);if(!t)throw new ke(`Cannot find a git repository at '${e}'. Install git and run this from inside a git worktree.`);return t}function BQ({repoRoot:e,relativePath:t}){if(!t||tl.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let n=tl.resolve(e),o=tl.resolve(n,t);if(o!==n&&!o.startsWith(`${n}${tl.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var UQ=new Set([".DS_Store","__MACOSX"]),HQ={status:(e,t)=>{if(e.status===t.status)return e.status;if(e.status==="FAILED"||t.status==="FAILED")return "FAILED";if(e.status==="CANCELLED"||t.status==="CANCELLED")return "CANCELLED";if(e.status==="RETRYING"||t.status==="RETRYING")return "RETRYING";if(e.status==="RUNNING"||t.status==="RUNNING")return "RUNNING";if(e.status==="PENDING"||t.status==="PENDING")return "PENDING";throw new Error(`Invalid run status merge: ${e.status} and ${t.status}`)},startedAt:(e,t)=>e.startedAt<t.startedAt?e.startedAt:t.startedAt,updatedAt:(e,t)=>e.updatedAt>t.updatedAt?e.updatedAt:t.updatedAt,finishedAt:(e,t)=>!e.finishedAt||!t.finishedAt?new Date:e.finishedAt>t.finishedAt?e.finishedAt:t.finishedAt,gitCommitTimestamp:(e,t)=>{if(!(!e&&!t)){if(!e.gitCommitTimestamp||!t.gitCommitTimestamp||e.gitCommitTimestamp.getTime()!==t.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${e.gitCommitTimestamp} and ${t.gitCommitTimestamp}`);return e.gitCommitTimestamp}},pipelineId:(e,t)=>e.pipelineId===t.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:e.startedAt<t.startedAt?t.pipelineId:e.pipelineId,labels:(e,t)=>{let n=new Set([...e.labels??[],...t.labels??[]]);return Array.from(n)},ai:(e,t)=>e.ai??t.ai,browser:(e,t)=>e.browser??t.browser,aiSelect:(e,t)=>{let n=[...e.aiSelect??[],...t.aiSelect??[]];return n.length>0?n:void 0},healRiskSummary:()=>{}};function D_e(e,t,n){if(HQ[n]){let i=HQ[n];return i(e,t)}let o=e[n],r=t[n];if(o===void 0)return r;if(r===void 0)return o;if(o!==r)throw new Error(`Metadata values for key "${n}" do not match: "${o}" vs "${r}"`);return o}var hD=class extends Error{constructor(t,n){let o=`${t} contains invalid Momentic results: ${n}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(o),this.name="InvalidMomenticResultsPathError";}};function GQ(e,t){try{let n=Jn__default.join(t,ct);return ua.parse(JSON.parse(Oo__default.readFileSync(n,"utf-8")))}catch{throw new hD(e,t)}}function jQ(e,t,n){let o=randomUUID(),r=e.child({runGroupId:o});Oo__default.rmSync(t,{recursive:true,force:true});let i=Oo__default.readdirSync(n).filter(l=>!UQ.has(l)).map(l=>Jn__default.join(n,l));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);Oo__default.mkdirSync(t,{recursive:true});let s={...GQ(n,i[0]),id:o,healRiskSummary:void 0,aiSelect:void 0};for(let l of i){let c=Jn__default.join(l,to);if(!Oo__default.existsSync(c))continue;let d=GQ(n,l);r.info({oldRunGroupId:d.id},"Merging run groups");for(let p in d){if(p==="id")continue;let m=p;s[m]=D_e(s,d,m);}let u=Oo__default.readdirSync(c);for(let p of u){if(UQ.has(p))continue;let m=Jn__default.join(c,p),h=Jn__default.join(t,to,p);Oo__default.cpSync(m,h,{recursive:true});}}let a=Jn__default.join(t,ct);Oo__default.writeFileSync(a,JSON.stringify(s,null,2));}var fe="v1",gD="cli",Tm="3.16.2";var F_e=9e4,B_e=3,U_e=1500,H_e=15e3,no=class extends Error{status;rawError;constructor(t,n,o,r={}){super(o,r),this.status=t,this.rawError=n;}},fD=class extends ke{constructor(t,n={}){super(t,n),this.name="PlanLimitExceededError";}};async function G_e(e){return e.text().then(t=>{try{return JSON.parse(t).error}catch{return t}})}var yD=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(){let t={"Content-Type":"application/json"};return (t[sv]=Tm),(t[U2]=gD),t}async sendRequest(t,n){let{retries:o=B_e,requestTimeoutMs:r=F_e,initialRetryDelayMs:i=U_e,maxRetryDelayMs:s=H_e,onFailedRequest:a}=n,l=o,c=o,d,u={path:t,baseUrl:this.baseUrl,method:n.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(t,n,r)}catch(p){d=p;try{a?.(d);}catch{}if(p instanceof no&&p.status>=400&&p.status<500)throw p.status===402?new fD(p.rawError,{cause:p}):p;if(p instanceof Error&&p.name==="AbortError"&&(d=new vu),l===0)throw d;let m=c-l,h=Math.min(i*Math.pow(2,m-1),s);await new Promise(g=>setTimeout(g,h));}throw this.logger.warn({...u,err:d},"Got fatal error response from Momentic server"),d}async sendSingleRequestHelper(t,n,o){let r={path:t,baseUrl:this.baseUrl,method:n.method},i=new AbortController,s=setTimeout(()=>i.abort(),o),a=()=>i.abort();n.signal&&n.signal.addEventListener("abort",a,{once:true});let l=Date.now(),c={...this.getHeaders(),...n.extraHeaders};try{let d=await fetch(`${this.baseUrl}${t}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:c,signal:i.signal});if(!d.ok){let m=await G_e(d);throw new no(d.status,m,`Request to ${n.method} ${t} failed with status ${d.status}: ${m}`)}let u;if(d.status===204)u={};else if(n.responseType==="buffer"){let m=await d.arrayBuffer();u=Buffer.from(m);}else {let m=await d.text();try{u=JSON.parse(m);}catch{u=m;}}this.logger&&n.logResponse===!0&&u&&this.logger.debug({result:u,status:d.status,durationMs:Date.now()-l,...r},"Got response from Momentic server");let p=n.responseHeadersObject;return p&&d.headers.forEach((m,h)=>{p[h.toLowerCase()]=m;}),u}finally{clearTimeout(s),n.signal&&n.signal.removeEventListener("abort",a);}}},Fi=class extends yD{apiKey;mode;runner;constructor(t){super(t),this.apiKey=t.apiKey,this.mode=t.mode,this.runner=t.runner;}getHeaders(){return {...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[B2]:this.mode,[av]:this.runner}}};var hw=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line;}};function SD(e){}function $Q(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=SD,onError:n=SD,onRetry:o=SD,onComment:r}=e,i="",s=true,a,l="",c="";function d(g){let f=s?g.replace(/^\xEF\xBB\xBF/,""):g,[y,S]=j_e(`${i}${f}`);for(let T of y)u(T);i=S,s=false;}function u(g){if(g===""){m();return}if(g.startsWith(":")){r&&r(g.slice(g.startsWith(": ")?2:1));return}let f=g.indexOf(":");if(f!==-1){let y=g.slice(0,f),S=g[f+1]===" "?2:1,T=g.slice(f+S);p(y,T,g);return}p(g,"",g);}function p(g,f,y){switch(g){case "event":c=f;break;case "data":l=`${l}${f}
260
+ `).filter(t=>t.length>0):[]}function mw(e){return [...new Set(e)]}function L_e(e){let t=e.split("\0"),n=[];for(let o=0;o<t.length;o++){let r=t[o];if(!r)continue;let i=r.split(" ");if(i.length<3)throw new Error("Cannot determine files touched by heal patch.");let s=i.slice(2).join(" ");if(s){n.push(s);continue}let a=t[++o],l=t[++o];if(!a||!l)throw new Error("Cannot determine renamed files touched by heal patch.");n.push(a,l);}return mw(n)}async function ff(e){let t=await Ed(e);if(!t)throw new ke(`Cannot find a git repository at '${e}'. Install git and run this from inside a git worktree.`);return t}function BQ({repoRoot:e,relativePath:t}){if(!t||tl.isAbsolute(t)||t.includes("\0"))throw new Error(`Unsafe pull request path: ${t}`);let n=tl.resolve(e),o=tl.resolve(n,t);if(o!==n&&!o.startsWith(`${n}${tl.sep}`))throw new Error(`Pull request path escapes repository root: ${t}`);return o}var UQ=new Set([".DS_Store","__MACOSX"]),HQ={status:(e,t)=>{if(e.status===t.status)return e.status;if(e.status==="FAILED"||t.status==="FAILED")return "FAILED";if(e.status==="CANCELLED"||t.status==="CANCELLED")return "CANCELLED";if(e.status==="RETRYING"||t.status==="RETRYING")return "RETRYING";if(e.status==="RUNNING"||t.status==="RUNNING")return "RUNNING";if(e.status==="PENDING"||t.status==="PENDING")return "PENDING";throw new Error(`Invalid run status merge: ${e.status} and ${t.status}`)},startedAt:(e,t)=>e.startedAt<t.startedAt?e.startedAt:t.startedAt,updatedAt:(e,t)=>e.updatedAt>t.updatedAt?e.updatedAt:t.updatedAt,finishedAt:(e,t)=>!e.finishedAt||!t.finishedAt?new Date:e.finishedAt>t.finishedAt?e.finishedAt:t.finishedAt,gitCommitTimestamp:(e,t)=>{if(!(!e&&!t)){if(!e.gitCommitTimestamp||!t.gitCommitTimestamp||e.gitCommitTimestamp.getTime()!==t.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${e.gitCommitTimestamp} and ${t.gitCommitTimestamp}`);return e.gitCommitTimestamp}},pipelineId:(e,t)=>e.pipelineId===t.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:e.startedAt<t.startedAt?t.pipelineId:e.pipelineId,labels:(e,t)=>{let n=new Set([...e.labels??[],...t.labels??[]]);return Array.from(n)},ai:(e,t)=>e.ai??t.ai,browser:(e,t)=>e.browser??t.browser,aiSelect:(e,t)=>{let n=[...e.aiSelect??[],...t.aiSelect??[]];return n.length>0?n:void 0},healRiskSummary:()=>{}};function D_e(e,t,n){if(HQ[n]){let i=HQ[n];return i(e,t)}let o=e[n],r=t[n];if(o===void 0)return r;if(r===void 0)return o;if(o!==r)throw new Error(`Metadata values for key "${n}" do not match: "${o}" vs "${r}"`);return o}var hD=class extends Error{constructor(t,n){let o=`${t} contains invalid Momentic results: ${n}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(o),this.name="InvalidMomenticResultsPathError";}};function GQ(e,t){try{let n=Jn__default.join(t,ct);return ua.parse(JSON.parse(Oo__default.readFileSync(n,"utf-8")))}catch{throw new hD(e,t)}}function jQ(e,t,n){let o=randomUUID(),r=e.child({runGroupId:o});Oo__default.rmSync(t,{recursive:true,force:true});let i=Oo__default.readdirSync(n).filter(l=>!UQ.has(l)).map(l=>Jn__default.join(n,l));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);Oo__default.mkdirSync(t,{recursive:true});let s={...GQ(n,i[0]),id:o,healRiskSummary:void 0,aiSelect:void 0};for(let l of i){let c=Jn__default.join(l,to);if(!Oo__default.existsSync(c))continue;let d=GQ(n,l);r.info({oldRunGroupId:d.id},"Merging run groups");for(let p in d){if(p==="id")continue;let m=p;s[m]=D_e(s,d,m);}let u=Oo__default.readdirSync(c);for(let p of u){if(UQ.has(p))continue;let m=Jn__default.join(c,p),h=Jn__default.join(t,to,p);Oo__default.cpSync(m,h,{recursive:true});}}let a=Jn__default.join(t,ct);Oo__default.writeFileSync(a,JSON.stringify(s,null,2));}var fe="v1",gD="cli",Tm="3.16.3";var F_e=9e4,B_e=3,U_e=1500,H_e=15e3,no=class extends Error{status;rawError;constructor(t,n,o,r={}){super(o,r),this.status=t,this.rawError=n;}},fD=class extends ke{constructor(t,n={}){super(t,n),this.name="PlanLimitExceededError";}};async function G_e(e){return e.text().then(t=>{try{return JSON.parse(t).error}catch{return t}})}var yD=class{baseUrl;logger;constructor(t){this.baseUrl=t.baseUrl,this.logger=t.logger;}getHeaders(){let t={"Content-Type":"application/json"};return (t[sv]=Tm),(t[U2]=gD),t}async sendRequest(t,n){let{retries:o=B_e,requestTimeoutMs:r=F_e,initialRetryDelayMs:i=U_e,maxRetryDelayMs:s=H_e,onFailedRequest:a}=n,l=o,c=o,d,u={path:t,baseUrl:this.baseUrl,method:n.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(t,n,r)}catch(p){d=p;try{a?.(d);}catch{}if(p instanceof no&&p.status>=400&&p.status<500)throw p.status===402?new fD(p.rawError,{cause:p}):p;if(p instanceof Error&&p.name==="AbortError"&&(d=new vu),l===0)throw d;let m=c-l,h=Math.min(i*Math.pow(2,m-1),s);await new Promise(g=>setTimeout(g,h));}throw this.logger.warn({...u,err:d},"Got fatal error response from Momentic server"),d}async sendSingleRequestHelper(t,n,o){let r={path:t,baseUrl:this.baseUrl,method:n.method},i=new AbortController,s=setTimeout(()=>i.abort(),o),a=()=>i.abort();n.signal&&n.signal.addEventListener("abort",a,{once:true});let l=Date.now(),c={...this.getHeaders(),...n.extraHeaders};try{let d=await fetch(`${this.baseUrl}${t}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:c,signal:i.signal});if(!d.ok){let m=await G_e(d);throw new no(d.status,m,`Request to ${n.method} ${t} failed with status ${d.status}: ${m}`)}let u;if(d.status===204)u={};else if(n.responseType==="buffer"){let m=await d.arrayBuffer();u=Buffer.from(m);}else {let m=await d.text();try{u=JSON.parse(m);}catch{u=m;}}this.logger&&n.logResponse===!0&&u&&this.logger.debug({result:u,status:d.status,durationMs:Date.now()-l,...r},"Got response from Momentic server");let p=n.responseHeadersObject;return p&&d.headers.forEach((m,h)=>{p[h.toLowerCase()]=m;}),u}finally{clearTimeout(s),n.signal&&n.signal.removeEventListener("abort",a);}}},Fi=class extends yD{apiKey;mode;runner;constructor(t){super(t),this.apiKey=t.apiKey,this.mode=t.mode,this.runner=t.runner;}getHeaders(){return {...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[B2]:this.mode,[av]:this.runner}}};var hw=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line;}};function SD(e){}function $Q(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=SD,onError:n=SD,onRetry:o=SD,onComment:r}=e,i="",s=true,a,l="",c="";function d(g){let f=s?g.replace(/^\xEF\xBB\xBF/,""):g,[y,S]=j_e(`${i}${f}`);for(let T of y)u(T);i=S,s=false;}function u(g){if(g===""){m();return}if(g.startsWith(":")){r&&r(g.slice(g.startsWith(": ")?2:1));return}let f=g.indexOf(":");if(f!==-1){let y=g.slice(0,f),S=g[f+1]===" "?2:1,T=g.slice(f+S);p(y,T,g);return}p(g,"",g);}function p(g,f,y){switch(g){case "event":c=f;break;case "data":l=`${l}${f}
261
261
  `;break;case "id":a=f.includes("\0")?void 0:f;break;case "retry":/^\d+$/.test(f)?o(parseInt(f,10)):n(new hw(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:y}));break;default:n(new hw(`Unknown field "${g.length>20?`${g.slice(0,20)}\u2026`:g}"`,{type:"unknown-field",field:g,value:f,line:y}));break}}function m(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
262
262
  `)?l.slice(0,-1):l}),a=void 0,l="",c="";}function h(g={}){i&&g.consume&&u(i),s=true,a=void 0,l="",c="",i="";}return {feed:d,reset:h}}function j_e(e){let t=[],n="",o=0;for(;o<e.length;){let r=e.indexOf("\r",o),i=e.indexOf(`
263
263
  `,o),s=-1;if(r!==-1&&i!==-1?s=Math.min(r,i):r!==-1?s=r:i!==-1&&(s=i),s===-1){n=e.slice(o);break}else {let a=e.slice(o,s);t.push(a),o=s+1,e[o-1]==="\r"&&e[o]===`
@@ -289,7 +289,7 @@ ${t}:`]}}function Z5({id:e,model:t,created:n}){return {id:e??void 0,modelId:t??v
289
289
 
290
290
  `,mLe=1e4,TZ=O__default.object({stream:O__default.boolean().optional(),type:O__default.literal("response.create").optional()}).passthrough(),hLe=TZ.extend({stream:O__default.literal(true)});function AZ(e={}){let t=new eF(e);return async(n,o)=>{if(!yLe(n,o))return fetch(n,o);let r=await gLe(o?.body);if(!r)return fetch(n,o);let i=hLe.safeParse(r);return i.success?t.fetch({httpUrl:EZ(n),init:o,request:i.data}):fetch(n,o)}}var eF=class{constructor(t){this.options=t;}websocket;openPromise;latestResponseId;previousFullInput;pendingRequest;async fetch({httpUrl:t,init:n,request:o}){if(this.pendingRequest)return fetch(t,n);let r=await this.open({httpUrl:t,init:n}),i=new ReadableStream({start:s=>{let a={controller:s,fullRequest:o,sentContinuation:false,startedStreaming:false,retryingFullContext:false};this.pendingRequest=a,this.sendRequest({websocket:r,pendingRequest:a});},cancel:()=>{this.websocket?.close(),this.websocket=void 0,this.openPromise=void 0,this.latestResponseId=void 0,this.previousFullInput=void 0,this.pendingRequest=void 0;}});return new Response(i,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform"}})}async open({httpUrl:t,init:n}){return this.websocket?.readyState===ZD.OPEN?this.websocket:this.openPromise?this.openPromise:(this.openPromise=new Promise((o,r)=>{let i=new ZD(SLe(t),{headers:bLe(n?.headers)}),s=setTimeout(()=>{i.terminate(),r(new Error("Timed out opening OpenAI responses websocket"));},mLe);i.once("open",()=>{clearTimeout(s),this.websocket=i,this.openPromise=void 0,o(i);}),i.once("error",a=>{clearTimeout(s),this.resetConnection(),r(a);}),i.on("close",()=>{this.resetConnection();}),i.on("message",a=>{this.handleMessage(a);});}),this.openPromise)}sendRequest({websocket:t,pendingRequest:n}){let o=this.buildPayload(n.fullRequest);n.sentContinuation=!!o.previous_response_id,t.send(JSON.stringify(o));}buildPayload(t){let{background:n,stream:o,...r}=t,i={...r,type:"response.create"};ELe({payload:i,compactThreshold:this.options.compactThreshold});let s=Array.isArray(t.input)?t.input:void 0,a=this.latestResponseId&&s&&this.previousFullInput?TLe({currentInput:s,previousInput:this.previousFullInput}):void 0;return a&&a.length>0?(i.input=a,i.previous_response_id=this.latestResponseId,i):(delete i.previous_response_id,i)}handleMessage(t){let n=this.pendingRequest;if(!n)return;let o=vLe(t),r;try{r=JSON.parse(o);}catch(a){n.controller.error(a),this.pendingRequest=void 0,this.websocket?.close();return}let i=rW.safeParse(r),s=i.success?i.data:void 0;if(CLe(s)&&n.sentContinuation&&!n.startedStreaming&&!n.retryingFullContext&&this.websocket?.readyState===ZD.OPEN){this.latestResponseId=void 0,this.previousFullInput=void 0,n.retryingFullContext=true,n.sentContinuation=false;let a=this.buildPayload(n.fullRequest);delete a.previous_response_id,this.websocket.send(JSON.stringify(a));return}if(n.startedStreaming=true,n.controller.enqueue(RLe(o)),s?.type==="response.completed"){this.latestResponseId=s.response.id,this.previousFullInput=Array.isArray(n.fullRequest.input)?n.fullRequest.input:void 0,this.closePendingRequest();return}s?.type==="error"&&(this.latestResponseId=void 0,this.previousFullInput=void 0,this.closePendingRequest());}closePendingRequest(){let t=this.pendingRequest;t&&(t.controller.enqueue(new TextEncoder().encode(pLe)),t.controller.close(),this.pendingRequest=void 0);}resetConnection(){this.websocket=void 0,this.openPromise=void 0,this.latestResponseId=void 0,this.previousFullInput=void 0;let t=this.pendingRequest;t&&(t.controller.error(new Error("OpenAI responses websocket connection closed")),this.pendingRequest=void 0);}};async function gLe(e){let t=await fLe(e);if(!t)return;let n=TZ.safeParse(JSON.parse(t));return n.success?n.data:void 0}async function fLe(e){if(typeof e=="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof Blob)return e.text();if(e instanceof ArrayBuffer)return new TextDecoder().decode(e);if(ArrayBuffer.isView(e))return new TextDecoder().decode(e)}function yLe(e,t){return (t?.method??(e instanceof Request?e.method:"GET")).toUpperCase()==="POST"&&EZ(e).endsWith("/responses")}function EZ(e){return e instanceof Request?e.url:e.toString()}function SLe(e){let t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function bLe(e){if(!e)return {};if(e instanceof Headers){let t={};return e.forEach((n,o)=>{t[o]=n;}),t}return Array.isArray(e)?Object.fromEntries(e):e}function TLe({currentInput:e,previousInput:t}){let n=0;for(;n<e.length&&n<t.length&&JSON.stringify(e[n])===JSON.stringify(t[n]);)n+=1;if(!(n<t.length))return e.slice(n).filter(ALe)}function ALe(e){return "role"in e&&e.role==="assistant"?false:"type"in e?e.type==="item_reference"||e.type==="reasoning"?false:e.type!=="function_call"&&e.type!=="custom_tool_call"&&e.type!=="local_shell_call":true}function ELe({payload:e,compactThreshold:t}){t&&(e.context_management=[{type:"compaction",compact_threshold:t}]);}function CLe(e){return e?.type==="error"&&e.code==="previous_response_not_found"}function vLe(e){return typeof e=="string"?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):Array.isArray(e)?Buffer.concat(e).toString("utf8"):e.toString("utf8")}function RLe(e){return new TextEncoder().encode(`data: ${e}
291
291
 
292
- `)}var ILe="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD",xLe=2e5;function Rf(e){let{apiKey:t,sessionId:n,loggerTags:o,runner:r,parentTraceId:i}=e,s={Authorization:`Bearer ${t}`,[sv]:Tm,...n&&{[G2]:n},...r&&{[av]:r},...i&&{[j2]:i},...o&&{[H2]:JSON.stringify(o)}};for(let[a,l]of Object.entries(s))s[a]=l.replace(/[\u0100-\uffff]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0"));return s}var CZ="bedrock/",vZ="azure/",RZ=e=>t=>{let n=Rf(e),o=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(CZ)?o=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(CZ.length))}`:t.startsWith(vZ)&&(o=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(vZ.length))}`),createAnthropic({baseURL:o,headers:n,apiKey:e.apiKey})(t)},wZ=e=>t=>{let n=Rf(e),o=e.useOpenAIResponsesWebSocket??false,r=o?e.openAIResponsesWebSocketCompactThreshold??_Le(process.env[ILe])??xLe:void 0;return vf({baseURL:`${e.baseUrl}/v1/llm/provider/openai/${t}`,headers:n,apiKey:e.apiKey,fetch:o?AZ({compactThreshold:r}):void 0})(t)},IZ=e=>t=>{let n=Rf(e);return vf({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:n,apiKey:e.apiKey})(t)},xZ=e=>t=>{let n=Rf(e);return vf({baseURL:`${e.baseUrl}/v1/llm/provider/azure/${t}`,headers:n,apiKey:e.apiKey})(t)};function tF(e){return t=>n=>{let o=Rf(t);return vf({baseURL:`${t.baseUrl}/v1/llm/provider/${e}/${n}`,headers:o,apiKey:t.apiKey}).chat(n)}}var _Z=tF("azure/deepseek"),PZ=tF("azure/kimi"),OZ=tF("fireworks/glm"),MZ=e=>t=>{let n=Rf(e);return HD({baseURL:`${e.baseUrl}/v1/llm/provider/vertex`,headers:n,apiKey:e.apiKey})(t)};function _Le(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}var lr=class extends Fi{agentConfig;constructor(t,n){let o={...og,...t};CC(o),super(n),this.agentConfig=o;}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(t,n){let o={...t,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/recommend-chunks-ai`,{method:"POST",body:o,signal:n.abortSignal});return FV.parse(r)}async rankChunksWithRag(t,n){let o=await this.sendRequest(`/${fe}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Tm,...t},signal:n.abortSignal});return DV.parse(o)}async getScreenshotFromS3(t){let n=await this.sendRequest(`/${fe}/s3/visual-diff-screenshot`,{method:"POST",body:{url:t}});return z$1.string().parse(n)}async getElementLocation(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,cacheBustReason:n.cacheBustReason,agentConfigVersion:this.agentConfig?.locator},r=await this.sendRequest(`/${fe}/web-agent/locate-element`,{method:"POST",body:o,signal:n.abortSignal});return z2.parse(r)}async getAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},r=await this.sendRequest(`/${fe}/web-agent/assertion`,{method:"POST",body:o,signal:n.abortSignal});return CN.parse(r)}async getLintStepResult(t,n){let o={...t,disableCache:!!n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/lint/step`,{method:"POST",body:o,signal:n.abortSignal});return V2.parse(r)}async getVisualAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},r=await this.sendRequest(`/${fe}/web-agent/visual-assertion`,{method:"POST",body:o,signal:n.abortSignal});return CN.parse(r)}async getAiActionCommand(t,n){let o=await this.sendRequest(`/${fe}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return $2.parse(o)}async getMultiturnAiActionCommand(t,n){return await this.sendRequest(`/${fe}/web-agent/ai-action/next-command`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(t,n){let o=await this.sendRequest(`/${fe}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return HO.parse(o)}async getReverseMappedDescription(t,n){let o=await this.sendRequest(`/${fe}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return W2.parse(o)}async getTextExtraction(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`/${fe}/web-agent/text-extraction`,{method:"POST",body:o,signal:n.abortSignal});return UO.parse(r)}async getPageSummary(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/page-summary`,{method:"POST",body:o,signal:n.abortSignal});return D$.parse(r)}async getSmartWaitingDecision(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/smart-waiting`,{method:"POST",body:o,signal:n.abortSignal});return F$.parse(r)}async getKnowledgeSuggestion(t,n){throw new Error("Knowledge suggestion generation is only available on InternalGenerator")}async getTestResultClassification(t,n){let o=await this.sendRequest(`/${fe}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return BE.parse(o)}async getExtractedKeywords(t,n){let o=await this.sendRequest(`/${fe}/web-agent/extract-keywords`,{method:"POST",body:t,signal:n.abortSignal});return YV.parse(o)}async getAutohealingProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return O$.parse(o)}async getFailureRecoveryProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return L$.parse(o)}async getFailureRecoveryPlan(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:n.abortSignal});return N$.parse(o)}async getIframeRegex(t,n){let o=await this.sendRequest(`/${fe}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return oj.parse(o)}createAgentTrace(t){let n=randomUUID(),{completionType:o,runId:r,orgId:i,logger:s}=t,a=async l=>{try{await this.sendRequest(`/${fe}/traces/result-classification`,{method:"POST",body:{id:n,completionType:o,input:{runId:r},...l,metadata:{orgId:i,runId:r,...l.metadata}}});}catch(c){s.warn({err:c},"Failed to upsert result classification trace");}};return a({}),{id:n,update:a}}getAnthropicModelFactory(t){return this.buildModelFactory(RZ,t)}getAnthropicBedrockModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`bedrock/${o}`)}getAnthropicFoundryModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`azure/${o}`)}getOpenAIModelFactory(t){let{sessionId:n,logger:o,streamType:r,useOpenAIResponsesWebSocket:i,parentTraceId:s}=t;return wZ({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...jt(o),promptType:r},sessionId:n,useOpenAIResponsesWebSocket:i,runner:this.runner,parentTraceId:s})}getXAIModelFactory(t){return this.buildModelFactory(IZ,t)}getAzureOpenAIModelFactory(t){return this.buildModelFactory(xZ,t)}getAzureDeepSeekModelFactory(t){return this.buildModelFactory(_Z,t)}getAzureKimiModelFactory(t){return this.buildModelFactory(PZ,t)}getFireworksGLMModelFactory(t){return this.buildModelFactory(OZ,t)}getVertexGeminiModelFactory(t){return this.buildModelFactory(MZ,t)}buildModelFactory(t,n){let{sessionId:o,logger:r,streamType:i,parentTraceId:s}=n;return t({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...jt(r),promptType:i},sessionId:o,runner:this.runner,parentTraceId:s})}};function Lw(e,t,n){return fetch(e,{method:"PUT",body:n,headers:{"Content-Type":t}})}var Dt=class extends Fi{getAppUrl(){return vg(this.baseUrl)}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${fe}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(n){throw n instanceof no?n.status>=400&&n.status<500?new Error(n.rawError,{cause:n}):new Error(`Momentic server error (HTTP ${n.status}). Please try again in a moment.`,{cause:n}):new Error(`Could not reach Momentic server at ${this.baseUrl}. Check your network connection. If you're on a restricted network (VPN, firewall, or proxy), you may need to whitelist Momentic's servers: https://momentic.ai/docs/environment/authentication#ip-whitelist`,{cause:n})}return aK.parse(t)}async getCliAnnouncements(){let t=await this.sendRequest(`/${fe}/announcements`,{method:"GET",retries:1,requestTimeoutMs:5e3});return PW.parse(t).announcements}async getQuotaStatus(){let t=await this.sendRequest(`/${fe}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return lK.parse(t)}async createRemoteBrowserConnection(t){let n=await this.sendRequest(`/${fe}/browsers/connection`,{method:"POST",body:{...t?.testId?{testId:t.testId}:{},...t?.testName?{testName:t.testName}:{},...t?.runId?{runId:t.runId}:{},...t?.attemptedProviders?{attemptedProviders:t.attemptedProviders}:{}},retries:3,requestTimeoutMs:1e4});return RK.parse(n)}async bulkGetRunStatus(t){let n=await this.sendRequest(`/${fe}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return nK.parse(n)}async getRunExport(t){let n=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4});return rK.parse(n)}async getResultClassificationCacheEntries(t){let n=await this.sendRequest(`/${fe}/result-classification-cache`,{method:"POST",body:t,retries:1,requestTimeoutMs:1e4});return NK.parse(n)}async createResultClassificationCacheEntries(t){await this.sendRequest(`/${fe}/result-classification-cache`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:1e4});}async saveRunClassification(t,n){await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadRunHealTraceZip(t,n){let o=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/heal-trace/upload-url`,{method:"POST",retries:3,requestTimeoutMs:1e4}),{uploadUrl:r}=cv.parse(o),i=await Lw(r,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload heal trace: ${await i.text()}`)}async saveRunHealMetadataBatch(t){await this.sendRequest(`/${fe}/runs/heal-metadata`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let n=await this.sendRequest(`/${fe}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return K2.parse(n)}async updateStepCaches(t,n){await this.sendRequest(`/${fe}/cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,n){await this.sendRequest(`/${fe}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return J2.parse(o)}async getSnapshotCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/snapshot-cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return X2.parse(o)}async deleteStepCacheEntry(t,n){await this.sendRequest(`/${fe}/cache/entry`,{method:"DELETE",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let n=await this.sendRequest(`/${fe}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return vN.parse(n)}cacheRouteForPlatform(t){switch(t){case "ANDROID":return "android-cache";case "IOS":return "ios-cache"}}async deleteMobileStepCacheEntry({platform:t,body:n,headers:o}){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:n,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,n){let o=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return vN.parse(o)}async updateMobileStepCaches(t){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t.platform)}`,{method:"PATCH",body:t.body,extraHeaders:t.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getMobileStepCacheForTest({platform:t,body:n,headers:o}){let r=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:n,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Q2[t](r)}async queueTests(t){let n=await this.sendRequest(`/${fe}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return q2.parse(n)}async uploadScreenshot(t){let n=await this.sendRequest(`/${fe}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return sK.parse(n)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${fe}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${fe}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let n={};return {data:await this.sendRequest(`/${fe}/on-demand-screenshots/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:n}),contentType:n["content-type"]??"image/jpeg"}}async getAllEnvironments(){let t=await this.sendRequest(`/${fe}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return cK.parse(t)}async acquireCacheLock(t,n){let o=await this.sendRequest(`/${fe}/result-cache/lock`,{method:"POST",body:t,signal:n,retries:3,requestTimeoutMs:3e4});return _K.parse(o)}async releaseCacheLock(t){await this.sendRequest(`/${fe}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${fe}/result-cache/entry`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(t){let n=await this.sendRequest(`/${fe}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return pK.parse(n)}async bulkGetRunGroupStatus(t){let n={runGroupIds:t},o=await this.sendRequest(`/${fe}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return _V.array().parse(o)}async getRunGroupWithRuns(t){try{let n=await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return PV.parse(n)}catch(n){if(n instanceof no&&n.status===404)return null;throw n}}async getRun(t){try{let n=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/metadata`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Qi.parse(n)}catch(n){if(n instanceof no&&n.status===404)return null;throw n}}async getRunsByCommit(t){let o=[];for(let r=1;;r++){let i=await this.listRuns({gitCommitSha:t,includeFailureDetails:true,limit:100,page:r});if(o.push(...i.runs.map(s=>({...s,test:null}))),i.runs.length<100||r>=i.pageCount)break}return o}async updateGithubPRHealRiskSummary(t,n){await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}/github-pr-heal-risk-summary`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadProposedSteps(t,n){try{await this.sendRequest(`/${fe}/test-fragments/`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});}catch(o){n.error({err:o},"Failed to upload proposed steps");}}async reportBillableEvents(t,n){try{await this.sendRequest(`/${fe}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4});}catch(o){t.error({err:o},"Failed to report billable event");}}async fetchTestFragment(t){let n=await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return mK.parse(n)}async patchTestFragment(t,n){await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,n){let o=await this.sendRequest(`/${fe}/results/tests/${t}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return hK.parse(o)}async listRuns(t){let n=await this.sendRequest(`/${fe}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return gK.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${fe}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return fK.parse(t)}async startProcessingResultsUpload(t,n){let o=await this.sendRequest(`/${fe}/results/uploads/${t}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return yK.parse(o)}async fetchIconKnowledgeBase(t){try{let n=await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return DK.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,n){try{await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});}catch(o){n.error({err:o},"Failed to save new icons to icon knowledge base");}}async retrieveKnowledgeBase({query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l,retries:c,signal:d},u){try{let p=await this.sendRequest(`/${fe}/knowledge-base/retrieve`,{method:"POST",body:{query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l},retries:c??3,requestTimeoutMs:5e3,signal:d});return Q$.parse(p)}catch(p){return u.warn({err:p},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let n=await this.sendRequest(`/${fe}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return XO.parse(n)}async getMergeBaseCommitFromGithub(t,n,o,r){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tb.parse(s)}async compareCommitsFromGithub({owner:t,repo:n,base:o,head:r}){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/compare?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zW.parse(s)}async getGithubFileContent({owner:t,repo:n,path:o,ref:r}){let i=new URLSearchParams;i.set("path",o),i.set("ref",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return WW.parse(s).content??void 0}async getGithubBranchMetadata(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/branch-metadata?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return qW.parse(i)}async createGithubPullRequest(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return jW.parse(r)}async createGithubCommit(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return $W.parse(r)}async getGithubPullRequestTemplate(t,n){try{let o=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YW.parse(o).template}catch(o){if(o instanceof no&&o.status===404)return;throw o}}async getGithubPullRequestForBranch(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i;try{i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof no&&s.status===404)return;throw s}return VW.parse(i)}async getCommitFromGithub(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tb.parse(r)}async getMergedBranchFromGithub(t,n,o,r){let i=encodeURIComponent(o),s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wN.parse(s)}async getMergeBaseCommitFromGitlab(t,n,o){let r=new URLSearchParams;r.set("base",n),r.set("head",o);let i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Tb.parse(s)}async getGitlabMergeRequestForBranch(t,n){let o=new URLSearchParams;o.set("branch",n);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${fe}/git/gitlab/${r}/merge-requests?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof no&&s.status===404)return;throw s}return KW.parse(i)}async getCommitFromGitlab(t,n){let o=encodeURIComponent(t),r=await this.sendRequest(`/${fe}/git/gitlab/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tb.parse(r)}async getMergedBranchFromGitlab(t,n,o){let r=encodeURIComponent(n),i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/${r}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wN.parse(s)}async getAgentConfig(){let t=await this.sendRequest(`/${fe}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return z$1.record(z$1.string(),z$1.string()).parse(t)}async getOrgSettings(){try{let t=await this.sendRequest(`/${fe}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return yV(t)}catch(t){if(t instanceof no&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),tg.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${fe}/quarantine`,{method:"GET"});return SK.parse(t)}async sendExploreSlackNotification(t){await this.sendRequest(`/${fe}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async recordExplorerSuggestedTests(t){await this.sendRequest(`/${fe}/explore/suggested-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine`,{method:"POST",body:{testId:t.id,testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}async unquarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine/${t.id}`,{method:"DELETE",body:{testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}platformRoute(t){switch(t){case "ANDROID":return "android";case "IOS":return "ios"}}async createAndroidEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/android`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return TK.parse(n)}async extendEmulatorTtl(t,n){try{await this.sendRequest(`/${fe}/limbar/${this.platformRoute(t)}/${n}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3});}catch{}}async generateAssetUploadUrl({channel:t,tag:n,md5:o,platform:r}){let i={channel:t,tag:n,md5:o},s=await this.sendRequest(`/${fe}/limbar/${this.platformRoute(r)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:true});return EK.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(`/${fe}/limbar/android/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(`/${fe}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return CK.parse(t)}async getLimbarAssetDownloadUrl(t,n,o){let r=await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return vK.parse(r)}async deleteAsset(t,n,o){await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/ios`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return AK.parse(n)}async deleteIosEmulator(t){await this.sendRequest(`/${fe}/limbar/ios/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let n=await this.sendRequest(`/${fe}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return vW.parse(n)}async generateMcpSessionTraceUploadUrl(t){let n=await this.sendRequest(`/${fe}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return cv.parse(n)}};async function wm(e){let t=process.versions.node,n=parseInt(t.split(".")[0]);(isNaN(n)||n<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${t}`);let o=await e.client.getAuthInfo();return R.debug("Got auth info from API"),o}var wd=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,n){await this.apiClient.reportBillableEvents(t,n);}};var Id=class extends Fi{generator;constructor(t,n){super(t),this.generator=n;}async runTemplateMatching(t,n={}){let o=await this.sendRequest(`/${fe}/web-agent/template-matching`,{method:"POST",body:t,signal:n?.signal});return rj.parse(o)}async constructIframeRegex(t,n={}){return this.generator.getIframeRegex(t,{abortSignal:n.signal,loggerTags:n.loggerTags})}};var wf=class{constructor(t,n){this.client=t;this.orgId=n;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return vg(t)}async acquireCacheLock(t,n){return this.client.acquireCacheLock(t,n)}async createOnDemandScreenshot(t,n,o){let{apiServerUrl:r}=await this.client.uploadOnDemandScreenshot({id:t,screenshot:n.toString("base64"),contentType:o});return {apiServerUrl:r,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${t}`,universalHandle:{id:t,contentType:o}}}async fetchOnDemandScreenshot(t){return this.client.fetchOnDemandScreenshot(t.id)}async releaseCacheLock(t){return this.client.releaseCacheLock(t)}async deleteCacheResult(t){return this.client.deleteCacheResult(t)}async setCacheResult(t){return this.client.setCacheResult(t)}async getCacheResult(t){return this.client.getCacheResult(t)}fetchIconKnowledgeBase(t){return this.client.fetchIconKnowledgeBase(t)}saveNewIcons(t,n){return this.client.saveNewIcons(t,n)}};var xd="v1",LLe=2e3,NZ="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",_d=class{httpClient;fakerInstance;supportsLease;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this),lease:this.leasePhoneNumber.bind(this),release:this.releasePhoneNumber.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this),create:this.createEmail.bind(this)};activeLeases=new Map;constructor(t){this.httpClient=t.httpClient,this.supportsLease=t.supportsLease??true,t.fakerSeed&&(this.fakerInstance=new Faker({locale:en$1}),this.fakerInstance.seed(t.fakerSeed));}async sendSms(t){return this.httpClient.sendRequest(`/${xd}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${xd}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof no?new Error(n.rawError):n})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(NZ);let n=await this.httpClient.sendRequest(`/${xd}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof no?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),o=OW.parse(n);return this.activeLeases.set(o.phoneNumber,{leaseToken:o.leaseToken}),o}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(NZ);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${xd}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to release phone number: ${n.message}`)})}async dispose(){let t=[...this.activeLeases.entries()];this.activeLeases.clear(),await Promise.allSettled(t.map(([n,{leaseToken:o}])=>_e(this.httpClient.sendRequest(`/${xd}/tools/sms/release`,{method:"POST",body:{phoneNumber:n,leaseToken:o}}),{milliseconds:LLe,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${xd}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${xd}/tools/email/fetchAll`,{method:"POST",body:t}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${xd}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${xd}/tools/email/create`,{method:"POST",body:{}}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to create email inbox: ${n.message}`)});return MW.parse(t)}};var kw=class{constructor(t){this.client=t;}async uploadResultsArchive(t){let{runGroupId:n,archive:o,persist:r}=t,{uploadUrl:i,id:s}=await this.client.generateTestResultsUploadUrl(),a=await Lw(i,"application/zip",o);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:l}=await this.client.startProcessingResultsUpload(s,{runGroupId:n,persist:r});return l}};function Pd({logger:e,orgId:t,client:n,gitMetadata:o,regenerateCache:r,alwaysSaveCache:i,noCache:s,isolateCachesByEnvironment:a=false,bustOldestCachePercentage:l}){return s?new pv:new oF(e,t,n,o,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:a})}var oF=class{constructor(t,n,o,r,i){this.orgId=n;this.client=o;let{regenerateCache:s,alwaysSaveCache:a,bustOldestCachePercentage:l,isolateCachesByEnvironment:c}=i,{gitBranchName:d,gitProtectedBranches:u}=r;t.info({options:i,gitBranchName:d,gitProtectedBranches:u},"Cache storage initialization options"),this.cacheHeaders=lv(r),this.isolateCachesByEnvironment=c,this.readCaches=!s;let p=d&&u.includes(d);a||!p?this.writeCaches=true:this.writeCaches=false,p||(this.bustOldestCachePercentage=l);}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:LN(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save step cache entries");}}async saveSnapshotCacheEntries({entries:t,logger:n}){if(t.length!==0){if(!this.writeCaches){n.debug("Skipping snapshot cache storage because branch is protected");return}try{await this.client.updateSnapshotCaches({entries:LN(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save snapshot cache entries");}}}async deleteStepCacheEntry({logger:t,testId:n,key:o,environment:r}){try{await this.client.deleteStepCacheEntry({testId:n,key:o,environment:this.isolateCachesByEnvironment?r:void 0},this.cacheHeaders);}catch(i){t.error({err:i},"Failed to delete step cache entry");}}async resolveStepCacheEntries(t){if(!this.readCaches){t.logger.debug("Skipping cache resolution because of regenerate flag");return}let n=t.useSnapshotIdentityCache?await this.tryRestoreStepIdsFromSnapshot(t):void 0,{steps:o,beforeSteps:r,afterSteps:i}=t.stepLists,s=await this.client.getStepCacheForTest({testId:t.testId,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);if(this.bustOldestCachePercentage!==void 0){let u=Object.entries(s).map(([h,g])=>({key:h,time:g.value.cache?.updatedAt?.getTime()??0}));u.sort((h,g)=>h.time-g.time);let p=u.length,m=Math.max(1,Math.floor(p*this.bustOldestCachePercentage/100));u.slice(0,m).forEach(({key:h})=>{delete s[h];}),t.logger.info({nCachesToBust:m,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:p},"Busted oldest caches");}let a={totalSteps:0,cacheKeysHit:[],cacheKeysMissed:[],uniqueKeysHit:[],cacheMissSamples:[]};for(let u of [o,r,i]){if(!u)continue;let p=ku({steps:u,stepCacheEntries:s,logger:t.logger});a.totalSteps+=p.totalSteps,a.cacheKeysHit.push(...p.cacheKeysHit),a.cacheKeysMissed.push(...p.cacheKeysMissed),a.uniqueKeysHit.push(...p.uniqueKeysHit),a.cacheMissSamples.push(...p.cacheMissSamples);}n&&DLe({cacheResolutionStats:a,logger:t.logger,restoredIdentity:n,schemaVersion:t.schemaVersion,testId:t.testId});let l=["platform:web","source:local",`fileFormat:${t.useSnapshotIdentityCache?"v2":"v1"}`,`snapshotIdentityCache:${t.useSnapshotIdentityCache}`,`orgId:${this.orgId}`,"cliVersion:3.16.2"];if(At.increment("step_cache_resolution",a.cacheKeysHit.length,[...l,"outcome:hit"]),At.increment("step_cache_resolution",a.cacheKeysMissed.length,[...l,"outcome:miss"]),At.increment("step_cache_resolution",a.totalSteps,[...l,"outcome:total"]),!this.writeCaches){t.logger.debug("Skipping cache last used at update because branch is protected");return}let{cachesToSave:c,snapshotCachesToSave:d}=await Yn({stepLists:t.stepLists,useSnapshotIdentityCache:t.useSnapshotIdentityCache,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});t.useSnapshotIdentityCache&&this.saveSnapshotCacheEntries({entries:d,logger:t.logger}),this.saveStepCacheEntries({entries:c,logger:t.logger});}async tryRestoreStepIdsFromSnapshot(t){try{return await this.restoreStepIdsFromSnapshot(t)}catch(n){t.logger.warn({err:n,testId:t.testId},"Failed to restore step ids from snapshot cache; proceeding without identity cache"),At.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:3.16.2","outcome:identity_restore_error"]);return}}async restoreStepIdsFromSnapshot(t){let{logger:n,testId:o}=t,r=await this.client.getSnapshotCacheForTest({testId:o,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);for(let a of r){if(!a.schema_version)continue;let l=XM(a.schema_version),c=XM(at);if(l&&c&&l.compare(c)>0){n.warn(`Snapshot cache for test ${o} was written at schema version ${a.schema_version}, which is newer than this CLI's latest (${at}). Please update your momentic package version. Skipping identity restoration from snapshot cache.`);return}}let i=FR({entries:r,orgId:this.orgId,testId:o,logger:n}),s=DR({currentStepLists:t.stepLists,previousSnapshot:i.testSnapshot,previousModuleSnapshots:i.moduleSnapshots,generateUuid:randomUUID});return t.stepLists.steps.splice(0,t.stepLists.steps.length,...s.stepLists.steps),t.stepLists.beforeSteps=s.stepLists.beforeSteps,t.stepLists.afterSteps=s.stepLists.afterSteps,n.debug({snapshotEntries:r.length,testSnapshotHit:!!i.testSnapshot,moduleSnapshots:Array.from(i.moduleSnapshots.keys()),mintedSteps:s.stats.mintedSteps,stats:s.stats,moduleRestoreResults:s.moduleRestoreResults.map(({moduleId:a,snapshotHit:l,stats:c})=>({moduleId:a,snapshotHit:l,stats:c}))},"Restored step ids from snapshot cache"),s}};function DLe({cacheResolutionStats:e,logger:t,restoredIdentity:n,schemaVersion:o,testId:r}){let i=e.cacheKeysHit.length,s=e.cacheKeysMissed.length,a=i+s,l=a>0?Math.round(s/a*1e3)/10:0,c=n.stats.matchedSteps+n.stats.mintedSteps,d=c>0?Math.round(n.stats.mintedSteps/c*1e3)/10:0,u=n.moduleRestoreResults.filter(({snapshotHit:g,stats:f})=>!g||f.mintedSteps>0||f.bustedConditionals>0).slice(0,10).map(({moduleId:g,snapshotHit:f,stats:y})=>({moduleId:g,snapshotHit:f,stats:y})),p=n.stats.mintedSteps>=5&&d>=25,m=p||n.stats.bustedConditionals>0||u.some(({stats:g})=>g.mintedSteps>=5||g.bustedConditionals>0),h={cacheHits:i,cacheMissRate:l,cacheMisses:s,cacheMissSamples:e.cacheMissSamples.slice(0,10),hasHighMintRate:p,identityMintRate:d,moduleIdentityIssueCount:u.length,moduleIdentityIssues:u,schemaVersion:o,snapshotIdentityCache:true,stepIdentityStats:n.stats,testId:r,totalCacheableSteps:e.totalSteps};if(!m){t.debug(h,"V2 cache resolution completed");return}t.warn(h,"V2 cache resolution degraded");}function FLe(e){let t=new WU,n=Jn__default.join(e,ct),o=ua.parse(JSON.parse(Oo__default.readFileSync(n,"utf-8")));t.addLocalFile(n);for(let r of Oo__default.readdirSync(Jn__default.join(e,to))){if(!r.endsWith(".zip"))continue;let i=r.replace(/\.zip$/,""),s=new WU(Jn__default.join(e,to,r));for(let a of s.getEntries())a.isDirectory||t.addFile(Jn__default.join(to,i,a.entryName),a.getData());}return {runGroupId:o.id,buffer:t.toBuffer()}}async function wT(e){let{client:t,resultsPath:n,persist:o}=e;if(!Oo__default.existsSync(n))return {success:false,error:"results path does not exist"};let r=new kw(t);try{let{runGroupId:i,buffer:s}=FLe(n),a=await r.uploadResultsArchive({runGroupId:i,archive:s,persist:o});return {success:!0,runGroupUrl:`${t.getAppUrl()}/run-groups/${a}`}}catch(i){return {success:false,error:X(i)}}}var BZ=101010256,iF=33639248,BLe=67324752,Fw=22,ULe=65535,Bw=4294967295,UZ=1024*1024;function Uw({zipPath:e,files:t,buffers:n}){let o=HZ(e);if(!o)return false;let{centralDirectory:r,cdOffset:i,entryCount:s}=o;if(GLe({centralDirectory:r,files:t,buffers:n}))return false;let a=Oo__default.openSync(e,"r+");try{let l=i,c=[];for(let p of t){let m=Oo__default.statSync(p.sourcePath);if(m.size>Bw||l+m.size>Bw)return !1;let h=jLe(p.sourcePath),g=Buffer.from(p.entryName,"utf-8"),f=kZ({nameBytes:g,crc:h,size:m.size});Oo__default.writeSync(a,f,0,f.length,l),c.push(DZ({nameBytes:g,crc:h,size:m.size,localHeaderOffset:l})),l+=f.length,l+=$Le(a,p.sourcePath,l);}for(let p of n){let m=Buffer.from(p.entryName,"utf-8"),h=FZ.crc32(p.data),g=kZ({nameBytes:m,crc:h,size:p.data.length});Oo__default.writeSync(a,g,0,g.length,l),c.push(DZ({nameBytes:m,crc:h,size:p.data.length,localHeaderOffset:l})),l+=g.length,Oo__default.writeSync(a,p.data,0,p.data.length,l),l+=p.data.length;}let d=l;Oo__default.writeSync(a,r,0,r.length,l),l+=r.length;for(let p of c)Oo__default.writeSync(a,p,0,p.length,l),l+=p.length;let u=VLe({entryCount:s+t.length+n.length,cdSize:l-d,cdOffset:d});return Oo__default.writeSync(a,u,0,u.length,l),Oo__default.ftruncateSync(a,l+u.length),!0}finally{Oo__default.closeSync(a);}}function HZ(e){let t=Oo__default.statSync(e).size,n=Math.min(t,Fw+ULe),o=Buffer.alloc(n),r=Oo__default.openSync(e,"r");try{Oo__default.readSync(r,o,0,n,t-n);let i=HLe(o);if(i<0)return;let s=o.readUInt16LE(i+10),a=o.readUInt16LE(i+8),l=o.readUInt32LE(i+12),c=o.readUInt32LE(i+16);if(o.readUInt16LE(i+4)!==0||s!==a||s===65535||l===Bw||c===Bw||c+l>t)return;let u=Buffer.alloc(l);return Oo__default.readSync(r,u,0,l,c),l>0&&u.readUInt32LE(0)!==iF?void 0:{centralDirectory:u,cdOffset:c,entryCount:s}}finally{Oo__default.closeSync(r);}}function HLe(e){for(let t=e.length-Fw;t>=0;t--){if(e.readUInt32LE(t)!==BZ)continue;let n=e.readUInt16LE(t+20);if(t+Fw+n===e.length)return t}return -1}function GZ(e){let t=HZ(e);return t&&jZ(t.centralDirectory)}function jZ(e){let t=[],n=0;for(;n+46<=e.length&&e.readUInt32LE(n)===iF;){let o=e.readUInt16LE(n+28),r=e.readUInt16LE(n+30),i=e.readUInt16LE(n+32);t.push(e.toString("utf-8",n+46,n+46+o)),n+=46+o+r+i;}return t}function GLe({centralDirectory:e,files:t,buffers:n}){let o=new Set(jZ(e));return t.some(r=>o.has(r.entryName))||n.some(r=>o.has(r.entryName))}function jLe(e){let t=Oo__default.openSync(e,"r");try{let n=Buffer.alloc(UZ),o=0,r;for(;(r=Oo__default.readSync(t,n,0,n.length,null))>0;)o=FZ.crc32(n.subarray(0,r),o);return o}finally{Oo__default.closeSync(t);}}function $Le(e,t,n){let o=Oo__default.openSync(t,"r");try{let r=Buffer.alloc(UZ),i=0,s;for(;(s=Oo__default.readSync(o,r,0,r.length,null))>0;)Oo__default.writeSync(e,r,0,s,n+i),i+=s;return i}finally{Oo__default.closeSync(o);}}function kZ({nameBytes:e,crc:t,size:n}){let o=Buffer.alloc(30+e.length);return o.writeUInt32LE(BLe,0),o.writeUInt16LE(20,4),o.writeUInt16LE(2048,6),o.writeUInt16LE(0,8),o.writeUInt32LE(0,10),o.writeUInt32LE(t>>>0,14),o.writeUInt32LE(n,18),o.writeUInt32LE(n,22),o.writeUInt16LE(e.length,26),o.writeUInt16LE(0,28),e.copy(o,30),o}function DZ({nameBytes:e,crc:t,size:n,localHeaderOffset:o}){let r=Buffer.alloc(46+e.length);return r.writeUInt32LE(iF,0),r.writeUInt16LE(20,4),r.writeUInt16LE(20,6),r.writeUInt16LE(2048,8),r.writeUInt16LE(0,10),r.writeUInt32LE(0,12),r.writeUInt32LE(t>>>0,16),r.writeUInt32LE(n,20),r.writeUInt32LE(n,24),r.writeUInt16LE(e.length,28),r.writeUInt16LE(0,30),r.writeUInt16LE(0,32),r.writeUInt16LE(0,34),r.writeUInt16LE(0,36),r.writeUInt32LE(0,38),r.writeUInt32LE(o,42),e.copy(r,46),r}function VLe({entryCount:e,cdSize:t,cdOffset:n}){let o=Buffer.alloc(Fw);return o.writeUInt32LE(BZ,0),o.writeUInt16LE(0,4),o.writeUInt16LE(0,6),o.writeUInt16LE(e,8),o.writeUInt16LE(e,10),o.writeUInt32LE(t,12),o.writeUInt32LE(n,16),o.writeUInt16LE(0,20),o}var IT=class e{constructor(t,n=true){this.filePath=t;n&&Oo__default.rmSync(this.filePath,{recursive:true,force:true}),Oo__default.mkdirSync(this.filePath,{recursive:true});}children=[];streams=[];close(){for(let t of this.children)t.close();for(let t of this.streams)t.end();}cd(t){let n=new e(Jn__default.join(this.filePath,t));return this.children.push(n),n}cwd(){return this.filePath}mkdir(t){Oo__default.mkdirSync(Jn__default.join(this.filePath,t),{recursive:true});}readFile(t){let n=Jn__default.join(this.filePath,t);if(Oo__default.existsSync(n))return Oo__default.readFileSync(n)}storeFile(t){let{name:n,contents:o}=t,r=Jn__default.join(this.filePath,n);try{Oo__default.mkdirSync(Jn__default.dirname(r),{recursive:!0}),Oo__default.writeFileSync(r,o);}catch{}}createFileStream(t){let n=Jn__default.join(this.filePath,t),o=Oo__default.createWriteStream(n);return this.streams.push(o),o}createRunArchive(t,n){let o=new sF(Jn__default.join(this.filePath,to),t,n);return this.children.push(o),o}},sF=class{children=[];tempPath;finalPath;logger;closed=false;constructor(t,n,o){this.tempPath=Jn__default.join(t,`temp-storage-${n}`),this.finalPath=Jn__default.join(t,`${n}.zip`),this.logger=o,Oo__default.rmSync(this.tempPath,{recursive:true,force:true}),Oo__default.rmSync(this.finalPath,{recursive:true,force:true}),Oo__default.mkdirSync(this.tempPath,{recursive:true});}readFile(t){let n=Jn__default.join(this.tempPath,t);if(Oo__default.existsSync(n))return Oo__default.readFileSync(n)}mkdir(t){Oo__default.mkdirSync(Jn__default.join(this.tempPath,t),{recursive:true});}cd(t){let n=new IT(Jn__default.join(this.tempPath,t));return this.children.push(n),n}cwd(){return this.tempPath}storeFile(t){if(this.closed)return;let{name:n,contents:o}=t,r=Jn__default.join(this.tempPath,n);Oo__default.mkdirSync(Jn__default.dirname(r),{recursive:true}),Oo__default.writeFileSync(r,o);}close(){if(!this.closed){this.closed=true;for(let t of this.children)t.close();try{let t=new WU;t.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store"&&!VZ(r));let n=t.toBuffer();Oo__default.writeFileSync(this.finalPath,n);let o=WLe(this.tempPath);if(o.length>0&&!Uw({zipPath:this.finalPath,files:o,buffers:[]})){let r=new WU(this.finalPath);for(let i of o)r.addLocalFile(i.sourcePath,i.entryName.split("/").slice(0,-1).join("/"));r.writeZip(this.finalPath);}Oo__default.rmSync(this.tempPath,{recursive:!0,force:!0});}catch(t){this.logger.warn({err:t,finalPath:this.finalPath,tempPath:this.tempPath},"Failed to archive run artifacts; leaving raw files on disk");}}}},zLe=[".webm",".mp4",".mov"];function VZ(e){let t=e.toLowerCase();return zLe.some(n=>t.endsWith(n))}function WLe(e){let t=[],n=Oo__default.readdirSync(e,{recursive:true,withFileTypes:true});for(let o of n){if(!o.isFile()||!VZ(o.name))continue;let r=Jn__default.join(o.parentPath,o.name),i=Jn__default.relative(e,r).split(Jn__default.sep).join("/");t.push({entryName:i,sourcePath:r});}return t}function KZ(e){try{return Oo__default.existsSync(e)?JSON.parse(Oo__default.readFileSync(e,"utf-8")):void 0}catch{return}}function zZ(e){return Oo__default.existsSync(e)?Oo__default.readFileSync(e,"utf-8").split(`
292
+ `)}var ILe="MOMENTIC_OPENAI_RESPONSES_WEBSOCKET_COMPACT_THRESHOLD",xLe=2e5;function Rf(e){let{apiKey:t,sessionId:n,loggerTags:o,runner:r,parentTraceId:i}=e,s={Authorization:`Bearer ${t}`,[sv]:Tm,...n&&{[G2]:n},...r&&{[av]:r},...i&&{[j2]:i},...o&&{[H2]:JSON.stringify(o)}};for(let[a,l]of Object.entries(s))s[a]=l.replace(/[\u0100-\uffff]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0"));return s}var CZ="bedrock/",vZ="azure/",RZ=e=>t=>{let n=Rf(e),o=`${e.baseUrl}/v1/llm/anthropic/${encodeURIComponent(t)}`;return t.startsWith(CZ)?o=`${e.baseUrl}/v1/llm/provider/bedrock/anthropic/${encodeURIComponent(t.slice(CZ.length))}`:t.startsWith(vZ)&&(o=`${e.baseUrl}/v1/llm/provider/foundry/anthropic/${encodeURIComponent(t.slice(vZ.length))}`),createAnthropic({baseURL:o,headers:n,apiKey:e.apiKey})(t)},wZ=e=>t=>{let n=Rf(e),o=e.useOpenAIResponsesWebSocket??false,r=o?e.openAIResponsesWebSocketCompactThreshold??_Le(process.env[ILe])??xLe:void 0;return vf({baseURL:`${e.baseUrl}/v1/llm/provider/openai/${t}`,headers:n,apiKey:e.apiKey,fetch:o?AZ({compactThreshold:r}):void 0})(t)},IZ=e=>t=>{let n=Rf(e);return vf({baseURL:`${e.baseUrl}/v1/llm/provider/xai/${t}`,headers:n,apiKey:e.apiKey})(t)},xZ=e=>t=>{let n=Rf(e);return vf({baseURL:`${e.baseUrl}/v1/llm/provider/azure/${t}`,headers:n,apiKey:e.apiKey})(t)};function tF(e){return t=>n=>{let o=Rf(t);return vf({baseURL:`${t.baseUrl}/v1/llm/provider/${e}/${n}`,headers:o,apiKey:t.apiKey}).chat(n)}}var _Z=tF("azure/deepseek"),PZ=tF("azure/kimi"),OZ=tF("fireworks/glm"),MZ=e=>t=>{let n=Rf(e);return HD({baseURL:`${e.baseUrl}/v1/llm/provider/vertex`,headers:n,apiKey:e.apiKey})(t)};function _Le(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}var lr=class extends Fi{agentConfig;constructor(t,n){let o={...og,...t};CC(o),super(n),this.agentConfig=o;}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(t,n){let o={...t,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/recommend-chunks-ai`,{method:"POST",body:o,signal:n.abortSignal});return FV.parse(r)}async rankChunksWithRag(t,n){let o=await this.sendRequest(`/${fe}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Tm,...t},signal:n.abortSignal});return DV.parse(o)}async getScreenshotFromS3(t){let n=await this.sendRequest(`/${fe}/s3/visual-diff-screenshot`,{method:"POST",body:{url:t}});return z$1.string().parse(n)}async getElementLocation(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,cacheBustReason:n.cacheBustReason,agentConfigVersion:this.agentConfig?.locator},r=await this.sendRequest(`/${fe}/web-agent/locate-element`,{method:"POST",body:o,signal:n.abortSignal});return z2.parse(r)}async getAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},r=await this.sendRequest(`/${fe}/web-agent/assertion`,{method:"POST",body:o,signal:n.abortSignal});return CN.parse(r)}async getLintStepResult(t,n){let o={...t,disableCache:!!n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/lint/step`,{method:"POST",body:o,signal:n.abortSignal});return V2.parse(r)}async getVisualAssertionResult(t,n){let o={...t,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},r=await this.sendRequest(`/${fe}/web-agent/visual-assertion`,{method:"POST",body:o,signal:n.abortSignal});return CN.parse(r)}async getAiActionCommand(t,n){let o=await this.sendRequest(`/${fe}/web-agent/next-command-dynamic`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return $2.parse(o)}async getMultiturnAiActionCommand(t,n){return await this.sendRequest(`/${fe}/web-agent/ai-action/next-command`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(t,n){let o=await this.sendRequest(`/${fe}/web-agent/ai-action/evaluate`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return HO.parse(o)}async getReverseMappedDescription(t,n){let o=await this.sendRequest(`/${fe}/web-agent/reverse-mapped-description`,{method:"POST",body:{...t,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return W2.parse(o)}async getTextExtraction(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},r=await this.sendRequest(`/${fe}/web-agent/text-extraction`,{method:"POST",body:o,signal:n.abortSignal});return UO.parse(r)}async getPageSummary(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/page-summary`,{method:"POST",body:o,signal:n.abortSignal});return D$.parse(r)}async getSmartWaitingDecision(t,n){let o={...t,disableCache:n.disableCache,loggerTags:n.loggerTags},r=await this.sendRequest(`/${fe}/web-agent/smart-waiting`,{method:"POST",body:o,signal:n.abortSignal});return F$.parse(r)}async getKnowledgeSuggestion(t,n){throw new Error("Knowledge suggestion generation is only available on InternalGenerator")}async getTestResultClassification(t,n){let o=await this.sendRequest(`/${fe}/web-agent/result-classification`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return BE.parse(o)}async getExtractedKeywords(t,n){let o=await this.sendRequest(`/${fe}/web-agent/extract-keywords`,{method:"POST",body:t,signal:n.abortSignal});return YV.parse(o)}async getAutohealingProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/autoheal-section`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return O$.parse(o)}async getFailureRecoveryProposal(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return L$.parse(o)}async getFailureRecoveryPlan(t,n){let o=await this.sendRequest(`/${fe}/web-agent/failure-recovery-plan`,{method:"POST",body:{...t,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["failure-recovery"]},signal:n.abortSignal});return N$.parse(o)}async getIframeRegex(t,n){let o=await this.sendRequest(`/${fe}/web-agent/iframe-regex`,{method:"POST",body:{...t,loggerTags:n.loggerTags},signal:n.abortSignal});return oj.parse(o)}createAgentTrace(t){let n=randomUUID(),{completionType:o,runId:r,orgId:i,logger:s}=t,a=async l=>{try{await this.sendRequest(`/${fe}/traces/result-classification`,{method:"POST",body:{id:n,completionType:o,input:{runId:r},...l,metadata:{orgId:i,runId:r,...l.metadata}}});}catch(c){s.warn({err:c},"Failed to upsert result classification trace");}};return a({}),{id:n,update:a}}getAnthropicModelFactory(t){return this.buildModelFactory(RZ,t)}getAnthropicBedrockModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`bedrock/${o}`)}getAnthropicFoundryModelFactory(t){let n=this.getAnthropicModelFactory(t);return o=>n(`azure/${o}`)}getOpenAIModelFactory(t){let{sessionId:n,logger:o,streamType:r,useOpenAIResponsesWebSocket:i,parentTraceId:s}=t;return wZ({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...jt(o),promptType:r},sessionId:n,useOpenAIResponsesWebSocket:i,runner:this.runner,parentTraceId:s})}getXAIModelFactory(t){return this.buildModelFactory(IZ,t)}getAzureOpenAIModelFactory(t){return this.buildModelFactory(xZ,t)}getAzureDeepSeekModelFactory(t){return this.buildModelFactory(_Z,t)}getAzureKimiModelFactory(t){return this.buildModelFactory(PZ,t)}getFireworksGLMModelFactory(t){return this.buildModelFactory(OZ,t)}getVertexGeminiModelFactory(t){return this.buildModelFactory(MZ,t)}buildModelFactory(t,n){let{sessionId:o,logger:r,streamType:i,parentTraceId:s}=n;return t({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:{...jt(r),promptType:i},sessionId:o,runner:this.runner,parentTraceId:s})}};function Lw(e,t,n){return fetch(e,{method:"PUT",body:n,headers:{"Content-Type":t}})}var Dt=class extends Fi{getAppUrl(){return vg(this.baseUrl)}async getAuthInfo(){let t;try{t=await this.sendRequest(`/${fe}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});}catch(n){throw n instanceof no?n.status>=400&&n.status<500?new Error(n.rawError,{cause:n}):new Error(`Momentic server error (HTTP ${n.status}). Please try again in a moment.`,{cause:n}):new Error(`Could not reach Momentic server at ${this.baseUrl}. Check your network connection. If you're on a restricted network (VPN, firewall, or proxy), you may need to whitelist Momentic's servers: https://momentic.ai/docs/environment/authentication#ip-whitelist`,{cause:n})}return aK.parse(t)}async getCliAnnouncements(){let t=await this.sendRequest(`/${fe}/announcements`,{method:"GET",retries:1,requestTimeoutMs:5e3});return PW.parse(t).announcements}async getQuotaStatus(){let t=await this.sendRequest(`/${fe}/billing/check-quota`,{method:"GET",retries:3,requestTimeoutMs:5e3});return lK.parse(t)}async createRemoteBrowserConnection(t){let n=await this.sendRequest(`/${fe}/browsers/connection`,{method:"POST",body:{...t?.testId?{testId:t.testId}:{},...t?.testName?{testName:t.testName}:{},...t?.runId?{runId:t.runId}:{},...t?.attemptedProviders?{attemptedProviders:t.attemptedProviders}:{}},retries:3,requestTimeoutMs:1e4});return RK.parse(n)}async bulkGetRunStatus(t){let n=await this.sendRequest(`/${fe}/runs/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return nK.parse(n)}async getRunExport(t){let n=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/export`,{method:"GET",retries:3,requestTimeoutMs:1e4});return rK.parse(n)}async getResultClassificationCacheEntries(t){let n=await this.sendRequest(`/${fe}/result-classification-cache`,{method:"POST",body:t,retries:1,requestTimeoutMs:1e4});return NK.parse(n)}async createResultClassificationCacheEntries(t){await this.sendRequest(`/${fe}/result-classification-cache`,{method:"PATCH",body:t,retries:1,requestTimeoutMs:1e4});}async saveRunClassification(t,n){await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/classification`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadRunHealTraceZip(t,n){let o=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/heal-trace/upload-url`,{method:"POST",retries:3,requestTimeoutMs:1e4}),{uploadUrl:r}=cv.parse(o),i=await Lw(r,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload heal trace: ${await i.text()}`)}async saveRunHealMetadataBatch(t){await this.sendRequest(`/${fe}/runs/heal-metadata`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4});}async getTestYAMLExport(t){let n=await this.sendRequest(`/${fe}/tests/export`,{method:"POST",body:t,retries:3,requestTimeoutMs:3e4});return K2.parse(n)}async updateStepCaches(t,n){await this.sendRequest(`/${fe}/cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async updateSnapshotCaches(t,n){await this.sendRequest(`/${fe}/snapshot-cache`,{method:"PATCH",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getStepCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return J2.parse(o)}async getSnapshotCacheForTest(t,n){let o=await this.sendRequest(`/${fe}/snapshot-cache`,{method:"POST",body:t,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return X2.parse(o)}async deleteStepCacheEntry(t,n){await this.sendRequest(`/${fe}/cache/entry`,{method:"DELETE",body:t,extraHeaders:n,retries:3,requestTimeoutMs:1e4});}async getWebStepCacheMemoryTraces(t){let n=await this.sendRequest(`/${fe}/cache/traces`,{method:"POST",body:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return vN.parse(n)}cacheRouteForPlatform(t){switch(t){case "ANDROID":return "android-cache";case "IOS":return "ios-cache"}}async deleteMobileStepCacheEntry({platform:t,body:n,headers:o}){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/entry`,{method:"DELETE",body:n,extraHeaders:o,retries:3,requestTimeoutMs:1e4});}async getMobileStepCacheMemoryTraces(t,n){let o=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}/traces`,{method:"POST",body:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return vN.parse(o)}async updateMobileStepCaches(t){await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t.platform)}`,{method:"PATCH",body:t.body,extraHeaders:t.headers,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3});}async getMobileStepCacheForTest({platform:t,body:n,headers:o}){let r=await this.sendRequest(`/${fe}/${this.cacheRouteForPlatform(t)}`,{method:"POST",body:n,extraHeaders:o,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Q2[t](r)}async queueTests(t){let n=await this.sendRequest(`/${fe}/tests/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return q2.parse(n)}async uploadScreenshot(t){let n=await this.sendRequest(`/${fe}/screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return sK.parse(n)}async uploadOnDemandScreenshot(t){return await this.sendRequest(`/${fe}/on-demand-screenshots`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3}),{apiServerUrl:`${this.baseUrl}/${fe}/on-demand-screenshots/${t.id}`}}async fetchOnDemandScreenshot(t){let n={};return {data:await this.sendRequest(`/${fe}/on-demand-screenshots/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:5e3,responseType:"buffer",responseHeadersObject:n}),contentType:n["content-type"]??"image/jpeg"}}async getAllEnvironments(){let t=await this.sendRequest(`/${fe}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return cK.parse(t)}async acquireCacheLock(t,n){let o=await this.sendRequest(`/${fe}/result-cache/lock`,{method:"POST",body:t,signal:n,retries:3,requestTimeoutMs:3e4});return _K.parse(o)}async releaseCacheLock(t){await this.sendRequest(`/${fe}/result-cache/lock`,{method:"DELETE",body:{key:t},retries:3,requestTimeoutMs:5e3});}async deleteCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"DELETE",body:t,retries:3,requestTimeoutMs:5e3});}async setCacheResult(t){await this.sendRequest(`/${fe}/result-cache/entry`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:5e3});}async getCacheResult(t){try{return await this.sendRequest(`/${fe}/result-cache/entry`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(t){let n=await this.sendRequest(`/${fe}/suites/queue`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return pK.parse(n)}async bulkGetRunGroupStatus(t){let n={runGroupIds:t},o=await this.sendRequest(`/${fe}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return _V.array().parse(o)}async getRunGroupWithRuns(t){try{let n=await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return PV.parse(n)}catch(n){if(n instanceof no&&n.status===404)return null;throw n}}async getRun(t){try{let n=await this.sendRequest(`/${fe}/runs/${encodeURIComponent(t)}/metadata`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Qi.parse(n)}catch(n){if(n instanceof no&&n.status===404)return null;throw n}}async getRunsByCommit(t){let o=[];for(let r=1;;r++){let i=await this.listRuns({gitCommitSha:t,includeFailureDetails:true,limit:100,page:r});if(o.push(...i.runs.map(s=>({...s,test:null}))),i.runs.length<100||r>=i.pageCount)break}return o}async updateGithubPRHealRiskSummary(t,n){await this.sendRequest(`/${fe}/run-groups/${encodeURIComponent(t)}/github-pr-heal-risk-summary`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async uploadProposedSteps(t,n){try{await this.sendRequest(`/${fe}/test-fragments/`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});}catch(o){n.error({err:o},"Failed to upload proposed steps");}}async reportBillableEvents(t,n){try{await this.sendRequest(`/${fe}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4});}catch(o){t.error({err:o},"Failed to report billable event");}}async fetchTestFragment(t){let n=await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return mK.parse(n)}async patchTestFragment(t,n){await this.sendRequest(`/${fe}/test-fragments/${t}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4});}async getPastTestResults(t,n){let o=await this.sendRequest(`/${fe}/results/tests/${t}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return hK.parse(o)}async listRuns(t){let n=await this.sendRequest(`/${fe}/results/runs`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return gK.parse(n)}async generateTestResultsUploadUrl(){let t=await this.sendRequest(`/${fe}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return fK.parse(t)}async startProcessingResultsUpload(t,n){let o=await this.sendRequest(`/${fe}/results/uploads/${t}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return yK.parse(o)}async fetchIconKnowledgeBase(t){try{let n=await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return DK.parse(n)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(t,n){try{await this.sendRequest(`/${fe}/knowledge-base/icons`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});}catch(o){n.error({err:o},"Failed to save new icons to icon knowledge base");}}async retrieveKnowledgeBase({query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l,retries:c,signal:d},u){try{let p=await this.sendRequest(`/${fe}/knowledge-base/retrieve`,{method:"POST",body:{query:t,clientName:n,testId:o,types:r,agentSubtype:i,limit:s,mode:a,scoreMultiplier:l},retries:c??3,requestTimeoutMs:5e3,signal:d});return Q$.parse(p)}catch(p){return u.warn({err:p},"Failed to retrieve from knowledge base"),null}}async createKnowledgeItem(t){let n=await this.sendRequest(`/${fe}/knowledge-base/items`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return XO.parse(n)}async getMergeBaseCommitFromGithub(t,n,o,r){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tb.parse(s)}async compareCommitsFromGithub({owner:t,repo:n,base:o,head:r}){let i=new URLSearchParams;i.set("base",o),i.set("head",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/compare?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zW.parse(s)}async getGithubFileContent({owner:t,repo:n,path:o,ref:r}){let i=new URLSearchParams;i.set("path",o),i.set("ref",r);let s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/contents?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return WW.parse(s).content??void 0}async getGithubBranchMetadata(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/branch-metadata?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return qW.parse(i)}async createGithubPullRequest(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return jW.parse(r)}async createGithubCommit(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits`,{method:"POST",body:o,retries:3,requestTimeoutMs:6e4});return $W.parse(r)}async getGithubPullRequestTemplate(t,n){try{let o=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-request-template`,{method:"GET",retries:3,requestTimeoutMs:1e4});return YW.parse(o).template}catch(o){if(o instanceof no&&o.status===404)return;throw o}}async getGithubPullRequestForBranch(t,n,o){let r=new URLSearchParams;r.set("branch",o);let i;try{i=await this.sendRequest(`/${fe}/git/github/${t}/${n}/pull-requests?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof no&&s.status===404)return;throw s}return VW.parse(i)}async getCommitFromGithub(t,n,o){let r=await this.sendRequest(`/${fe}/git/github/${t}/${n}/commits/${o}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tb.parse(r)}async getMergedBranchFromGithub(t,n,o,r){let i=encodeURIComponent(o),s=await this.sendRequest(`/${fe}/git/github/${t}/${n}/${i}/${r}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wN.parse(s)}async getMergeBaseCommitFromGitlab(t,n,o){let r=new URLSearchParams;r.set("base",n),r.set("head",o);let i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/merge-base-commit?${r.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Tb.parse(s)}async getGitlabMergeRequestForBranch(t,n){let o=new URLSearchParams;o.set("branch",n);let r=encodeURIComponent(t),i;try{i=await this.sendRequest(`/${fe}/git/gitlab/${r}/merge-requests?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});}catch(s){if(s instanceof no&&s.status===404)return;throw s}return KW.parse(i)}async getCommitFromGitlab(t,n){let o=encodeURIComponent(t),r=await this.sendRequest(`/${fe}/git/gitlab/${o}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Tb.parse(r)}async getMergedBranchFromGitlab(t,n,o){let r=encodeURIComponent(n),i=encodeURIComponent(t),s=await this.sendRequest(`/${fe}/git/gitlab/${i}/${r}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return wN.parse(s)}async getAgentConfig(){let t=await this.sendRequest(`/${fe}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return z$1.record(z$1.string(),z$1.string()).parse(t)}async getOrgSettings(){try{let t=await this.sendRequest(`/${fe}/org-settings`,{method:"GET",retries:3,requestTimeoutMs:5e3});return yV(t)}catch(t){if(t instanceof no&&t.status===404)return this.logger.warn({err:t},"Momentic server does not expose org settings; continuing with local project settings"),tg.parse({});throw t}}async getQuarantinedTests(){let t=await this.sendRequest(`/${fe}/quarantine`,{method:"GET"});return SK.parse(t)}async sendExploreSlackNotification(t){await this.sendRequest(`/${fe}/explore/slack-notification`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async recordExplorerSuggestedTests(t){await this.sendRequest(`/${fe}/explore/suggested-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:1e4});}async quarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine`,{method:"POST",body:{testId:t.id,testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}async unquarantineTest(t,n,o){await this.sendRequest(`/${fe}/quarantine/${t.id}`,{method:"DELETE",body:{testName:t.name,reason:n,...o??{}},retries:3,requestTimeoutMs:1e4});}platformRoute(t){switch(t){case "ANDROID":return "android";case "IOS":return "ios"}}async createAndroidEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/android`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return TK.parse(n)}async extendEmulatorTtl(t,n){try{await this.sendRequest(`/${fe}/limbar/${this.platformRoute(t)}/${n}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3});}catch{}}async generateAssetUploadUrl({channel:t,tag:n,md5:o,platform:r}){let i={channel:t,tag:n,md5:o},s=await this.sendRequest(`/${fe}/limbar/${this.platformRoute(r)}/upload-url`,{method:"POST",retries:3,body:i,requestTimeoutMs:15e3,logResponse:true});return EK.parse(s)}async deleteAndroidEmulator(t){await this.sendRequest(`/${fe}/limbar/android/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async getMobileAssets(){let t=await this.sendRequest(`/${fe}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return CK.parse(t)}async getLimbarAssetDownloadUrl(t,n,o){let r=await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}/download-url`,{method:"GET",retries:2,requestTimeoutMs:3e4});return vK.parse(r)}async deleteAsset(t,n,o){await this.sendRequest(`/${fe}/limbar/assets/${t}/${n}/${this.platformRoute(o)}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4});}async createIosEmulator(t){let n=await this.sendRequest(`/${fe}/limbar/ios`,{method:"POST",retries:3,body:t,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return AK.parse(n)}async deleteIosEmulator(t){await this.sendRequest(`/${fe}/limbar/ios/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4});}async generateMobileLogcatUploadUrl(t){let n=await this.sendRequest(`/${fe}/logcat/mobile/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return vW.parse(n)}async generateMcpSessionTraceUploadUrl(t){let n=await this.sendRequest(`/${fe}/mcp/upload`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return cv.parse(n)}};async function wm(e){let t=process.versions.node,n=parseInt(t.split(".")[0]);(isNaN(n)||n<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${t}`);let o=await e.client.getAuthInfo();return R.debug("Got auth info from API"),o}var wd=class{apiClient;constructor(t){this.apiClient=t;}async reportBillableEvents(t,n){await this.apiClient.reportBillableEvents(t,n);}};var Id=class extends Fi{generator;constructor(t,n){super(t),this.generator=n;}async runTemplateMatching(t,n={}){let o=await this.sendRequest(`/${fe}/web-agent/template-matching`,{method:"POST",body:t,signal:n?.signal});return rj.parse(o)}async constructIframeRegex(t,n={}){return this.generator.getIframeRegex(t,{abortSignal:n.signal,loggerTags:n.loggerTags})}};var wf=class{constructor(t,n){this.client=t;this.orgId=n;}getApiServerUrl(){return this.client.baseUrl}getAppServerUrl(){let t=this.getApiServerUrl();return vg(t)}async acquireCacheLock(t,n){return this.client.acquireCacheLock(t,n)}async createOnDemandScreenshot(t,n,o){let{apiServerUrl:r}=await this.client.uploadOnDemandScreenshot({id:t,screenshot:n.toString("base64"),contentType:o});return {apiServerUrl:r,appServerUrl:`${this.getAppServerUrl()}/api/on-demand-screenshots/${t}`,universalHandle:{id:t,contentType:o}}}async fetchOnDemandScreenshot(t){return this.client.fetchOnDemandScreenshot(t.id)}async releaseCacheLock(t){return this.client.releaseCacheLock(t)}async deleteCacheResult(t){return this.client.deleteCacheResult(t)}async setCacheResult(t){return this.client.setCacheResult(t)}async getCacheResult(t){return this.client.getCacheResult(t)}fetchIconKnowledgeBase(t){return this.client.fetchIconKnowledgeBase(t)}saveNewIcons(t,n){return this.client.saveNewIcons(t,n)}};var xd="v1",LLe=2e3,NZ="sms.lease() and sms.release() are only supported when running tests via the Momentic CLI.",_d=class{httpClient;fakerInstance;supportsLease;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this),lease:this.leasePhoneNumber.bind(this),release:this.releasePhoneNumber.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this),create:this.createEmail.bind(this)};activeLeases=new Map;constructor(t){this.httpClient=t.httpClient,this.supportsLease=t.supportsLease??true,t.fakerSeed&&(this.fakerInstance=new Faker({locale:en$1}),this.fakerInstance.seed(t.fakerSeed));}async sendSms(t){return this.httpClient.sendRequest(`/${xd}/tools/sms/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(t){return this.httpClient.sendRequest(`/${xd}/tools/sms/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof no?new Error(n.rawError):n})}async leasePhoneNumber(t){if(!this.supportsLease)throw new Error(NZ);let n=await this.httpClient.sendRequest(`/${xd}/tools/sms/lease`,{method:"POST",body:t??{}}).catch(r=>{throw r instanceof no?new Error(r.rawError):new Error(`Failed to lease phone number: ${r.message}`)}),o=OW.parse(n);return this.activeLeases.set(o.phoneNumber,{leaseToken:o.leaseToken}),o}async releasePhoneNumber(t){if(!this.supportsLease)throw new Error(NZ);return this.activeLeases.delete(t.phoneNumber),this.httpClient.sendRequest(`/${xd}/tools/sms/release`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to release phone number: ${n.message}`)})}async dispose(){let t=[...this.activeLeases.entries()];this.activeLeases.clear(),await Promise.allSettled(t.map(([n,{leaseToken:o}])=>_e(this.httpClient.sendRequest(`/${xd}/tools/sms/release`,{method:"POST",body:{phoneNumber:n,leaseToken:o}}),{milliseconds:LLe,fallback:()=>{}})));}async sendEmail(t){return this.httpClient.sendRequest(`/${xd}/tools/email/send`,{method:"POST",body:t}).then(()=>{}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(t){return this.httpClient.sendRequest(`/${xd}/tools/email/fetchAll`,{method:"POST",body:t}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(t){return this.httpClient.sendRequest(`/${xd}/tools/email/fetchLatest`,{method:"POST",body:t}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}async createEmail(){let t=await this.httpClient.sendRequest(`/${xd}/tools/email/create`,{method:"POST",body:{}}).catch(n=>{throw n instanceof no?new Error(n.rawError):new Error(`Failed to create email inbox: ${n.message}`)});return MW.parse(t)}};var kw=class{constructor(t){this.client=t;}async uploadResultsArchive(t){let{runGroupId:n,archive:o,persist:r}=t,{uploadUrl:i,id:s}=await this.client.generateTestResultsUploadUrl(),a=await Lw(i,"application/zip",o);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:l}=await this.client.startProcessingResultsUpload(s,{runGroupId:n,persist:r});return l}};function Pd({logger:e,orgId:t,client:n,gitMetadata:o,regenerateCache:r,alwaysSaveCache:i,noCache:s,isolateCachesByEnvironment:a=false,bustOldestCachePercentage:l}){return s?new pv:new oF(e,t,n,o,{regenerateCache:r,alwaysSaveCache:i,bustOldestCachePercentage:l,isolateCachesByEnvironment:a})}var oF=class{constructor(t,n,o,r,i){this.orgId=n;this.client=o;let{regenerateCache:s,alwaysSaveCache:a,bustOldestCachePercentage:l,isolateCachesByEnvironment:c}=i,{gitBranchName:d,gitProtectedBranches:u}=r;t.info({options:i,gitBranchName:d,gitProtectedBranches:u},"Cache storage initialization options"),this.cacheHeaders=lv(r),this.isolateCachesByEnvironment=c,this.readCaches=!s;let p=d&&u.includes(d);a||!p?this.writeCaches=true:this.writeCaches=false,p||(this.bustOldestCachePercentage=l);}cacheHeaders;readCaches;writeCaches;isolateCachesByEnvironment;bustOldestCachePercentage;async saveStepCacheEntries({entries:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:LN(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save step cache entries");}}async saveSnapshotCacheEntries({entries:t,logger:n}){if(t.length!==0){if(!this.writeCaches){n.debug("Skipping snapshot cache storage because branch is protected");return}try{await this.client.updateSnapshotCaches({entries:LN(t,this.isolateCachesByEnvironment)},this.cacheHeaders);}catch(o){n.error({err:o},"Failed to save snapshot cache entries");}}}async deleteStepCacheEntry({logger:t,testId:n,key:o,environment:r}){try{await this.client.deleteStepCacheEntry({testId:n,key:o,environment:this.isolateCachesByEnvironment?r:void 0},this.cacheHeaders);}catch(i){t.error({err:i},"Failed to delete step cache entry");}}async resolveStepCacheEntries(t){if(!this.readCaches){t.logger.debug("Skipping cache resolution because of regenerate flag");return}let n=t.useSnapshotIdentityCache?await this.tryRestoreStepIdsFromSnapshot(t):void 0,{steps:o,beforeSteps:r,afterSteps:i}=t.stepLists,s=await this.client.getStepCacheForTest({testId:t.testId,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);if(this.bustOldestCachePercentage!==void 0){let u=Object.entries(s).map(([h,g])=>({key:h,time:g.value.cache?.updatedAt?.getTime()??0}));u.sort((h,g)=>h.time-g.time);let p=u.length,m=Math.max(1,Math.floor(p*this.bustOldestCachePercentage/100));u.slice(0,m).forEach(({key:h})=>{delete s[h];}),t.logger.info({nCachesToBust:m,bustOldestCachePercentage:this.bustOldestCachePercentage,totalCaches:p},"Busted oldest caches");}let a={totalSteps:0,cacheKeysHit:[],cacheKeysMissed:[],uniqueKeysHit:[],cacheMissSamples:[]};for(let u of [o,r,i]){if(!u)continue;let p=ku({steps:u,stepCacheEntries:s,logger:t.logger});a.totalSteps+=p.totalSteps,a.cacheKeysHit.push(...p.cacheKeysHit),a.cacheKeysMissed.push(...p.cacheKeysMissed),a.uniqueKeysHit.push(...p.uniqueKeysHit),a.cacheMissSamples.push(...p.cacheMissSamples);}n&&DLe({cacheResolutionStats:a,logger:t.logger,restoredIdentity:n,schemaVersion:t.schemaVersion,testId:t.testId});let l=["platform:web","source:local",`fileFormat:${t.useSnapshotIdentityCache?"v2":"v1"}`,`snapshotIdentityCache:${t.useSnapshotIdentityCache}`,`orgId:${this.orgId}`,"cliVersion:3.16.3"];if(At.increment("step_cache_resolution",a.cacheKeysHit.length,[...l,"outcome:hit"]),At.increment("step_cache_resolution",a.cacheKeysMissed.length,[...l,"outcome:miss"]),At.increment("step_cache_resolution",a.totalSteps,[...l,"outcome:total"]),!this.writeCaches){t.logger.debug("Skipping cache last used at update because branch is protected");return}let{cachesToSave:c,snapshotCachesToSave:d}=await Yn({stepLists:t.stepLists,useSnapshotIdentityCache:t.useSnapshotIdentityCache,cacheCreationParams:{environment:t.environment,testId:t.testId,orgId:this.orgId}});t.useSnapshotIdentityCache&&this.saveSnapshotCacheEntries({entries:d,logger:t.logger}),this.saveStepCacheEntries({entries:c,logger:t.logger});}async tryRestoreStepIdsFromSnapshot(t){try{return await this.restoreStepIdsFromSnapshot(t)}catch(n){t.logger.warn({err:n,testId:t.testId},"Failed to restore step ids from snapshot cache; proceeding without identity cache"),At.increment("step_cache_resolution",1,["platform:web","source:local","fileFormat:v2","snapshotIdentityCache:true",`orgId:${this.orgId}`,"cliVersion:3.16.3","outcome:identity_restore_error"]);return}}async restoreStepIdsFromSnapshot(t){let{logger:n,testId:o}=t,r=await this.client.getSnapshotCacheForTest({testId:o,environment:this.isolateCachesByEnvironment?t.environment:void 0},this.cacheHeaders);for(let a of r){if(!a.schema_version)continue;let l=XM(a.schema_version),c=XM(at);if(l&&c&&l.compare(c)>0){n.warn(`Snapshot cache for test ${o} was written at schema version ${a.schema_version}, which is newer than this CLI's latest (${at}). Please update your momentic package version. Skipping identity restoration from snapshot cache.`);return}}let i=FR({entries:r,orgId:this.orgId,testId:o,logger:n}),s=DR({currentStepLists:t.stepLists,previousSnapshot:i.testSnapshot,previousModuleSnapshots:i.moduleSnapshots,generateUuid:randomUUID});return t.stepLists.steps.splice(0,t.stepLists.steps.length,...s.stepLists.steps),t.stepLists.beforeSteps=s.stepLists.beforeSteps,t.stepLists.afterSteps=s.stepLists.afterSteps,n.debug({snapshotEntries:r.length,testSnapshotHit:!!i.testSnapshot,moduleSnapshots:Array.from(i.moduleSnapshots.keys()),mintedSteps:s.stats.mintedSteps,stats:s.stats,moduleRestoreResults:s.moduleRestoreResults.map(({moduleId:a,snapshotHit:l,stats:c})=>({moduleId:a,snapshotHit:l,stats:c}))},"Restored step ids from snapshot cache"),s}};function DLe({cacheResolutionStats:e,logger:t,restoredIdentity:n,schemaVersion:o,testId:r}){let i=e.cacheKeysHit.length,s=e.cacheKeysMissed.length,a=i+s,l=a>0?Math.round(s/a*1e3)/10:0,c=n.stats.matchedSteps+n.stats.mintedSteps,d=c>0?Math.round(n.stats.mintedSteps/c*1e3)/10:0,u=n.moduleRestoreResults.filter(({snapshotHit:g,stats:f})=>!g||f.mintedSteps>0||f.bustedConditionals>0).slice(0,10).map(({moduleId:g,snapshotHit:f,stats:y})=>({moduleId:g,snapshotHit:f,stats:y})),p=n.stats.mintedSteps>=5&&d>=25,m=p||n.stats.bustedConditionals>0||u.some(({stats:g})=>g.mintedSteps>=5||g.bustedConditionals>0),h={cacheHits:i,cacheMissRate:l,cacheMisses:s,cacheMissSamples:e.cacheMissSamples.slice(0,10),hasHighMintRate:p,identityMintRate:d,moduleIdentityIssueCount:u.length,moduleIdentityIssues:u,schemaVersion:o,snapshotIdentityCache:true,stepIdentityStats:n.stats,testId:r,totalCacheableSteps:e.totalSteps};if(!m){t.debug(h,"V2 cache resolution completed");return}t.warn(h,"V2 cache resolution degraded");}function FLe(e){let t=new WU,n=Jn__default.join(e,ct),o=ua.parse(JSON.parse(Oo__default.readFileSync(n,"utf-8")));t.addLocalFile(n);for(let r of Oo__default.readdirSync(Jn__default.join(e,to))){if(!r.endsWith(".zip"))continue;let i=r.replace(/\.zip$/,""),s=new WU(Jn__default.join(e,to,r));for(let a of s.getEntries())a.isDirectory||t.addFile(Jn__default.join(to,i,a.entryName),a.getData());}return {runGroupId:o.id,buffer:t.toBuffer()}}async function wT(e){let{client:t,resultsPath:n,persist:o}=e;if(!Oo__default.existsSync(n))return {success:false,error:"results path does not exist"};let r=new kw(t);try{let{runGroupId:i,buffer:s}=FLe(n),a=await r.uploadResultsArchive({runGroupId:i,archive:s,persist:o});return {success:!0,runGroupUrl:`${t.getAppUrl()}/run-groups/${a}`}}catch(i){return {success:false,error:X(i)}}}var BZ=101010256,iF=33639248,BLe=67324752,Fw=22,ULe=65535,Bw=4294967295,UZ=1024*1024;function Uw({zipPath:e,files:t,buffers:n}){let o=HZ(e);if(!o)return false;let{centralDirectory:r,cdOffset:i,entryCount:s}=o;if(GLe({centralDirectory:r,files:t,buffers:n}))return false;let a=Oo__default.openSync(e,"r+");try{let l=i,c=[];for(let p of t){let m=Oo__default.statSync(p.sourcePath);if(m.size>Bw||l+m.size>Bw)return !1;let h=jLe(p.sourcePath),g=Buffer.from(p.entryName,"utf-8"),f=kZ({nameBytes:g,crc:h,size:m.size});Oo__default.writeSync(a,f,0,f.length,l),c.push(DZ({nameBytes:g,crc:h,size:m.size,localHeaderOffset:l})),l+=f.length,l+=$Le(a,p.sourcePath,l);}for(let p of n){let m=Buffer.from(p.entryName,"utf-8"),h=FZ.crc32(p.data),g=kZ({nameBytes:m,crc:h,size:p.data.length});Oo__default.writeSync(a,g,0,g.length,l),c.push(DZ({nameBytes:m,crc:h,size:p.data.length,localHeaderOffset:l})),l+=g.length,Oo__default.writeSync(a,p.data,0,p.data.length,l),l+=p.data.length;}let d=l;Oo__default.writeSync(a,r,0,r.length,l),l+=r.length;for(let p of c)Oo__default.writeSync(a,p,0,p.length,l),l+=p.length;let u=VLe({entryCount:s+t.length+n.length,cdSize:l-d,cdOffset:d});return Oo__default.writeSync(a,u,0,u.length,l),Oo__default.ftruncateSync(a,l+u.length),!0}finally{Oo__default.closeSync(a);}}function HZ(e){let t=Oo__default.statSync(e).size,n=Math.min(t,Fw+ULe),o=Buffer.alloc(n),r=Oo__default.openSync(e,"r");try{Oo__default.readSync(r,o,0,n,t-n);let i=HLe(o);if(i<0)return;let s=o.readUInt16LE(i+10),a=o.readUInt16LE(i+8),l=o.readUInt32LE(i+12),c=o.readUInt32LE(i+16);if(o.readUInt16LE(i+4)!==0||s!==a||s===65535||l===Bw||c===Bw||c+l>t)return;let u=Buffer.alloc(l);return Oo__default.readSync(r,u,0,l,c),l>0&&u.readUInt32LE(0)!==iF?void 0:{centralDirectory:u,cdOffset:c,entryCount:s}}finally{Oo__default.closeSync(r);}}function HLe(e){for(let t=e.length-Fw;t>=0;t--){if(e.readUInt32LE(t)!==BZ)continue;let n=e.readUInt16LE(t+20);if(t+Fw+n===e.length)return t}return -1}function GZ(e){let t=HZ(e);return t&&jZ(t.centralDirectory)}function jZ(e){let t=[],n=0;for(;n+46<=e.length&&e.readUInt32LE(n)===iF;){let o=e.readUInt16LE(n+28),r=e.readUInt16LE(n+30),i=e.readUInt16LE(n+32);t.push(e.toString("utf-8",n+46,n+46+o)),n+=46+o+r+i;}return t}function GLe({centralDirectory:e,files:t,buffers:n}){let o=new Set(jZ(e));return t.some(r=>o.has(r.entryName))||n.some(r=>o.has(r.entryName))}function jLe(e){let t=Oo__default.openSync(e,"r");try{let n=Buffer.alloc(UZ),o=0,r;for(;(r=Oo__default.readSync(t,n,0,n.length,null))>0;)o=FZ.crc32(n.subarray(0,r),o);return o}finally{Oo__default.closeSync(t);}}function $Le(e,t,n){let o=Oo__default.openSync(t,"r");try{let r=Buffer.alloc(UZ),i=0,s;for(;(s=Oo__default.readSync(o,r,0,r.length,null))>0;)Oo__default.writeSync(e,r,0,s,n+i),i+=s;return i}finally{Oo__default.closeSync(o);}}function kZ({nameBytes:e,crc:t,size:n}){let o=Buffer.alloc(30+e.length);return o.writeUInt32LE(BLe,0),o.writeUInt16LE(20,4),o.writeUInt16LE(2048,6),o.writeUInt16LE(0,8),o.writeUInt32LE(0,10),o.writeUInt32LE(t>>>0,14),o.writeUInt32LE(n,18),o.writeUInt32LE(n,22),o.writeUInt16LE(e.length,26),o.writeUInt16LE(0,28),e.copy(o,30),o}function DZ({nameBytes:e,crc:t,size:n,localHeaderOffset:o}){let r=Buffer.alloc(46+e.length);return r.writeUInt32LE(iF,0),r.writeUInt16LE(20,4),r.writeUInt16LE(20,6),r.writeUInt16LE(2048,8),r.writeUInt16LE(0,10),r.writeUInt32LE(0,12),r.writeUInt32LE(t>>>0,16),r.writeUInt32LE(n,20),r.writeUInt32LE(n,24),r.writeUInt16LE(e.length,28),r.writeUInt16LE(0,30),r.writeUInt16LE(0,32),r.writeUInt16LE(0,34),r.writeUInt16LE(0,36),r.writeUInt32LE(0,38),r.writeUInt32LE(o,42),e.copy(r,46),r}function VLe({entryCount:e,cdSize:t,cdOffset:n}){let o=Buffer.alloc(Fw);return o.writeUInt32LE(BZ,0),o.writeUInt16LE(0,4),o.writeUInt16LE(0,6),o.writeUInt16LE(e,8),o.writeUInt16LE(e,10),o.writeUInt32LE(t,12),o.writeUInt32LE(n,16),o.writeUInt16LE(0,20),o}var IT=class e{constructor(t,n=true){this.filePath=t;n&&Oo__default.rmSync(this.filePath,{recursive:true,force:true}),Oo__default.mkdirSync(this.filePath,{recursive:true});}children=[];streams=[];close(){for(let t of this.children)t.close();for(let t of this.streams)t.end();}cd(t){let n=new e(Jn__default.join(this.filePath,t));return this.children.push(n),n}cwd(){return this.filePath}mkdir(t){Oo__default.mkdirSync(Jn__default.join(this.filePath,t),{recursive:true});}readFile(t){let n=Jn__default.join(this.filePath,t);if(Oo__default.existsSync(n))return Oo__default.readFileSync(n)}storeFile(t){let{name:n,contents:o}=t,r=Jn__default.join(this.filePath,n);try{Oo__default.mkdirSync(Jn__default.dirname(r),{recursive:!0}),Oo__default.writeFileSync(r,o);}catch{}}createFileStream(t){let n=Jn__default.join(this.filePath,t),o=Oo__default.createWriteStream(n);return this.streams.push(o),o}createRunArchive(t,n){let o=new sF(Jn__default.join(this.filePath,to),t,n);return this.children.push(o),o}},sF=class{children=[];tempPath;finalPath;logger;closed=false;constructor(t,n,o){this.tempPath=Jn__default.join(t,`temp-storage-${n}`),this.finalPath=Jn__default.join(t,`${n}.zip`),this.logger=o,Oo__default.rmSync(this.tempPath,{recursive:true,force:true}),Oo__default.rmSync(this.finalPath,{recursive:true,force:true}),Oo__default.mkdirSync(this.tempPath,{recursive:true});}readFile(t){let n=Jn__default.join(this.tempPath,t);if(Oo__default.existsSync(n))return Oo__default.readFileSync(n)}mkdir(t){Oo__default.mkdirSync(Jn__default.join(this.tempPath,t),{recursive:true});}cd(t){let n=new IT(Jn__default.join(this.tempPath,t));return this.children.push(n),n}cwd(){return this.tempPath}storeFile(t){if(this.closed)return;let{name:n,contents:o}=t,r=Jn__default.join(this.tempPath,n);Oo__default.mkdirSync(Jn__default.dirname(r),{recursive:true}),Oo__default.writeFileSync(r,o);}close(){if(!this.closed){this.closed=true;for(let t of this.children)t.close();try{let t=new WU;t.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store"&&!VZ(r));let n=t.toBuffer();Oo__default.writeFileSync(this.finalPath,n);let o=WLe(this.tempPath);if(o.length>0&&!Uw({zipPath:this.finalPath,files:o,buffers:[]})){let r=new WU(this.finalPath);for(let i of o)r.addLocalFile(i.sourcePath,i.entryName.split("/").slice(0,-1).join("/"));r.writeZip(this.finalPath);}Oo__default.rmSync(this.tempPath,{recursive:!0,force:!0});}catch(t){this.logger.warn({err:t,finalPath:this.finalPath,tempPath:this.tempPath},"Failed to archive run artifacts; leaving raw files on disk");}}}},zLe=[".webm",".mp4",".mov"];function VZ(e){let t=e.toLowerCase();return zLe.some(n=>t.endsWith(n))}function WLe(e){let t=[],n=Oo__default.readdirSync(e,{recursive:true,withFileTypes:true});for(let o of n){if(!o.isFile()||!VZ(o.name))continue;let r=Jn__default.join(o.parentPath,o.name),i=Jn__default.relative(e,r).split(Jn__default.sep).join("/");t.push({entryName:i,sourcePath:r});}return t}function KZ(e){try{return Oo__default.existsSync(e)?JSON.parse(Oo__default.readFileSync(e,"utf-8")):void 0}catch{return}}function zZ(e){return Oo__default.existsSync(e)?Oo__default.readFileSync(e,"utf-8").split(`
293
293
  `).map(n=>n.trim()).filter(n=>n.length>0):[]}function YLe(e,t){let n=e.attemptIdToAttemptNumber.get(t);if(n)return Jn__default.join(e.inflatedPath,"attempts",n);let o=Jn__default.join(e.inflatedPath,"attempts");if(!Oo__default.existsSync(o))return;let r=Oo__default.readdirSync(o,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of r){let s=Jn__default.join(o,i,ct),a=KZ(s);if(typeof a!="object"||a===null)continue;let l=a.id;if(typeof l=="string"&&l===t)return e.attemptIdToAttemptNumber.set(t,i),Jn__default.join(o,i)}}function WZ(e,t,n){let o=Jn__default.join(e,"attempts");if(!Oo__default.existsSync(o))return;let r=Oo__default.readdirSync(o,{withFileTypes:true}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of r){let s=Jn__default.join(o,i,"assets",`${t}.${n}`);if(Oo__default.existsSync(s))return s}}var Hw=class{constructor(t,n,o){this.outputDir=t;this.runId=n;this.runAttemptId=o;this.runsDir=Jn__default.join(t,to),this.zipPath=Jn__default.join(this.runsDir,`${n}.zip`);}inflatedByRunId=new Map;zipPath;runsDir;ensureInflatedRun(t){let n=this.inflatedByRunId.get(t);if(n)return n;if(t!==this.runId||!Oo__default.existsSync(this.zipPath))return;let o=Jn__default.join(this.runsDir,`temp-unzipped-${t}-${randomUUID()}`);Oo__default.mkdirSync(o,{recursive:true}),new WU(this.zipPath).extractAllTo(o,true);let i={runId:t,zipPath:this.zipPath,inflatedPath:o,attemptIdToAttemptNumber:new Map};return this.inflatedByRunId.set(t,i),i}close(){for(let t of this.inflatedByRunId.values())Oo__default.rmSync(t.inflatedPath,{recursive:true,force:true});this.inflatedByRunId.clear();}getAttemptDir(){let t=this.ensureInflatedRun(this.runId);if(t)return YLe(t,this.runAttemptId)}listVideoAssetPaths(){let t=this.getAttemptDir();if(!t)return [];let n=Jn__default.join(t,"assets");return Oo__default.existsSync(n)?Oo__default.readdirSync(n,{withFileTypes:true}).filter(r=>r.isFile()).map(r=>Jn__default.join(n,r.name)).filter(r=>{let i=Jn__default.extname(r).toLowerCase();return i===".webm"||i===".mp4"}):[]}readAttemptAssetText(t,n){let o=this.getAttemptDir();if(!o)return;let r=Jn__default.join(o,"assets",`${t}.${n}`);if(Oo__default.existsSync(r))try{return Oo__default.readFileSync(r,"utf-8")}catch{return}}async getConsoleLogsForRunAttempt(t,n,o){if(n!==this.runId||o!==this.runAttemptId)return;let r=this.getAttemptDir();if(!r)return;let i=KZ(Jn__default.join(r,"console.json")),s=QM.safeParse(i);return s.success?s.data:void 0}async getNetworkLogsForRunAttempt(t,n,o){if(n!==this.runId||o!==this.runAttemptId)return;let r=this.getAttemptDir();if(!r)return;let i=Jn__default.join(r,"assets","har-pages.log"),s=Jn__default.join(r,"assets","har-entries.log"),a={};for(let d of zZ(i)){let u=ab.safeParse(qZ(d));u.success&&(a[u.data.id]=u.data);}let l={},c=zZ(s);for(let d=0;d<c.length;d++){let u=c[d],p=lb.safeParse(qZ(u));if(!p.success)continue;let m=`${p.data.startedDateTime}-${d}`;l[m]=p.data;}if(Object.keys(l).length!==0)return ZM(a,l)}async getHtmlSnapshot(t,n){let o=this.readAttemptAssetText(n,"html");if(o)return o;let r=this.ensureInflatedRun(this.runId);if(!r)return;let i=WZ(r.inflatedPath,n,"html");if(i)try{return Oo__default.readFileSync(i,"utf-8")}catch{return}}async getA11yTreeSnapshot(t,n){let o=this.readAttemptAssetText(n,"xml");if(o)return o;let r=this.ensureInflatedRun(this.runId);if(!r)return;let i=WZ(r.inflatedPath,n,"xml");if(i)try{return Oo__default.readFileSync(i,"utf-8")}catch{return}}async getScreenshot(t,n){if(!this.ensureInflatedRun(this.runId))return;let r=this.getAttemptDir();if(r)for(let i of ["png","jpeg"])try{return Oo__default.readFileSync(Jn__default.join(r,"assets",`${n}.${i}`))}catch{continue}}};function qZ(e){try{return JSON.parse(e)}catch{return}}function YZ(e,t){let n=JLe(e);return n==="EACCES"||n==="EPERM"?{status:403,body:{error:`Permission denied: ${t}`}}:n==="ENOENT"?{status:404,body:{error:`Not found: ${t}`}}:n==="ENOTDIR"?{status:400,body:{error:`Not a directory: ${t}`}}:n==="EISDIR"?{status:400,body:{error:`Is a directory: ${t}`}}:n==="EEXIST"?{status:409,body:{error:`Already exists: ${t}`}}:n==="ENOTEMPTY"?{status:409,body:{error:`Directory is not empty: ${t}`}}:{status:500,body:{error:`${t}: ${X(e)}`}}}function JLe(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}function If({test:e,envNameOverride:t,urlOverride:n,resolveEnv:o}){let r=t??XLe(e),i,s={};if(r){try{i=o(r);}catch(l){let c=`Failed to resolve environment ${r} for test ${e.name}: ${X(l)}`;throw l instanceof ke?new ke(c,{cause:l}):new Error(c,{cause:l})}s=i.variables;}let a=e.baseUrl;if(n)a=n;else if(!a){let l=s[Eo];typeof l=="string"&&(a=l);}if(!a)throw new su(`Cannot run test with no base URL and no ${Eo} variable defined in its environment`);return {envName:r,resolvedEnv:i,environmentVariables:s,baseUrl:a}}function XLe(e){for(let t of e.envs??[])if(t.default)return t.name}async function xT(e,t,n,o,r=pt){let i=o??await Ve(e,false,r),s=i[n],a=QLe(s,t);if(t.id){if(a.length===0)throw new mt(`No ${n} found with id '${t.id}' in project '${e.rootDir}'.`);return Gw(a,i)}if(t.name){if(a.length===0)throw new mt(`No ${n} found with exact name '${t.name}' in project '${e.rootDir}'.`);if(a.length>1){let l=a.map(c=>({id:c.id,path:c.relativePath}));throw new mt([`Multiple ${n} found with exact name '${t.name}'. Please disambiguate by id or path.`,JSON.stringify(l,null,2)].join(`
294
294
  `))}return Gw(a,i)}if(t.path){let l=t.path;if(a.length===0)throw new mt(`No ${n} found at path '${l}'. Provide an absolute path or a path relative to '${e.rootDir}'.`);if(a.length>1){let c=a.filter(u=>u.fullFilePath===l||u.relativePath===l||u.fullFilePath.endsWith(`/${l}`)||u.relativePath.endsWith(`/${l}`));if(c.length===1)return Gw(c,i);let d=a.map(u=>({id:u.id,path:u.fullFilePath}));throw new mt([`Multiple ${n} matched the provided path '${l}'. Please pass the absolute path.`,JSON.stringify(d,null,2)].join(`
295
295
  `))}return Gw(a,i)}throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Gw(e,t){let n=e[0];if(!n)throw e.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return {entity:n,momenticFiles:t}}function QLe(e,t){if(t.id){let n=Object.values(e).find(o=>o.id===t.id);return n?[n]:[]}if(t.name)return Object.values(e).filter(n=>n.name===t.name);if(t.path){let n=t.path;return Object.values(e).filter(o=>o.fullFilePath.includes(n)||o.relativePath.includes(n))}throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}function JZ({momenticFiles:e,logger:t}){let n=new Set,o=new Set,r=Object.values(e.tests).map(i=>i.fullFilePath);for(;r.length>0;){let i=r.shift();if(!i||o.has(i))continue;o.add(i);let s=ZLe({fullFilePath:i,momenticFiles:e,logger:t});for(let a of s){let l=e.modules[a];!l||n.has(a)||(n.add(a),r.push(l.fullFilePath));}}return Object.values(e.modules).filter(i=>!n.has(i.id)).sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function ZLe({fullFilePath:e,momenticFiles:t,logger:n}){try{return aw(e,t)}catch(o){return n.warn({err:o,fullFilePath:e},"Failed to analyze a file while searching for unused modules."),new Set}}async function XZ({cwd:e,projectName:t}){let n=Jn__default.join(e,pc);if(Oo__default.existsSync(n))throw new Error(`A ${pc} file already exists at ${n}. Please rename or remove it to initialize a new project.`);let o=await MQ(e)??"main",r={name:t,include:df,gitMainBranch:o,fileFormat:"v2",browser:{disableSecondaryCacheResolution:true},ai:{useMemory:true,failureRecovery:true,agentConfig:{...og}}};return Ad(r,n),{configPath:n}}var nke="npx skills@latest add momentic-ai/skills",oke="https://momentic.ai/docs/integrations/mcp-server",rke={web:["https://momentic.ai/docs/quickstart/web"],mobile:["https://momentic.ai/docs/quickstart/ios","https://momentic.ai/docs/quickstart/android"]};function QZ({platform:e}){let t="npx momentic app",n=rke[e].map(r=>$a.underline.cyan(r)).join($a.dim(" \xB7 ")),o=(r,i)=>` ${$a.dim(r.padEnd(14))}${i}`;R.log(""),R.log($a.bold("Next steps")),R.log(o("Editor skills",$a.cyan(nke))),R.log(o("Coding agent",`${$a.dim("Momentic MCP \u2192")} ${$a.underline.cyan(oke)}`)),R.log(o("Local editor",$a.cyan(t))),R.log(o("Docs",n));}var ZZ=["cursor","claude-code","codex","opencode","copilot"],ske={cursor:Jn__default.join(".cursor","skills"),"claude-code":Jn__default.join(".claude","skills"),codex:Jn__default.join(".agents","skills"),opencode:Jn__default.join(".opencode","skills"),copilot:Jn__default.join(".github","skills")};function e6({editor:e,skillsDir:t,cwd:n=process.cwd()}){Oo__default.existsSync(t)||(R.error(`Could not find skills directory at ${t}. Is the CLI package installed correctly?`),process.exit(1));let o=Oo__default.readdirSync(t).filter(s=>s.endsWith(".md"));o.length===0&&(R.error(`No skill markdown files found in ${t}. Is the CLI package installed correctly?`),process.exit(1));let r=ake({cwd:n}),i=Jn__default.join(r,ske[e]);for(let s of o){let a=Jn__default.basename(s,".md"),l=Jn__default.join(i,a),c=Oo__default.readFileSync(Jn__default.join(t,s),"utf8");Oo__default.mkdirSync(l,{recursive:true}),Oo__default.writeFileSync(Jn__default.join(l,"SKILL.md"),c),R.success(`Installed SKILL.md at ${Jn__default.join(l,"SKILL.md")}.`);}}function ake({cwd:e}){try{return execSync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||e}catch{return e}}var n6=Jn__default.join(sd.homedir(),".momentic"),Od=Jn__default.join(n6,"auth.json"),cke=new Set(["EPERM","EACCES","EROFS"]),dke=z$1.object({workos:z$1.object({accessToken:z$1.string(),refreshToken:z$1.string(),expiresAt:z$1.number()}),user:z$1.object({id:z$1.string(),email:z$1.string().optional()}),organizationId:z$1.string(),apiKey:z$1.string(),apiKeyName:z$1.string(),serverUrl:z$1.string(),createdAt:z$1.string(),selfServe:z$1.boolean().optional()});function o6(){if(!Oo__default.existsSync(Od))return null;try{let e=Oo__default.readFileSync(Od,"utf-8"),t=dke.safeParse(JSON.parse(e));return t.success?t.data:null}catch{return null}}function r6(e){try{Oo__default.mkdirSync(n6,{recursive:!0,mode:448}),Oo__default.writeFileSync(Od,JSON.stringify(e,null,2),{mode:384});}catch(t){throw n3(t)&&cke.has(t.code)?new ke(`Couldn't save your Momentic credentials to ${Od} (${t.code}). Make sure that file and its parent directory are writable and owned by you \u2014 for example, they may have been created by a previous \`sudo\` run. Fix the permissions and try again.`,{cause:t}):t}}function i6(){return Oo__default.existsSync(Od)?(Oo__default.unlinkSync(Od),true):false}function jw(){return o6()?.apiKey||void 0}function $w(){return o6()?.serverUrl||void 0}var uke=["unable to get local issuer certificate","self-signed certificate","self-signed certificate in certificate chain","certificate has expired","unable to verify the first certificate"],pke=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","CERT_HAS_EXPIRED","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]);function mke(e){if(!(e instanceof Error))return false;let t=[e];e.cause instanceof Error&&t.push(e.cause);for(let n of t)if("code"in n&&typeof n.code=="string"&&pke.has(n.code)||uke.some(o=>n.message.includes(o)))return true;return false}function PT(e,t){if(mke(e))throw new ke(`Network request to ${t} failed due to a TLS certificate error.
@@ -318,7 +318,7 @@ ${l}`:a}function dF(e,t,n={}){if(e.length===0)return "";let o=zo(t),r=Math.max(n
318
318
  ${r}
319
319
  `);}catch(n){e.logger.warn({err:n},"Failed to check CLI version against npm");}}async function zke(e,t,n){if(!v6){v6=true;try{let o=await e.getCliAnnouncements();for(let{announcement:r,level:i}of o)R.log(`
320
320
  ${b6({announcement:r,level:i},n)}
321
- `);}catch(o){t.warn({err:o},"Failed to fetch CLI announcements");}}}var uF="^22.12.0 || >=24.0.0";function x6(){(Ld.satisfies(process.version,uF)||(R.error(`Momentic requires Node.js ${uF}, but you are running ${process.version}. Upgrade Node.js (https://nodejs.org/en/download) and try again.`),process.exit(1)));}var MT=25;function _6(e){return {v2ProjectConfig:{...e.config,fileFormat:"v2"},migratedFilePaths:[]}}function P6(e){return {legacyProjectConfig:{...e.config,fileFormat:"v1"},migratedFilePaths:[]}}function pF({project:e,newProjectConfig:t,fileFormatLabel:n,migratedFilePaths:o}){e.config=t,Ad(e.config,e.configFilePath),o.push(e.configFilePath),R.info(`Updated ${e.configFilePath} to use ${n} file format`),t.hooks?.postSave&&(R.info(`Running post-save hook for ${o.length} migrated files`),ew([...new Set(o)],t));}async function NT(e,t,n){for(let o=0;o<e.length;o+=t)await Promise.all(e.slice(o,o+t).map(n));}function mF(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function qke(e){let t=e.ai??={},n=t.agentConfig??={},o=[];for(let[s,a]of Object.entries(og)){let l=n[s];l!==a&&(l?.startsWith(`${a}.`)||(n[s]=a,o.push({type:s,newValue:a})));}let r=t.useMemory!==true;r&&(t.useMemory=true);let i=t.failureRecovery!==true;return i&&(t.failureRecovery=true),{upgradedAgents:o,enabledUseMemory:r,enabledFailureRecovery:i}}async function O6({project:e,dryRun:t,migrate:n}){let o=e.config.fileFormat!=="v2",r=qke(e.config);return o?{fileFormatChanged:o,aiSettings:r,migration:await n()}:(!t&&mF(r)&&Ad(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:r,migration:hF()})}function hF(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function gF({summary:e,fileFormatChanged:t,aiSettings:n,dryRun:o,testNoun:r="test",moduleNoun:i="module"}){let s=o?"Would migrate":"Migrated",a=jb(r,e.migratedTestPaths.length),l=jb(i,e.migratedModulePaths.length);R.info(`${s} ${e.migratedTestPaths.length} ${a} and ${e.migratedModulePaths.length} ${l} to v2.`),(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&R.dimmed(` Skipped ${e.alreadyV2TestCount} already-v2 ${jb(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-v2 ${jb(i,e.alreadyV2ModuleCount)}.`),t&&R.dimmed(" + fileFormat: v2");for(let c of n.upgradedAgents)R.dimmed(` + ai.agentConfig.${c.type}: ${c.newValue}`);n.enabledUseMemory&&R.dimmed(" + ai.useMemory: true"),n.enabledFailureRecovery&&R.dimmed(" + ai.failureRecovery: true");}var fF=false,M6;try{let e=await import('@sentry/node'),t="production";e.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:t,enabled:t!=="development",dist:"production",release:"cli@3.16.2",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(n,o){return v3(o?.originalException)||VE(o?.originalException,ke)||R3(o?.originalException)?null:n}}),EY(e.captureException),M6=n=>{if(!n){e.setUser(null);return}e.setUser({id:n.userId,organizationId:n.orgId,...n.email&&{email:n.email}});},fF=!0;}catch{}var N6=e=>M6?.(e);var Yke=new pR(30,60*1e3),nI="https://api.momentic.ai",Mf,L6,kd=e=>{nI=e;},$r=()=>nI,k6=()=>vg(nI),Qu=e=>{L6=e;},cl=()=>L6,qo=()=>Mf,D6=()=>{if(!Mf)throw new Error("Global API client has not been initialized.");return Mf};var LT,Qw,F6,B6,U6,Zw,H6,G6=({authInfo:e,apiKey:t,apiClient:n})=>{Mf=n,LT=e.orgId,Qw=e.userId,F6=e.email,B6=e.name,U6=e.pylonEmailHash,Zw=t,H6=e.selfServe;},Nf=async({apiClient:e,apiKey:t,skipPrompts:n})=>{let o=await wm({client:e});return G6({authInfo:o,apiKey:t,apiClient:e}),o},oI=async({apiKey:e,mode:t,runner:n})=>{if(Mf&&LT&&Zw)return LT;let o=new Dt({baseUrl:nI,apiKey:e,logger:R,mode:t,runner:n});Mf=o;try{let r=await o.getAuthInfo();return G6({authInfo:r,apiKey:e,apiClient:o}),r.orgId}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},oo=()=>{if(!LT)throw new Error("Your organization ID is invalid.");return LT},yc=()=>{if(!Qw)throw new Error("Your user ID is invalid.");return Qw},j6=()=>Qw,Lf=()=>F6,$6=()=>B6,V6=()=>U6,rI=()=>H6,Hs=()=>{if(!Zw)throw new Error("Your API key is invalid.");return Zw},eI,tI,Dd=()=>{tI?.abort(),tI=void 0;},kf=(e,t)=>{eI=e,Dd(),tI=new AbortController;let n=tI.signal,o=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=Jn__default.resolve(e.rootDir,r.envFile);try{if(Oo__default.lstatSync(i).isSymbolicLink())return;Oo__default.existsSync(i)&&o.push(i);}catch(s){R.warn({err:s},`Failed to check if env file ${i} exists`);}});try{Jke({filesToWatch:o,revalidator:t,signal:n,project:e});}catch(r){R.error({err:r},"Failed to start config file watchers");}};async function Df({project:e,apiClient:t}){let n=o=>Fs({project:o,apiClient:t});kf(await n(e),async o=>n(await sn({configFilePath:o})));}var st=()=>{if(!eI)throw new ke("No Momentic project is currently loaded. Open or select a project before invoking this action.");return eI};function Jke({filesToWatch:e,revalidator:t,signal:n,project:o}){R.debug("Starting watch on the following files:"),e.forEach(r=>{R.debug(`- ${r}`);}),e.forEach(r=>{let i=async(a,l)=>{if(a.mtime.getTime()!==l.mtime.getTime()){Yke.increment("setLocalProject")&&R.warn(`A file change under the ${o.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`);try{eI=await Promise.resolve(t(o.configFilePath));}catch(c){R.warn({err:c},`Failed to reload Momentic configuration after a change to ${r}; continuing with the previously loaded configuration`);}}};Oo__default.watchFile(r,{persistent:false},i);let s=()=>{Oo__default.unwatchFile(r,i),n.removeEventListener("abort",s);};n.addEventListener("abort",s);});}function St(e){return function(...t){let n=t[t.length-1],o=e(...t);Promise.resolve(o).catch(n);}}var Qke="3.16.2",_m=xg({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:Qke});(async()=>{try{let e=await Aa(_m);e.gitBranchName&&_m.addBinding("branch",e.gitBranchName);}catch{}})();var z6=Router();z6.get("/",async(e,t)=>{let n=st(),o=qo();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await ri(_m,o,n),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:s,alwaysSaveCache:a}=cl(),l=!s&&(a||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var yF=z6;var tDe=5e3,nDe=[".js",".mjs",".cjs",".ts"];function SF(e={}){let t=Router();function n(){let u=st();return Jn__default.dirname(u.configFilePath)}function o(u){return Jn__default.join(n(),...u)}function r(u){let p=Jn__default.relative(n(),u);return p?p.split(Jn__default.sep):[]}function i(u,p){let m=Oo__default.statSync(u),h=r(u);return oN.parse({name:p,absolutePath:u,relativePath:h.join(Jn__default.sep),pathSegments:h,isDirectory:m.isDirectory(),size:m.size,createdAt:m.birthtime,modifiedAt:m.mtime,accessedAt:m.atime})}function s(u){let p=Jn__default.relative(n(),u);return p===""||!p.startsWith("..")&&!Jn__default.isAbsolute(p)}async function a(u){let p=st();return Sd(["*"],{cwd:u,ignore:p.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(tDe)})}function l(u){let p=u.trimStart().replace(/^file:\/\//,"").replaceAll("\\","/"),m=p.lastIndexOf("/");return m===-1?{directoryText:"",filePrefix:p}:{directoryText:p.slice(0,m+1),filePrefix:p.slice(m+1)}}function c(u){return u.replaceAll("\\","/").split("/").filter(p=>p&&p!==".")}function d({sourceDirectoryPath:u,targetPath:p,isDirectory:m}){let h=Jn__default.relative(u,p).split(Jn__default.sep).join("/");return m?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",St(async(u,p,m)=>{let h=m1.safeParse(u.body);if(!h.success){p.status(400).json({error:`Failed to parse file-reference-suggestions body: ${h.error.message}`});return}let{sourceDirectoryPath:g="",value:f}=h.data,y=new Set((h.data.allowedExtensions??nDe).map(v=>v.toLowerCase())),S=l(f);if(S.directoryText.startsWith("/")){p.status(200).json({suggestions:[]});return}let T=Jn__default.resolve(n(),...c(g)),E=Jn__default.resolve(T,...c(S.directoryText));if(!s(T)||!s(E)){p.status(200).json({suggestions:[]});return}if(!Oo__default.existsSync(E)||!Oo__default.statSync(E).isDirectory()){p.status(200).json({suggestions:[]});return}let C;try{C=await a(E);}catch(v){if(v instanceof Error&&v.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw v}let w=C.map(v=>{let _=Jn__default.join(E,v);return {entryName:v,targetPath:_,isDirectory:Oo__default.statSync(_).isDirectory()}}),x=S.filePrefix.toLowerCase(),I=w.filter(v=>v.entryName.startsWith(".")||!v.entryName.toLowerCase().startsWith(x)?false:v.isDirectory?true:y.has(Jn__default.extname(v.entryName).toLowerCase())).sort((v,_)=>v.isDirectory!==_.isDirectory?v.isDirectory?-1:1:v.entryName.localeCompare(_.entryName)).map(v=>({name:v.entryName,isDirectory:v.isDirectory,value:d({sourceDirectoryPath:T,targetPath:v.targetPath,isDirectory:v.isDirectory})}));p.status(200).json({suggestions:I});})),t.post("/",St(async(u,p,m)=>{let h;try{h=p1.parse(u.body).pathSegments;}catch(E){p.status(400).json({error:`Failed to parse folder read body: ${E}`});return}let g=o(h);if(!Oo__default.existsSync(g)){p.status(404).json({error:`Path not found: ${h.join(Jn__default.sep)}`});return}if(!Oo__default.statSync(g).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(Jn__default.sep)}`});return}let y;try{y=await a(g);}catch(E){if(E instanceof Error&&E.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw E}let S=y.map(E=>{let C=Jn__default.join(g,E);return i(C,E)});if(e.allowedFileTypes){let E=new Set(e.allowedFileTypes);S=(await Promise.all(S.map(async C=>{if(C.isDirectory||!(C.name.endsWith(".test.yaml")||C.name.endsWith(".module.yaml")))return C;let x=await oDe(C.absolutePath);return x!==void 0&&E.has(x)?C:null}))).filter(C=>C!==null);}let T={absolutePath:g,pathSegments:h,contents:S};p.status(200).json(T);})),t.put("/",St(async(u,p,m)=>{let h;try{h=h1.parse(u.body).pathSegments;}catch(y){p.status(400).json({error:`Failed to parse folder create body: ${y}`});return}let g=o(h);if(Oo__default.existsSync(g)){p.status(200).json({success:true,message:`Folder already exists: ${h.join(Jn__default.sep)}`,pathSegments:h});return}Oo__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(Jn__default.sep)}`,pathSegments:h};p.status(201).json(f);})),t.patch("/",St(async(u,p,m)=>{let h,g;try{let E=g1.parse(u.body);h=E.pathSegments,g=E.newPathSegments;}catch(E){p.status(400).json({error:`Failed to parse folder update body: ${E}`});return}let f=o(h),y=o(g);if(!Oo__default.existsSync(f)){p.status(400).json({error:`Folder not found: ${h.join(Jn__default.sep)}`});return}if(Oo__default.existsSync(y)){p.status(400).json({error:`Destination already exists: ${g.join(Jn__default.sep)}`});return}let S=Jn__default.dirname(y);Oo__default.existsSync(S)||Oo__default.mkdirSync(S,{recursive:true}),Oo__default.renameSync(f,y);let T={success:true,message:`Folder moved from ${h.join(Jn__default.sep)} to ${g.join(Jn__default.sep)}`,pathSegments:g};p.status(200).json(T);})),t.delete("/",St(async(u,p,m)=>{let h,g=true;try{let T=f1.parse(u.body);h=T.pathSegments,g=T.recursive??!0;}catch(T){p.status(400).json({error:`Failed to parse folder delete body: ${T}`});return}let f=o(h);if(!Oo__default.existsSync(f)){p.status(200).json({success:true,message:`Folder not found: ${h.join(Jn__default.sep)}`,pathSegments:h});return}if(!Oo__default.statSync(f).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(Jn__default.sep)}`});return}try{if(g)Oo__default.rmSync(f,{recursive:!0,force:!0});else {if(Oo__default.readdirSync(f).length>0){p.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}Oo__default.rmdirSync(f);}}catch(T){let{status:E,body:C}=YZ(T,`delete folder ${h.join("/")}`);p.status(E).json(C);return}let S={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};p.status(200).json(S);})),t}async function oDe(e){try{let t=await Oo__default.promises.open(e,"r");try{let n=Buffer.alloc(4096),{bytesRead:o}=await t.read(n,0,n.length,0);return n.toString("utf-8",0,o).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await t.close();}}catch{}}var W6=Router();W6.get("/",async(e,t)=>{let n=st(),o=qo();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await ri(_m,o,n);t.status(200).json(r);});var bF=W6;var iDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async()=>{t.info({sessionId:o},"Cancel event received");let r=n.getSession(o);if(!r)throw new Error("No active session found");try{r.controller.setClosed();}catch{}}},q6={event:"cancel",createHandler:iDe};var sDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{testId:o,sessionId:r}=e;return async(i,s)=>{let{stepId:a,environment:l,parentStepIdChain:c}=i;t.info({testId:o,stepId:a},"Clearing AI action cache");try{let d=n.getSession(r);if(!d)throw new Error("No active session found");let u=AR(a,c.join(":")||void 0);await Promise.all(u.map(p=>d.cacheStorage.deleteStepCacheEntry({logger:t,testId:o,key:p,environment:l}))),s({ok:!0});}catch(d){t.error({testId:o,stepId:a,err:d},"Failed to clear AI action cache"),s({ok:false,error:X(d)});}}},K6={event:"clearAIActionCache",createHandler:sDe};var aDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let c=(await a.getBrowserState({skipWait:!0})).serialize();t.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c});}catch(l){t.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message});}}},Y6={event:"fetchA11yTree",createHandler:aDe};var lDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let l=await a.html();i({html:l});}catch(l){t.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message});}}},J6={event:"fetchDom",createHandler:lDe};var cDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return r=>{t.info({sessionId:o,reason:r},`Disconnect event received (${r})`),n.removeSession(o,t);}},X6={event:"disconnect",createHandler:cDe};function cs(e){let{result:t,nestedResults:n}=e;if(!e.nestedResults.length)return;let{firstMetadata:o,lastMetadata:r}=dDe(n);uDe(t,o,r);let i=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await pDe(i,t,o,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function dDe(e){let t=e[0],n;for(;;){switch(t.type){case "PRESET_ACTION":case "CONDITIONAL":n=t;break;case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!t.results.length){n=t;break}t=t.results[0];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(n)break}let o=e[e.length-1],r;for(;;){switch(o.type){case "PRESET_ACTION":{r=o;break}case "AI_ACTION_DYNAMIC":case "CONDITIONAL":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!o.results.length){r=o;break}o=o.results[o.results.length-1];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(r)break}return {firstMetadata:n,lastMetadata:r}}function uDe(e,t,n){t&&(e.beforeUrl=t.beforeUrl),n&&(e.afterUrl=n.afterUrl,e.data=n.data,n.status!=="SUCCESS"&&(e.message=n.message,e.failureClassification=n.failureClassification));}async function pDe(e,t,n,o){await Promise.allSettled(e),n&&(t.beforeSnapshot=n.beforeSnapshot),o&&(t.afterSnapshot=o.afterSnapshot);}async function Q6(e){let t;try{t=new URL(e.url).hostname;}catch{}let n=[];return e.headers.getSetCookie()?.forEach(o=>{let r=BC(o,t);n.push(...r);}),n}function TDe(e,t){if(!e&&!t)return;let n;if(e){let{url:r,options:i}=e;n=new Request(r,i);}let o;if(t){let{body:r,options:i}=t;o=new Response(r??null,i);}return {request:n,response:o}}async function ADe(e,t){switch(e){case "RAW":return t;case "RESPONSE":if(t instanceof Response){let n=[];return t.headers.forEach((r,i)=>{n.push([i,r]);}),{status:t.status,headers:n,body:await t.text()}}else throw new Error("Result is not a Response object")}}var EDe=Object.getPrototypeOf(async function(){}).constructor;async function Z6(e,t,n){let o=t.code;t.options.fragment&&(o=`return ${t.code}`),o=`${o}
321
+ `);}catch(o){t.warn({err:o},"Failed to fetch CLI announcements");}}}var uF="^22.12.0 || >=24.0.0";function x6(){(Ld.satisfies(process.version,uF)||(R.error(`Momentic requires Node.js ${uF}, but you are running ${process.version}. Upgrade Node.js (https://nodejs.org/en/download) and try again.`),process.exit(1)));}var MT=25;function _6(e){return {v2ProjectConfig:{...e.config,fileFormat:"v2"},migratedFilePaths:[]}}function P6(e){return {legacyProjectConfig:{...e.config,fileFormat:"v1"},migratedFilePaths:[]}}function pF({project:e,newProjectConfig:t,fileFormatLabel:n,migratedFilePaths:o}){e.config=t,Ad(e.config,e.configFilePath),o.push(e.configFilePath),R.info(`Updated ${e.configFilePath} to use ${n} file format`),t.hooks?.postSave&&(R.info(`Running post-save hook for ${o.length} migrated files`),ew([...new Set(o)],t));}async function NT(e,t,n){for(let o=0;o<e.length;o+=t)await Promise.all(e.slice(o,o+t).map(n));}function mF(e){return e.upgradedAgents.length>0||e.enabledUseMemory||e.enabledFailureRecovery}function qke(e){let t=e.ai??={},n=t.agentConfig??={},o=[];for(let[s,a]of Object.entries(og)){let l=n[s];l!==a&&(l?.startsWith(`${a}.`)||(n[s]=a,o.push({type:s,newValue:a})));}let r=t.useMemory!==true;r&&(t.useMemory=true);let i=t.failureRecovery!==true;return i&&(t.failureRecovery=true),{upgradedAgents:o,enabledUseMemory:r,enabledFailureRecovery:i}}async function O6({project:e,dryRun:t,migrate:n}){let o=e.config.fileFormat!=="v2",r=qke(e.config);return o?{fileFormatChanged:o,aiSettings:r,migration:await n()}:(!t&&mF(r)&&Ad(e.config,e.configFilePath),{fileFormatChanged:false,aiSettings:r,migration:hF()})}function hF(){return {migratedTestPaths:[],migratedModulePaths:[],alreadyV2TestCount:0,alreadyV2ModuleCount:0}}function gF({summary:e,fileFormatChanged:t,aiSettings:n,dryRun:o,testNoun:r="test",moduleNoun:i="module"}){let s=o?"Would migrate":"Migrated",a=jb(r,e.migratedTestPaths.length),l=jb(i,e.migratedModulePaths.length);R.info(`${s} ${e.migratedTestPaths.length} ${a} and ${e.migratedModulePaths.length} ${l} to v2.`),(e.alreadyV2TestCount>0||e.alreadyV2ModuleCount>0)&&R.dimmed(` Skipped ${e.alreadyV2TestCount} already-v2 ${jb(r,e.alreadyV2TestCount)} and ${e.alreadyV2ModuleCount} already-v2 ${jb(i,e.alreadyV2ModuleCount)}.`),t&&R.dimmed(" + fileFormat: v2");for(let c of n.upgradedAgents)R.dimmed(` + ai.agentConfig.${c.type}: ${c.newValue}`);n.enabledUseMemory&&R.dimmed(" + ai.useMemory: true"),n.enabledFailureRecovery&&R.dimmed(" + ai.failureRecovery: true");}var fF=false,M6;try{let e=await import('@sentry/node'),t="production";e.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:t,enabled:t!=="development",dist:"production",release:"cli@3.16.3",tracesSampleRate:0,skipOpenTelemetrySetup:!0,sendDefaultPii:!0,beforeSend(n,o){return v3(o?.originalException)||VE(o?.originalException,ke)||R3(o?.originalException)?null:n}}),EY(e.captureException),M6=n=>{if(!n){e.setUser(null);return}e.setUser({id:n.userId,organizationId:n.orgId,...n.email&&{email:n.email}});},fF=!0;}catch{}var N6=e=>M6?.(e);var Yke=new pR(30,60*1e3),nI="https://api.momentic.ai",Mf,L6,kd=e=>{nI=e;},$r=()=>nI,k6=()=>vg(nI),Qu=e=>{L6=e;},cl=()=>L6,qo=()=>Mf,D6=()=>{if(!Mf)throw new Error("Global API client has not been initialized.");return Mf};var LT,Qw,F6,B6,U6,Zw,H6,G6=({authInfo:e,apiKey:t,apiClient:n})=>{Mf=n,LT=e.orgId,Qw=e.userId,F6=e.email,B6=e.name,U6=e.pylonEmailHash,Zw=t,H6=e.selfServe;},Nf=async({apiClient:e,apiKey:t,skipPrompts:n})=>{let o=await wm({client:e});return G6({authInfo:o,apiKey:t,apiClient:e}),o},oI=async({apiKey:e,mode:t,runner:n})=>{if(Mf&&LT&&Zw)return LT;let o=new Dt({baseUrl:nI,apiKey:e,logger:R,mode:t,runner:n});Mf=o;try{let r=await o.getAuthInfo();return G6({authInfo:r,apiKey:e,apiClient:o}),r.orgId}catch(r){throw new Error(`Error checking API key against server: ${r}`,{cause:r})}},oo=()=>{if(!LT)throw new Error("Your organization ID is invalid.");return LT},yc=()=>{if(!Qw)throw new Error("Your user ID is invalid.");return Qw},j6=()=>Qw,Lf=()=>F6,$6=()=>B6,V6=()=>U6,rI=()=>H6,Hs=()=>{if(!Zw)throw new Error("Your API key is invalid.");return Zw},eI,tI,Dd=()=>{tI?.abort(),tI=void 0;},kf=(e,t)=>{eI=e,Dd(),tI=new AbortController;let n=tI.signal,o=[e.configFilePath];e.config.environments?.forEach(r=>{if(!r.envFile)return;let i=Jn__default.resolve(e.rootDir,r.envFile);try{if(Oo__default.lstatSync(i).isSymbolicLink())return;Oo__default.existsSync(i)&&o.push(i);}catch(s){R.warn({err:s},`Failed to check if env file ${i} exists`);}});try{Jke({filesToWatch:o,revalidator:t,signal:n,project:e});}catch(r){R.error({err:r},"Failed to start config file watchers");}};async function Df({project:e,apiClient:t}){let n=o=>Fs({project:o,apiClient:t});kf(await n(e),async o=>n(await sn({configFilePath:o})));}var st=()=>{if(!eI)throw new ke("No Momentic project is currently loaded. Open or select a project before invoking this action.");return eI};function Jke({filesToWatch:e,revalidator:t,signal:n,project:o}){R.debug("Starting watch on the following files:"),e.forEach(r=>{R.debug(`- ${r}`);}),e.forEach(r=>{let i=async(a,l)=>{if(a.mtime.getTime()!==l.mtime.getTime()){Yke.increment("setLocalProject")&&R.warn(`A file change under the ${o.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`);try{eI=await Promise.resolve(t(o.configFilePath));}catch(c){R.warn({err:c},`Failed to reload Momentic configuration after a change to ${r}; continuing with the previously loaded configuration`);}}};Oo__default.watchFile(r,{persistent:false},i);let s=()=>{Oo__default.unwatchFile(r,i),n.removeEventListener("abort",s);};n.addEventListener("abort",s);});}function St(e){return function(...t){let n=t[t.length-1],o=e(...t);Promise.resolve(o).catch(n);}}var Qke="3.16.3",_m=xg({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:Qke});(async()=>{try{let e=await Aa(_m);e.gitBranchName&&_m.addBinding("branch",e.gitBranchName);}catch{}})();var z6=Router();z6.get("/",async(e,t)=>{let n=st(),o=qo();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await ri(_m,o,n),i=r?.gitProtectedBranches&&r?.gitBranchName&&r.gitProtectedBranches.includes(r.gitBranchName),{noCache:s,alwaysSaveCache:a}=cl(),l=!s&&(a||!i);t.status(200).json({saveCaches:l,checkedOutBranch:r?.gitBranchName});});var yF=z6;var tDe=5e3,nDe=[".js",".mjs",".cjs",".ts"];function SF(e={}){let t=Router();function n(){let u=st();return Jn__default.dirname(u.configFilePath)}function o(u){return Jn__default.join(n(),...u)}function r(u){let p=Jn__default.relative(n(),u);return p?p.split(Jn__default.sep):[]}function i(u,p){let m=Oo__default.statSync(u),h=r(u);return oN.parse({name:p,absolutePath:u,relativePath:h.join(Jn__default.sep),pathSegments:h,isDirectory:m.isDirectory(),size:m.size,createdAt:m.birthtime,modifiedAt:m.mtime,accessedAt:m.atime})}function s(u){let p=Jn__default.relative(n(),u);return p===""||!p.startsWith("..")&&!Jn__default.isAbsolute(p)}async function a(u){let p=st();return Sd(["*"],{cwd:u,ignore:p.config.exclude??[],maxDepth:1,nodir:false,signal:AbortSignal.timeout(tDe)})}function l(u){let p=u.trimStart().replace(/^file:\/\//,"").replaceAll("\\","/"),m=p.lastIndexOf("/");return m===-1?{directoryText:"",filePrefix:p}:{directoryText:p.slice(0,m+1),filePrefix:p.slice(m+1)}}function c(u){return u.replaceAll("\\","/").split("/").filter(p=>p&&p!==".")}function d({sourceDirectoryPath:u,targetPath:p,isDirectory:m}){let h=Jn__default.relative(u,p).split(Jn__default.sep).join("/");return m?h?`${h}/`:"./":h}return t.post("/file-reference-suggestions",St(async(u,p,m)=>{let h=m1.safeParse(u.body);if(!h.success){p.status(400).json({error:`Failed to parse file-reference-suggestions body: ${h.error.message}`});return}let{sourceDirectoryPath:g="",value:f}=h.data,y=new Set((h.data.allowedExtensions??nDe).map(v=>v.toLowerCase())),S=l(f);if(S.directoryText.startsWith("/")){p.status(200).json({suggestions:[]});return}let T=Jn__default.resolve(n(),...c(g)),E=Jn__default.resolve(T,...c(S.directoryText));if(!s(T)||!s(E)){p.status(200).json({suggestions:[]});return}if(!Oo__default.existsSync(E)||!Oo__default.statSync(E).isDirectory()){p.status(200).json({suggestions:[]});return}let C;try{C=await a(E);}catch(v){if(v instanceof Error&&v.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw v}let w=C.map(v=>{let _=Jn__default.join(E,v);return {entryName:v,targetPath:_,isDirectory:Oo__default.statSync(_).isDirectory()}}),x=S.filePrefix.toLowerCase(),I=w.filter(v=>v.entryName.startsWith(".")||!v.entryName.toLowerCase().startsWith(x)?false:v.isDirectory?true:y.has(Jn__default.extname(v.entryName).toLowerCase())).sort((v,_)=>v.isDirectory!==_.isDirectory?v.isDirectory?-1:1:v.entryName.localeCompare(_.entryName)).map(v=>({name:v.entryName,isDirectory:v.isDirectory,value:d({sourceDirectoryPath:T,targetPath:v.targetPath,isDirectory:v.isDirectory})}));p.status(200).json({suggestions:I});})),t.post("/",St(async(u,p,m)=>{let h;try{h=p1.parse(u.body).pathSegments;}catch(E){p.status(400).json({error:`Failed to parse folder read body: ${E}`});return}let g=o(h);if(!Oo__default.existsSync(g)){p.status(404).json({error:`Path not found: ${h.join(Jn__default.sep)}`});return}if(!Oo__default.statSync(g).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(Jn__default.sep)}`});return}let y;try{y=await a(g);}catch(E){if(E instanceof Error&&E.name==="TimeoutError"){p.status(408).json({error:"Folder listing timed out. This directory may contain too many files."});return}throw E}let S=y.map(E=>{let C=Jn__default.join(g,E);return i(C,E)});if(e.allowedFileTypes){let E=new Set(e.allowedFileTypes);S=(await Promise.all(S.map(async C=>{if(C.isDirectory||!(C.name.endsWith(".test.yaml")||C.name.endsWith(".module.yaml")))return C;let x=await oDe(C.absolutePath);return x!==void 0&&E.has(x)?C:null}))).filter(C=>C!==null);}let T={absolutePath:g,pathSegments:h,contents:S};p.status(200).json(T);})),t.put("/",St(async(u,p,m)=>{let h;try{h=h1.parse(u.body).pathSegments;}catch(y){p.status(400).json({error:`Failed to parse folder create body: ${y}`});return}let g=o(h);if(Oo__default.existsSync(g)){p.status(200).json({success:true,message:`Folder already exists: ${h.join(Jn__default.sep)}`,pathSegments:h});return}Oo__default.mkdirSync(g,{recursive:true});let f={success:true,message:`Folder created: ${h.join(Jn__default.sep)}`,pathSegments:h};p.status(201).json(f);})),t.patch("/",St(async(u,p,m)=>{let h,g;try{let E=g1.parse(u.body);h=E.pathSegments,g=E.newPathSegments;}catch(E){p.status(400).json({error:`Failed to parse folder update body: ${E}`});return}let f=o(h),y=o(g);if(!Oo__default.existsSync(f)){p.status(400).json({error:`Folder not found: ${h.join(Jn__default.sep)}`});return}if(Oo__default.existsSync(y)){p.status(400).json({error:`Destination already exists: ${g.join(Jn__default.sep)}`});return}let S=Jn__default.dirname(y);Oo__default.existsSync(S)||Oo__default.mkdirSync(S,{recursive:true}),Oo__default.renameSync(f,y);let T={success:true,message:`Folder moved from ${h.join(Jn__default.sep)} to ${g.join(Jn__default.sep)}`,pathSegments:g};p.status(200).json(T);})),t.delete("/",St(async(u,p,m)=>{let h,g=true;try{let T=f1.parse(u.body);h=T.pathSegments,g=T.recursive??!0;}catch(T){p.status(400).json({error:`Failed to parse folder delete body: ${T}`});return}let f=o(h);if(!Oo__default.existsSync(f)){p.status(200).json({success:true,message:`Folder not found: ${h.join(Jn__default.sep)}`,pathSegments:h});return}if(!Oo__default.statSync(f).isDirectory()){p.status(400).json({error:`Path is not a directory: ${h.join(Jn__default.sep)}`});return}try{if(g)Oo__default.rmSync(f,{recursive:!0,force:!0});else {if(Oo__default.readdirSync(f).length>0){p.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${h.join("/")}`});return}Oo__default.rmdirSync(f);}}catch(T){let{status:E,body:C}=YZ(T,`delete folder ${h.join("/")}`);p.status(E).json(C);return}let S={success:true,message:`Folder deleted: ${h.join("/")}`,pathSegments:h};p.status(200).json(S);})),t}async function oDe(e){try{let t=await Oo__default.promises.open(e,"r");try{let n=Buffer.alloc(4096),{bytesRead:o}=await t.read(n,0,n.length,0);return n.toString("utf-8",0,o).match(/^fileType:\s*(.+)$/m)?.[1]?.trim()}finally{await t.close();}}catch{}}var W6=Router();W6.get("/",async(e,t)=>{let n=st(),o=qo();if(!o){t.status(500).json({message:"API client not initialized"});return}let r=await ri(_m,o,n);t.status(200).json(r);});var bF=W6;var iDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async()=>{t.info({sessionId:o},"Cancel event received");let r=n.getSession(o);if(!r)throw new Error("No active session found");try{r.controller.setClosed();}catch{}}},q6={event:"cancel",createHandler:iDe};var sDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{testId:o,sessionId:r}=e;return async(i,s)=>{let{stepId:a,environment:l,parentStepIdChain:c}=i;t.info({testId:o,stepId:a},"Clearing AI action cache");try{let d=n.getSession(r);if(!d)throw new Error("No active session found");let u=AR(a,c.join(":")||void 0);await Promise.all(u.map(p=>d.cacheStorage.deleteStepCacheEntry({logger:t,testId:o,key:p,environment:l}))),s({ok:!0});}catch(d){t.error({testId:o,stepId:a,err:d},"Failed to clear AI action cache"),s({ok:false,error:X(d)});}}},K6={event:"clearAIActionCache",createHandler:sDe};var aDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let c=(await a.getBrowserState({skipWait:!0})).serialize();t.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c});}catch(l){t.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message});}}},Y6={event:"fetchA11yTree",createHandler:aDe};var lDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return async(r,i)=>{let s=n.getSession(o);if(!s)throw new Error("No active session found");s.controller.setOpen();let a=s.controller.browser;try{let l=await a.html();i({html:l});}catch(l){t.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message});}}},J6={event:"fetchDom",createHandler:lDe};var cDe=({metadata:e,logger:t,globalE2eStateManager:n})=>{let{sessionId:o}=e;return r=>{t.info({sessionId:o,reason:r},`Disconnect event received (${r})`),n.removeSession(o,t);}},X6={event:"disconnect",createHandler:cDe};function cs(e){let{result:t,nestedResults:n}=e;if(!e.nestedResults.length)return;let{firstMetadata:o,lastMetadata:r}=dDe(n);uDe(t,o,r);let i=[...e.asyncTasks];e.asyncTasks.push((async()=>{try{await pDe(i,t,o,r);}catch(s){e.logger.error({result:e.result,err:s},"Error hoisting scalar result metadata");}})());}function dDe(e){let t=e[0],n;for(;;){switch(t.type){case "PRESET_ACTION":case "CONDITIONAL":n=t;break;case "AI_ACTION_DYNAMIC":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!t.results.length){n=t;break}t=t.results[0];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(n)break}let o=e[e.length-1],r;for(;;){switch(o.type){case "PRESET_ACTION":{r=o;break}case "AI_ACTION_DYNAMIC":case "CONDITIONAL":case "AI_ACTION":case "MODULE":case "SECTION":case "WHILE_LOOP":if(!o.results.length){r=o;break}o=o.results[o.results.length-1];break;default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}if(r)break}return {firstMetadata:n,lastMetadata:r}}function uDe(e,t,n){t&&(e.beforeUrl=t.beforeUrl),n&&(e.afterUrl=n.afterUrl,e.data=n.data,n.status!=="SUCCESS"&&(e.message=n.message,e.failureClassification=n.failureClassification));}async function pDe(e,t,n,o){await Promise.allSettled(e),n&&(t.beforeSnapshot=n.beforeSnapshot),o&&(t.afterSnapshot=o.afterSnapshot);}async function Q6(e){let t;try{t=new URL(e.url).hostname;}catch{}let n=[];return e.headers.getSetCookie()?.forEach(o=>{let r=BC(o,t);n.push(...r);}),n}function TDe(e,t){if(!e&&!t)return;let n;if(e){let{url:r,options:i}=e;n=new Request(r,i);}let o;if(t){let{body:r,options:i}=t;o=new Response(r??null,i);}return {request:n,response:o}}async function ADe(e,t){switch(e){case "RAW":return t;case "RESPONSE":if(t instanceof Response){let n=[];return t.headers.forEach((r,i)=>{n.push([i,r]);}),{status:t.status,headers:n,body:await t.text()}}else throw new Error("Result is not a Response object")}}var EDe=Object.getPrototypeOf(async function(){}).constructor;async function Z6(e,t,n){let o=t.code;t.options.fragment&&(o=`return ${t.code}`),o=`${o}
322
322
  //# sourceURL=${$C}`;let{env:r,additionalBindings:i,request:s,response:a}=t.bindings,l=t.tools,c={},d=(T,E)=>{r[T]=E,c[T]=E;},u={},p=(T,E)=>{r[T]=E,u[T]=E;},m;o.includes("Octokit")&&(m=(await import('@octokit/rest')).Octokit);let h;o.includes("createAppAuth")&&(h=(await import('@octokit/auth-app')).createAppAuth);let g=async()=>{try{return await Promise.resolve(new EDe("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","mock",...Object.keys(i??{}),o)(gDe,yDe,l.fakerInstance??faker,hDe,bDe,m,h,SDe,fDe,Q6,r,t.options.disallowVariableUpdates?void 0:d,t.options.disallowVariableUpdates?void 0:p,E=>l.sms.send(E),E=>l.sms.fetchLatest(E),l.email,l.sms,TDe(s,a),...Object.values(i??{})))}catch(T){throw new UE(X(T),{cause:T})}},f=true,y,S;try{let T=await _e(g(),{milliseconds:t.options.timeoutMs,message:`Timeout of ${t.options.timeoutMs}ms exceeded for code execution`,signal:t.signal});y=await ADe(t.options.responseSerialization??"RAW",T);}catch(T){n.error({err:T,env:r,evalCode:o},`[${e}] Error executing code: ${T}`),f=false,T instanceof vu?S=`Timeout of ${t.options.timeoutMs}ms exceeded for code execution`:S=T instanceof Error?T.message:`${T}`;}return {result:y,variableUpdates:c,persistentVariableUpdates:u,success:f,error:S}}async function e8({code:e,fragment:t,context:n,localTools:o,logger:r,signal:i,timeoutMs:s=Tu,disallowVariableUpdates:a,additionalBindings:l,responseSerialization:c,mock:d}){let u=randomUUID(),p=await Z6(u,{code:e,options:{fragment:t,timeoutMs:s,disallowVariableUpdates:a,responseSerialization:c},bindings:{...n.toObjectCopy(),...d,additionalBindings:l},tools:o,signal:i},r);return R.debug(`[${u}] Got execution result: ${JSON.stringify(p)}`),p}var IDe=vAe(global.fetch,{retries:3,retryOn:function(e,t,n){return !!(t!==null||n&&n.status>=500)},retryDelay:function(e){return Math.pow(2,e)*500}}),t8=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,n8=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function o8({orgId:e,code:t,fragment:n,context:o,timeoutMs:r=Tu,retries:i=2,signal:s,logger:a,additionalBindings:l,disallowVariableUpdates:c,responseSerialization:d,mock:u}){if(!t8)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,h=0;if(!n8)throw new Error("Missing lambda auth secret.");let g=createHmac("sha256",n8).update(e).digest("hex");for(;h<=i;){h++,s?.throwIfAborted();let y={id:randomUUID(),orgId:e,momenticLambdaAuthHash:g,code:t,fragment:n,state:{...o.toObjectCopy(),...u,additionalBindings:l},timeoutMs:r,disallowVariableUpdates:c,responseSerialization:d};try{if(p=await _e(IDe(t8,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{milliseconds:r,message:`Timeout of ${r}ms exceeded for code execution`,signal:s}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);m=void 0;break}catch(S){m=S;}}if(m)throw a.error({err:m},"Failed to evaluate code remotely"),m;if(!p)throw new Error(`An unexpected code evaluation error occurred${m?`: ${m}`:""}`);let f;try{f=LW.parse(await p.json());}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Zu(e){let t;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)t=await o8(e);else if(e.localTools)t=await e8({...e,localTools:e.localTools});else throw new Error("No code evaluation environment available");if(t.error){let n=`Failed to evaluate code:
323
323
  ${t.error}
324
324
  Code received:
@@ -5773,7 +5773,7 @@ ${e}`;case "ELEMENT_CHECK":return `${n7}
5773
5773
  ${e}`;default:return e}}async function wa({frameConfig:e,action:t,browser:n}){let o=n.getActiveFrameConfig();e?n.setActiveFrameConfig(e):o?.type==="auto"&&n.setActiveFrameConfig(void 0);try{return await t()}finally{n.setActiveFrameConfig(o);}}var sBe=["NAVIGATE","NEW_TAB","CLOSE_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function i7({beforeUrl:e,beforePages:t,browser:n,command:o,logger:r}){if(sBe.includes(o.type))return;await yo().startAsyncSpan("AUTO_FOLLOW_NEW_TABS",async s=>{let c=("cache"in o&&o.cache&&"target"in o.cache?o.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??false?300:3e3,d=Date.now(),u=0;for(r.info({command:o.type,beforePages:t,beforeUrl:e,timeout:c},"Checking for new tabs to auto-follow");u===0||Date.now()-d<c;){await Qe(250),u++;let p=(await n.getOpenPages()).map(h=>h.url),m=n.url();if(p.length!==t.length)for(let h=p.length-1;h>=t.length;h--){let g=p[h];if(Fu(g,r)&&g!==e&&g!==m){r.info({beforePages:t,afterPages:p,beforeUrl:e},"Auto-following new tab after preset action"),await n.switchToPage({type:"INDEX",index:String(h)}),s.result={followed:true};return}}}s.result={followed:false};});}async function Ac(e,t={}){let n=await e.getBrowserState(t);return {serializedTree:n.serialize(t.serializationOpts),tree:n}}var s7=e=>!!e&&Sh(e),a7=e=>{let{cache:t,description:n,disableSecondaryCacheResolution:o,logger:r}=e,i=t,s=false,a;if(i&&o&&i.targetSource==="HEURISTIC_HEALED"&&(s=true,a="Heuristic healed cache incompatible",i=void 0),i){let l=i.inputDescription;(l?!o7(n,l):!!n)&&(r.warn({old:i.inputDescription,new:n},"Target cache was generated with a different description, clearing it automatically"),s=true,a="Description changed",i=void 0);}return {cache:i,cacheBustedBeforeAction:s,cacheBustReason:a}};var c7={minChunkTokenCount:1e4,acceptableChunkTokenCount:25e3,maxChunkTokenCount:5e4,maxLineLength:4e3},l7=/<(\S+) id="(\d+)".*?>/g,aBe=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,d7=["h1","h2","section","footer","nav","aside","form","label","dialog"],lBe=[...d7,"span","div","h3"],cBe=["table","select","form","ul","ol","menu","pre","code","dialog"],dBe=["table","form","dialog","nav","section","ul","select"];function u7(e){return uBe(e)}function uBe({logger:e,serializedTree:t,options:n}){let{minChunkTokenCount:o,acceptableChunkTokenCount:r,maxChunkTokenCount:i,maxLineLength:s}=n,a=[],l=t.split(`
5774
5774
  `),c=0,d=[],u=0,p=[],m=[],h=false;for(;c<l.length;){h&&(a.push({ids:p,content:d.join(`
5775
5775
  `),tokenLength:u}),d=[],u=0,p=m.length?[m[m.length-1].id]:[],h=false);let g=l[c],f=Et(g);u+=f,g.length>s&&(g=g.slice(0,s));let T=Array.from(g.matchAll(l7)).map(V=>V&&V.length>=3?{tagName:V[1],id:V[2]}:void 0).filter(V=>!!V),C=Array.from(g.matchAll(aBe)).map(V=>V&&(V[2]||V[4])).filter(V=>!!V);C.reverse();let w=g.replace(/ id="[0-9]+"/g,"");d.push(w);for(let V of T)p.push(V.id),m.push(V);for(let V of C){let re=m[m.length-1];re&&re.tagName===V&&m.pop();}let x=m.some(V=>cBe.includes(V.tagName)),I=l[c+1]??"",v=Et(I),P=Array.from(I.matchAll(l7)).map(V=>V&&V.length>2?V[1]:void 0).filter(V=>!!V),L=P.some(V=>d7.includes(V)),k=P.some(V=>lBe.includes(V));u+v>=i&&(h=true),u>=o&&(L&&!x||C.some(V=>dBe.includes(V)))&&(h=true),u>=r&&k&&!x&&(h=true),c++;}return d.length&&a.push({ids:p,content:d.join(`
5776
- `),tokenLength:u}),a.forEach((g,f)=>{let y=g.ids[0],S=g.ids[g.ids.length-1];e.debug({tokenLength:g.tokenLength,minId:y,maxId:S},`Chunk for page filtering (index ${f+1}/${a.length})`);}),{chunks:a}}var p7=5e6,mBe=1e5,hBe=3e4,gBe=6e4,fBe=1e5;async function Gs(e){let{fixtures:t}=e,{logger:n}=t,o=e.tree,r=e.serializedTree,i=Et(r);if(i>p7)throw new te("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${p7} tokens.`);if(i>mBe){let s=u7({serializedTree:r,options:c7,logger:n}),a=randomUUID();o=await yBe({...e,chunks:s.chunks,callId:a}),r=o.serialize();let l=Et(r);n.info({oldTokens:i,newTokens:l,langfuseCallId:a},"Filtered page using AI chunk ranking");}return r}async function yBe({type:e,callId:t,chunks:n,description:o,fixtures:r,tree:i}){let{generator:s,signal:a,logger:l}=r,c=await s.rankChunksWithAi({chunks:n,description:o,type:e,softTokenLimit:hBe,mediumTokenLimit:gBe,hardTokenLimit:fBe,callId:t},{abortSignal:a,logger:l,loggerTags:jt(l)}),d=[];return n.forEach((p,m)=>{c.indices.includes(m)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}async function p0(e,t){if(!e.description)throw new te("UserConfigurationError","Cannot locate element with empty description");return wa({action:async()=>bBe(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function bBe(e,t){let{disableCache:n,testContext:o,filterByViewport:r,skipWait:i,source:s,memory:a,logger:l,allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,skipSavingVisualAttributes:p,isAutoHeal:m,cacheBustReason:h,acceptElementMovedError:g}=e,{orgId:f,browser:y,localCodeEvalTools:S,generator:T,abortSignal:E}=t,C=e.description,w=yo(),x=e.useMemory&&!n;o&&(C=await li({orgId:f,s:C,context:o,localTools:S,signal:E,logger:l})),s&&(C=r7(C,s));let{serializedTree:I,tree:v}=await w.startAsyncSpan("GET_PAGE_STATE",async()=>Ac(y,{allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,filterByViewport:r,abortSignal:E,skipWait:i,logger:l}),{}),_=await w.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let $,B=Date.now(),Q;for(;!$&&Date.now()-B<3e3;){E.throwIfAborted();try{$=await y.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(K){Q=K;}}if(!$)throw new te("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${Q?.message}`);return $}),P=I,L=false,V=`data:image/jpeg;base64,${_.toString("base64")}`,re=jt(l);P=await Gs({type:"locator",description:C,screenshot:V,serializedTree:I,tree:v,fixtures:{generator:T,signal:E,logger:l,orgId:f}}),P!==I&&(L=true);let ne=await w.startAsyncSpan("AI_LOCATOR_CALL",async $=>{m&&($.attributes.isAutoHeal=true),h&&($.attributes.cacheBustReason=h);let B=await T.getElementLocation({browserState:P,goal:C,screenshot:V,source:s,memory:x?a:void 0},{disableCache:n,abortSignal:E,logger:l,loggerTags:re,useMemory:x,cacheBustReason:h});if($.result=B,x&&($.attributes.useMemory=true,$.attributes.memoryTraces=B.rememberedTraces??[],B.updatedMemory&&($.attributes.memorySavedNewResult=true)),w.storeTraceAsset){let Q=randomUUID();w.storeTraceAsset({snapshotId:Q,data:_}),$.screenshotSnapshotId=Q;}return B});if(l.debug({usedRag:L,result:ne},"Got locator result"),!(ne.id>0))throw new Nh(`Could not find any relevant element: ${ne.thoughts}`,ne.updatedMemory?{type:"GCS_TRACES",traces:ne.updatedMemory}:void 0);let{resolution:W,target:M,frameConfig:Y}=await w.startAsyncSpan("TARGET_RESOLUTION",async $=>{let B=await y.createTargetFromA11yId({id:ne.id,requirements:ne.requirements,additionalElements:ne.additionalElements,description:C,targetSource:"AI",logger:l,skipSavingVisualAttributes:p,acceptElementMovedError:g});return $.result={serializedElement:B.target.nodeOnlySerializedHtml??"Unknown HTML element"},B});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new te("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${W.displayString}`);return x&&(ne.updatedMemory?M.memory={type:"GCS_TRACES",traces:ne.updatedMemory}:a&&(M.memory=a)),{thoughts:ne.thoughts,target:M,resolution:W,frameConfig:Y,screenshot:V}}var TBe=15;async function CI({command:e,logger:t,fixtures:n,useMemory:o,maxRetries:r=TBe,recoveryHint:i}){if(!e.assertion.trim())throw new te("ActionFailureError","Assertion command is missing the assertion content");let s=lM.optional().catch(void 0).parse(e.source);e.source&&!s&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let a=yo();return a.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,d=e.timeout?e.timeout*1e3:c.smartWaitingTimeout,u=VX(d,r-1),p=0,m=Date.now(),h=m+d,g=m,f,y,S;try{await wa({action:()=>c.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:c,logger:t});}catch(C){t.warn({err:C},"Failed to clear highlights before AI check, continuing...");}for(;p<r;){n.abortSignal.throwIfAborted();let C=Date.now();if(p>0){if(C>=h)break;let I=h-C,v=g-C,_=Math.min(v,I);_>0&&await Qe(_,n.abortSignal);}let w=Date.now();if(p>0&&w>=h)break;let x=false;try{if(f=await wa({action:async()=>{let v=await h7(c,t,n.abortSignal);return y&&y.serializedTree===v.serializedTree&&y.screenshotBuff.equals(v.screenshotBuff)?(x=!0,f):(y=v,g7({command:e,state:v,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:p,logger:t,source:s,recoveryHint:i}))},frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c}),f?.aiResult.result){f?.updatedMemory&&Kb(e,f.updatedMemory,t);break}else throw f?.aiResult.thoughts?new te("AssertionFailureError",f.aiResult.thoughts):new te("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(I){n.abortSignal.throwIfAborted(),S=I instanceof Error?I:new Error(`${I}`),x?t.info(`AI check attempt ${p} failed (re-used previous result)`):t.info({err:I},`AI check assert attempt ${p} failed, retrying...`);}finally{p++,g=w+u;}}if(!f?.aiResult.result){let C=h-Date.now();C>0&&await Qe(C,n.abortSignal);}if(!f?.aiResult.result)try{f=await wa({action:async()=>g7({command:e,state:await h7(c,t,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:p,logger:t,recoveryHint:i}),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c});}catch(C){n.abortSignal.throwIfAborted(),S=C instanceof Error?C:new Error(`${C}`);}finally{p++;}f?.updatedMemory&&Kb(e,f.updatedMemory,t);let T=f?.afterScreenshotOverride;if(T&&a.storeTraceAsset){let C=randomUUID();a.storeTraceAsset({snapshotId:C,data:T}),l.screenshotSnapshotId=C;}let E=f?.elementScreenshotOverride;if(E&&a.storeTraceAsset){let C=randomUUID();a.storeTraceAsset({snapshotId:C,data:E}),l.elementScreenshotSnapshotId=C;}if(o&&(l.attributes.useMemory=true,l.attributes.memoryTraces=f?.aiResult.rememberedTraces??[],f?.updatedMemory&&(l.attributes.memorySavedNewResult=true)),!f?.aiResult.result){l.result=f?.aiResult??{thoughts:S?.message??"AI check failed after all attempts",result:false};let C=`AI check still failing after ${p} attempts.`;throw S&&(C+=` Latest result: ${S.message}`),new te("AssertionFailureError",C)}return l.result=f.aiResult,{...f,thoughts:f.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:c.url()}})}async function h7(e,t,n){await e.waitForPageLoad({signal:n});let[o,r]=await Promise.all([Ac(e,{abortSignal:n,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...o,screenshotBuff:r}}async function g7({command:e,state:t,fixtures:n,useConsensus:o,useMemory:r,highlightElementsOnFailure:i,attemptNumber:s,source:a,logger:l,recoveryHint:c}){let {browser:d,generator:u,abortSignal:p}=n,{serializedTree:h,tree:g}=t,f=t.screenshotBuff,y=f.toString("base64"),S=d.url(),T=e.contextChoice??"MULTIMODAL",E=h;T!=="VISION_ONLY"&&(E=await Gs({type:"assertion",serializedTree:h,tree:g,description:e.assertion,screenshot:y,fixtures:{generator:u,signal:p,logger:l,orgId:n.orgId}}),E);let C={goal:e.assertion,url:S,memory:r?e.cache?.memory:void 0,browserState:E,screenshot:y,contextChoice:T,source:a,recoveryHint:c},x=await(T==="VISION_ONLY"?(v,_)=>u.getVisualAssertionResult(v,_):(v,_)=>u.getAssertionResult(v,_))(C,{useConsensus:o,attemptNumber:s,useMemory:r,disableCache:!!e.disableCache,abortSignal:p,logger:l,loggerTags:jt(l)}),I;if((x.result||i)&&x.relevantElements?.length){x.relevantElements.map(v=>d.getSerializedFormFromA11yId(v)).filter(v=>!!v);try{let v=x.relevantElements[0],{resolution:_}=await d.createTargetFromA11yId({id:v,description:null,targetSource:"AI",skipSaveToCache:!0});I=await d.screenshot({locator:_.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(v){l.debug({err:v},"Failed to capture element screenshot for trace, continuing...");}await ABe(x.relevantElements,d,l);}return {aiResult:x,afterScreenshotOverride:f,elementScreenshotOverride:I,updatedMemory:r?x.updatedMemory:void 0}}async function ABe(e,t,n){let o=Date.now();for(let r of e){if(Date.now()-o>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await _e(t.highlightA11yId(r),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}});}catch(i){n.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}async function y7(e){let{command:t,logger:n,fixtures:o,disableCache:r}=e,{browser:i,generator:s,abortSignal:a}=o;if(!t.goal.trim())throw new te("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let u=GK(t.schema);if(u)throw new te("UserConfigurationError",u)}let l=await i.getCondensedHtml(),c=await i.screenshot({retries:2}),d=yo();try{return await d.startAsyncSpan("AI_EXTRACTION_CALL",async u=>{let p=await s.getTextExtraction({goal:t.goal,browserState:l,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${c.toString("base64")}`},{disableCache:r,abortSignal:a,loggerTags:jt(n)});if(u.result=p,EBe({tracer:d,span:u,screenshot:c,htmlState:l,logger:n}),p.result==="NOT_FOUND")throw new te("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new te("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:i.url()}})}catch(u){let p=X(u);throw p.includes("MaxGenerationLengthExceededError")?new te("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):p.includes("AIProviderError")&&p.includes("time")?new te("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:u}}):u}}function EBe(e){let{tracer:t,span:n,screenshot:o,htmlState:r,logger:i}=e;if(t.storeTraceAsset)try{let s=randomUUID();t.storeTraceAsset({snapshotId:s,data:o}),n.screenshotSnapshotId=s;let a=randomUUID();t.storeTraceAsset({snapshotId:a,data:Buffer.from(r),extension:"html"}),n.browserStateSnapshotId=a;}catch(s){i.debug({err:s},"Failed to store extraction trace assets");}}async function S7(e,t){let{logger:n}=e,{abortSignal:o,browser:r}=t,i=Date.now();try{await CBe(i,e,t);}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")||o.aborted)return;n.warn({err:s},"Unexpected error occurred during AI smart waiting");let a=r.smartWaitingTimeout-(Date.now()-i);a>0&&await Qe(a,o);}finally{n.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function CBe(e,t,n){let{abortSignal:o,browser:r}=n;if(r.smartWaitingTimeout<3e3){await Qe(r.smartWaitingTimeout,o);return}if(!t.description)throw new te("UserConfigurationError","Cannot locate element with empty description");await _e(vBe(e,t,n),{milliseconds:r.smartWaitingTimeout});}async function vBe(e,t,n){let{logger:o,iframeUrl:r}=t,{browser:i}=n;for(;Date.now()-e<i.smartWaitingTimeout;)if(await wa({action:async()=>RBe(t,n),frameConfig:r?{type:"url",url:r}:void 0,browser:i,logger:o}))return}async function RBe(e,t){let{testContext:n,logger:o}=e,{browser:r,abortSignal:i,localCodeEvalTools:s,orgId:a,generator:l}=t,c=e.description;n&&(c=await li({orgId:a,s:c,context:n,localTools:s,signal:i,logger:o})),i.throwIfAborted();let d;try{d=await r.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(h){throw new te("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${h instanceof Error?h.message:h}`)}let p=`data:image/jpeg;base64,${d.toString("base64")}`;i.throwIfAborted();let m=await l.getSmartWaitingDecision({description:c,screenshot:p},{abortSignal:i,loggerTags:jt(o)});return o.debug({result:m},"Got smart waiting result"),m.isPageReady}var wBe=3e4;async function A7(e){return yo().startAsyncSpan("ELEMENT_ASSERTION",async n=>IBe(e,n),{name:"Element check"})}async function IBe(e,t){let{command:n,timeoutMs:o,fixtures:r,disableCache:i}=e,{abortSignal:s}=r,a=()=>_E(n.cache)?n.cache:void 0,l=a(),c=!i&&!!l?.target&&Sh(l.target),d=cloneDeep(l),u=(E=false)=>{if(l=a(),!!l)if(E){let C=yk(d,l);l.target=C.target,l.updatedAt=C.updatedAt;}else {if(!d){l=void 0;return}l.target=d.target,l.updatedAt=d.updatedAt;}},p=Date.now(),m=c?Math.max(o/10,wBe):0,h=p,g=0,f,y=500,S=false;for(;g<2||Date.now()-p<o;){g++,g>1&&await Qe(y,s),s?.throwIfAborted(),l=a();let E=g===1,C=c&&Date.now()-h>=m;C&&(h=Date.now());let{result:w,elementWasFound:x}=await b7({cacheToUse:l,skipAISmartWaiting:!E,useAIIfCacheFails:!c||C,params:e});if(f=w,S=S||x,w.success)break;u(),y=Math.min(y*1.25,1e4);}if(!f)throw new te("InternalPlatformError",`Failed to evaluate manual element assertion in ${o}ms.`);if(s?.throwIfAborted(),!f.success){let E=a(),C=E?.target?.memory?{target:{id:-1,memory:E.target.memory}}:void 0,{result:w,elementWasFound:x}=await b7({cacheToUse:C,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});f=w,S=S||x,f.success||u(true);}let T=a();return f.success&&T?.target&&!S&&(T.target=qb(T.target),T.updatedAt=new Date),t.result={success:f.success,message:f.err?.message},f}async function b7({cacheToUse:e,skipAISmartWaiting:t,useAIIfCacheFails:n,params:o}){let{command:r,disableCache:i,fixtures:s,tracer:a,targetingWrapper:l}=o,{logger:c}=s;if(r.target&&!Hc(r.target))throw new Error("Element assertion with x/y is not supported yet");let d=P3(r.assertion),u=xBe(r.assertion),p,m=false,h=cloneDeep(e);try{let{elementInteractedDisplayString:g,result:f,thoughts:y}=await l({tracer:a,command:r,target:r.target,cache:h?.target,action:async S=>_Be(S.locator,o),options:{...r,allowNotActionableNodesOverride:u,allowIneligibleTagRedirect:u,showZeroOpacityElementsOverride:!0,disableCache:i,memory:h?.target?.memory,disableGlobalLocatorRedirect:!0,source:Vp(r),skipAISmartWaiting:t,targetName:"target"},retriesWithAI:n?1:0});return p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:g,thoughts:y},m=!0,f.success||(c.warn({aiThoughts:y,elementString:g,err:f.err},"Element check found an element but failed"),p={...f,thoughts:y}),{result:p,elementWasFound:m}}catch(g){if(d)return p={success:true,thoughts:`The element described does not exist on the page: ${g.message}`,err:void 0,data:void 0},{result:p,elementWasFound:m};if(!(g instanceof te)||g.reason!="ActionFailureError")throw g;return p={success:false,err:g,data:void 0,thoughts:void 0},c.warn({err:g},"Element check did not find an element and failed"),{result:p,elementWasFound:m}}}function xBe(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function _Be(e,{command:t,fixtures:n}){return await n.browser.highlight(e),await PBe(e,t.assertion)}async function PBe(e,t){let n=true,o,r;switch(t.type){case "ELEMENT_CONTENT":{let s=await e.textContent()??"";if(r={elementTextContent:hn(s,500,true)},!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Gg(t);n=false,o=new te("AssertionFailureError",`The content ${a} '${t.value}': ${s}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:hn(await e.evaluate(a=>a.cloneNode(false).outerHTML),500,true)};let s=null;try{s=await e.getAttribute(t.attr,{timeout:3e3});}catch(a){o=new te("AssertionFailureError",X(a)),n=false;break}if(!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Gg(t);n=false,t.operation==="EXISTS"?o=new te("AssertionFailureError",`The attribute ${t.attr} ${a}`):o=new te("AssertionFailureError",`The attribute ${t.attr} ${a} '${t.value}': ${s}`);}break}case "ELEMENT_EXISTENCE":{switch(t.condition){case "VISIBLE":{n=await e.evaluate(async(a,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(u=>setTimeout(u,250));let d=a.getBoundingClientRect();if(!(d.width===0||d.height===0)&&window.getComputedStyle(a).visibility!=="hidden"&&window.getComputedStyle(a).display!=="none")return true}return false},Zs*1e3);break}case "EDITABLE":{n=await e.isEditable({timeout:Zs*1e3});break}case "EXISTS":{n=true;break}case "ENABLED":{n=await e.isEnabled({timeout:Zs*1e3});break}case "FOCUSED":{n=await e.evaluate(a=>a===document.activeElement);break}default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})(t.condition)}if(n=t.negated?!n:n,!n){let s=Gg(t);o=new te("AssertionFailureError",`The element ${s}`);}break}case "ELEMENT_NAME":{let s=await e.evaluate(a=>a.tagName);if(!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let a=Gg(t);n=false,o=new te("AssertionFailureError",`The element tag name ${a} '${t.value}': ${s}`);}break}case "ELEMENT_STYLE":{let s=await e.evaluate((a,l)=>window.getComputedStyle(a).getPropertyValue(l),t.property);if(!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Gg(t);n=false,t.operation==="EXISTS"?o=new te("AssertionFailureError",`The style property ${t.property} ${a}`):o=new te("AssertionFailureError",`The style property ${t.property} ${a} '${t.value}': ${s}`);}break}default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {thoughts:void 0,success:n,data:r,err:o}}function E7(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function HT(e,t){let n=await e.screenshot(t),{width:o,height:r}=imageSize(n);return {buffer:n,width:Math.ceil(o),height:Math.ceil(r)}}async function v7(e){let{command:t,browser:n,logger:o}=e;if(t.target&&!Hc(t.target))throw new Error("Visual Diff with x/y is not supported yet");return await n.waitForStability({logger:o}),yo().startAsyncSpan("VISUAL_DIFF",async i=>{try{let s=await NBe(e);return i.result={success:!s.fail,message:s.thoughts},s}catch(s){throw s instanceof te&&(i.result={success:false,message:s.message}),s}},{name:"Compare against golden"})}async function NBe({tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:r,logger:i,screenshotStorage:s}){let a={clearHighlights:true,hideCaret:true},l=t.target&&Hc(t.target)?t.target:void 0,c;l?.elementDescriptor?c=(await r({tracer:e,command:t,target:l,cache:t.cache?.target,action:async P=>HT(o,{locator:P.locator,...a}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:c=await HT(o,a);let d=await s.prepareGoldenScreenshotForComparison(i,t,c);if((c.height!==d.height||c.width!==d.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let _=`${c.width}x${c.height}`,P=`${d.width}x${d.height}`;return {fail:true,thoughts:`Current screenshot (${_}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:false,urlAfterCommand:o.url()}}let u=await Jimp.fromBuffer(c.buffer),p={width:c.width,height:c.height},m=await Jimp.fromBuffer(d.buffer),h={width:d.width,height:d.height},g,f=p.width*p.height,y=h.width*h.height,S=Math.abs(p.height-h.height),T=Math.abs(p.width-h.width);if(f>y){let _=u.cover({w:h.width,h:h.height});c.buffer=await _.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height;}else if(y>f){let _=m.cover({w:p.width,h:p.height});d.buffer=await _.getBuffer("image/jpeg"),g="saved";}let E={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},C=t.threshold??.1,x=p0e(m0.decode(d.buffer).data,m0.decode(c.buffer).data,E.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,I=x>C*100,v=`Visual diff of ${x.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${C*100}%.`;if(g&&(v+=` The ${g} screenshot was cropped since it was taller by ${S} pixels and wider by ${T} pixels.`),I)throw new te("ActionFailureError",v);return {fail:I,thoughts:v,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:m0.encode(E,75).data,succeedImmediately:false,urlAfterCommand:o.url()}}var LBe=3e4;function kBe(e){if(!e.body)return {};switch(e.body.type){case "json":return {content:e.body.content,contentType:"application/json"};case "form-urlencoded":{let t=new URLSearchParams;return Object.entries(e.body.content).forEach(([n,o])=>{t.append(n,o);}),{content:t.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function R7({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??LBe/1e3,i=Object.fromEntries(Object.entries(e.headers||{}).filter(([h,g])=>h&&g)),s=new URLSearchParams;Object.entries(e.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{s.append(h,g);});let a=s.toString(),l;if(Kg(e.url)&&(l=e.url),n&&Yg(e.url,n)&&(l=new URL(e.url,n).toString()),!l)throw new te("ActionFailureError",`Invalid URL: ${e.url}`);let c=l;t.info({url:c,searchParams:a,headers:i,body:e.body,method:e.method},"Making HTTP request");let u=await _e((async()=>{let h=a?`${c}?${a}`:c;try{let g=kBe(e),f=new Headers(i);return g.contentType&&!f.has("Content-Type")&&f.set("Content-Type",g.contentType),await o(h,{headers:f,method:e.method,body:g.content})}catch(g){throw new te("ActionFailureError",`Failed to make HTTP request: ${X(g)}`,{errOptions:{cause:g}})}})(),{milliseconds:r*1e3,fallback:()=>{throw new te("ActionFailureError",`Fetch request timed out after ${r} seconds`)}});if(!u.ok){let h;try{h=await u.text();}catch(g){h=`Failed to read response body: ${g}`;}throw new te("ActionFailureError",`Fetch request failed with status ${u.status}: ${h}`)}let p={};u.headers.forEach((h,g)=>{p[g]=h;});let m={status:u.status,headers:p,request:{url:u.url,method:e.method,headers:i}};if(e.body?.type==="json"&&e.body.content)try{m.request.json=JSON.parse(e.body.content);}catch{}if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json();}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var DBe=5e3;async function vI({timeout:e=Zs,...t}){let n=Date.now(),o=e*1e3,r=o+1e4,i,s=0,a=500;for(;s-n<o;){if(Date.now()-n>r){t.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}t.signal?.throwIfAborted();let l=Date.now();i=await w7(t),s=Date.now();let c=s-l;if(c>1e3&&t.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Qe(a,t.signal),a=Math.min(Math.floor(a*1.5),DBe);else return i}return i=await w7(t),i}async function w7(e){return yo().startAsyncSpan("PAGE_ASSERTION",async n=>{let o=await FBe(e);return n.result={success:o.success,message:o.err?.message},o},{name:"Page check"})}async function FBe({assertion:e,browser:t,autoExpandIframes:n}){switch(e.type){case "CONTENT":case "CONTENT":{let r,i=false,s;try{let a;if(n){let l=await t.evaluateFunctionInAllFrames(I7,{value:e.value,negated:!!e.negated,returnHtml:!1});i=e.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml;}else ({evaluation:i,pageHtml:a}=await t.evaluateFunctionInPage(I7,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?cd.CONTAINS:dd.CONTAINS;s=new te("AssertionFailureError",`The page ${l} '${e.value}'.`),r=a;}}catch(a){s=new te("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`);}return {success:i,err:s,data:i||!r?void 0:{pageContent:r}}}default:return (r=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}}function I7({value:e,negated:t,returnHtml:n}){let o=document.body.innerHTML,r=o.includes(e)===!t;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),{evaluation:r,pageHtml:!r&&n?o:void 0}}var BBe=3e4;async function x7({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??BBe/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(e.headers||{}).filter(([u,p])=>u&&p));s["Content-Type"]="application/json";let a;if(Kg(e.url)&&(a=e.url),n&&Yg(e.url,n)&&(a=new URL(e.url,n).toString()),!a)throw new te("ActionFailureError",`Invalid URL: ${e.url}`);let c=await _e((async()=>{try{return await o(a,{headers:s,method:"POST",body:JSON.stringify({query:e.query,variables:e.variables?JSON.parse(e.variables):void 0}),signal:i.signal})}catch(u){throw new Error(`Failed to make HTTP request: ${u}`,{cause:u})}})(),{milliseconds:r*1e3});if(!c)throw new te("ActionFailureError",`GraphQL request timed out after ${r} seconds`);if(!c.ok){let u,p=await c.text();try{u=JSON.parse(p);}catch{throw new te("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}throw u?.errors?.length&&u?.errors[0]?.message?new te("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new te("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}let d={};return c.headers.forEach((u,p)=>{d[p]=u;}),{status:c.status,headers:d,json:await c.json()}}var Hf=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:t,generator:n,logger:o,storage:r,orgId:i,localCodeEvalTools:s,uploadedFileStorage:a,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=t,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=r,this.uploadedFileStorage=a,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=s,this.generator=n,this.logger=o;}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal);}setClosed(){this.executeAbortController.abort();}throwIfClosed(){this.executeAbortController.signal.throwIfAborted();}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(t,n){this.executionOptionsStack.push(t);try{return await n()}finally{this.executionOptionsStack.pop();}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:t,startingScreenshot:n,history:o,disableCache:r,langfuseSessionId:i,lastError:s,logger:a=this.logger}){let[l,c]=await Promise.all([Ac(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:a}),this.browser.screenshot({retries:1,clearHighlights:true})]),d=`data:image/jpeg;base64,${c.toString("base64")}`,u=await Gs({type:"ai-action",description:t,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:this.browser.url(),browserState:u,startingScreenshot:n,history:o,goal:t,screenshot:d,lastError:s};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:{...jt(a)},langfuseSessionId:i})}async promptToCommand({goal:t,startingScreenshot:n,history:o,actionHint:r,disableCache:i,logger:s=this.logger,langfuseSessionId:a}){let l=this.browser.url(),[c,d]=await Promise.all([Ac(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:s}),this.browser.screenshot({retries:1,clearHighlights:true})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,p=await Gs({type:"ai-action",description:t,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:l,browserState:p,startingScreenshot:n,history:o,goal:t,actionHint:r,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...jt(s)},langfuseSessionId:a})}catch(h){throw new te("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return Ac(this.browser,t)}async locateElement(t){return await p0(t,this.getControllerFixtures())}async locateElementWithSelector(t,n){return wa({action:async()=>{let o=await this.browser.resolveHardcodedCssSelector({selector:t,timeoutMs:2e3,logger:this.logger});return {thoughts:"Located element with selector",target:{id:-1,selector:t,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:o}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return {browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??true}async wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:i,action:s,options:a,retriesWithAI:l=1}){let c=[];for(let d=0;d<r.length;d++){let u=r[d],p=await this.wrapElementTargetingCommand({tracer:t,command:n,target:u,cache:i[d],action:async m=>m,options:{...a,targetName:o[d]}});c.push(p);}try{let d=await s(...c.map(m=>m.result)),u=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",p=c.map((m,h)=>m.thoughts?`${u(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return {result:d,elementInteractedDisplayStrings:c.map(m=>m.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:r.map(()=>{}),action:s,options:a,retriesWithAI:l-1});throw new te("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapHardcodedCssTargetingCommandHelper({target:t,action:n,options:o,command:r}){let i=this.logger.child({commandId:r.id}),{targetName:s}=o;if(t.type!=="description")throw new te("ActionFailureError","Cannot use selector with non-description target");let a,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({selector:t.elementDescriptor,targetName:s,logger:i});return {result:await n({locator:d.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;a=d,i.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Qe(500);}}throw a}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:n,disableGlobalLocatorRedirect:o,logger:r}=t,i=yo(),s=!o&&this.browser.userBrowserSettings.globalLocatorRedirect!==false;(this.browser.userBrowserSettings.visualActions||s)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(n.locator);});let a;return s&&(a=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:d}=await this.browser.performTargetRedirection(n,r);if(l.result=d,d.outcome==="redirected to new element"&&c&&i.storeTraceAsset&&!this.browser.userBrowserSettings.disableBrowserMonitoring){let u=randomUUID();(async()=>{try{let p=await this.browser.screenshot({locator:c.locator,clearHighlights:!0,boundingBoxOverride:c.serverSideBoundingBox??void 0});i.storeTraceAsset?.({snapshotId:u,data:p});}catch(p){r.debug({err:p},"Failed to capture element screenshot for redirect trace");}})(),l.elementScreenshotSnapshotId=u;}return c})),a||(a={locator:n.locator,serverSideBoundingBox:await n.locator.boundingBox({timeout:et}),originalElementLocationResult:n.originalElementLocationResult}),a}async resolveCachedTargetForAction(t){let{cache:n,options:o,logger:r}=t,s=await yo().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=n.targetSource,l.attributes.smartWaitingTimeoutMs=this.browser.smartWaitingTimeout;try{let c=await this.browser.resolveTarget(n,{allowNotActionableNodesOverride:o.allowNotActionableNodesOverride,logger:r,signal:this.executeAbortController.signal,...o.resolveTargetOptions,acceptElementMovedError:o.force});l.attributes.targetDisplayString=c.displayString,l.attributes.decisions=c.decisions;let d=c.decisions.find(u=>u.matched);return d&&(l.resolutionMethod=d.type),c}catch(c){throw c instanceof Ei&&(l.cacheMissReason=c.cacheMissReason,l.attributes.decisions=c.decisions),c}}),a=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:s,disableGlobalLocatorRedirect:o.disableGlobalLocatorRedirect,logger:r});return o.force||await s.revalidator?.(),{resolutionResult:s,finalTarget:a}}async wrapElementTargetingCommand(t){return await wa({action:()=>this.wrapElementTargetingCommandHelper(t),frameConfig:t.options.iframeUrl?{type:"url",url:t.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(t){let{tracer:n,target:o,action:r,options:i,command:s,finalAttempt:a=false,originalCache:l=t.cache}=t,{retriesWithAI:c=1}=t,{disableCache:d,useSelector:u,targetName:p}=i,m=yo(),h=this.logger.child({commandId:s.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||d)&&!aj(o))throw new te("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(t);let y=false,S;d&&(h.info("Cache explicitly disabled for this step"),y=true,S="Cache explicitly disabled",f=void 0);let T=a7({cache:f,description:o.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:h});f=T.cache,y=y||T.cacheBustedBeforeAction,!S&&T.cacheBustReason&&(S=T.cacheBustReason);let E=true;if(!s7(f))return c--,E=false,this.executeTargetingCommandWithAI({tracer:m,stepTracer:n,target:o,options:i,command:s,action:r,originalCache:l,logger:h,useMemory:g,cacheBustedBeforeAction:y,cacheBustReason:S});try{let{resolutionResult:C,finalTarget:w}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),x=await r(w);if(At.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.16.2"]),ER({cmd:s,key:p,newTarget:f,logger:h,updatedWithAI:!1}),E){let I=C.decisions.filter(v=>v.matched);if(I.length!==1)h.warn({decisions:C.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let v=I[0].type;n.recordTargetAutoHeal({healType:v});}}return {result:x,elementInteractedDisplayString:C.displayString}}catch(C){this.throwIfClosed();let w=vO(C);if(w&&!a)return h.warn({err:C},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,action:r,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:true,options:i});if(C instanceof te&&!w)throw h.warn({err:C},"Failed to execute command with target (fatal)"),C;if(c>0&&o){h.info({err:C},"Failed to execute action with cached target, retrying with AI"),At.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.16.2",`missReason:${C instanceof Ei?C.cacheMissReason:"unknown"}`]);let x;f.memory&&IE(f.memory)&&(x=f.memory);let I=C instanceof Ei&&C.cacheMissReason==="failing-ldist";return this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,cache:void 0,action:r,originalCache:l,retriesWithAI:c,finalAttempt:true,options:{...i,memory:x,targetHealingInProgress:true},skipInitialLocateWait:I})}throw new te("ActionFailureError",`Failed to execute interactive command: ${C instanceof Error?C.message:`${C}`}`,{errOptions:{cause:C}})}}async executeTargetingCommandWithAI(t){let{tracer:n,stepTracer:o,target:r,options:i,command:s,action:a,originalCache:l,logger:c,useMemory:d,cacheBustedBeforeAction:u,cacheBustReason:p,skipInitialLocateWait:m}=t;c.info({description:r.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:u,memory:i.memory,useMemory:d},"Prompting AI for an updated element location");let h=false;(u||!l)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?(await n.startAsyncSpan("SMART_WAITING",async()=>await S7({description:r.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())),h=true):(u||!l)&&(i.skipAISmartWaiting?c.debug("Skipping AI smart waiting for this targeting attempt"):c.debug("Skipping AI smart waiting due to controller execution options"));let g=2;for(let f=1;f<=g;f++){let y=false,S=this.browser.getActiveFrameConfig(),T=i.force||f>1;try{let E;try{E=await p0({description:r.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:d,memory:d?i.memory:void 0,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,allowIneligibleTagRedirect:i.allowIneligibleTagRedirect,showZeroOpacityElementsOverride:i.showZeroOpacityElementsOverride,logger:c,skipWait:h||m,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:p,acceptElementMovedError:T},this.getControllerFixtures());}catch(x){if(x instanceof Nh&&x.updatedLocatorMemory){let I={id:-1,...l,memory:x.updatedLocatorMemory};ER({cmd:s,key:i.targetName,newTarget:I,logger:c,updatedWithAI:!0});}throw x}E.frameConfig&&(this.browser.setActiveFrameConfig(E.frameConfig),y=!0);let C=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:E.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),w=await a(C);return ER({cmd:s,key:i.targetName,newTarget:E.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(o.recordTargetAutoHeal({healType:"AI"}),E.target.targetSource="AI_HEALED",E.target.targetUpdateTime=new Date().toUTCString(),E.target.targetUpdateLoggerTags=jt(c)),{result:w,elementInteractedDisplayString:E.resolution.displayString,thoughts:E.thoughts}}catch(E){if(y&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),f<g&&vO(E)){c.warn({err:E,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw E instanceof te?E:new te("ActionFailureError",E.message)}}throw new te("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return HT(this.browser,t)}async executePresetCommand(t,n,o,r,i){this.options?.slowMoMs&&await Qe(this.options.slowMoMs);let s=await this.browser.getOpenPages(),a=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(n,o);}catch(c){throw this.throwIfClosed(),new te("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await He({name:`cli.command.${n.type}`,attributes:{"momentic.command_type":n.type,"momentic.command_id":n.id},fn:()=>this.executePresetCommandHelper(t,n,o,r,i)});return this.options?.autoFollowNewTabs&&await i7({beforeUrl:a,command:n,beforePages:s.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{i8(n,l);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>UF(t)}}async traceBrowserInteraction(t,n,o){return yo().startAsyncSpan("BROWSER_INTERACTION",async i=>n(i),{name:t,...o})}async resolveCommandTemplateStrings(t,n){return iI({obj:t,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(t,n,o,r,i){r=r||"disableCache"in n&&!!n.disableCache;let s=this.logger.child({commandId:n.id});switch(n.type){case "SUCCESS":{let a=n.condition;return a?.assertion.trim()?CI({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i}):{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AI_ASSERTION":{if(!n.assertion.trim())throw new te("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new te("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return CI({command:n,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i})}case "AI_EXTRACT":return y7({command:n,logger:s,fixtures:this.getControllerFixtures(),disableCache:r});case "NAVIGATE":if(!Kg(n.url)&&!Yg(n.url,this.browser.baseUrl))throw new te("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "DIALOG":this.browser.registerDialogHandler(n.action);break;case "CAPTCHA":throw new te("UserConfigurationError","Captcha solving is no longer available on Momentic");case "GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case "GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_DOWN":case "SCROLL_UP":{let a,l;if(n.target&&Il(n.target)){let u=qr(n.target.pixels);await this.browser.hoverUsingVisualCoordinates(u);}else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:p}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:m=>this.browser.hover(m),options:{...n,targetName:"target",disableGlobalLocatorRedirect:true,disableCache:r}});a=u,l=p;}let c=this.browser.getViewport()?.height??kr.height,d=this.browser.getViewport()?.width??kr.width;switch(n.type){case "SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(n.deltaY??c)));break;case "SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(n.deltaY??c));break;case "SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(n.deltaX??d)));break;case "SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(n.deltaX??d));break}return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new te("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case "WAIT":{if(n.delay>1800)throw new te("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=n.delay*1e3;await Qe(a,this.executeAbortController.signal);break}case "REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "CLICK":{if(Il(n.target)){let p=qr(n.target.pixels),m={...n,relativePosition:n.relativePosition?qr(n.relativePosition):void 0};await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(p,m),{coordinates:p});break}let a=this.browser.url(),{elementInteractedDisplayString:l,result:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:p=>this.traceBrowserInteraction("Click",async m=>{let h={...n,relativePosition:n.relativePosition?qr(n.relativePosition):void 0},g=await this.browser.click(p,this.createCallbacksForBrowser(this.orgId),h);return g.coordinates&&(m.coordinates=g.coordinates),g},{selector:p.locator.toString()}),options:{...n,targetName:"target",disableCache:r}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:d,data:c.downloadedFile?{downloadedFile:c.downloadedFile}:void 0};return MR(a,u.urlAfterCommand)&&(u.succeedImmediately=true,u.succeedImmediatelyReason="URL changed"),u}case "COPY":return await this.browser.copy(n.value),{succeedImmediately:false,data:n.value,urlAfterCommand:this.browser.url()};case "PASTE":{await this.browser.paste();break}case "DRAG":{if(Il(n.fromTarget)&&Il(n.toTarget)){let c=qr(n.fromTarget.pixels),d=qr(n.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(Il(n.fromTarget)||Il(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:l}=await this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(c,d)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps})),options:{...n,disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:l}}case "MOUSE_DRAG":{let a=parseInt(n.deltaX),l=parseInt(n.deltaY),c=n.steps??5;if(isNaN(a)||isNaN(l))throw new te("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Il(n.target)){let p=qr(n.target.pixels);await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:l,steps:c,fromTarget:p}),{coordinates:p});break}let d,u;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:p,thoughts:m}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async h=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,h.locator,{force:n.force})),options:{...n,targetName:"target",disableCache:r}});d=p,u=m;}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,void 0,{force:n.force}));return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:d,thoughts:u}}case "SELECT_OPTION":{if(!Hc(n.target))throw new Error("Select with x/y is not supported yet");let a=n.target.elementDescriptor,l=n.choice,{elementInteractedDisplayString:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:{type:"description",elementDescriptor:a},cache:n.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,l,n.force),{value:l.type==="LABEL"?l.label:l.type==="VALUE"?l.value:l.index}),options:{...n,targetName:"target",disableCache:r,source:Vp(n)}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:d}}case "TAB":{let a={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:true};await this.browser.switchToPage(n.action,a);break}case "NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case "CLOSE_TAB":await this.browser.closePage(n.action,{retry:true});break;case "COOKIE":{if(!n.value)break;let a=await this.browser.setCookie(n.value);s.debug({results:a},"Set cookies");break}case "LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case "JAVASCRIPT":{let a;try{n.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),s.info({result:a},"Executed JavaScript in browser")):a=await Zu({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async l=>{if(!this.options?.scratchPadId){s.warn({updates:l},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:l,logger:s});}}});}catch(l){throw this.throwIfClosed(),new te("ActionFailureError",l instanceof Error?l.message:`${l}`,{errOptions:{cause:l}})}try{JSON.stringify(a);}catch(l){throw new te("ActionFailureError",`Return value is not serializable: ${l instanceof Error?l.message:`${l}`}`,{errOptions:{cause:l}})}return {urlAfterCommand:this.browser.url(),succeedImmediately:false,data:a}}case "TYPE":{if(n.target&&Il(n.target)){let m=qr(n.target.pixels),h={...n,relativePosition:n.relativePosition?qr(n.relativePosition):void 0};await this.browser.clickUsingVisualCoordinates(m,h),await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});break}let a=this.browser.url(),l,c,d=cloneDeep(n.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(d){let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:d,cache:n.cache?.target,action:g=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(n.value,g,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),{value:n.value,selector:g.locator.toString()}),options:{...n,targetName:"target",disableCache:r,disableGlobalLocatorRedirect:!u,source:Vp(n)}});l=m,c=h;}else await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});let p={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:c};return MR(a,p.urlAfterCommand)&&(p.succeedImmediately=true,p.succeedImmediatelyReason="URL changed"),p}case "HOVER":{if(Il(n.target)){let c=qr(n.target.pixels);await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(c),{coordinates:c});break}let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(c,{relativePosition:n.relativePosition?qr(n.relativePosition):void 0}),{selector:c.locator.toString()}),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "FOCUS":{if(!Hc(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.browser.focus(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "BLUR":{if(n.target&&!Hc(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:false,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:c=>this.browser.blur(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??true,delayMs:n.delayMs}),{value:n.value});let l={urlAfterCommand:this.browser.url(),succeedImmediately:false};return MR(a,l.urlAfterCommand)&&(l.succeedImmediately=true,l.succeedImmediatelyReason="URL changed"),l}case "KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "REQUEST":{let a=new CookieJar,l=HBe(fetch,a),c;try{c=new URL(n.url).hostname;}catch{}let d=await R7({command:n,baseUrl:this.browser.baseUrl,logger:s,fetchImplementation:l});return {data:Jy.parse({...d,cookies:lW(a,c)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await x7({command:n,baseUrl:this.browser.baseUrl,logger:s}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return v7({tracer:t,command:n,disableCache:r,browser:this.browser,logger:s,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case "FILE_UPLOAD":{let a,l;if(n.fileSource.type==="URL"?(l=n.fileSource.url,a=await z8({uri:n.fileSource.url,logger:s,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(l=n.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!a)throw new te("UserConfigurationError",`Attempted to use non-existent file for upload step: ${l}`);await this.browser.setFileChooserHandler({...a,filename:n.filename});break}case "AUTH_SAVE":{let a=await this.browser.saveAuthState();if(n.storageState&&ju(n.storageState)){let l=Jn__default.resolve(n.storageState);Oo__default.mkdirSync(Jn__default.dirname(l),{recursive:true}),Oo__default.writeFileSync(l,`${JSON.stringify(a,null,2)}
5776
+ `),tokenLength:u}),a.forEach((g,f)=>{let y=g.ids[0],S=g.ids[g.ids.length-1];e.debug({tokenLength:g.tokenLength,minId:y,maxId:S},`Chunk for page filtering (index ${f+1}/${a.length})`);}),{chunks:a}}var p7=5e6,mBe=1e5,hBe=3e4,gBe=6e4,fBe=1e5;async function Gs(e){let{fixtures:t}=e,{logger:n}=t,o=e.tree,r=e.serializedTree,i=Et(r);if(i>p7)throw new te("UserConfigurationError",`Page accessibility tree is too large for AI page filtering (${i} tokens). Maximum supported size is ${p7} tokens.`);if(i>mBe){let s=u7({serializedTree:r,options:c7,logger:n}),a=randomUUID();o=await yBe({...e,chunks:s.chunks,callId:a}),r=o.serialize();let l=Et(r);n.info({oldTokens:i,newTokens:l,langfuseCallId:a},"Filtered page using AI chunk ranking");}return r}async function yBe({type:e,callId:t,chunks:n,description:o,fixtures:r,tree:i}){let{generator:s,signal:a,logger:l}=r,c=await s.rankChunksWithAi({chunks:n,description:o,type:e,softTokenLimit:hBe,mediumTokenLimit:gBe,hardTokenLimit:fBe,callId:t},{abortSignal:a,logger:l,loggerTags:jt(l)}),d=[];return n.forEach((p,m)=>{c.indices.includes(m)&&(d=d.concat(p.ids));}),i.pruneUsingRelevantIds(new Set(d))}async function p0(e,t){if(!e.description)throw new te("UserConfigurationError","Cannot locate element with empty description");return wa({action:async()=>bBe(e,t),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:t.browser,logger:e.logger})}async function bBe(e,t){let{disableCache:n,testContext:o,filterByViewport:r,skipWait:i,source:s,memory:a,logger:l,allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,skipSavingVisualAttributes:p,isAutoHeal:m,cacheBustReason:h,acceptElementMovedError:g}=e,{orgId:f,browser:y,localCodeEvalTools:S,generator:T,abortSignal:E}=t,C=e.description,w=yo(),x=e.useMemory&&!n;o&&(C=await li({orgId:f,s:C,context:o,localTools:S,signal:E,logger:l})),s&&(C=r7(C,s));let{serializedTree:I,tree:v}=await w.startAsyncSpan("GET_PAGE_STATE",async()=>Ac(y,{allowNotActionableNodesOverride:c,allowIneligibleTagRedirect:d,showZeroOpacityElementsOverride:u,filterByViewport:r,abortSignal:E,skipWait:i,logger:l}),{}),_=await w.startAsyncSpan("GET_PAGE_SCREENSHOT",async()=>{let $,B=Date.now(),Q;for(;!$&&Date.now()-B<3e3;){E.throwIfAborted();try{$=await y.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(K){Q=K;}}if(!$)throw new te("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${Q?.message}`);return $}),P=I,L=false,V=`data:image/jpeg;base64,${_.toString("base64")}`,re=jt(l);P=await Gs({type:"locator",description:C,screenshot:V,serializedTree:I,tree:v,fixtures:{generator:T,signal:E,logger:l,orgId:f}}),P!==I&&(L=true);let ne=await w.startAsyncSpan("AI_LOCATOR_CALL",async $=>{m&&($.attributes.isAutoHeal=true),h&&($.attributes.cacheBustReason=h);let B=await T.getElementLocation({browserState:P,goal:C,screenshot:V,source:s,memory:x?a:void 0},{disableCache:n,abortSignal:E,logger:l,loggerTags:re,useMemory:x,cacheBustReason:h});if($.result=B,x&&($.attributes.useMemory=true,$.attributes.memoryTraces=B.rememberedTraces??[],B.updatedMemory&&($.attributes.memorySavedNewResult=true)),w.storeTraceAsset){let Q=randomUUID();w.storeTraceAsset({snapshotId:Q,data:_}),$.screenshotSnapshotId=Q;}return B});if(l.debug({usedRag:L,result:ne},"Got locator result"),!(ne.id>0))throw new Nh(`Could not find any relevant element: ${ne.thoughts}`,ne.updatedMemory?{type:"GCS_TRACES",traces:ne.updatedMemory}:void 0);let{resolution:W,target:M,frameConfig:Y}=await w.startAsyncSpan("TARGET_RESOLUTION",async $=>{let B=await y.createTargetFromA11yId({id:ne.id,requirements:ne.requirements,additionalElements:ne.additionalElements,description:C,targetSource:"AI",logger:l,skipSavingVisualAttributes:p,acceptElementMovedError:g});return $.result={serializedElement:B.target.nodeOnlySerializedHtml??"Unknown HTML element"},B});if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new te("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${W.displayString}`);return x&&(ne.updatedMemory?M.memory={type:"GCS_TRACES",traces:ne.updatedMemory}:a&&(M.memory=a)),{thoughts:ne.thoughts,target:M,resolution:W,frameConfig:Y,screenshot:V}}var TBe=15;async function CI({command:e,logger:t,fixtures:n,useMemory:o,maxRetries:r=TBe,recoveryHint:i}){if(!e.assertion.trim())throw new te("ActionFailureError","Assertion command is missing the assertion content");let s=lM.optional().catch(void 0).parse(e.source);e.source&&!s&&t.warn(`Invalid source ${e.source} for AI assertion, ignoring...`);let a=yo();return a.startAsyncSpan("AI_ASSERTION_CALL",async l=>{let{browser:c}=n,d=e.timeout?e.timeout*1e3:c.smartWaitingTimeout,u=VX(d,r-1),p=0,m=Date.now(),h=m+d,g=m,f,y,S;try{await wa({action:()=>c.clearHighlights(),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,browser:c,logger:t});}catch(C){t.warn({err:C},"Failed to clear highlights before AI check, continuing...");}for(;p<r;){n.abortSignal.throwIfAborted();let C=Date.now();if(p>0){if(C>=h)break;let I=h-C,v=g-C,_=Math.min(v,I);_>0&&await Qe(_,n.abortSignal);}let w=Date.now();if(p>0&&w>=h)break;let x=false;try{if(f=await wa({action:async()=>{let v=await h7(c,t,n.abortSignal);return y&&y.serializedTree===v.serializedTree&&y.screenshotBuff.equals(v.screenshotBuff)?(x=!0,f):(y=v,g7({command:e,state:v,fixtures:n,useMemory:o,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:p,logger:t,source:s,recoveryHint:i}))},frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c}),f?.aiResult.result){f?.updatedMemory&&Kb(e,f.updatedMemory,t);break}else throw f?.aiResult.thoughts?new te("AssertionFailureError",f.aiResult.thoughts):new te("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(I){n.abortSignal.throwIfAborted(),S=I instanceof Error?I:new Error(`${I}`),x?t.info(`AI check attempt ${p} failed (re-used previous result)`):t.info({err:I},`AI check assert attempt ${p} failed, retrying...`);}finally{p++,g=w+u;}}if(!f?.aiResult.result){let C=h-Date.now();C>0&&await Qe(C,n.abortSignal);}if(!f?.aiResult.result)try{f=await wa({action:async()=>g7({command:e,state:await h7(c,t,n.abortSignal),fixtures:n,useMemory:o,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:p,logger:t,recoveryHint:i}),frameConfig:e.iframeUrl?{type:"url",url:e.iframeUrl}:void 0,logger:t,browser:c});}catch(C){n.abortSignal.throwIfAborted(),S=C instanceof Error?C:new Error(`${C}`);}finally{p++;}f?.updatedMemory&&Kb(e,f.updatedMemory,t);let T=f?.afterScreenshotOverride;if(T&&a.storeTraceAsset){let C=randomUUID();a.storeTraceAsset({snapshotId:C,data:T}),l.screenshotSnapshotId=C;}let E=f?.elementScreenshotOverride;if(E&&a.storeTraceAsset){let C=randomUUID();a.storeTraceAsset({snapshotId:C,data:E}),l.elementScreenshotSnapshotId=C;}if(o&&(l.attributes.useMemory=true,l.attributes.memoryTraces=f?.aiResult.rememberedTraces??[],f?.updatedMemory&&(l.attributes.memorySavedNewResult=true)),!f?.aiResult.result){l.result=f?.aiResult??{thoughts:S?.message??"AI check failed after all attempts",result:false};let C=`AI check still failing after ${p} attempts.`;throw S&&(C+=` Latest result: ${S.message}`),new te("AssertionFailureError",C)}return l.result=f.aiResult,{...f,thoughts:f.aiResult.thoughts,succeedImmediately:false,urlAfterCommand:c.url()}})}async function h7(e,t,n){await e.waitForPageLoad({signal:n});let[o,r]=await Promise.all([Ac(e,{abortSignal:n,skipWait:true,skipWaitForPageLoad:true,logger:t}),e.screenshot({retries:1,respectActiveFrame:true})]);return {...o,screenshotBuff:r}}async function g7({command:e,state:t,fixtures:n,useConsensus:o,useMemory:r,highlightElementsOnFailure:i,attemptNumber:s,source:a,logger:l,recoveryHint:c}){let {browser:d,generator:u,abortSignal:p}=n,{serializedTree:h,tree:g}=t,f=t.screenshotBuff,y=f.toString("base64"),S=d.url(),T=e.contextChoice??"MULTIMODAL",E=h;T!=="VISION_ONLY"&&(E=await Gs({type:"assertion",serializedTree:h,tree:g,description:e.assertion,screenshot:y,fixtures:{generator:u,signal:p,logger:l,orgId:n.orgId}}),E);let C={goal:e.assertion,url:S,memory:r?e.cache?.memory:void 0,browserState:E,screenshot:y,contextChoice:T,source:a,recoveryHint:c},x=await(T==="VISION_ONLY"?(v,_)=>u.getVisualAssertionResult(v,_):(v,_)=>u.getAssertionResult(v,_))(C,{useConsensus:o,attemptNumber:s,useMemory:r,disableCache:!!e.disableCache,abortSignal:p,logger:l,loggerTags:jt(l)}),I;if((x.result||i)&&x.relevantElements?.length){x.relevantElements.map(v=>d.getSerializedFormFromA11yId(v)).filter(v=>!!v);try{let v=x.relevantElements[0],{resolution:_}=await d.createTargetFromA11yId({id:v,description:null,targetSource:"AI",skipSaveToCache:!0});I=await d.screenshot({locator:_.locator,clearHighlights:!0,respectActiveFrame:!0});}catch(v){l.debug({err:v},"Failed to capture element screenshot for trace, continuing...");}await ABe(x.relevantElements,d,l);}return {aiResult:x,afterScreenshotOverride:f,elementScreenshotOverride:I,updatedMemory:r?x.updatedMemory:void 0}}async function ABe(e,t,n){let o=Date.now();for(let r of e){if(Date.now()-o>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await _e(t.highlightA11yId(r),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}});}catch(i){n.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}async function y7(e){let{command:t,logger:n,fixtures:o,disableCache:r}=e,{browser:i,generator:s,abortSignal:a}=o;if(!t.goal.trim())throw new te("ActionFailureError","Cannot perform AI extraction without goal");if(t.schema){let u=GK(t.schema);if(u)throw new te("UserConfigurationError",u)}let l=await i.getCondensedHtml(),c=await i.screenshot({retries:2}),d=yo();try{return await d.startAsyncSpan("AI_EXTRACTION_CALL",async u=>{let p=await s.getTextExtraction({goal:t.goal,browserState:l,returnSchema:t.schema,screenshot:`data:image/jpeg;base64,${c.toString("base64")}`},{disableCache:r,abortSignal:a,loggerTags:jt(n)});if(u.result=p,EBe({tracer:d,span:u,screenshot:c,htmlState:l,logger:n}),p.result==="NOT_FOUND")throw new te("ActionFailureError","No relevant data found for extraction goal on this page");if(p.thoughts?.includes("MaxGenerationLengthExceededError"))throw new te("UserConfigurationError",p.thoughts);return {thoughts:p.thoughts||void 0,data:p.result,succeedImmediately:!1,urlAfterCommand:i.url()}})}catch(u){let p=X(u);throw p.includes("MaxGenerationLengthExceededError")?new te("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):p.includes("AIProviderError")&&p.includes("time")?new te("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:u}}):u}}function EBe(e){let{tracer:t,span:n,screenshot:o,htmlState:r,logger:i}=e;if(t.storeTraceAsset)try{let s=randomUUID();t.storeTraceAsset({snapshotId:s,data:o}),n.screenshotSnapshotId=s;let a=randomUUID();t.storeTraceAsset({snapshotId:a,data:Buffer.from(r),extension:"html"}),n.browserStateSnapshotId=a;}catch(s){i.debug({err:s},"Failed to store extraction trace assets");}}async function S7(e,t){let{logger:n}=e,{abortSignal:o,browser:r}=t,i=Date.now();try{await CBe(i,e,t);}catch(s){if(s instanceof Error&&(s.name==="AbortError"||s.name==="TimeoutError")||o.aborted)return;n.warn({err:s},"Unexpected error occurred during AI smart waiting");let a=r.smartWaitingTimeout-(Date.now()-i);a>0&&await Qe(a,o);}finally{n.debug({durationMs:Date.now()-i},"AI smart waiting complete");}}async function CBe(e,t,n){let{abortSignal:o,browser:r}=n;if(r.smartWaitingTimeout<3e3){await Qe(r.smartWaitingTimeout,o);return}if(!t.description)throw new te("UserConfigurationError","Cannot locate element with empty description");await _e(vBe(e,t,n),{milliseconds:r.smartWaitingTimeout});}async function vBe(e,t,n){let{logger:o,iframeUrl:r}=t,{browser:i}=n;for(;Date.now()-e<i.smartWaitingTimeout;)if(await wa({action:async()=>RBe(t,n),frameConfig:r?{type:"url",url:r}:void 0,browser:i,logger:o}))return}async function RBe(e,t){let{testContext:n,logger:o}=e,{browser:r,abortSignal:i,localCodeEvalTools:s,orgId:a,generator:l}=t,c=e.description;n&&(c=await li({orgId:a,s:c,context:n,localTools:s,signal:i,logger:o})),i.throwIfAborted();let d;try{d=await r.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2});}catch(h){throw new te("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${h instanceof Error?h.message:h}`)}let p=`data:image/jpeg;base64,${d.toString("base64")}`;i.throwIfAborted();let m=await l.getSmartWaitingDecision({description:c,screenshot:p},{abortSignal:i,loggerTags:jt(o)});return o.debug({result:m},"Got smart waiting result"),m.isPageReady}var wBe=3e4;async function A7(e){return yo().startAsyncSpan("ELEMENT_ASSERTION",async n=>IBe(e,n),{name:"Element check"})}async function IBe(e,t){let{command:n,timeoutMs:o,fixtures:r,disableCache:i}=e,{abortSignal:s}=r,a=()=>_E(n.cache)?n.cache:void 0,l=a(),c=!i&&!!l?.target&&Sh(l.target),d=cloneDeep(l),u=(E=false)=>{if(l=a(),!!l)if(E){let C=yk(d,l);l.target=C.target,l.updatedAt=C.updatedAt;}else {if(!d){l=void 0;return}l.target=d.target,l.updatedAt=d.updatedAt;}},p=Date.now(),m=c?Math.max(o/10,wBe):0,h=p,g=0,f,y=500,S=false;for(;g<2||Date.now()-p<o;){g++,g>1&&await Qe(y,s),s?.throwIfAborted(),l=a();let E=g===1,C=c&&Date.now()-h>=m;C&&(h=Date.now());let{result:w,elementWasFound:x}=await b7({cacheToUse:l,skipAISmartWaiting:!E,useAIIfCacheFails:!c||C,params:e});if(f=w,S=S||x,w.success)break;u(),y=Math.min(y*1.25,1e4);}if(!f)throw new te("InternalPlatformError",`Failed to evaluate manual element assertion in ${o}ms.`);if(s?.throwIfAborted(),!f.success){let E=a(),C=E?.target?.memory?{target:{id:-1,memory:E.target.memory}}:void 0,{result:w,elementWasFound:x}=await b7({cacheToUse:C,skipAISmartWaiting:true,useAIIfCacheFails:true,params:e});f=w,S=S||x,f.success||u(true);}let T=a();return f.success&&T?.target&&!S&&(T.target=qb(T.target),T.updatedAt=new Date),t.result={success:f.success,message:f.err?.message},f}async function b7({cacheToUse:e,skipAISmartWaiting:t,useAIIfCacheFails:n,params:o}){let{command:r,disableCache:i,fixtures:s,tracer:a,targetingWrapper:l}=o,{logger:c}=s;if(r.target&&!Hc(r.target))throw new Error("Element assertion with x/y is not supported yet");let d=P3(r.assertion),u=xBe(r.assertion),p,m=false,h=cloneDeep(e);try{let{elementInteractedDisplayString:g,result:f,thoughts:y}=await l({tracer:a,command:r,target:r.target,cache:h?.target,action:async S=>_Be(S.locator,o),options:{...r,allowNotActionableNodesOverride:u,allowIneligibleTagRedirect:u,showZeroOpacityElementsOverride:!0,disableCache:i,memory:h?.target?.memory,disableGlobalLocatorRedirect:!0,source:Vp(r),skipAISmartWaiting:t,targetName:"target"},retriesWithAI:n?1:0});return p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:g,thoughts:y},m=!0,f.success||(c.warn({aiThoughts:y,elementString:g,err:f.err},"Element check found an element but failed"),p={...f,thoughts:y}),{result:p,elementWasFound:m}}catch(g){if(d)return p={success:true,thoughts:`The element described does not exist on the page: ${g.message}`,err:void 0,data:void 0},{result:p,elementWasFound:m};if(!(g instanceof te)||g.reason!="ActionFailureError")throw g;return p={success:false,err:g,data:void 0,thoughts:void 0},c.warn({err:g},"Element check did not find an element and failed"),{result:p,elementWasFound:m}}}function xBe(e){return !(e.type==="ELEMENT_EXISTENCE"&&e.condition==="VISIBLE"&&!e.negated)}async function _Be(e,{command:t,fixtures:n}){return await n.browser.highlight(e),await PBe(e,t.assertion)}async function PBe(e,t){let n=true,o,r;switch(t.type){case "ELEMENT_CONTENT":{let s=await e.textContent()??"";if(r={elementTextContent:hn(s,500,true)},!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Gg(t);n=false,o=new te("AssertionFailureError",`The content ${a} '${t.value}': ${s}`);}break}case "ELEMENT_ATTRIBUTE":{r={elementOuterHtml:hn(await e.evaluate(a=>a.cloneNode(false).outerHTML),500,true)};let s=null;try{s=await e.getAttribute(t.attr,{timeout:3e3});}catch(a){o=new te("AssertionFailureError",X(a)),n=false;break}if(!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Gg(t);n=false,t.operation==="EXISTS"?o=new te("AssertionFailureError",`The attribute ${t.attr} ${a}`):o=new te("AssertionFailureError",`The attribute ${t.attr} ${a} '${t.value}': ${s}`);}break}case "ELEMENT_EXISTENCE":{switch(t.condition){case "VISIBLE":{n=await e.evaluate(async(a,l)=>{let c=Date.now();for(;Date.now()-c<l;){await new Promise(u=>setTimeout(u,250));let d=a.getBoundingClientRect();if(!(d.width===0||d.height===0)&&window.getComputedStyle(a).visibility!=="hidden"&&window.getComputedStyle(a).display!=="none")return true}return false},Zs*1e3);break}case "EDITABLE":{n=await e.isEditable({timeout:Zs*1e3});break}case "EXISTS":{n=true;break}case "ENABLED":{n=await e.isEnabled({timeout:Zs*1e3});break}case "FOCUSED":{n=await e.evaluate(a=>a===document.activeElement);break}default:return (a=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})(t.condition)}if(n=t.negated?!n:n,!n){let s=Gg(t);o=new te("AssertionFailureError",`The element ${s}`);}break}case "ELEMENT_NAME":{let s=await e.evaluate(a=>a.tagName);if(!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:true})){let a=Gg(t);n=false,o=new te("AssertionFailureError",`The element tag name ${a} '${t.value}': ${s}`);}break}case "ELEMENT_STYLE":{let s=await e.evaluate((a,l)=>window.getComputedStyle(a).getPropertyValue(l),t.property);if(!$b(s,t.value,t.operation,{negated:!!t.negated,ignoreCase:false})){let a=Gg(t);n=false,t.operation==="EXISTS"?o=new te("AssertionFailureError",`The style property ${t.property} ${a}`):o=new te("AssertionFailureError",`The style property ${t.property} ${a} '${t.value}': ${s}`);}break}default:return (s=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {thoughts:void 0,success:n,data:r,err:o}}function E7(e){return e.type==="ELEMENT_EXISTENCE"&&e.negated&&e.condition==="EXISTS"}async function HT(e,t){let n=await e.screenshot(t),{width:o,height:r}=imageSize(n);return {buffer:n,width:Math.ceil(o),height:Math.ceil(r)}}async function v7(e){let{command:t,browser:n,logger:o}=e;if(t.target&&!Hc(t.target))throw new Error("Visual Diff with x/y is not supported yet");return await n.waitForStability({logger:o}),yo().startAsyncSpan("VISUAL_DIFF",async i=>{try{let s=await NBe(e);return i.result={success:!s.fail,message:s.thoughts},s}catch(s){throw s instanceof te&&(i.result={success:false,message:s.message}),s}},{name:"Compare against golden"})}async function NBe({tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:r,logger:i,screenshotStorage:s}){let a={clearHighlights:true,hideCaret:true},l=t.target&&Hc(t.target)?t.target:void 0,c;l?.elementDescriptor?c=(await r({tracer:e,command:t,target:l,cache:t.cache?.target,action:async P=>HT(o,{locator:P.locator,...a}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:true,memory:t.cache?.target?.memory,targetName:"target"}})).result:c=await HT(o,a);let d=await s.prepareGoldenScreenshotForComparison(i,t,c);if((c.height!==d.height||c.width!==d.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let _=`${c.width}x${c.height}`,P=`${d.width}x${d.height}`;return {fail:true,thoughts:`Current screenshot (${_}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:false,urlAfterCommand:o.url()}}let u=await Jimp.fromBuffer(c.buffer),p={width:c.width,height:c.height},m=await Jimp.fromBuffer(d.buffer),h={width:d.width,height:d.height},g,f=p.width*p.height,y=h.width*h.height,S=Math.abs(p.height-h.height),T=Math.abs(p.width-h.width);if(f>y){let _=u.cover({w:h.width,h:h.height});c.buffer=await _.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height;}else if(y>f){let _=m.cover({w:p.width,h:p.height});d.buffer=await _.getBuffer("image/jpeg"),g="saved";}let E={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},C=t.threshold??.1,x=p0e(m0.decode(d.buffer).data,m0.decode(c.buffer).data,E.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,I=x>C*100,v=`Visual diff of ${x.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${C*100}%.`;if(g&&(v+=` The ${g} screenshot was cropped since it was taller by ${S} pixels and wider by ${T} pixels.`),I)throw new te("ActionFailureError",v);return {fail:I,thoughts:v,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:m0.encode(E,75).data,succeedImmediately:false,urlAfterCommand:o.url()}}var LBe=3e4;function kBe(e){if(!e.body)return {};switch(e.body.type){case "json":return {content:e.body.content,contentType:"application/json"};case "form-urlencoded":{let t=new URLSearchParams;return Object.entries(e.body.content).forEach(([n,o])=>{t.append(n,o);}),{content:t.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function R7({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??LBe/1e3,i=Object.fromEntries(Object.entries(e.headers||{}).filter(([h,g])=>h&&g)),s=new URLSearchParams;Object.entries(e.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{s.append(h,g);});let a=s.toString(),l;if(Kg(e.url)&&(l=e.url),n&&Yg(e.url,n)&&(l=new URL(e.url,n).toString()),!l)throw new te("ActionFailureError",`Invalid URL: ${e.url}`);let c=l;t.info({url:c,searchParams:a,headers:i,body:e.body,method:e.method},"Making HTTP request");let u=await _e((async()=>{let h=a?`${c}?${a}`:c;try{let g=kBe(e),f=new Headers(i);return g.contentType&&!f.has("Content-Type")&&f.set("Content-Type",g.contentType),await o(h,{headers:f,method:e.method,body:g.content})}catch(g){throw new te("ActionFailureError",`Failed to make HTTP request: ${X(g)}`,{errOptions:{cause:g}})}})(),{milliseconds:r*1e3,fallback:()=>{throw new te("ActionFailureError",`Fetch request timed out after ${r} seconds`)}});if(!u.ok){let h;try{h=await u.text();}catch(g){h=`Failed to read response body: ${g}`;}throw new te("ActionFailureError",`Fetch request failed with status ${u.status}: ${h}`)}let p={};u.headers.forEach((h,g)=>{p[g]=h;});let m={status:u.status,headers:p,request:{url:u.url,method:e.method,headers:i}};if(e.body?.type==="json"&&e.body.content)try{m.request.json=JSON.parse(e.body.content);}catch{}if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json();}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var DBe=5e3;async function vI({timeout:e=Zs,...t}){let n=Date.now(),o=e*1e3,r=o+1e4,i,s=0,a=500;for(;s-n<o;){if(Date.now()-n>r){t.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}t.signal?.throwIfAborted();let l=Date.now();i=await w7(t),s=Date.now();let c=s-l;if(c>1e3&&t.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Qe(a,t.signal),a=Math.min(Math.floor(a*1.5),DBe);else return i}return i=await w7(t),i}async function w7(e){return yo().startAsyncSpan("PAGE_ASSERTION",async n=>{let o=await FBe(e);return n.result={success:o.success,message:o.err?.message},o},{name:"Page check"})}async function FBe({assertion:e,browser:t,autoExpandIframes:n}){switch(e.type){case "CONTENT":case "CONTENT":{let r,i=false,s;try{let a;if(n){let l=await t.evaluateFunctionInAllFrames(I7,{value:e.value,negated:!!e.negated,returnHtml:!1});i=e.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),a=l.find(c=>c.pageHtml)?.pageHtml;}else ({evaluation:i,pageHtml:a}=await t.evaluateFunctionInPage(I7,{value:e.value,negated:!!e.negated,returnHtml:!0},"checking page content"));if(!i){let l=e.negated?cd.CONTAINS:dd.CONTAINS;s=new te("AssertionFailureError",`The page ${l} '${e.value}'.`),r=a;}}catch(a){s=new te("AssertionFailureError",`Failed to evaluate page content assertion: ${a instanceof Error?a.message:`${a}`}`);}return {success:i,err:s,data:i||!r?void 0:{pageContent:r}}}default:return (r=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}}function I7({value:e,negated:t,returnHtml:n}){let o=document.body.innerHTML,r=o.includes(e)===!t;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),{evaluation:r,pageHtml:!r&&n?o:void 0}}var BBe=3e4;async function x7({command:e,logger:t,baseUrl:n,fetchImplementation:o=fetch}){let r=e.timeout??BBe/1e3,i=new AbortController,s=Object.fromEntries(Object.entries(e.headers||{}).filter(([u,p])=>u&&p));s["Content-Type"]="application/json";let a;if(Kg(e.url)&&(a=e.url),n&&Yg(e.url,n)&&(a=new URL(e.url,n).toString()),!a)throw new te("ActionFailureError",`Invalid URL: ${e.url}`);let c=await _e((async()=>{try{return await o(a,{headers:s,method:"POST",body:JSON.stringify({query:e.query,variables:e.variables?JSON.parse(e.variables):void 0}),signal:i.signal})}catch(u){throw new Error(`Failed to make HTTP request: ${u}`,{cause:u})}})(),{milliseconds:r*1e3});if(!c)throw new te("ActionFailureError",`GraphQL request timed out after ${r} seconds`);if(!c.ok){let u,p=await c.text();try{u=JSON.parse(p);}catch{throw new te("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}throw u?.errors?.length&&u?.errors[0]?.message?new te("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new te("ActionFailureError",`GraphQL request failed with status ${c.status}: ${p}`)}let d={};return c.headers.forEach((u,p)=>{d[p]=u;}),{status:c.status,headers:d,json:await c.json()}}var Hf=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;executionOptionsStack=[];recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:t,generator:n,logger:o,storage:r,orgId:i,localCodeEvalTools:s,uploadedFileStorage:a,visualDiffScreenshotStorage:l,options:c}){this.orgId=i,this.options=c,this.browser=t,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=r,this.uploadedFileStorage=a,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=s,this.generator=n,this.logger=o;}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal);}setClosed(){this.executeAbortController.abort();}throwIfClosed(){this.executeAbortController.signal.throwIfAborted();}get closed(){return this.executeAbortController.signal.aborted}async withExecutionOptions(t,n){this.executionOptionsStack.push(t);try{return await n()}finally{this.executionOptionsStack.pop();}}getCurrentExecutionOptions(){return this.executionOptionsStack[this.executionOptionsStack.length-1]??{}}async evaluateAiAction({goal:t,startingScreenshot:n,history:o,disableCache:r,langfuseSessionId:i,lastError:s,logger:a=this.logger}){let[l,c]=await Promise.all([Ac(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:a}),this.browser.screenshot({retries:1,clearHighlights:true})]),d=`data:image/jpeg;base64,${c.toString("base64")}`,u=await Gs({type:"ai-action",description:t,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),p={url:this.browser.url(),browserState:u,startingScreenshot:n,history:o,goal:t,screenshot:d,lastError:s};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:{...jt(a)},langfuseSessionId:i})}async promptToCommand({goal:t,startingScreenshot:n,history:o,actionHint:r,disableCache:i,logger:s=this.logger,langfuseSessionId:a}){let l=this.browser.url(),[c,d]=await Promise.all([Ac(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:true,skipWaitForPageLoad:true,logger:s}),this.browser.screenshot({retries:1,clearHighlights:true})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,p=await Gs({type:"ai-action",description:t,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:l,browserState:p,startingScreenshot:n,history:o,goal:t,actionHint:r,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...jt(s)},langfuseSessionId:a})}catch(h){throw new te("InternalWebAgentError",`Error generating command: ${h instanceof Error?h.message:h}`,{errOptions:{cause:h}})}}async getBrowserState(t){return Ac(this.browser,t)}async locateElement(t){return await p0(t,this.getControllerFixtures())}async locateElementWithSelector(t,n){return wa({action:async()=>{let o=await this.browser.resolveHardcodedCssSelector({selector:t,timeoutMs:2e3,logger:this.logger});return {thoughts:"Located element with selector",target:{id:-1,selector:t,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:o}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(){return {browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??true}async wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:i,action:s,options:a,retriesWithAI:l=1}){let c=[];for(let d=0;d<r.length;d++){let u=r[d],p=await this.wrapElementTargetingCommand({tracer:t,command:n,target:u,cache:i[d],action:async m=>m,options:{...a,targetName:o[d]}});c.push(p);}try{let d=await s(...c.map(m=>m.result)),u=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",p=c.map((m,h)=>m.thoughts?`${u(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return {result:d,elementInteractedDisplayStrings:c.map(m=>m.elementInteractedDisplayString),thoughts:p}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:o,descriptions:r,caches:r.map(()=>{}),action:s,options:a,retriesWithAI:l-1});throw new te("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapHardcodedCssTargetingCommandHelper({target:t,action:n,options:o,command:r}){let i=this.logger.child({commandId:r.id}),{targetName:s}=o;if(t.type!=="description")throw new te("ActionFailureError","Cannot use selector with non-description target");let a,l=Date.now(),c=Date.now();for(;Date.now()-c<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({selector:t.elementDescriptor,targetName:s,logger:i});return {result:await n({locator:d.locator,originalElementLocationResult:void 0,serverSideBoundingBox:null}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;a=d,i.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await Qe(500);}}throw a}async scrollIntoViewAndResolveFinalTarget(t){let{resolutionResult:n,disableGlobalLocatorRedirect:o,logger:r}=t,i=yo(),s=!o&&this.browser.userBrowserSettings.globalLocatorRedirect!==false;(this.browser.userBrowserSettings.visualActions||s)&&await i.startAsyncSpan("SCROLL_ELEMENT_INTO_VIEW",async()=>{await this.browser.scrollIntoViewIfNeeded(n.locator);});let a;return s&&(a=await i.startAsyncSpan("LOCATOR_REDIRECT",async l=>{let{targetingResult:c,metadata:d}=await this.browser.performTargetRedirection(n,r);if(l.result=d,d.outcome==="redirected to new element"&&c&&i.storeTraceAsset&&!this.browser.userBrowserSettings.disableBrowserMonitoring){let u=randomUUID();(async()=>{try{let p=await this.browser.screenshot({locator:c.locator,clearHighlights:!0,boundingBoxOverride:c.serverSideBoundingBox??void 0});i.storeTraceAsset?.({snapshotId:u,data:p});}catch(p){r.debug({err:p},"Failed to capture element screenshot for redirect trace");}})(),l.elementScreenshotSnapshotId=u;}return c})),a||(a={locator:n.locator,serverSideBoundingBox:await n.locator.boundingBox({timeout:et}),originalElementLocationResult:n.originalElementLocationResult}),a}async resolveCachedTargetForAction(t){let{cache:n,options:o,logger:r}=t,s=await yo().startAsyncSpan("CACHE_RESOLUTION",async l=>{l.targetSource=n.targetSource,l.attributes.smartWaitingTimeoutMs=this.browser.smartWaitingTimeout;try{let c=await this.browser.resolveTarget(n,{allowNotActionableNodesOverride:o.allowNotActionableNodesOverride,logger:r,signal:this.executeAbortController.signal,...o.resolveTargetOptions,acceptElementMovedError:o.force});l.attributes.targetDisplayString=c.displayString,l.attributes.decisions=c.decisions;let d=c.decisions.find(u=>u.matched);return d&&(l.resolutionMethod=d.type),c}catch(c){throw c instanceof Ei&&(l.cacheMissReason=c.cacheMissReason,l.attributes.decisions=c.decisions),c}}),a=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:s,disableGlobalLocatorRedirect:o.disableGlobalLocatorRedirect,logger:r});return o.force||await s.revalidator?.(),{resolutionResult:s,finalTarget:a}}async wrapElementTargetingCommand(t){return await wa({action:()=>this.wrapElementTargetingCommandHelper(t),frameConfig:t.options.iframeUrl?{type:"url",url:t.options.iframeUrl}:void 0,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper(t){let{tracer:n,target:o,action:r,options:i,command:s,finalAttempt:a=false,originalCache:l=t.cache}=t,{retriesWithAI:c=1}=t,{disableCache:d,useSelector:u,targetName:p}=i,m=yo(),h=this.logger.child({commandId:s.id}),g=this.shouldUseMemory(),f=cloneDeep(t.cache);if((!f||d)&&!aj(o))throw new te("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(t);let y=false,S;d&&(h.info("Cache explicitly disabled for this step"),y=true,S="Cache explicitly disabled",f=void 0);let T=a7({cache:f,description:o.elementDescriptor,disableSecondaryCacheResolution:!!this.browser.userBrowserSettings.disableSecondaryCacheResolution,logger:h});f=T.cache,y=y||T.cacheBustedBeforeAction,!S&&T.cacheBustReason&&(S=T.cacheBustReason);let E=true;if(!s7(f))return c--,E=false,this.executeTargetingCommandWithAI({tracer:m,stepTracer:n,target:o,options:i,command:s,action:r,originalCache:l,logger:h,useMemory:g,cacheBustedBeforeAction:y,cacheBustReason:S});try{let{resolutionResult:C,finalTarget:w}=await this.resolveCachedTargetForAction({cache:f,options:i,logger:h}),x=await r(w);if(At.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.16.3"]),ER({cmd:s,key:p,newTarget:f,logger:h,updatedWithAI:!1}),E){let I=C.decisions.filter(v=>v.matched);if(I.length!==1)h.warn({decisions:C.decisions},"Expected exactly 1 matching method for element location, got more or less");else {let v=I[0].type;n.recordTargetAutoHeal({healType:v});}}return {result:x,elementInteractedDisplayString:C.displayString}}catch(C){this.throwIfClosed();let w=vO(C);if(w&&!a)return h.warn({err:C},"Encountered error that is retryable with cache"),this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,action:r,cache:l,originalCache:l,retriesWithAI:c,finalAttempt:true,options:i});if(C instanceof te&&!w)throw h.warn({err:C},"Failed to execute command with target (fatal)"),C;if(c>0&&o){h.info({err:C},"Failed to execute action with cached target, retrying with AI"),At.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!f.requirements}`,`hasAdditionalElements:${!!f.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:3.16.3",`missReason:${C instanceof Ei?C.cacheMissReason:"unknown"}`]);let x;f.memory&&IE(f.memory)&&(x=f.memory);let I=C instanceof Ei&&C.cacheMissReason==="failing-ldist";return this.wrapElementTargetingCommandHelper({tracer:n,command:s,target:o,cache:void 0,action:r,originalCache:l,retriesWithAI:c,finalAttempt:true,options:{...i,memory:x,targetHealingInProgress:true},skipInitialLocateWait:I})}throw new te("ActionFailureError",`Failed to execute interactive command: ${C instanceof Error?C.message:`${C}`}`,{errOptions:{cause:C}})}}async executeTargetingCommandWithAI(t){let{tracer:n,stepTracer:o,target:r,options:i,command:s,action:a,originalCache:l,logger:c,useMemory:d,cacheBustedBeforeAction:u,cacheBustReason:p,skipInitialLocateWait:m}=t;c.info({description:r.elementDescriptor,targetHealingInProgress:i.targetHealingInProgress,cacheBustedBeforeAction:u,memory:i.memory,useMemory:d},"Prompting AI for an updated element location");let h=false;(u||!l)&&!this.getCurrentExecutionOptions().skipAISmartWaiting&&!i.skipAISmartWaiting?(await n.startAsyncSpan("SMART_WAITING",async()=>await S7({description:r.elementDescriptor,iframeUrl:i.iframeUrl,source:i.source,logger:c,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride},this.getControllerFixtures())),h=true):(u||!l)&&(i.skipAISmartWaiting?c.debug("Skipping AI smart waiting for this targeting attempt"):c.debug("Skipping AI smart waiting due to controller execution options"));let g=2;for(let f=1;f<=g;f++){let y=false,S=this.browser.getActiveFrameConfig(),T=i.force||f>1;try{let E;try{E=await p0({description:r.elementDescriptor,disableCache:!!i.disableCache,iframeUrl:i.iframeUrl,source:i.source,useMemory:d,memory:d?i.memory:void 0,allowNotActionableNodesOverride:i.allowNotActionableNodesOverride,allowIneligibleTagRedirect:i.allowIneligibleTagRedirect,showZeroOpacityElementsOverride:i.showZeroOpacityElementsOverride,logger:c,skipWait:h||m,isAutoHeal:!!i.targetHealingInProgress,cacheBustReason:p,acceptElementMovedError:T},this.getControllerFixtures());}catch(x){if(x instanceof Nh&&x.updatedLocatorMemory){let I={id:-1,...l,memory:x.updatedLocatorMemory};ER({cmd:s,key:i.targetName,newTarget:I,logger:c,updatedWithAI:!0});}throw x}E.frameConfig&&(this.browser.setActiveFrameConfig(E.frameConfig),y=!0);let C=await this.scrollIntoViewAndResolveFinalTarget({resolutionResult:E.resolution,disableGlobalLocatorRedirect:i.disableGlobalLocatorRedirect,logger:c}),w=await a(C);return ER({cmd:s,key:i.targetName,newTarget:E.target,logger:c,updatedWithAI:!0}),i.targetHealingInProgress&&(o.recordTargetAutoHeal({healType:"AI"}),E.target.targetSource="AI_HEALED",E.target.targetUpdateTime=new Date().toUTCString(),E.target.targetUpdateLoggerTags=jt(c)),{result:w,elementInteractedDisplayString:E.resolution.displayString,thoughts:E.thoughts}}catch(E){if(y&&this.browser.setActiveFrameConfig(S),this.throwIfClosed(),f<g&&vO(E)){c.warn({err:E,aiAttempt:f},"Encountered retryable AI targeting error; retrying with AI once");continue}throw E instanceof te?E:new te("ActionFailureError",E.message)}}throw new te("ActionFailureError","Failed to execute AI targeting after retry")}async screenshotWithDimensions(t){return HT(this.browser,t)}async executePresetCommand(t,n,o,r,i){this.options?.slowMoMs&&await Qe(this.options.slowMoMs);let s=await this.browser.getOpenPages(),a=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(n,o);}catch(c){throw this.throwIfClosed(),new te("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await He({name:`cli.command.${n.type}`,attributes:{"momentic.command_type":n.type,"momentic.command_id":n.id},fn:()=>this.executePresetCommandHelper(t,n,o,r,i)});return this.options?.autoFollowNewTabs&&await i7({beforeUrl:a,command:n,beforePages:s.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{i8(n,l);}}createCallbacksForBrowser(t){return {createIsolatedFolder:()=>UF(t)}}async traceBrowserInteraction(t,n,o){return yo().startAsyncSpan("BROWSER_INTERACTION",async i=>n(i),{name:t,...o})}async resolveCommandTemplateStrings(t,n){return iI({obj:t,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(t,n,o,r,i){r=r||"disableCache"in n&&!!n.disableCache;let s=this.logger.child({commandId:n.id});switch(n.type){case "SUCCESS":{let a=n.condition;return a?.assertion.trim()?CI({command:a,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i}):{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AI_ASSERTION":{if(!n.assertion.trim())throw new te("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new te("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return CI({command:n,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory(),logger:s,recoveryHint:i})}case "AI_EXTRACT":return y7({command:n,logger:s,fixtures:this.getControllerFixtures(),disableCache:r});case "NAVIGATE":if(!Kg(n.url)&&!Yg(n.url,this.browser.baseUrl))throw new te("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.traceBrowserInteraction("Navigate",()=>this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "DIALOG":this.browser.registerDialogHandler(n.action);break;case "CAPTCHA":throw new te("UserConfigurationError","Captcha solving is no longer available on Momentic");case "GO_BACK":await this.traceBrowserInteraction("Go back",()=>this.browser.goBack());break;case "GO_FORWARD":await this.traceBrowserInteraction("Go forward",()=>this.browser.goForward());break;case "SCROLL_LEFT":case "SCROLL_RIGHT":case "SCROLL_DOWN":case "SCROLL_UP":{let a,l;if(n.target&&Il(n.target)){let u=qr(n.target.pixels);await this.browser.hoverUsingVisualCoordinates(u);}else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:u,thoughts:p}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:m=>this.browser.hover(m),options:{...n,targetName:"target",disableGlobalLocatorRedirect:true,disableCache:r}});a=u,l=p;}let c=this.browser.getViewport()?.height??kr.height,d=this.browser.getViewport()?.width??kr.width;switch(n.type){case "SCROLL_UP":await this.traceBrowserInteraction("Scroll up",()=>this.browser.scrollVertical(-(n.deltaY??c)));break;case "SCROLL_DOWN":await this.traceBrowserInteraction("Scroll down",()=>this.browser.scrollVertical(n.deltaY??c));break;case "SCROLL_LEFT":await this.traceBrowserInteraction("Scroll left",()=>this.browser.scrollHorizontal(-(n.deltaX??d)));break;case "SCROLL_RIGHT":await this.traceBrowserInteraction("Scroll right",()=>this.browser.scrollHorizontal(n.deltaX??d));break}return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new te("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let a=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:a},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case "WAIT":{if(n.delay>1800)throw new te("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let a=n.delay*1e3;await Qe(a,this.executeAbortController.signal);break}case "REFRESH":await this.traceBrowserInteraction("Refresh",()=>this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0}));break;case "CLICK":{if(Il(n.target)){let p=qr(n.target.pixels),m={...n,relativePosition:n.relativePosition?qr(n.relativePosition):void 0};await this.traceBrowserInteraction("Click",()=>this.browser.clickUsingVisualCoordinates(p,m),{coordinates:p});break}let a=this.browser.url(),{elementInteractedDisplayString:l,result:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:p=>this.traceBrowserInteraction("Click",async m=>{let h={...n,relativePosition:n.relativePosition?qr(n.relativePosition):void 0},g=await this.browser.click(p,this.createCallbacksForBrowser(this.orgId),h);return g.coordinates&&(m.coordinates=g.coordinates),g},{selector:p.locator.toString()}),options:{...n,targetName:"target",disableCache:r}}),u={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:d,data:c.downloadedFile?{downloadedFile:c.downloadedFile}:void 0};return MR(a,u.urlAfterCommand)&&(u.succeedImmediately=true,u.succeedImmediatelyReason="URL changed"),u}case "COPY":return await this.browser.copy(n.value),{succeedImmediately:false,data:n.value,urlAfterCommand:this.browser.url()};case "PASTE":{await this.browser.paste();break}case "DRAG":{if(Il(n.fromTarget)&&Il(n.toTarget)){let c=qr(n.fromTarget.pixels),d=qr(n.toTarget.pixels);await this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDropUsingVisualCoordinates(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0}),{coordinates:c});break}if(Il(n.fromTarget)||Il(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:a,thoughts:l}=await this.wrapMultiElementTargetingCommand({tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(c,d)=>this.traceBrowserInteraction("Drag",()=>this.browser.dragAndDrop(c,d,{hoverDurationMs:n.hoverSeconds?n.hoverSeconds*1e3:void 0,steps:n.steps})),options:{...n,disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a[0],thoughts:l}}case "MOUSE_DRAG":{let a=parseInt(n.deltaX),l=parseInt(n.deltaY),c=n.steps??5;if(isNaN(a)||isNaN(l))throw new te("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Il(n.target)){let p=qr(n.target.pixels);await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDragUsingVisualCoordinates({deltaX:a,deltaY:l,steps:c,fromTarget:p}),{coordinates:p});break}let d,u;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:p,thoughts:m}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async h=>this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,h.locator,{force:n.force})),options:{...n,targetName:"target",disableCache:r}});d=p,u=m;}else await this.traceBrowserInteraction("Mouse drag",()=>this.browser.mouseDrag(a,l,c,void 0,{force:n.force}));return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:d,thoughts:u}}case "SELECT_OPTION":{if(!Hc(n.target))throw new Error("Select with x/y is not supported yet");let a=n.target.elementDescriptor,l=n.choice,{elementInteractedDisplayString:c,thoughts:d}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:{type:"description",elementDescriptor:a},cache:n.cache?.target,action:u=>this.traceBrowserInteraction("Select option",()=>this.browser.selectOption(u,l,n.force),{value:l.type==="LABEL"?l.label:l.type==="VALUE"?l.value:l.index}),options:{...n,targetName:"target",disableCache:r,source:Vp(n)}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:c,thoughts:d}}case "TAB":{let a={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:true};await this.browser.switchToPage(n.action,a);break}case "NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case "CLOSE_TAB":await this.browser.closePage(n.action,{retry:true});break;case "COOKIE":{if(!n.value)break;let a=await this.browser.setCookie(n.value);s.debug({results:a},"Set cookies");break}case "LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case "JAVASCRIPT":{let a;try{n.environment==="BROWSER"?(a=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),s.info({result:a},"Executed JavaScript in browser")):a=await Zu({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async l=>{if(!this.options?.scratchPadId){s.warn({updates:l},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:l,logger:s});}}});}catch(l){throw this.throwIfClosed(),new te("ActionFailureError",l instanceof Error?l.message:`${l}`,{errOptions:{cause:l}})}try{JSON.stringify(a);}catch(l){throw new te("ActionFailureError",`Return value is not serializable: ${l instanceof Error?l.message:`${l}`}`,{errOptions:{cause:l}})}return {urlAfterCommand:this.browser.url(),succeedImmediately:false,data:a}}case "TYPE":{if(n.target&&Il(n.target)){let m=qr(n.target.pixels),h={...n,relativePosition:n.relativePosition?qr(n.relativePosition):void 0};await this.browser.clickUsingVisualCoordinates(m,h),await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});break}let a=this.browser.url(),l,c,d=cloneDeep(n.target),u=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(d){let{elementInteractedDisplayString:m,thoughts:h}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:d,cache:n.cache?.target,action:g=>this.traceBrowserInteraction("Type",()=>this.browser.typeIntoTarget(n.value,g,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),{value:n.value,selector:g.locator.toString()}),options:{...n,targetName:"target",disableCache:r,disableGlobalLocatorRedirect:!u,source:Vp(n)}});l=m,c=h;}else await this.traceBrowserInteraction("Type",()=>this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},true),{value:n.value});let p={urlAfterCommand:this.browser.url(),succeedImmediately:false,elementInteracted:l,thoughts:c};return MR(a,p.urlAfterCommand)&&(p.succeedImmediately=true,p.succeedImmediatelyReason="URL changed"),p}case "HOVER":{if(Il(n.target)){let c=qr(n.target.pixels);await this.traceBrowserInteraction("Hover",()=>this.browser.hoverUsingVisualCoordinates(c),{coordinates:c});break}let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.traceBrowserInteraction("Hover",()=>this.browser.hover(c,{relativePosition:n.relativePosition?qr(n.relativePosition):void 0}),{selector:c.locator.toString()}),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "FOCUS":{if(!Hc(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,command:n,target:n.target,cache:n.cache?.target,action:c=>this.browser.focus(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "BLUR":{if(n.target&&!Hc(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:false,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:a,thoughts:l}=await this.wrapElementTargetingCommand({tracer:t,target:n.target,command:n,cache:n.cache?.target,action:c=>this.browser.blur(c),options:{...n,targetName:"target",disableCache:r}});return {succeedImmediately:false,urlAfterCommand:this.browser.url(),elementInteracted:a,thoughts:l}}case "PRESS":{let a=this.browser.url();await this.traceBrowserInteraction("Press key",()=>this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??true,delayMs:n.delayMs}),{value:n.value});let l={urlAfterCommand:this.browser.url(),succeedImmediately:false};return MR(a,l.urlAfterCommand)&&(l.succeedImmediately=true,l.succeedImmediatelyReason="URL changed"),l}case "KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??true}),{urlAfterCommand:this.browser.url(),succeedImmediately:false};case "REQUEST":{let a=new CookieJar,l=HBe(fetch,a),c;try{c=new URL(n.url).hostname;}catch{}let d=await R7({command:n,baseUrl:this.browser.baseUrl,logger:s,fetchImplementation:l});return {data:Jy.parse({...d,cookies:lW(a,c)}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GRAPHQL_REQUEST":return {data:await x7({command:n,baseUrl:this.browser.baseUrl,logger:s}),succeedImmediately:false,urlAfterCommand:this.browser.url()};case "VISUAL_DIFF":return v7({tracer:t,command:n,disableCache:r,browser:this.browser,logger:s,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:a=>this.wrapElementTargetingCommand(a)});case "FILE_UPLOAD":{let a,l;if(n.fileSource.type==="URL"?(l=n.fileSource.url,a=await z8({uri:n.fileSource.url,logger:s,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(l=n.fileSource.name,a=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!a)throw new te("UserConfigurationError",`Attempted to use non-existent file for upload step: ${l}`);await this.browser.setFileChooserHandler({...a,filename:n.filename});break}case "AUTH_SAVE":{let a=await this.browser.saveAuthState();if(n.storageState&&ju(n.storageState)){let l=Jn__default.resolve(n.storageState);Oo__default.mkdirSync(Jn__default.dirname(l),{recursive:true}),Oo__default.writeFileSync(l,`${JSON.stringify(a,null,2)}
5777
5777
  `,"utf8");}return {data:a,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AUTH_LOAD":{let a;if(ju(n.storageState))try{a=JSON.parse(Oo__default.readFileSync(Jn__default.resolve(n.storageState),"utf8"));}catch(c){throw new te("UserConfigurationError",`Failed to read auth state from '${n.storageState}': ${X(c)}`,{errOptions:{cause:c}})}else if(!n.storageState.trim())a=void 0;else if(a=await Zu({orgId:this.orgId,code:n.storageState,fragment:false,context:o,logger:s,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof a!="object")throw new te("ActionFailureError",`Credentials must evaluate to an object (received ${typeof a} instead)`);let l;try{l=UC.optional().parse(a);}catch(c){throw new te("ActionFailureError",`Credentials provided do not follow the required format: ${c}`)}await this.browser.loadAuthState(l);break}case "ELEMENT_CHECK":{let a=(n.timeout??Zs)*1e3,l=this.generator.getAgentConfig()?.assertion;if(E7(n.assertion)&&!n.useSelector&&n.target.type==="description"&&l&&l!=="v1"){let d={id:n.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${n.target.elementDescriptor}`,iframeUrl:n.iframeUrl,timeout:n.timeout,source:"NEGATED_CHECK",cache:n.cache&&"memory"in n.cache?{memory:n.cache?.memory}:void 0};try{let u=await CI({command:d,logger:s,fixtures:this.getControllerFixtures(),useMemory:this.shouldUseMemory()});return {succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${u.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:u.afterScreenshotOverride}}finally{d.cache?.memory&&Kb(n,d.cache?.memory.traces,s);}}let c=await A7({command:n,tracer:t,timeoutMs:a,targetingWrapper:d=>this.wrapElementTargetingCommand(d),fixtures:this.getControllerFixtures(),disableCache:r});return {fail:!c.success,data:c.data,elementInteracted:c.elementInteractedDisplayString,thoughts:c.err?.message??c.thoughts??`Element assertion ${c.success?"succeeded":"failed"}.`,succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "PAGE_CHECK":{let a=await wa({action:async()=>vI({assertion:n.assertion,browser:this.browser,logger:s,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:s});return {fail:!a.success,data:a.data,thoughts:a.success?"Page assertion passed.":a.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:false}}case "REGISTER_REQUEST_LISTENER":{let a=new sp(n.requestMatcher),l=this.browser.registerRequestListener(a);return this.registeredListeners[n.key]=l.then(async c=>await $F(c)).catch(c=>{s.error({err:c},"Failed to get request listener response");}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "AWAIT_LISTENER":{let a=this.registeredListeners[n.key];if(!a)throw new te("ActionFailureError",`No listener registered with key: ${n.key}`);let l=n.timeout??10;return {data:await _e(a,{milliseconds:l*1e3,message:`Request listener timed out after ${l} seconds`}),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "RECORD_REQUESTS":{let a=new sp(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:l=>a.matches({url:l.request.url,method:l.request.method}),onRequestStart:(l,c)=>{this.recordedRequests[n.key][l]=mI(c);},onRequestComplete:(l,c)=>{this.recordedRequests[n.key]?.[l]&&(this.recordedRequests[n.key][l]=mI(c));}}),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "GET_RECORDED_REQUESTS":{let a=this.recordedRequests[n.key];if(!a)throw new te("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(a),succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "SET_HEADER":{let a;return n.requestMatcher&&(a=new sp(n.requestMatcher)),this.browser.setHeader(n.name,n.value,a),{succeedImmediately:false,urlAfterCommand:this.browser.url()}}case "MOCK_ROUTE":return {data:{key:this.browser.registerMock(n.key,new sp(n.requestMatcher),async(l,c)=>{let d=await Zu({orgId:this.orgId,code:n.responseGenerator,fragment:false,context:o,timeoutMs:void 0,logger:s,localTools:this.localCodeEvalTools,mock:{request:l,response:c},disallowVariableUpdates:true,responseSerialization:"RESPONSE"}),u=NW.parse(d);return new Response(u.body,{status:u.status,headers:u.headers})},n.fetchOriginalResponse??false)},succeedImmediately:false,urlAfterCommand:this.browser.url()};case "REMOVE_ROUTE_MOCK":return this.browser.removeMock(n.key),{succeedImmediately:false,urlAfterCommand:this.browser.url()};case "OFFLINE_MODE":return await this.browser.setOfflineMode(n.enable),{succeedImmediately:false,urlAfterCommand:this.browser.url()};default:return (l=>{throw "If Typescript complains about the line below, you missed a case or break in the switch above"})()}return {succeedImmediately:false,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:t,targetId:n,disableCache:o,screenshot:r}){return (await this.generator.getReverseMappedDescription({browserState:t,target:n,screenshot:r},{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:jt(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights();}async startRecordMode({params:t,abortController:n,isClickToRecord:o}){this.recordAbortController=n;let r=new bI({signal:n.signal,...t});return await this.browser.startRecording(this.recordAbortController.signal,r,o),r}async runSectionAutohealing(t){return this.generator.getAutohealingProposal(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:jt(this.logger)})}async getFailureRecoveryPlan(t,n){return this.generator.getFailureRecoveryPlan(t,{disableCache:true,abortSignal:this.executeAbortController.signal,loggerTags:jt(n??this.logger)})}};var f0=async e=>{let{step:t,resolvedInputs:n}=e.moduleParams,{logger:o,context:r,storage:i,codeEvalTools:s,controller:a}=e.fixtures,l=a.browser,{orgId:c,runId:d}=e.inputs,u=a.executeAbortController.signal;Object.keys(n).length>0&&(r.setInputs(n),o.info(ki({json:{inputs:n,moduleId:t.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let p,m=false,h,g;if(t.cacheConfig||t.defaultCacheAllInvocations){let f=t.cacheConfig?.cacheKey||t.defaultCacheKey||"",y=await li({orgId:c,s:f,context:r,logger:o,localTools:s,signal:u});g={orgId:c,cacheKeys:[y,...Object.entries(n).map(([T,E])=>`${T}:${E}`)]},o.info({original:f,keyParams:g},"Module cache key params");let S=Date.now();for(;Date.now()-S<b1;){u?.throwIfAborted();let T=await i.getCacheResult(g);if(T){o.info({cacheResult:hn(T,1e3,true)},"Got result from module execution cache"),p=RI(t,n,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(T),m=true;break}else o.info({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let E=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${hostname()};runId:${d}`},u);if(E.acquired){h=E.keyPrefix,o.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else o.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Qe(2500+Math.random()*1e4,u);}}try{if(!p)p=await $Be(e);else if(t.autoAuth){let f=UC.safeParse(p.data);if(!f.success)throw new te("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);o.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let y=!1,S=t.advanced?.cacheInvalidation;if(S&&S.type==="PAGE_CHECK"){let T={type:"CONTENT",value:S.substring},E=await vI({timeout:Zs,assertion:T,browser:l,logger:o,signal:u,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});E.success?o.debug({invalResult:E},"Cached result still valid after page check, continuing..."):(o.info({invalResult:E},"Invalidating cached result due to page check failure"),y=!0);}if(g&&y)return await i.deleteCacheResult(g),f0(e)}}finally{try{h!==void 0&&!m&&p?.status==="SUCCESS"&&await VBe({step:t,result:p,browser:a.browser,cacheKeyPrefix:h,logger:o,storage:i});}finally{h!==void 0&&await i.releaseCacheLock(h);}}return p},$Be=async e=>{let{currentParentIdChain:t}=e,{step:n,tracer:o}=e.moduleParams,r=RI(n,e.moduleParams.resolvedInputs,"SUCCESS"),i=await o.startSubSteps(),{status:s,results:a}=await e.executeStepList({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:i,currentParentIdChain:t}});return r.results=a,r.status=s,r.finishedAt=new Date,cs({asyncTasks:e.work.asyncTasks,nestedResults:a,result:r,logger:e.fixtures.logger}),r};function RI(e,t,n){let o={};return Object.entries(t).forEach(([i,s])=>{o[i]=JSON.stringify(s);}),{type:"MODULE",id:e.id,moduleId:e.moduleId,moduleName:e.name,startedAt:new Date,cacheConfig:e.cacheConfig,inputs:o,results:[],finishedAt:new Date,status:n}}async function P7({orgId:e,step:t,context:n,logger:o,codeEvalTools:r,signal:i}){let s={};try{for(let a of t.parameters??[]){let l=t.inputs?.[a]??t.defaultParameters?.[a];if(!l){o.warn(`No value or default found for parameter '${a}' that is required by module '${t.name}'`);continue}s[a]=await Zu({orgId:e,code:l,fragment:!0,context:n,logger:o,localTools:r,signal:i});}return s}catch(a){throw i?.throwIfAborted(),new te("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function VBe({step:e,result:t,browser:n,cacheKeyPrefix:o,logger:r,storage:i}){let s=e.cacheConfig?.cacheExpiryMs;(!s||s===PK)&&(s=e.defaultCacheTtl??OK);let a;e.autoAuth?a=JSON.stringify(await n.saveAuthState()):t.data!==void 0?a=JSON.stringify(t.data):a='""',r.debug({cacheKeyPrefix:o,ttlMs:s,truncatedCacheResultJson:ki({json:a,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:a,keyPrefix:o,ttlMs:s});}async function lp(e,t,n){return zBe(e,t,n)}async function zBe(e,t,n){let o=new Date;try{return n.throwIfAborted(),await t()}catch(r){let i=new Date,s="FAILED",a;if(n.aborted||r instanceof DOMException&&r.name==="AbortError"?(a="Step aborted by user.",s="CANCELLED"):r instanceof te?a=`${r}`:a=`An unexpected error occurred: ${r.message}`,e.type==="RESOLVED_MODULE"){let l=RI(e,{},"FAILED");return l.message=a,l.startedAt=o,l.finishedAt=i,l}return {...qg(e),startedAt:o,finishedAt:i,status:s,data:null,message:a,results:[]}}}async function di(e,t){let n=false;try{return e&&!e.state.failureRecoveryDisabled&&(e.state.failureRecoveryDisabled=!0,n=!0),await t()}finally{e&&n&&(e.state.failureRecoveryDisabled=void 0);}}var O7=500,M7=120;async function k7({gitContext:e,remoteGitContext:t,remoteGitClient:n,githubRepository:o,branchName:r,mainBranchName:i,logger:s}){if(!(!e&&!t))try{let a=e?await qBe(e):YBe(t),l=r!==void 0&&r===i,c=[];if(l){let d=e?await KBe(e):t.comparison.commits.at(-1)?.message;d&&c.push(`Last commit on ${i}:
5778
5778
  ${N7(d.trim())}`);}else {let d=await WBe({remoteGitContext:t,remoteGitClient:n,githubRepository:o,branchName:r,logger:s});d&&c.push(`Open pull request #${d.issueNumber}: ${d.title??"(no title)"}${d.body?`
5779
5779
 
@@ -6891,7 +6891,7 @@ ${uB}`;if(Array.isArray(e))return [...e,{role:"system",content:uB}];if(e&&typeof
6891
6891
  - **Code**: \`JAVASCRIPT\` runs custom code (see JavaScript steps below).
6892
6892
  - **Dynamic**: \`AI_ACTION\` dynamically generates a short sequence of sub-steps from a natural-language goal (see AI_ACTION below).
6893
6893
  - **Composition**: \`MODULE\` invokes a reusable parameterized step group (see Modules below).
6894
- Within the check family there is a natural preference order when more than one check type can express the same intent: \`ELEMENT_CHECK\` > \`PAGE_CHECK\` > \`AI_ASSERTION\` > \`WAIT_FOR_URL\`. \`AI_ASSERTION\` is the right tool when the assertion needs visual or semantic judgement that an element- or page-level check cannot represent.
6894
+ Within the check family there is a natural preference order when more than one check type can express the same intent: \`ELEMENT_CHECK\` > \`PAGE_CHECK\` > \`AI_ASSERTION\` > \`WAIT_FOR_URL\`. Use \`PAGE_CHECK\` on text that will stay stable as the product evolves; for parts of the page subject to change, prefer an element check or AI assertion. \`AI_ASSERTION\` is the right tool when the assertion needs visual or semantic judgement that an element- or page-level check cannot represent.
6895
6895
 
6896
6896
  ## Element descriptions
6897
6897
  Interaction and element-check steps target elements by **natural-language descriptions**, not CSS selectors, XPath, HTML snippets, ids, classes, data attributes, or tag-name overfitting. A description like "the close button in the top right of the modal" stays correct across DOM refactors; ".modal-close" does not. Descriptions are evaluated against the rendered page using a combination of accessibility tree and visual cues.
@@ -6986,7 +6986,7 @@ ${uB}`;if(Array.isArray(e))return [...e,{role:"system",content:uB}];if(e&&typeof
6986
6986
  Choose high-signal elements that distinguish the intended page or state: for example, a page-specific heading, the primary result or status, a confirmation message, or the control enabled by the completed transition. Do not assert every visible element, shared navigation, decorative details, incidental copy, etc. Each resulting check must prove a necessary part of the intended state, and the group must be intent preserving in the strength of an assertion.
6987
6987
 
6988
6988
  ## Check discipline
6989
- - Choose the best check that fully proves the behavior. Prefer \`ELEMENT_CHECK\` or \`PAGE_CHECK\` when the fact is deterministic. Use \`AI_ASSERTION\` when the behavior requires visual or semantic judgment. Use \`WAIT_FOR_URL\` when the behavior being verified is a URL transition.
6989
+ - Choose the best check that fully proves the behavior. Prefer \`ELEMENT_CHECK\` or \`PAGE_CHECK\` when the fact is deterministic, reserving \`PAGE_CHECK\` for copy that will stay stable on the passing path. Use \`AI_ASSERTION\` when the behavior requires visual or semantic judgment. Use \`WAIT_FOR_URL\` when the behavior being verified is a URL transition.
6990
6990
  - \`PAGE_CHECK\` is a direct substring check and does not need an element locator or LLM.
6991
6991
  - \`ELEMENT_CHECK\` may use an LLM to resolve its element, but then caches the resulting Playwright locator and evaluates the configured assertion deterministically on later runs.
6992
6992
  - \`AI_ASSERTION\` calls an LLM on every run, so it is slower but able to assert about anything in the screenshot or A11y tree.
@@ -7520,7 +7520,7 @@ with this test we are editing:
7520
7520
  to pick which of these modules are relevant:
7521
7521
 
7522
7522
  `;let p=w1e(c);u+=p;let m=streamObject({schema:XB,model:d("claude-sonnet-4-5-20250929"),system:R1e,messages:[{role:"user",content:u}],providerOptions:{anthropic:ds}}),h=[];for await(let T of m.textStream)h.push(T);let g=h.join(""),f;try{let T=JSON.parse(g);f=XB.parse(T);}catch(T){r.error({rawResponse:g,parseError:T},"Failed to parse AI response as JSON"),n.addError(`Failed to parse AI response: ${X(T)}. Raw response: ${g}`);return}let y=new Set(c.map(T=>T.moduleId)),S=f.recommendations.filter(T=>y.has(T.moduleId)?!0:(r.warn({moduleId:T.moduleId,moduleName:T.moduleName},"AI recommended a module that doesn't exist"),!1));n.addPartFromText(JSON.stringify({recommendations:S,totalModulesAnalyzed:c.length},null,2));}catch(c){r.error({err:c},"Error in module recommendation"),n.addError(`Failed to recommend modules: ${X(c)}`);}}}),n_=[x1e,C1e];var _1e=1e5,Gre=Xo({schema:{name:uS,description:"Get the current browser state for a granular session. Defaults: screenshot on, browser snapshot off. The browser snapshot includes the URL, accessibility tree, and other context. Ask for it (returnBrowserState: true) when you need it for locator resolution or richer page structure\u2014e.g. when screenshot-only output is insufficient. For large pages, pass `hint` to AI-filter the snapshot down to the relevant sections.",inputSchema:{sessionId:z$1.string().describe("The session id to query."),returnBrowserState:z$1.boolean().default(false).describe("Include the serialized browser snapshot. Default false. Set to true when you need the browser snapshot for element targeting or page structure."),returnScreenshot:z$1.boolean().default(true).describe("Include a screenshot. Default true. Set to false if you already have a screenshot of the present state and don't need a new one. EX: you just previewed a step and see that the page is too complicated and need the browser snapshot."),hint:z$1.string().optional().describe("Short natural-language description of what you need from the page (e.g. the action you are about to take or the element you are looking for). Required when returnBrowserState=true and the page is large: the hint is fed into an AI page-filtering step that returns only the most relevant sections of the accessibility tree, keeping the snapshot under the per-tool token budget.")}},handle:async(e,t,n)=>{let o=Wd({response:n,sessionId:t.sessionId,toolName:uS});if(!o)return;o.controller.setOpen();let r=await qB({browser:o.controller.browser,supportsFileOutput:e.supportsFileOutput,returnBrowserState:t.returnBrowserState,returnScreenshot:t.returnScreenshot,tokenLimit:_1e,hint:t.hint,filtering:{generator:e.generator,orgId:e.orgId,logger:e.logger,signal:o.controller.executeAbortController.signal}});n.addContentParts(r);}}),jre=Xo({schema:{name:pS,description:"Get the current environment variables for a session.",inputSchema:{sessionId:z$1.string()}},handle:async(e,t,n)=>{let o=Wd({response:n,sessionId:t.sessionId,toolName:pS});if(!o)return;let r=await qs({testContext:o.context,supportsFileOutput:e.supportsFileOutput});n.addContentParts(r);}});var $re=Xo({schema:{name:zc,description:`Start a granular browser session for a specific test. Requires a testId. Returns session metadata (sessionId, testId, testFileAbsolutePath, projectConfigAbsolutePath, cwd, viewport, etc.), a Step Authoring Guide artifact that includes projectRootAbsolutePath, projectConfigAbsolutePath, and cwd, and a Test Content section that lists every step in the bound test with its stable stepId context. ${eA} Read the Step Authoring Guide artifact before creating, previewing, running, or splicing CLI-style steps. Use the Test Content section for the step ids required by tools that operate on existing steps in this session's test. After editing with splice, prefer the splice response or request returnTest for the updated active-session step ids. Use ${Sr} to inspect persisted test state by id or path, especially for a different test.`,inputSchema:{testId:z$1.string().describe("The test id to target when starting a session."),envName:z$1.string().optional().describe("Optional environment override (matches CLI --env behavior). Defaults to the test's default env when omitted."),projectConfigPath:z$1.string().optional().describe("Optional path to a momentic.config.yaml file (matches CLI --config)."),projectNameFilter:z$1.string().optional().describe("Optional project name filter for workspace configs (matches CLI --filter)."),headfulBrowser:z$1.boolean().optional().describe("Whether to launch a headful browser for the session. When omitted, uses the MCP server default if configured."),video:z$1.boolean().optional().describe("Whether to record a video of the browser session. When omitted, uses the MCP server default if configured. When the session is terminated, the response will include the path to the video output directory.")}},handle:async(e,t,n)=>{let{logger:o}=e,r=t.video??e.videoDefault??false,i;r&&(Hi(e.project.rootDir),i=Gi({rootDir:e.project.rootDir,entity:"video",ext:"d"}),mkdirSync(i,{recursive:true}));let s;try{let l=qo();if(!l){n.addError("API client is not initialized; cannot start MCP session.");return}let c=await Fs({project:await sn({configFilePath:t.projectConfigPath??e.project.configFilePath,nameFilter:t.projectNameFilter,skipExitOnError:!0}),apiClient:l}),d=new Ys(l,e.orgId,c);s=await Ks.startSession({logger:o,storage:d,testId:t.testId,idleTimeoutMs:e.sessionIdleTimeoutMs,runner:"mcp",envName:t.envName,headfulOverride:t.headfulBrowser??e.headfulDefault??!0,customHeaders:e.customHeaders,devicePixelRatio:e.devicePixelRatio,videoOutputDir:i});}catch(l){n.addError(X(l));return}Ws({type:"mcp:session_started",test_platform:"web"});let a=s.controller.browser.getViewport();n.addPartFromText(JSON.stringify({sessionId:s.sessionId,testId:s.testId,testFileAbsolutePath:s.testFileAbsolutePath,projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:process.cwd(),createdAt:s.createdAt,expiresAt:s.lastAccessedAt+s.idleTimeoutMs,idleTimeoutMinutes:s.idleTimeoutMs/(60*1e3),envName:s.envName,baseUrl:s.baseUrl,viewport:a},null,2)),n.addContentParts(await fte({projectRootAbsolutePath:e.project.rootDir,projectConfigAbsolutePath:e.project.configFilePath,cwd:process.cwd(),stepSchema:ms(),stepSchemaTitle:"Step schema",supportsFileOutput:e.supportsFileOutput}));try{let l=await Tp({project:s.storage.getProject(),storage:s.storage,selector:{id:s.testId},envName:s.envName,logger:o,mutableStepState:s.mutableStepState,includeCache:!1,hydrateStepIdentity:!0,supportsFileOutput:e.supportsFileOutput});n.addContentParts(l);}catch(l){o.warn({sessionId:s.sessionId,err:l},"Session started but resolved test content could not be loaded");}try{n.addContentParts(await zr({browser:s.controller.browser,supportsFileOutput:e.supportsFileOutput}));}catch(l){o.warn({sessionId:s.sessionId,err:l},"Session started but initial screenshot capture failed"),n.addPartFromText(JSON.stringify({warning:"Session started successfully, but initial screenshot capture failed.",screenshotError:X(l)},null,2));}i&&n.addContentParts(z({text:_r({filePath:i,title:"Video output directory"}),section:"Video Output"}));}}),Vre=Xo({schema:{name:XE,description:"Kill a granular browser session by sessionId. Returns available session ids if the target is missing.",inputSchema:{sessionId:z$1.string().describe("The session id to terminate.")}},handle:async(e,t,n)=>{let{sessionId:o}=t;try{let r=Ks.getSession(o),i=r?.videoOutputDir,s=await Ks.killSession(t.sessionId,"explicit kill");if(s.killed&&Ws({type:"mcp:session_killed",test_platform:"web",reason:"explicit kill"}),!s.killed){r?n.addError(`Failed to terminate session '${t.sessionId}'.`):n.addError(JSON.stringify({message:`No active session found for id '${t.sessionId}'.`,availableSessionIds:Ks.listSessionIds()},null,2));return}n.addPartFromText(JSON.stringify({sessionId:t.sessionId,killed:!0},null,2));let a=await yte({killResult:s,rootDir:e.project.rootDir});a&&n.addContentParts(z({text:_r({filePath:a.filePath,title:"Session span report"}),section:"Session Spans"})),i&&n.addContentParts(z({text:_r({filePath:i,title:"Video output directory"}),section:"Video Output"}));}catch(r){n.addError(X(r));}}});var uy=async({step:e,controller:t,executionOptions:n,storage:o,codeEvalTools:r,logger:i,socket:s,testContext:a,orgId:l,sessionId:c,usageTracker:d,apiClient:u})=>{let{results:p}=await QB({steps:[e],controller:t,executionOptions:n,storage:o,codeEvalTools:r,logger:i,socket:s,testContext:a,orgId:l,sessionId:c,usageTracker:d,apiClient:u});return p[0]},QB=async({steps:e,fromStep:t,toStep:n,tracer:o,controller:r,executionOptions:i,storage:s,codeEvalTools:a,logger:l,socket:c,testContext:d,orgId:u,sessionId:p,usageTracker:m,apiClient:h})=>{let g={controller:r,storage:s,codeEvalTools:a,logger:l,context:d,usageTracker:m},f=o??(c?new Vd({orgId:u,parentStep:null,parentTracer:null,socket:c}):new Ab);r.setOpen();let y={results:[],asyncTasks:[],state:{autoHealingDisabled:true,failureRecoveryDisabled:true,failureRecoveryAttempts:0},...t&&{fastForwardingToStep:true}},S=()=>zs({listParams:{containerName:"agent-step-list",steps:e,tracer:f},fixtures:g,options:{collectDebugData:false,reinitializeBrowser:false,disableHealing:true},inputs:{orgId:u,userId:j6(),runId:randomUUID(),sessionId:p,steps:e,testMetadata:null,orgSettings:{},fromStep:t,toStep:n},callbacks:{test:{},step:{}},runParams:h?{apiClient:h}:null,work:y});return i?r.withExecutionOptions(i,S):S()};async function o_({step:e,project:t,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,tempCaches:u,usageTracker:p,apiClient:m}){let h=await hx(e,{project:t,logger:n,tempCaches:u});switch(h.type){case "PRESET_ACTION":return L1e({step:h,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,tempCaches:u,usageTracker:p,apiClient:m});case "AI_ACTION_DYNAMIC":return k1e({step:h,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,usageTracker:p,apiClient:m});case "RESOLVED_MODULE":return D1e({step:h,logger:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,testContext:c,supportsFileOutput:d,usageTracker:p,apiClient:m});default:{let[g,f]=await Promise.all([zr({browser:r.browser,supportsFileOutput:d}),qs({testContext:c,supportsFileOutput:d})]);return [...z({text:`Preview for step type ${h.type} is not supported. Only PRESET_ACTION, RESOLVED_MODULE, and AI_ACTION_DYNAMIC are supported.`,section:"Error"}),...g,...f]}}}async function L1e({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,tempCaches:d,usageTracker:u,apiClient:p}){let m=await uy({step:e,logger:t,storage:n,controller:o,executionOptions:{skipAISmartWaiting:true},codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,usageTracker:u,apiClient:p}),h=[];m?m.status==="SUCCESS"?(F1e({logger:t,tempCaches:d,command:e.command,parts:h}),h.push(...z({text:`Step Execution successful: ${m.message}`,section:"Successful Result"}))):h.push(...z({text:`Step Execution failed: ${m.message}`,section:"Error"})):h.push(...z({text:"Step Execution errored for an unknown reason.",section:"Error"}));let[g,f]=await Promise.all([zr({browser:o.browser,supportsFileOutput:c}),qs({testContext:l,supportsFileOutput:c})]);return h.push(...g,...f),h}async function k1e({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,usageTracker:d,apiClient:u}){let p=await uy({step:e,logger:t,storage:n,controller:o,executionOptions:{skipAISmartWaiting:true},codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,usageTracker:d,apiClient:u}),m=[];p?p.status==="SUCCESS"?m.push(...z({text:`AI action completed successfully: ${p.message??"Goal achieved"}`,section:"Successful Result"})):m.push(...z({text:`AI action failed: ${p.message??"Unknown error while previewing AI action"}`,section:"Error"})):m.push(...z({text:"AI action executed with unknown result.",section:"Error"}));let[h,g]=await Promise.all([zr({browser:o.browser,supportsFileOutput:c}),qs({testContext:l,supportsFileOutput:c})]);return m.push(...h,...g),m}async function D1e({step:e,logger:t,storage:n,controller:o,codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,supportsFileOutput:c,usageTracker:d,apiClient:u}){let p=await uy({step:e,logger:t,storage:n,controller:o,executionOptions:{skipAISmartWaiting:true},codeEvalTools:r,socket:i,orgId:s,sessionId:a,testContext:l,usageTracker:d,apiClient:u}),m=[];p?p.status==="SUCCESS"?m.push(...z({text:`Module executed successfully: ${p.message}`,section:"Successful Result"})):m.push(...z({text:`Module execution failed: ${p.message}`,section:"Error"})):m.push(...z({text:"Module execution errored for an unknown reason.",section:"Error"}));let[h,g]=await Promise.all([zr({browser:o.browser,supportsFileOutput:c}),qs({testContext:l,supportsFileOutput:c})]);return m.push(...h,...g),m}function F1e({logger:e,tempCaches:t,command:n,parts:o}){if(t&&tr(n)&&n.cache)try{let r=randomUUID();t[r]=Ml.parse(cloneDeep({type:n.type,cache:n.cache})),o.push(...z({text:r,section:"CacheId"}));}catch(r){e.warn({err:r},"Failed to save temp cache for step. Continuing...");}}var zre=({steps:e,fromStep:t,toStep:n})=>{let o={total:0,fastForwardingToStep:true},r=(i,s)=>{if(i.skipped)return false;let a=s.map(c=>c.id),l=hA(i.id,a,t.fromStepId,t.parentStepIdChain);if(o.fastForwardingToStep){if(!l)return false;o.fastForwardingToStep=false;}return o.total+=1,!!(n&&hA(i.id,a,n.toStepId,n.parentStepIdChain))};return Li({steps:e,earlyStop:true,onPresetAction:(i,s)=>r(i,s.parentChain),onConditional:(i,s)=>{if(i.skipped)return false;let a=s.parentChain.map(c=>c.id),l=hA(i.id,a,t.fromStepId,t.parentStepIdChain);if(o.fastForwardingToStep){if(!l)return false;o.fastForwardingToStep=false;}return !!(n&&hA(i.id,a,n.toStepId,n.parentStepIdChain))},onSimpleStepContainer:(i,s)=>r(i,s.parentChain)}),o.total};var U1e="Cannot add a module step inside another module. Modules cannot be nested.";function ZB(e,t){switch(t){case "setup":return e.beforeSteps??[];case "teardown":return e.afterSteps??[];case "main":return e.steps;default:{throw new Error("Unknown test section")}}}function H1e(e,t,n){let o=ZB(e,t);if(!n?.length)return o;let r=M3(o,n);if(!r)throw new Error(`No step found with parent chain [${n.join(", ")}] in ${t} section, or parent does not support nested steps`);return r}function Wre(e,t){let n=t.moduleId,o=r=>{r.type!=="RESOLVED_MODULE"||r.moduleId!==n||(t.parameters!==void 0&&(r.parameters=t.parameters),t.parameterEnums!==void 0&&(r.parameterEnums=t.parameterEnums),t.defaultParameters!==void 0&&(r.defaultParameters=t.defaultParameters),t.name!==void 0&&(r.name=t.name),t.description!==void 0&&(r.description=t.description),t.enabled!==void 0&&(r.enabled=t.enabled),t.steps!==void 0&&(r.steps=t.steps));};for(let r of [e.steps,e.beforeSteps,e.afterSteps])Li({steps:r,onPresetAction:o,onConditional:o,onSimpleStepContainer:o});}async function r_({project:e,storage:t,orgId:n,logger:o,testPath:r,saveChangesToDisk:i,supportsFileOutput:s,tempCaches:a,mutableStepState:l,params:c,envName:d}){let u=Jn__default.join(e.rootDir,r),p=await t.getTestByPath({relativeTestPath:r,logger:o}),m=l?.stepLists??p,h=cloneDeep({steps:m.steps??[],beforeSteps:m.beforeSteps??[],afterSteps:m.afterSteps??[]}),g=cloneDeep(h),f=await Promise.all(c.steps.map(v=>hx(v,{project:e,logger:o,tempCaches:a}))),y=cloneDeep(f),S=c.parentStepIdChain,T;try{T=H1e(g,c.targetSection,S);}catch(v){return oe(z({text:`Error: ${X(v)}`,section:"Error"}))}if(c.startIndex<0||c.startIndex>T.length)return oe(z({text:`Error: Invalid startIndex ${c.startIndex} for splicing ${c.targetSection} section with ${T.length} steps (must be 0-${T.length})`,section:"Error"}));let E=f.length,C=c.deleteCount,w=cloneDeep(T.slice(c.startIndex,c.startIndex+C)),x=[];if(S?.length){let v=N3(ZB(g,c.targetSection),S,c.targetSection);if(x.push(...v),v.some(P=>P.type==="RESOLVED_MODULE")&&f.some(P=>P.type==="RESOLVED_MODULE"))return oe(z({text:`Error: ${U1e}`,section:"Error"}))}T.splice(c.startIndex,c.deleteCount,...f);for(let v of f)v.type==="RESOLVED_MODULE"&&Wre(g,v);for(let v of x)v.type==="RESOLVED_MODULE"&&Wre(g,v);if(l&&(l.stepLists=g),i){let v=await t.updateTestByPath({logger:o,relativeTestPath:r,stepLists:g,schemaVersion:at});o.info({testPath:r,testFilePath:u,projectFileFormat:e.config.fileFormat,moduleUpdateCount:v.moduleUpdates.length,snapshotCacheCount:v.snapshotCachesToSave.length},"MCP splice persisted test changes to disk");}else o.info({testPath:r,testFilePath:u,projectFileFormat:e.config.fileFormat},"MCP splice skipped disk persistence");let I=[...z({text:`Successfully spliced ${E} step(s) at index ${c.startIndex} in the ${c.targetSection} section, removing ${C} step(s).`,section:"Result"})];return I.push(...await $1e({logger:o,project:e,orgId:n,testId:p.id,environment:d,originalSteps:h,updatedSteps:g})),I.push(...await Kne({rootDir:e.rootDir,supportsFileOutput:s,deletedStepRefs:w.map((v,_)=>({id:v.id,index:c.startIndex+_})),insertedStepRefs:y.map((v,_)=>({id:v.id,index:c.startIndex+_})),deletedSteps:Bu(w,{includeCache:false}),insertedSteps:Bu(y,{includeCache:false}),metadata:{section:c.targetSection,parentStepIdChain:S??[],startIndex:c.startIndex,deleteCount:C,insertedCount:E},artifactEntity:"splice-restoration-payload"})),c.returnTest&&I.push(...z({text:JSON.stringify(await Xx({project:e,storage:t,selector:{path:r},envName:d,logger:o,mutableStepState:l,supportsFileOutput:s,hydrateStepIdentity:false}),null,2),section:"Test Content"})),oe(I)}async function i_({project:e,logger:t,testPath:n,storage:o,controller:r,codeEvalTools:i,socket:s,orgId:a,sessionId:l,envName:c,testContext:d,tracer:u,params:p,tokenLimit:m,supportsFileOutput:h,usageTracker:g,mutableStepState:f,apiClient:y,disableCache:S}){let{fromStep:T,toStep:E,targetSection:C}=p,w=await o.getTestByPath({relativeTestPath:n,logger:t}),{alwaysSaveCache:x,noCache:I}=cl(),v=await ui({logger:t,orgId:a,project:e,alwaysSaveCache:x,noCache:I||S===true}),_=f?.stepLists??{beforeSteps:w.beforeSteps??[],afterSteps:w.afterSteps??[],steps:w.steps};await v.resolveStepCacheEntries({logger:t,schemaVersion:w.schemaVersion,stepLists:_,testId:w.id,environment:c,useSnapshotIdentityCache:!f&&e.config.fileFormat==="v2"}),f&&(f.stepLists=_);let P=S?cloneDeep(_):_;S&&G1e(P);let L=ZB(P,C),k=cloneDeep({steps:P.steps,beforeSteps:P.beforeSteps,afterSteps:P.afterSteps}),{result:V}=dm(L,T.fromStepId,T.parentStepIdChain);if(!V)return oe(z({text:`Error: No step found with id "${T.fromStepId}" and parent chain [${T.parentStepIdChain.join(", ")}] in ${C} section.`,section:"Error"}));if(E){let{result:Re}=dm(L,E.toStepId,E.parentStepIdChain);if(!Re)return oe(z({text:`Error: No step found with id "${E.toStepId}" and parent chain [${E.parentStepIdChain.join(", ")}] in ${C} section.`,section:"Error"}))}if(u?.setProgressTotal){let Re=zre({steps:L,fromStep:T,toStep:E});u.setProgressTotal(Re);}r.setOpen();let re;try{re=await QB({steps:L,controller:r,storage:o,codeEvalTools:i,logger:t,socket:s,orgId:a,sessionId:l,testContext:d,fromStep:T,toStep:E,tracer:u,usageTracker:g,apiClient:y});}finally{await g.flush(t);}let{results:ne}=re;if(!ne||ne.length===0)return oe(z({text:"Error: No steps were executed.",section:"Error"}));let G=ne.at(-1);if(!G)return oe(z({text:"Error: No steps were executed.",section:"Error"}));let W={logger:t,cacheStorage:v,orgId:a,testId:w.id,environment:c,originalStepsWithCaches:k,updatedStepsWithCaches:{steps:P.steps,beforeSteps:P.beforeSteps??[],afterSteps:P.afterSteps??[]}},M=G.status!=="SUCCESS";await um({logger:t,cacheStorage:v,orgId:a,testId:w.id,environment:c,stepLists:W.updatedStepsWithCaches,useSnapshotIdentityCache:e.config.fileFormat==="v2"}),M?G.status==="FAILED"&&await Vg(W):await pm(W);let Y=C==="main"?"":` in ${C}`,$=Re=>{let Ye="fromStepId"in Re?Re.fromStepId:Re.toStepId;return Re.parentStepIdChain.length>0?`id "${Ye}" (parent chain [${Re.parentStepIdChain.join(", ")}])`:`id "${Ye}"`},B=T?$(T):"beginning",Q=E?`Steps from ${B} through ${$(E)}${Y}`:`Steps from ${B} to end${Y}`,K=[];if(M)K.push(...z({text:`Error: step with id ${G.id} failed: ${G.message}`,section:"Error"}));else {r.setOpen();let Re=`${Q} executed successfully.`;K.push(...z({text:Re,section:"Result"})),G.data&&K.push(...z({text:`Data: ${JSON.stringify(G.data,null,2)}`,section:"Result Data"}));}let[ve,pe]=await Promise.all([zr({browser:r.browser,supportsFileOutput:h}),qs({testContext:d,supportsFileOutput:h,limits:{tokenLimit:m}})]);return oe([...K,...ve,...pe])}function G1e(e){for(let t of [e.steps,e.beforeSteps,e.afterSteps])t&&j1e(t);}function j1e(e){Li({steps:e,earlyStop:false,onPresetAction:t=>(tr(t.command)&&delete t.command.cache,false),onSimpleStepContainer:()=>false,onConditional:()=>false});}async function $1e({logger:e,project:t,orgId:n,testId:o,environment:r,originalSteps:i,updatedSteps:s}){let a=[];try{let{alwaysSaveCache:l,noCache:c}=cl(),d=await ui({logger:e,orgId:n,project:t,alwaysSaveCache:l,noCache:c});await um({logger:e,cacheStorage:d,orgId:n,testId:o,environment:r,stepLists:s,useSnapshotIdentityCache:t.config.fileFormat==="v2"}),await pm({logger:e,cacheStorage:d,orgId:n,testId:o,environment:r,originalStepsWithCaches:i,updatedStepsWithCaches:s});}catch(l){e.warn({err:l},"Failed to save step caches after execution, future runs may be slower"),a.push(...z({text:"Warning: Steps were saved successfully, but updating the step cache failed. Future runs may be slower until the cache is refreshed.",section:"Warning"}));}return a}var eU=class{constructor(t,n,o,r){this.reporter=t;this.step=n;this.parentStepIdChain=o;this.setTotal=r;}loggerBindings;attachBeforeScreenshot(t){}attachAfterScreenshot(t){}attachBeforeHtmlSnapshot(t){}attachAfterHtmlSnapshot(t){}recordTargetAutoHeal(t){}storeTraceAsset(){}async finish(t){this.reporter.onStepComplete(this.step);}async startSubSteps(){return new s_(this.reporter,this.parentStepIdChain.concat(this.step.id),this.setTotal)}},s_=class{constructor(t,n=[],o){this.reporter=t;this.parentStepIdChain=n;this.setTotal=o;}loggerBindings;setProgressTotal(t){this.setTotal(t);}async getScreenshot(t,n){}async getHtmlSnapshot(t,n){}flushResults(t){}async startStep(t,n){return this.reporter.onStepStart(t.step),new eU(this.reporter,t.step,this.parentStepIdChain,this.setTotal)}};function qre(e,t,n,o,r){let i=mA(e),s={completed:0,total:0},a=new AbortController,l=false,c=m=>{i&&xne(e,s,m,t,a,n);},d=()=>{i&&(l||(l=true,c("Starting step execution...")));},u=m=>{!Number.isFinite(m)||m<0||(s.total=m);},p={onStepStart:m=>{d(),s.total===s.completed&&(s.total+=1);let h=Kn(m);r&&(r.currentStep=h),c(`Starting: ${h}`);},onStepComplete:m=>{o(),d(),s.completed+=1,s.total<s.completed&&(s.total=s.completed);let h=Kn(m);r&&(r.currentStep=void 0,r.lastCompletedStep=h),c(`Completed: ${h}`);}};return new s_(p,[],u)}var Yre=`CLI-style step definition. Use the Step Authoring Guide artifact returned from ${zc} when you start your session to get the full step schema.`,V1e=Xo({schema:{name:v$,description:"Create a test. The name must satisfy Momentic entity naming rules, and you must provide either a baseUrl or environment or the tool will fail.",inputSchema:nN},handle:async(e,t,n,o)=>{try{let r=await e.storage.createTest(t);Ws({type:"mcp:test_create",test_platform:"web"}),n.addPartFromText(JSON.stringify(r,null,2));}catch(r){n.addError(X(r));return}}}),z1e=Xo({schema:{name:Sr,description:`Fetch a loaded test by id or path, including resolved module steps and stable stepId and parentStepIdChain values for the persisted test state. Use this to inspect a test before starting a session or to inspect a different test. For the active session after ${jp}, prefer the splice response or request returnTest on the splice call for updated step ids. Step ids from another test are inspection-only for the active session. Start a session for that test before running or editing it.`,inputSchema:{testId:z$1.string().optional().describe(`Id of the test to fetch. If you do not already know it, list project tests with ${BO}. Either testId or testPath is required.`),testPath:z$1.string().optional().describe("Path to the test file, relative to the project root or absolute. When provided, skips the entity-registry lookup. Either testId or testPath is required.")}},handle:async(e,t,n,o)=>{try{let r=t.testId?{id:t.testId}:t.testPath?{path:t.testPath}:void 0;if(!r){n.addError("Either testId or testPath is required.");return}let i=await Tp({project:e.project,storage:e.storage,selector:r,envName:void 0,logger:e.logger,includeCache:!1,hydrateStepIdentity:!0,supportsFileOutput:e.supportsFileOutput});n.addContentParts(i);}catch(r){n.addError(X(r));return}}}),Kre=Xo({schema:{name:JE,description:`Reload the active session's test from disk into mutable in-memory step state. Use this after manually editing a v2 YAML test/module on disk and running lint, before ${oa}. Returns updated Test Content with step ids for the active session.`,inputSchema:{sessionId:z$1.string().describe("The active session whose bound test should be reloaded.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:JE});if(!r)return;let i=r.storage.getProject();if(i.config.fileFormat!=="v2"){n.addError(`${JE} is only available for v2 file-format projects.`);return}let s=await r.storage.getTestByPath({relativeTestPath:r.relativeTestPath,logger:e.logger}),a={beforeSteps:s.beforeSteps,steps:s.steps,afterSteps:s.afterSteps},{alwaysSaveCache:l,noCache:c}=cl(),d=await ui({logger:e.logger,orgId:r.orgId,project:i,alwaysSaveCache:l,noCache:c});r.mutableStepState.testId=s.id,r.mutableStepState.stepLists=await ga({cacheStorage:d,logger:e.logger,schemaVersion:s.schemaVersion,stepLists:a,testId:s.id,environment:r.envName,useSnapshotIdentityCache:true}),n.addContentParts(z({text:`Reloaded test ${s.id} from disk into session ${r.sessionId}.`,section:"Result"})),n.addContentParts(await Tp({project:i,storage:r.storage,selector:{path:r.relativeTestPath},envName:r.envName,logger:e.logger,mutableStepState:r.mutableStepState,includeCache:false,hydrateStepIdentity:false,supportsFileOutput:e.supportsFileOutput}));}}),W1e={...Kre,addToolToMcpServer:(e,t)=>{e.project.config.fileFormat==="v2"&&Kre.addToolToMcpServer(e,t);}},q1e=Xo({schema:{name:BO,description:`List local test artifacts. Returns a Project Context section with projectRootAbsolutePath, projectConfigAbsolutePath, and cwd, plus separate segments for each relevant artifact type: tests, modules, and environments. ${eA} When file output is enabled, the artifact links are relative to cwd. Read or grep only the specific artifact files you need instead of loading everything at once. Assume nothing changed since your last successful call to this tool unless the user indicates updates (e.g. new/changed tests, modules, environments, or project config change); avoid redundant calls just to refresh.`,inputSchema:{}},handle:async(e,t,n,o)=>{let{project:r,logger:i}=e,s=[],a=[];try{let[c,d]=await Promise.all([e.storage.listTests(),e.storage.listModules()]),u=c.map(m=>({id:m.id,name:m.name,description:m.description,testFileAbsolutePath:m.fullFilePath,labels:m.labels||[]}));s.push({title:"Tests",entity:"test-list",payload:{tests:u}});let p=d.map(m=>({id:m.id,name:m.name,description:m.description,fullFilePath:m.fullFilePath,type:m.type}));s.push({title:"Modules",entity:"module-list",payload:{modules:p}});}catch(c){a.push(`Tests and modules discovery failed: ${X(c)}`);}try{let c=e.storage.listEnvironments(i);s.push({title:"Environments",entity:"environment-list",payload:{environments:c}});}catch(c){a.push(`Environments discovery failed: ${X(c)}`);}let l=await Ste({artifacts:s,rootDir:r.rootDir,supportsFileOutput:e.supportsFileOutput,projectRootAbsolutePath:r.rootDir,projectConfigAbsolutePath:r.configFilePath,cwd:process.cwd()});n.addContentParts(l),a.length>0&&n.addContentParts(z({section:"Discovery Errors",text:a.map(c=>`- ${c}`).join(`
7523
- `)}));}}),Jre=Xo({schema:{name:mS,description:"Execute a step without adding it to the test. IMPORTANT: do NOT preview an AI Action (AI_ACTION_DYNAMIC) step with this tool. AI Actions run many sub-steps and routinely take well over 60s, and MCP tool calls are capped at 60s and cancelled regardless of progress \u2014 the step is killed and its work lost. ALWAYS preview an AI Action with the equivalent `momentic preview-step` CLI command in your terminal, which has no MCP tool-call timeout. When this server runs with --daemon the CLI shares this session, so pass the same sessionId; otherwise drive the whole flow over the CLI.",inputSchema:{sessionId:z$1.string(),step:z$1.string().describe(Yre)}},handle:async(e,t,n,o)=>{let{sessionId:r,step:i}=t,s=Wd({response:n,sessionId:r,toolName:mS});if(!s)return;s.controller.setOpen();let a;try{a=await o_({project:s.storage.getProject(),step:i,logger:e.logger,storage:s.storage,controller:s.controller,codeEvalTools:s.codeEvalTools,orgId:s.orgId,sessionId:s.sessionId,testContext:s.context,supportsFileOutput:e.supportsFileOutput,tempCaches:s.tempCaches,usageTracker:s.usageTracker,apiClient:qo()});}finally{await s.usageTracker.flush(e.logger);}n.addContentParts(a);}}),Xre=Xo({schema:{name:jp,description:"Insert, delete, or replace steps in the active session's test by index. Use parentStepIdChain to splice into nested steps (e.g. inside a conditional or module). The response includes inserted/deleted step refs with the updated active-session ids; use those ids for later run_step calls. The response always includes a recovery artifact with the full deleted and inserted payloads; only inspect it when you need to undo or inspect a mistaken splice.",inputSchema:{sessionId:z$1.string(),startIndex:z$1.number(),deleteCount:z$1.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:z$1.array(z$1.string()).describe(Yre),targetSection:$p.default("main"),parentStepIdChain:z$1.array(z$1.string()).optional().describe("When splicing into a nested step (e.g. conditional or module), the chain of parent step ids from root to the container. Empty or omit for top-level."),returnTest:z$1.boolean().default(false).describe("Return the full post-splice test snapshot. Avoid this by default. Use true only when you truly need the full updated test; the normal response already includes inserted/deleted step references plus a recovery artifact for mistaken-splice recovery.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:jp});if(!r)return;let i=await r_({project:r.storage.getProject(),storage:r.storage,orgId:r.orgId,logger:e.logger,testPath:r.relativeTestPath,envName:r.envName,saveChangesToDisk:e.saveChangesToDisk,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,mutableStepState:r.mutableStepState,params:{startIndex:t.startIndex,deleteCount:t.deleteCount,steps:t.steps,targetSection:t.targetSection,parentStepIdChain:t.parentStepIdChain,returnTest:t.returnTest}});t.steps.length>0&&Ws({type:"mcp:step_added",test_platform:"web",step_count:t.steps.length});let s=i.value.map(a=>a.type==="media"?{type:"media",data:a.data,mediaType:"image/jpeg"}:a);n.addContentParts(s);}}),Qre=Xo({schema:{name:oa,description:`${YE} Use step ids from the active session: the Test Content section returned by ${zc}, or the inserted/deleted refs returned by ${jp}. If you need a full updated post-splice view, set returnTest on the splice call. Do not parse the raw YAML at testFileAbsolutePath for step ids; v2 simplified test files do not store step ids on disk. If execution takes longer than ${Rx/1e3} seconds, this tool responds early with the currently executing step while execution continues in the background; call ${jh} to poll progress and collect the final result. Avoid starting multiple runs in the same session at once unless you intentionally want overlapping execution; overlapping runs share browser state and can race each other.`,inputSchema:{sessionId:z$1.string(),fromStep:cC,toStep:dC.optional(),targetSection:$p.default("main"),resetSession:z$1.boolean().default(false).describe("Whether to reset the browser session before running the steps."),disableCache:z$1.boolean().default(false).describe("Run this invocation without reading or writing step caches.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:oa});if(!r)return;r.controller.setOpen(),t.resetSession&&await Qx({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,apiKey:Hs(),baseUrl:$r(),controller:r.controller,testContext:r.context,supportsFileOutput:e.supportsFileOutput});let i=Gne({runs:r.runStepRuns,run:async a=>{let l=qre(o,e.logger,n,()=>{Ks.touchSession(r.sessionId);},jne({runs:r.runStepRuns,stepRunnerId:a})),c=await i_({project:r.storage.getProject(),logger:e.logger,testPath:r.relativeTestPath,storage:r.storage,controller:r.controller,codeEvalTools:r.codeEvalTools,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,tracer:l,params:{fromStep:t.fromStep,toStep:t.toStep,targetSection:t.targetSection},supportsFileOutput:e.supportsFileOutput,envName:r.envName,usageTracker:r.usageTracker,mutableStepState:r.mutableStepState,apiClient:qo(),disableCache:t.disableCache});return Ws({type:"mcp:run_step_completed",test_platform:"web",status:"completed"}),c.value.map(u=>u.type==="media"?{type:"media",data:u.data,mediaType:"image/jpeg"}:u)}}),s=await vB({runs:r.runStepRuns,stepRunnerId:i.stepRunnerId,activeRunCountAtStart:i.activeRunCountAtStart});RB({result:s,response:n,runStepToolName:oa,statusToolName:jh});}}),Zre=Xo({schema:{name:jh,description:`Check ${oa} executions for the active session. Responds with active runs, finished runs, and any newly finished results. Poll this after ${oa} reports that execution is taking longer than ${Rx/1e3} seconds. Prefer passing the stepRunnerId reported by ${oa} to scope the response to that run; only omit it when you need to see every run for the session. Optionally pass timeoutSeconds (0-${CB}, default 0) alongside stepRunnerId to wait up to that long for that run to finish before responding.`,inputSchema:{sessionId:z$1.string(),stepRunnerId:z$1.string().optional().describe(`Scope the poll to a single run reported by ${oa}. Recommended for most polls.`),timeoutSeconds:z$1.number().min(0).max(CB).default(0).describe("How long to wait for the run identified by stepRunnerId to finish before responding. 0 responds immediately with a snapshot. Ignored when stepRunnerId is not provided.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:jh});if(!r)return;let i=await vB({runs:r.runStepRuns,stepRunnerId:t.stepRunnerId,timeoutMs:t.timeoutSeconds*1e3});RB({result:i,response:n,runStepToolName:oa,statusToolName:jh});}}),eie=[q1e,V1e,z1e,W1e];var tie=[Gre,jre,$re,Vre,Jre,Qre,Zre,Xre];async function J1e({testPath:e,logger:t,project:n,storage:o,orgId:r,mutableStepState:i}){let s=await o.getTestByPath({relativeTestPath:e,logger:t}),a=s.envs?.find(u=>u.default)?.name;if(i&&i.testId!==s.id)throw new Error(`Cannot extract a module from test ${s.id} with mutable state for ${i.testId}.`);let l=i?.stepLists??{steps:s.steps,beforeSteps:s.beforeSteps??void 0,afterSteps:s.afterSteps??void 0},c=await ui({logger:t,orgId:r,project:n}),d=await ga({cacheStorage:c,logger:t,schemaVersion:s.schemaVersion,stepLists:l,testId:s.id,environment:a,useSnapshotIdentityCache:n.config.fileFormat==="v2"});return {availableSteps:d.steps,baseState:{steps:d.steps,beforeSteps:d.beforeSteps??[],afterSteps:d.afterSteps??[]},cacheSaveContext:{testId:s.id,environment:a,stepCacheStorage:c}}}async function a_({project:e,storage:t,logger:n,relativeTestPath:o,saveChangesToDisk:r,mutableStepState:i,params:s}){let a=oo();Fl(s.name);let l=await t.scanEntities(),c;s.startIndex!==void 0&&o!==void 0&&(c=await J1e({testPath:o,logger:n,project:e,storage:t,orgId:a,mutableStepState:i}));let{stepsToExtract:d,startIndex:u,endIndex:p}=Yne({moduleName:s.name,existingModuleNames:Object.values(l.modules).map(v=>v.name),...s,parameterNames:s.parameters,testPath:o,availableSteps:c?.availableSteps,containsNestedModuleStep:O3}),{module:m}=await t.createModule({name:s.name,description:s.description??"",enabled:s.enabled??true,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,steps:d,subDir:s.subDir,momenticFiles:l});if(s.startIndex===void 0)return {module:m};if(!o||!c)throw new Error("Failed to initialize extraction state for module create");let h=Object.keys(s.moduleInputs??{}).length>0,g=(m.parameters?.length??0)>0,f;h?f=s.moduleInputs:g?f={}:f=void 0;let y={...m,type:"RESOLVED_MODULE",id:randomUUID(),steps:m.steps,inputs:f},S=cloneDeep(c.baseState);S.steps.splice(u,p-u,y),i&&(i.stepLists=S);let{environment:T,stepCacheStorage:E,testId:C}=c.cacheSaveContext,w=e.config.fileFormat==="v2",{cachesToSave:x,snapshotCachesToSave:I}=await Yn({stepLists:S,useSnapshotIdentityCache:w,cacheCreationParams:{orgId:a,testId:C,environment:T}});return w&&await E.saveSnapshotCacheEntries({logger:n,entries:I}),await E.saveStepCacheEntries({logger:n,entries:x}),r&&await t.updateTestByPath({logger:n,relativeTestPath:o,stepLists:S,schemaVersion:at}),{module:m}}var nie=Xo({schema:{name:E$,description:"Create a module. The name must satisfy Momentic entity naming rules or the tool will fail. If startIndex is provided, testPath is required and the specified test range is extracted into the module, then replaced with a module invocation in that test. endIndex may only be provided when startIndex is set.",inputSchema:{name:z$1.string().describe(Xp),description:z$1.string(),enabled:z$1.boolean().default(true),parameters:z$1.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:z$1.record(z$1.string(),z$1.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:z$1.record(z$1.string(),z$1.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:z$1.record(z$1.string(),z$1.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant when extracting from a test."),subDir:z$1.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:z$1.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:z$1.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:z$1.number().optional().describe("End index of steps to extract from the target test (exclusive). Only valid when startIndex is provided. If not provided, extracts just startIndex.")}},handle:async(e,t,n,o)=>{let{testPath:r,...i}=t;try{let s=U7({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),a=await a_({project:e.project,storage:e.storage,logger:e.logger,relativeTestPath:s,saveChangesToDisk:e.saveChangesToDisk,params:i});n.addPartFromText(JSON.stringify(a.module,null,2));}catch(s){n.addError(X(s));}}});var my=[...eie,...n_,...tie,nie,Lte,jte,qte,Fte];var oie=my.map(e=>e.tool),l_=new Map(oie.map(e=>[e.schema.name,e]));async function rie(e){let{project:t,applicationName:n,daemonPort:o,daemonToken:r,daemonSessionId:i,logger:s,cliVersion:a}=e,l=t.configFilePath;await Zx(e);let{context:c}=e_({...e,logger:s.child({daemonSessionId:i}),applicationName:`${n}-daemon`,serverId:i});await Dne({adapter:{getTool:d=>{let u=l_.get(d);if(!u)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(l_.keys()).join(", ")}`);return {name:u.schema.name,execute:async({input:p,extra:m})=>await Nne({context:c,tool:u,input:p,extra:m})}}},sessionManager:Ks,daemonPort:o,daemonToken:r,daemonId:i,cliVersion:a,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:JB(e)*2,onShutdown:()=>{Dd();}});}async function tU(e){let{project:t,logger:n,apiKey:o,serverUrl:r,cliVersion:i,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u}=e,p=t.configFilePath;return Ine({workerType:"momentic-web-mcp",configPath:p,apiKey:o,serverUrl:r,cliVersion:i,logger:n,buildDaemonArgs:({entryScript:m})=>Z1e({entryScript:m,serverUrl:r,configPath:p,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u})})}async function iie(e){let{logger:t,applicationName:n,cliVersion:o,serverUrl:r}=e;kd(r),await tU(e);let{info:i,mcpLogger:s}=YB({logger:t,applicationName:`${n}-daemon-proxy`,cliVersion:o});return vx({context:{logger:s},info:i,tools:Lne({tools:oie,resolveDaemonStateForCall:()=>tU(e),logger:s})})}var Q1e=30*6e4;async function nU({options:e,toolName:t,input:n,timeoutMs:o=Q1e}){kd(e.serverUrl);let r=l_.get(t);if(!r)throw new Error(`Unknown web MCP tool '${t}'. Known tools: ${Array.from(l_.keys()).join(", ")}`);let i=r.schema.inputSchema.parse(n),s=await tU(e);return AB({state:s,toolName:t,input:i,timeoutMs:o})}function Z1e({entryScript:e,serverUrl:t,configPath:n,alwaysSaveCache:o,noCache:r,videoDefault:i,headfulDefault:s,devicePixelRatio:a,sessionIdleTimeoutMinutes:l}){let c=[e,"mcp","--server",t,"--daemon","--config",n,"--headful-browser",s?"true":"false","--video",i?"true":"false"];return o&&c.push("--save-cache"),r&&c.push("--disable-cache"),c.push("--pixel-ratio",String(a)),l!==void 0&&c.push("--session-idle-timeout-minutes",String(l)),c}var oU=async(e,t)=>{try{let{killed:n,failed:o}=await Ks.killAllSessions(e);o.length>0?t.warn({failed:o,reason:e},"Some browser sessions failed to terminate on shutdown"):n.length>0&&t.info({killedCount:n.length,reason:e},"Terminated browser sessions on shutdown");}catch(n){t.warn({err:n,reason:e},"Failed to terminate browser sessions on shutdown");}};async function rU(e){let{daemon:t,logger:n}=e,o=wne.safeParse(process.env);if(t&&o.success&&o.data[Ex]==="momentic-web-mcp")return rie({...e,daemonPort:o.data[Tx],daemonToken:o.data[Ax],daemonSessionId:o.data[Cx]});if(Ou(n,true),t)return await iie(e);await Zx(e);let{context:r,info:i}=e_(e);return vx({context:r,info:i,tools:my,shutdownHandlers:[oU,Dd,async()=>{await Yx();}]})}var OA="3.16.2",Cn=xg({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:OA});(async()=>{try{let e=await Aa(Cn);e.gitBranchName&&Cn.addBinding("branch",e.gitBranchName);}catch{}})();var Ep=Router();async function d_(e){return (await pf(e,Cn)).map(o=>{let r=e.modules[o.moduleId];if(!r){R.warn(`Found a dangling module with ID ${o.moduleId} that could not be found on disk.`);return}return {...r,content:o}}).filter(o=>o!==void 0)}Ep.get("/",St(async(e,t)=>{let n=st(),o=await ks(n),r=await d_(o);t.status(200).json(r);}));Ep.post("/",St(async(e,t)=>{let n;try{n=s1.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{Fl(n.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let o=st(),r=await Ve(o),i=r.modules;if(Object.values(i).find(l=>l.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=Jn__default.join(o.rootDir,n.folderPath??Jn__default.dirname(n.testFilePath));if(!Oo__default.existsSync(s)||!Oo__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let a=await nw({...n,folder:s,project:o,momenticFiles:r});t.status(201).json(a);}));Ep.get("/:moduleId/tests",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=st(),o=await Ve(n),r=e.params.moduleId;if(!o.modules[r]){t.status(404).json({error:"Module not found."});return}let i=[];for(let a of Object.values(o.tests))mQ(a.fullFilePath,o).has(r)&&i.push({id:a.id,name:a.name,relativePath:a.relativePath});let s={tests:i};t.status(200).json(s);}));Ep.get("/:moduleId",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=await ks(st()),o=n.modules[e.params.moduleId];if(!o){t.status(404).json({error:"Module not found."});return}try{let r=await uc({modHandle:o,momenticFiles:n,logger:R});t.json(r);}catch(r){t.status(400).json({err:r});}}));Ep.post("/:moduleId/duplicate",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=i1.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Fl(n.name);}catch(h){t.status(400).json({error:h.message});return}let o=st(),r=await Ve(o),i=r.modules[e.params.moduleId];if(!i){t.status(404).json({error:"Module not found."});return}if(Object.values(r.modules).find(h=>h.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=n.sourceModuleContent;if(s.moduleId!==e.params.moduleId){t.status(400).json({error:"Duplicate source module content does not match moduleId."});return}let a=Jn__default.join(o.rootDir,Jn__default.dirname(i.relativePath));if(!Oo__default.existsSync(a)||!Oo__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let l=In(n.name),c=Jn__default.join(a,`${l}.module.yaml`),d=cc({projectConfig:o.config,momenticFiles:r,entityType:"module"}),{stepsToSave:u}=await Yn({stepLists:{steps:s.steps},createNewCacheIds:true}),p={fileType:De.MODULE,schemaVersion:at,moduleId:d,name:n.name,description:"",enabled:true,steps:u.steps,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,defaultCacheKey:s.defaultCacheKey,defaultCacheTtl:s.defaultCacheTtl,defaultCacheAllInvocations:s.defaultCacheAllInvocations,autoAuth:s.autoAuth,advanced:s.advanced,defaultRetries:s.defaultRetries};ya({module:p,filePath:c,projectConfig:o.config,momenticFiles:r});let m={relativeFilePath:Jn__default.relative(o.rootDir,c)};t.status(201).json(m);}));Ep.patch("/:moduleId/move",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=l1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${X(i)}`});return}let o=st();if(!(await ks(o)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await yQ({moduleId:e.params.moduleId,targetFolderRelativePath:n.folderPath,project:o}),t.status(200).json({message:"ok"});}));Ep.patch("/:moduleId/metadata",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=a1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let o=st(),r=await ks(o);await SQ({moduleId:e.params.moduleId,content:n,momenticFiles:r,logger:R,project:o}),t.status(201).json({message:"ok"});}));var sie=Ep;var MA=Router();MA.get("/",St(async(e,t)=>{let n=st(),o=await Ve(n),r=new Set;o?.tests&&Object.values(o.tests).forEach(c=>{c.labels?.forEach(d=>r.add(d));});let i=Array.from(r).sort(),s=Object.values(o.tests),a=await d_(o),l={labels:i,tests:s,modules:a};t.status(200).json(l);}));MA.get("/folders",St(async(e,t)=>{let n=st(),o=await sQ(n);t.status(200).json(o);}));MA.get("/labels",St(async(e,t)=>{let n=st(),o=await Ve(n),r=new Set;for(let s of Object.values(o.tests))s.labels?.forEach(a=>r.add(a));let i=Array.from(r).sort();t.status(200).json(i);}));MA.post("/in-folder",St(async(e,t)=>{let n=e1.safeParse(e.body);if(!n.success){t.status(400).json({error:`Failed to parse entities-in-folder body: ${n.error.message}`});return}let{pathSegments:o}=n.data,r=st(),[i,s]=await Promise.all([iQ(r,o),ks(r)]),a=Object.values(i.tests),l=await d_(s),c=new Set(Object.keys(i.modules)),d=l.filter(p=>c.has(p.id)),u={tests:a,modules:d};t.status(200).json(u);}));var aie=MA;var iU=Router();iU.get("/",St((e,t)=>{let n=lw(st(),Cn);t.status(200).json(n);}));iU.get("/names",St((e,t)=>{let o=st().config.environments?.map(r=>r.name)??[];t.status(200).json(o);}));var lie=iU;var cie=Router();cie.get("/",St((e,t)=>{let n={userId:yc(),orgId:oo(),email:Lf(),name:$6(),pylonEmailHash:V6(),cliVersion:OA};t.status(200).json(n);}));var die=cie;var sU="mcp-session-id",uie="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",u_=Router();function lqe(){let e=process.env[uie];if(!e)return zd*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(Cn.warn({envVar:uie,rawValue:e,fallback:zd},"Invalid MCP session idle timeout env var; falling back to default"),zd*60*1e3):t*60*1e3}function cqe(e){let{headfulDefault:t,supportsFileOutput:n}={},o={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:OA},r=st(),i=Hs(),s=$r(),a=Cn.child({orgId:oo(),userId:yc(),...o}),l=new Dt({baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),c=rb(process.env.MOMENTIC_HEADFUL_BROWSER),d=new lr(r.config.ai?.agentConfig,{baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),u=oo(),p=new Ys(l,u,r);return {context:{project:r,orgId:u,logger:a,generator:d,apiClient:l,storage:p,serverId:o.serverId,extractBaseDir:$s(r.rootDir),saveChangesToDisk:true,supportsFileOutput:n??true,knowledgeRetrievalResults:Xt,knowledgeCitations:[],sessionIdleTimeoutMs:lqe(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??qi},info:o}}var qd={};u_.post("/",async(e,t)=>{let n=String(e.headers[sU]??"");try{if(n&&qd[n]){await qd[n].handleRequest(e,t,e.body);return}if(!n&&isInitializeRequest(e.body)){let{context:o,info:r}=cqe(),i=EB(o,r,my),s=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:a=>{qd[a]=s;}});s.onclose=()=>{let a=s.sessionId;a&&qd[a]&&delete qd[a],i.close().catch(()=>{});},await i.connect(s),await s.handleRequest(e,t,e.body);return}t.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});}catch{t.headersSent||t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null});}});u_.get("/",async(e,t)=>{let n=String(e.headers[sU]??"");if(!n||!qd[n]){t.status(400).send("Invalid or missing session ID");return}await qd[n].handleRequest(e,t);});u_.delete("/",async(e,t)=>{let n=String(e.headers[sU]??"");if(!n||!qd[n]){t.status(400).send("Invalid or missing session ID");return}let o=qd[n];try{await o.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var mie=u_;var hie=Router();hie.get("/:id",St(async(e,t)=>{let{id:n}=e.params;if(!n){t.status(400).json({error:"Missing ID"});return}let o=qo();if(!o){t.status(500).json({error:"API client not initialized"});return}try{let{data:r,contentType:i}=await o.fetchOnDemandScreenshot(n);t.setHeader("Content-Type",i),t.status(200).send(r);}catch(r){Cn.error({err:r,screenshotId:n},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var gie=hie;var p_=Router();p_.get("/",St(async(e,t)=>{let n=new Map;for(let i of await sD())n.set(i.configFilePath,i);let o=st();n.set(o.configFilePath,o);let r=[...n.values()].map(i=>({name:i.config.name,configFilePath:i.configFilePath,fileFormat:i.config.fileFormat}));t.status(200).json(r);}));p_.get("/current",St((e,t)=>{let n=st();if(!n){t.status(404).json({error:"No project found."});return}let o={name:n.config.name,configFilePath:n.configFilePath,fileFormat:n.config.fileFormat};t.status(200).json(o);}));p_.post("/set",St(async(e,t)=>{let n;try{n=u1.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}Cn.info("Setting local project");try{let o=await sn({configFilePath:n.configFilePath}),r=qo();if(!r)throw new Error("API client is not initialized.");await Df({project:o,apiClient:r});}catch(o){t.status(400).json({error:`Error setting project: ${o}`});return}t.sendStatus(204);}));var fie=p_;var yie=Router();yie.get("/",St((e,t)=>{let n=st(),o={ai:n.config.ai,browser:n.config.browser,displayRoot:n.config.displayRoot};t.status(200).json(o);}));var Sie=yie;var Oc=Router();Oc.post("/",St(async(e,t)=>{let n;try{n=o1.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}try{let o=st(),r=await _A({project:o,input:n});Ws({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(o){if(o instanceof mt){t.status(400).json({error:o.message});return}throw o}}));Oc.get("/:testPath",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=st(),r=await ks(o),i;try{i=await rs(Jn__default.join(o.rootDir,n),Cn,r),await(await ui({logger:Cn,orgId:oo(),project:o})).resolveStepCacheEntries({schemaVersion:i.schemaVersion,testId:i.id,environment:i.envs?.find(a=>a.default)?.name,stepLists:{beforeSteps:i.beforeSteps,steps:i.steps,afterSteps:i.afterSteps},logger:Cn,useSnapshotIdentityCache:o.config.fileFormat==="v2"}),t.status(200).json(i);}catch(s){t.status(400).send({error:s.message});return}(async()=>{try{await sw({relativeTestPath:n,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:at,momenticFiles:r,project:o});}catch(s){Cn.error({err:s},"Failed to save migrated test to disk after initial fetch");}})();}));Oc.get("/:testPath/metadata",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=st(),r=Jn__default.join(o.rootDir,n);if(!Oo__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=Oo__default.statSync(r),s=await Aa(Cn),a={gitBranch:s.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:s.gitCommitSha??"unknown"};t.status(200).json(a);}));Oc.patch("/:testPath/metadata",St(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=n1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:fT(e.params.testPath,n,st()).newRelativeTestPath};t.status(200).json(r);}));Oc.patch("/:testPath",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=t1.parse(e.body);}catch(m){Cn.warn({err:m},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${m}`});return}Cn.info({testPath:n},"Save received");let r=st(),i=await ks(r),s;try{s=bd(n,r);}catch(m){t.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let a=r.config.fileFormat==="v2",{stepsToSave:l,moduleUpdates:c,cachesToSave:d,snapshotCachesToSave:u}=await Yn({stepLists:o.stepLists,useSnapshotIdentityCache:a,cacheCreationParams:{orgId:oo(),testId:s.id,environment:s.envs?.find(m=>m.default)?.name}}),p=await ui({logger:Cn,orgId:oo(),project:r});a&&await p.saveSnapshotCacheEntries({logger:Cn,entries:u}),await p.saveStepCacheEntries({logger:Cn,entries:d}),nD({relativeTestPath:n,stepsToSave:l,moduleUpdates:c,schemaVersion:o.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));Oc.patch("/:testPath/environments",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=d1.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}fT(n,{envs:o.defaultEnv?[{name:o.defaultEnv,default:true}]:[]},st()),t.status(201).json({message:"ok"});}));Oc.patch("/:testPath/move",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=c1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${X(i)}`});return}let r=st();if(!Oo__default.existsSync(Jn__default.join(r.rootDir,n))){t.status(404).json({error:"Test not found."});return}await bQ({relativeTestPath:n,targetFolderRelativePath:o.folderPath,project:r}),t.status(200).json({message:"ok"});}));Oc.delete("/:testPath",St((e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=st(),r=Jn__default.join(o.rootDir,n);if(!Oo__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}Oo__default.unlinkSync(r),t.status(200).json({message:"ok"});}));Oc.post("/:testPath/duplicate",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=r1.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Fl(o.name);}catch(h){t.status(400).json({error:h.message});return}let r=st(),i=Jn__default.join(r.rootDir,n);if(!Oo__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let s=await Ve(r),a;try{a=await rs(i,Cn,s);}catch(h){t.status(400).send({error:h.message});return}let l=cc({projectConfig:r.config,momenticFiles:s,entityType:"test"}),c=Zn.parse({...a,name:o.name,id:l}),{stepsToSave:d}=await Yn({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewCacheIds:true}),u=Jn__default.dirname(i),p=Jn__default.join(u,`${o.name}.test.yaml`);Sa({test:{fileType:De.TEST,...c,...d},filePath:p,projectConfig:r.config,momenticFiles:s});let m={relativeFilePath:Jn__default.relative(r.rootDir,p)};Ws({type:"test_editor:test_duplicated"}),t.status(201).json(m);}));var bie=Oc;var Tie=z$1.object({name:z$1.string().min(1).describe("Short, human-readable name for the slice you are delegating (used as a label)."),instructions:z$1.string().min(1).describe("Focused, self-contained instructions for the child: which area it should own and what to cover. The child inherits the same input you received but cannot see your conversation, so these instructions must stand alone."),budget:z$1.number().int().positive().optional().describe("Maximum number of test plans this child should produce. Allocate a portion of your remaining budget to each child. Omit to let the child use its own judgement.")});function Aie(e){return e.kind==="diff"?e.diffSummary:yt`
7523
+ `)}));}}),Jre=Xo({schema:{name:mS,description:"Execute a step without adding it to the test. IMPORTANT: do NOT preview an AI Action (AI_ACTION_DYNAMIC) step with this tool. AI Actions run many sub-steps and routinely take well over 60s, and MCP tool calls are capped at 60s and cancelled regardless of progress \u2014 the step is killed and its work lost. ALWAYS preview an AI Action with the equivalent `momentic preview-step` CLI command in your terminal, which has no MCP tool-call timeout. When this server runs with --daemon the CLI shares this session, so pass the same sessionId; otherwise drive the whole flow over the CLI.",inputSchema:{sessionId:z$1.string(),step:z$1.string().describe(Yre)}},handle:async(e,t,n,o)=>{let{sessionId:r,step:i}=t,s=Wd({response:n,sessionId:r,toolName:mS});if(!s)return;s.controller.setOpen();let a;try{a=await o_({project:s.storage.getProject(),step:i,logger:e.logger,storage:s.storage,controller:s.controller,codeEvalTools:s.codeEvalTools,orgId:s.orgId,sessionId:s.sessionId,testContext:s.context,supportsFileOutput:e.supportsFileOutput,tempCaches:s.tempCaches,usageTracker:s.usageTracker,apiClient:qo()});}finally{await s.usageTracker.flush(e.logger);}n.addContentParts(a);}}),Xre=Xo({schema:{name:jp,description:"Insert, delete, or replace steps in the active session's test by index. Use parentStepIdChain to splice into nested steps (e.g. inside a conditional or module). The response includes inserted/deleted step refs with the updated active-session ids; use those ids for later run_step calls. The response always includes a recovery artifact with the full deleted and inserted payloads; only inspect it when you need to undo or inspect a mistaken splice.",inputSchema:{sessionId:z$1.string(),startIndex:z$1.number(),deleteCount:z$1.number().describe("Number of steps to remove. Use 0 to insert without deleting, 1 to replace a single step, or N to delete N steps."),steps:z$1.array(z$1.string()).describe(Yre),targetSection:$p.default("main"),parentStepIdChain:z$1.array(z$1.string()).optional().describe("When splicing into a nested step (e.g. conditional or module), the chain of parent step ids from root to the container. Empty or omit for top-level."),returnTest:z$1.boolean().default(false).describe("Return the full post-splice test snapshot. Avoid this by default. Use true only when you truly need the full updated test; the normal response already includes inserted/deleted step references plus a recovery artifact for mistaken-splice recovery.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:jp});if(!r)return;let i=await r_({project:r.storage.getProject(),storage:r.storage,orgId:r.orgId,logger:e.logger,testPath:r.relativeTestPath,envName:r.envName,saveChangesToDisk:e.saveChangesToDisk,supportsFileOutput:e.supportsFileOutput,tempCaches:r.tempCaches,mutableStepState:r.mutableStepState,params:{startIndex:t.startIndex,deleteCount:t.deleteCount,steps:t.steps,targetSection:t.targetSection,parentStepIdChain:t.parentStepIdChain,returnTest:t.returnTest}});t.steps.length>0&&Ws({type:"mcp:step_added",test_platform:"web",step_count:t.steps.length});let s=i.value.map(a=>a.type==="media"?{type:"media",data:a.data,mediaType:"image/jpeg"}:a);n.addContentParts(s);}}),Qre=Xo({schema:{name:oa,description:`${YE} Use step ids from the active session: the Test Content section returned by ${zc}, or the inserted/deleted refs returned by ${jp}. If you need a full updated post-splice view, set returnTest on the splice call. Do not parse the raw YAML at testFileAbsolutePath for step ids; v2 simplified test files do not store step ids on disk. If execution takes longer than ${Rx/1e3} seconds, this tool responds early with the currently executing step while execution continues in the background; call ${jh} to poll progress and collect the final result. Avoid starting multiple runs in the same session at once unless you intentionally want overlapping execution; overlapping runs share browser state and can race each other.`,inputSchema:{sessionId:z$1.string(),fromStep:cC,toStep:dC.optional(),targetSection:$p.default("main"),resetSession:z$1.boolean().default(false).describe("Whether to reset the browser session before running the steps."),disableCache:z$1.boolean().default(false).describe("Run this invocation without reading or writing step caches.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:oa});if(!r)return;r.controller.setOpen(),t.resetSession&&await Qx({project:r.storage.getProject(),logger:e.logger,relativeTestPath:r.relativeTestPath,orgId:r.orgId,storage:r.storage,apiKey:Hs(),baseUrl:$r(),controller:r.controller,testContext:r.context,supportsFileOutput:e.supportsFileOutput});let i=Gne({runs:r.runStepRuns,run:async a=>{let l=qre(o,e.logger,n,()=>{Ks.touchSession(r.sessionId);},jne({runs:r.runStepRuns,stepRunnerId:a})),c=await i_({project:r.storage.getProject(),logger:e.logger,testPath:r.relativeTestPath,storage:r.storage,controller:r.controller,codeEvalTools:r.codeEvalTools,orgId:r.orgId,sessionId:r.sessionId,testContext:r.context,tracer:l,params:{fromStep:t.fromStep,toStep:t.toStep,targetSection:t.targetSection},supportsFileOutput:e.supportsFileOutput,envName:r.envName,usageTracker:r.usageTracker,mutableStepState:r.mutableStepState,apiClient:qo(),disableCache:t.disableCache});return Ws({type:"mcp:run_step_completed",test_platform:"web",status:"completed"}),c.value.map(u=>u.type==="media"?{type:"media",data:u.data,mediaType:"image/jpeg"}:u)}}),s=await vB({runs:r.runStepRuns,stepRunnerId:i.stepRunnerId,activeRunCountAtStart:i.activeRunCountAtStart});RB({result:s,response:n,runStepToolName:oa,statusToolName:jh});}}),Zre=Xo({schema:{name:jh,description:`Check ${oa} executions for the active session. Responds with active runs, finished runs, and any newly finished results. Poll this after ${oa} reports that execution is taking longer than ${Rx/1e3} seconds. Prefer passing the stepRunnerId reported by ${oa} to scope the response to that run; only omit it when you need to see every run for the session. Optionally pass timeoutSeconds (0-${CB}, default 0) alongside stepRunnerId to wait up to that long for that run to finish before responding.`,inputSchema:{sessionId:z$1.string(),stepRunnerId:z$1.string().optional().describe(`Scope the poll to a single run reported by ${oa}. Recommended for most polls.`),timeoutSeconds:z$1.number().min(0).max(CB).default(0).describe("How long to wait for the run identified by stepRunnerId to finish before responding. 0 responds immediately with a snapshot. Ignored when stepRunnerId is not provided.")}},handle:async(e,t,n,o)=>{let r=Wd({response:n,sessionId:t.sessionId,toolName:jh});if(!r)return;let i=await vB({runs:r.runStepRuns,stepRunnerId:t.stepRunnerId,timeoutMs:t.timeoutSeconds*1e3});RB({result:i,response:n,runStepToolName:oa,statusToolName:jh});}}),eie=[q1e,V1e,z1e,W1e];var tie=[Gre,jre,$re,Vre,Jre,Qre,Zre,Xre];async function J1e({testPath:e,logger:t,project:n,storage:o,orgId:r,mutableStepState:i}){let s=await o.getTestByPath({relativeTestPath:e,logger:t}),a=s.envs?.find(u=>u.default)?.name;if(i&&i.testId!==s.id)throw new Error(`Cannot extract a module from test ${s.id} with mutable state for ${i.testId}.`);let l=i?.stepLists??{steps:s.steps,beforeSteps:s.beforeSteps??void 0,afterSteps:s.afterSteps??void 0},c=await ui({logger:t,orgId:r,project:n}),d=await ga({cacheStorage:c,logger:t,schemaVersion:s.schemaVersion,stepLists:l,testId:s.id,environment:a,useSnapshotIdentityCache:n.config.fileFormat==="v2"});return {availableSteps:d.steps,baseState:{steps:d.steps,beforeSteps:d.beforeSteps??[],afterSteps:d.afterSteps??[]},cacheSaveContext:{testId:s.id,environment:a,stepCacheStorage:c}}}async function a_({project:e,storage:t,logger:n,relativeTestPath:o,saveChangesToDisk:r,mutableStepState:i,params:s}){let a=oo();Fl(s.name);let l=await t.scanEntities(),c;s.startIndex!==void 0&&o!==void 0&&(c=await J1e({testPath:o,logger:n,project:e,storage:t,orgId:a,mutableStepState:i}));let{stepsToExtract:d,startIndex:u,endIndex:p}=Yne({moduleName:s.name,existingModuleNames:Object.values(l.modules).map(v=>v.name),...s,parameterNames:s.parameters,testPath:o,availableSteps:c?.availableSteps,containsNestedModuleStep:O3}),{module:m}=await t.createModule({name:s.name,description:s.description??"",enabled:s.enabled??true,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,steps:d,subDir:s.subDir,momenticFiles:l});if(s.startIndex===void 0)return {module:m};if(!o||!c)throw new Error("Failed to initialize extraction state for module create");let h=Object.keys(s.moduleInputs??{}).length>0,g=(m.parameters?.length??0)>0,f;h?f=s.moduleInputs:g?f={}:f=void 0;let y={...m,type:"RESOLVED_MODULE",id:randomUUID(),steps:m.steps,inputs:f},S=cloneDeep(c.baseState);S.steps.splice(u,p-u,y),i&&(i.stepLists=S);let{environment:T,stepCacheStorage:E,testId:C}=c.cacheSaveContext,w=e.config.fileFormat==="v2",{cachesToSave:x,snapshotCachesToSave:I}=await Yn({stepLists:S,useSnapshotIdentityCache:w,cacheCreationParams:{orgId:a,testId:C,environment:T}});return w&&await E.saveSnapshotCacheEntries({logger:n,entries:I}),await E.saveStepCacheEntries({logger:n,entries:x}),r&&await t.updateTestByPath({logger:n,relativeTestPath:o,stepLists:S,schemaVersion:at}),{module:m}}var nie=Xo({schema:{name:E$,description:"Create a module. The name must satisfy Momentic entity naming rules or the tool will fail. If startIndex is provided, testPath is required and the specified test range is extracted into the module, then replaced with a module invocation in that test. endIndex may only be provided when startIndex is set.",inputSchema:{name:z$1.string().describe(Xp),description:z$1.string(),enabled:z$1.boolean().default(true),parameters:z$1.string().array().optional().describe("Array of parameter names for the module, e.g., ['apiKey', 'userId']."),defaultParameters:z$1.record(z$1.string(),z$1.string()).optional().describe("Default values for parameters, e.g., { 'apiKey': 'default123' }. Keys must match parameters."),parameterEnums:z$1.record(z$1.string(),z$1.string().array()).optional().describe("Enum options for parameters, e.g., { 'role': ['admin', 'user'] }. Keys must match parameters."),moduleInputs:z$1.record(z$1.string(),z$1.string()).optional().describe("Input parameters to pass to the new module when it's inserted into the test. Keys must match the module's defined parameters. Only relevant when extracting from a test."),subDir:z$1.string().optional().describe("Subdirectory to create the module in. If not provided, the module is created in the project root."),testPath:z$1.string().optional().describe("Relative path to the test to extract steps from. Required when startIndex is provided."),startIndex:z$1.number().optional().describe("Start index of steps to extract from the target test (0-based)."),endIndex:z$1.number().optional().describe("End index of steps to extract from the target test (exclusive). Only valid when startIndex is provided. If not provided, extracts just startIndex.")}},handle:async(e,t,n,o)=>{let{testPath:r,...i}=t;try{let s=U7({projectRoot:e.project.rootDir,filePath:r,pathLabel:"testPath"}),a=await a_({project:e.project,storage:e.storage,logger:e.logger,relativeTestPath:s,saveChangesToDisk:e.saveChangesToDisk,params:i});n.addPartFromText(JSON.stringify(a.module,null,2));}catch(s){n.addError(X(s));}}});var my=[...eie,...n_,...tie,nie,Lte,jte,qte,Fte];var oie=my.map(e=>e.tool),l_=new Map(oie.map(e=>[e.schema.name,e]));async function rie(e){let{project:t,applicationName:n,daemonPort:o,daemonToken:r,daemonSessionId:i,logger:s,cliVersion:a}=e,l=t.configFilePath;await Zx(e);let{context:c}=e_({...e,logger:s.child({daemonSessionId:i}),applicationName:`${n}-daemon`,serverId:i});await Dne({adapter:{getTool:d=>{let u=l_.get(d);if(!u)throw new Error(`Unknown web MCP tool '${d}'. Known tools: ${Array.from(l_.keys()).join(", ")}`);return {name:u.schema.name,execute:async({input:p,extra:m})=>await Nne({context:c,tool:u,input:p,extra:m})}}},sessionManager:Ks,daemonPort:o,daemonToken:r,daemonId:i,cliVersion:a,workerType:"momentic-web-mcp",configPath:l,inactivityTimeoutMsOverride:JB(e)*2,onShutdown:()=>{Dd();}});}async function tU(e){let{project:t,logger:n,apiKey:o,serverUrl:r,cliVersion:i,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u}=e,p=t.configFilePath;return Ine({workerType:"momentic-web-mcp",configPath:p,apiKey:o,serverUrl:r,cliVersion:i,logger:n,buildDaemonArgs:({entryScript:m})=>Z1e({entryScript:m,serverUrl:r,configPath:p,alwaysSaveCache:s,noCache:a,videoDefault:l,headfulDefault:c,devicePixelRatio:d,sessionIdleTimeoutMinutes:u})})}async function iie(e){let{logger:t,applicationName:n,cliVersion:o,serverUrl:r}=e;kd(r),await tU(e);let{info:i,mcpLogger:s}=YB({logger:t,applicationName:`${n}-daemon-proxy`,cliVersion:o});return vx({context:{logger:s},info:i,tools:Lne({tools:oie,resolveDaemonStateForCall:()=>tU(e),logger:s})})}var Q1e=30*6e4;async function nU({options:e,toolName:t,input:n,timeoutMs:o=Q1e}){kd(e.serverUrl);let r=l_.get(t);if(!r)throw new Error(`Unknown web MCP tool '${t}'. Known tools: ${Array.from(l_.keys()).join(", ")}`);let i=r.schema.inputSchema.parse(n),s=await tU(e);return AB({state:s,toolName:t,input:i,timeoutMs:o})}function Z1e({entryScript:e,serverUrl:t,configPath:n,alwaysSaveCache:o,noCache:r,videoDefault:i,headfulDefault:s,devicePixelRatio:a,sessionIdleTimeoutMinutes:l}){let c=[e,"mcp","--server",t,"--daemon","--config",n,"--headful-browser",s?"true":"false","--video",i?"true":"false"];return o&&c.push("--save-cache"),r&&c.push("--disable-cache"),c.push("--pixel-ratio",String(a)),l!==void 0&&c.push("--session-idle-timeout-minutes",String(l)),c}var oU=async(e,t)=>{try{let{killed:n,failed:o}=await Ks.killAllSessions(e);o.length>0?t.warn({failed:o,reason:e},"Some browser sessions failed to terminate on shutdown"):n.length>0&&t.info({killedCount:n.length,reason:e},"Terminated browser sessions on shutdown");}catch(n){t.warn({err:n,reason:e},"Failed to terminate browser sessions on shutdown");}};async function rU(e){let{daemon:t,logger:n}=e,o=wne.safeParse(process.env);if(t&&o.success&&o.data[Ex]==="momentic-web-mcp")return rie({...e,daemonPort:o.data[Tx],daemonToken:o.data[Ax],daemonSessionId:o.data[Cx]});if(Ou(n,true),t)return await iie(e);await Zx(e);let{context:r,info:i}=e_(e);return vx({context:r,info:i,tools:my,shutdownHandlers:[oU,Dd,async()=>{await Yx();}]})}var OA="3.16.3",Cn=xg({app:"desktop-server",hostname:hostname(),disableConsoleLogs:true}).child({cliVersion:OA});(async()=>{try{let e=await Aa(Cn);e.gitBranchName&&Cn.addBinding("branch",e.gitBranchName);}catch{}})();var Ep=Router();async function d_(e){return (await pf(e,Cn)).map(o=>{let r=e.modules[o.moduleId];if(!r){R.warn(`Found a dangling module with ID ${o.moduleId} that could not be found on disk.`);return}return {...r,content:o}}).filter(o=>o!==void 0)}Ep.get("/",St(async(e,t)=>{let n=st(),o=await ks(n),r=await d_(o);t.status(200).json(r);}));Ep.post("/",St(async(e,t)=>{let n;try{n=s1.parse(e.body);}catch(l){t.status(400).json({error:`Invalid request body: ${l}`});return}try{Fl(n.name);}catch(l){t.status(400).json({error:`Invalid module name: ${l}`});return}let o=st(),r=await Ve(o),i=r.modules;if(Object.values(i).find(l=>l.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=Jn__default.join(o.rootDir,n.folderPath??Jn__default.dirname(n.testFilePath));if(!Oo__default.existsSync(s)||!Oo__default.statSync(s).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let a=await nw({...n,folder:s,project:o,momenticFiles:r});t.status(201).json(a);}));Ep.get("/:moduleId/tests",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=st(),o=await Ve(n),r=e.params.moduleId;if(!o.modules[r]){t.status(404).json({error:"Module not found."});return}let i=[];for(let a of Object.values(o.tests))mQ(a.fullFilePath,o).has(r)&&i.push({id:a.id,name:a.name,relativePath:a.relativePath});let s={tests:i};t.status(200).json(s);}));Ep.get("/:moduleId",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n=await ks(st()),o=n.modules[e.params.moduleId];if(!o){t.status(404).json({error:"Module not found."});return}try{let r=await uc({modHandle:o,momenticFiles:n,logger:R});t.json(r);}catch(r){t.status(400).json({err:r});}}));Ep.post("/:moduleId/duplicate",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=i1.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Fl(n.name);}catch(h){t.status(400).json({error:h.message});return}let o=st(),r=await Ve(o),i=r.modules[e.params.moduleId];if(!i){t.status(404).json({error:"Module not found."});return}if(Object.values(r.modules).find(h=>h.name===n.name)){t.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let s=n.sourceModuleContent;if(s.moduleId!==e.params.moduleId){t.status(400).json({error:"Duplicate source module content does not match moduleId."});return}let a=Jn__default.join(o.rootDir,Jn__default.dirname(i.relativePath));if(!Oo__default.existsSync(a)||!Oo__default.statSync(a).isDirectory()){t.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let l=In(n.name),c=Jn__default.join(a,`${l}.module.yaml`),d=cc({projectConfig:o.config,momenticFiles:r,entityType:"module"}),{stepsToSave:u}=await Yn({stepLists:{steps:s.steps},createNewCacheIds:true}),p={fileType:De.MODULE,schemaVersion:at,moduleId:d,name:n.name,description:"",enabled:true,steps:u.steps,parameters:s.parameters,defaultParameters:s.defaultParameters,parameterEnums:s.parameterEnums,defaultCacheKey:s.defaultCacheKey,defaultCacheTtl:s.defaultCacheTtl,defaultCacheAllInvocations:s.defaultCacheAllInvocations,autoAuth:s.autoAuth,advanced:s.advanced,defaultRetries:s.defaultRetries};ya({module:p,filePath:c,projectConfig:o.config,momenticFiles:r});let m={relativeFilePath:Jn__default.relative(o.rootDir,c)};t.status(201).json(m);}));Ep.patch("/:moduleId/move",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=l1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${X(i)}`});return}let o=st();if(!(await ks(o)).modules[e.params.moduleId]){t.status(404).json({error:"Module not found."});return}await yQ({moduleId:e.params.moduleId,targetFolderRelativePath:n.folderPath,project:o}),t.status(200).json({message:"ok"});}));Ep.patch("/:moduleId/metadata",St(async(e,t)=>{if(!e.params.moduleId){t.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=a1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let o=st(),r=await ks(o);await SQ({moduleId:e.params.moduleId,content:n,momenticFiles:r,logger:R,project:o}),t.status(201).json({message:"ok"});}));var sie=Ep;var MA=Router();MA.get("/",St(async(e,t)=>{let n=st(),o=await Ve(n),r=new Set;o?.tests&&Object.values(o.tests).forEach(c=>{c.labels?.forEach(d=>r.add(d));});let i=Array.from(r).sort(),s=Object.values(o.tests),a=await d_(o),l={labels:i,tests:s,modules:a};t.status(200).json(l);}));MA.get("/folders",St(async(e,t)=>{let n=st(),o=await sQ(n);t.status(200).json(o);}));MA.get("/labels",St(async(e,t)=>{let n=st(),o=await Ve(n),r=new Set;for(let s of Object.values(o.tests))s.labels?.forEach(a=>r.add(a));let i=Array.from(r).sort();t.status(200).json(i);}));MA.post("/in-folder",St(async(e,t)=>{let n=e1.safeParse(e.body);if(!n.success){t.status(400).json({error:`Failed to parse entities-in-folder body: ${n.error.message}`});return}let{pathSegments:o}=n.data,r=st(),[i,s]=await Promise.all([iQ(r,o),ks(r)]),a=Object.values(i.tests),l=await d_(s),c=new Set(Object.keys(i.modules)),d=l.filter(p=>c.has(p.id)),u={tests:a,modules:d};t.status(200).json(u);}));var aie=MA;var iU=Router();iU.get("/",St((e,t)=>{let n=lw(st(),Cn);t.status(200).json(n);}));iU.get("/names",St((e,t)=>{let o=st().config.environments?.map(r=>r.name)??[];t.status(200).json(o);}));var lie=iU;var cie=Router();cie.get("/",St((e,t)=>{let n={userId:yc(),orgId:oo(),email:Lf(),name:$6(),pylonEmailHash:V6(),cliVersion:OA};t.status(200).json(n);}));var die=cie;var sU="mcp-session-id",uie="MOMENTIC_SESSION_IDLE_TIMEOUT_MINUTES",u_=Router();function lqe(){let e=process.env[uie];if(!e)return zd*60*1e3;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<1?(Cn.warn({envVar:uie,rawValue:e,fallback:zd},"Invalid MCP session idle timeout env var; falling back to default"),zd*60*1e3):t*60*1e3}function cqe(e){let{headfulDefault:t,supportsFileOutput:n}={},o={serverId:randomUUID(),applicationName:"momentic-mcp-desktop-server",cliVersion:OA},r=st(),i=Hs(),s=$r(),a=Cn.child({orgId:oo(),userId:yc(),...o}),l=new Dt({baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),c=rb(process.env.MOMENTIC_HEADFUL_BROWSER),d=new lr(r.config.ai?.agentConfig,{baseUrl:s,apiKey:i,logger:a,mode:"interactive",runner:"mcp"}),u=oo(),p=new Ys(l,u,r);return {context:{project:r,orgId:u,logger:a,generator:d,apiClient:l,storage:p,serverId:o.serverId,extractBaseDir:$s(r.rootDir),saveChangesToDisk:true,supportsFileOutput:n??true,knowledgeRetrievalResults:Xt,knowledgeCitations:[],sessionIdleTimeoutMs:lqe(),headfulDefault:t??c??true,categoryDefinitions:r.config.ai?.classification?.categories??qi},info:o}}var qd={};u_.post("/",async(e,t)=>{let n=String(e.headers[sU]??"");try{if(n&&qd[n]){await qd[n].handleRequest(e,t,e.body);return}if(!n&&isInitializeRequest(e.body)){let{context:o,info:r}=cqe(),i=EB(o,r,my),s=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableDnsRebindingProtection:!1,onsessioninitialized:a=>{qd[a]=s;}});s.onclose=()=>{let a=s.sessionId;a&&qd[a]&&delete qd[a],i.close().catch(()=>{});},await i.connect(s),await s.handleRequest(e,t,e.body);return}t.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});}catch{t.headersSent||t.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null});}});u_.get("/",async(e,t)=>{let n=String(e.headers[sU]??"");if(!n||!qd[n]){t.status(400).send("Invalid or missing session ID");return}await qd[n].handleRequest(e,t);});u_.delete("/",async(e,t)=>{let n=String(e.headers[sU]??"");if(!n||!qd[n]){t.status(400).send("Invalid or missing session ID");return}let o=qd[n];try{await o.handleRequest(e,t);}catch{t.headersSent||t.status(500).send("Error processing session termination");}});var mie=u_;var hie=Router();hie.get("/:id",St(async(e,t)=>{let{id:n}=e.params;if(!n){t.status(400).json({error:"Missing ID"});return}let o=qo();if(!o){t.status(500).json({error:"API client not initialized"});return}try{let{data:r,contentType:i}=await o.fetchOnDemandScreenshot(n);t.setHeader("Content-Type",i),t.status(200).send(r);}catch(r){Cn.error({err:r,screenshotId:n},"Failed to proxy on-demand screenshot"),t.status(404).json({error:"Screenshot not found"});}}));var gie=hie;var p_=Router();p_.get("/",St(async(e,t)=>{let n=new Map;for(let i of await sD())n.set(i.configFilePath,i);let o=st();n.set(o.configFilePath,o);let r=[...n.values()].map(i=>({name:i.config.name,configFilePath:i.configFilePath,fileFormat:i.config.fileFormat}));t.status(200).json(r);}));p_.get("/current",St((e,t)=>{let n=st();if(!n){t.status(404).json({error:"No project found."});return}let o={name:n.config.name,configFilePath:n.configFilePath,fileFormat:n.config.fileFormat};t.status(200).json(o);}));p_.post("/set",St(async(e,t)=>{let n;try{n=u1.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}Cn.info("Setting local project");try{let o=await sn({configFilePath:n.configFilePath}),r=qo();if(!r)throw new Error("API client is not initialized.");await Df({project:o,apiClient:r});}catch(o){t.status(400).json({error:`Error setting project: ${o}`});return}t.sendStatus(204);}));var fie=p_;var yie=Router();yie.get("/",St((e,t)=>{let n=st(),o={ai:n.config.ai,browser:n.config.browser,displayRoot:n.config.displayRoot};t.status(200).json(o);}));var Sie=yie;var Oc=Router();Oc.post("/",St(async(e,t)=>{let n;try{n=o1.parse(e.body);}catch(o){t.status(400).json({error:`Invalid request body: ${o}`});return}try{let o=st(),r=await _A({project:o,input:n});Ws({type:"test_editor:test_create",test_platform:"web"}),t.status(201).json(r);}catch(o){if(o instanceof mt){t.status(400).json({error:o.message});return}throw o}}));Oc.get("/:testPath",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=st(),r=await ks(o),i;try{i=await rs(Jn__default.join(o.rootDir,n),Cn,r),await(await ui({logger:Cn,orgId:oo(),project:o})).resolveStepCacheEntries({schemaVersion:i.schemaVersion,testId:i.id,environment:i.envs?.find(a=>a.default)?.name,stepLists:{beforeSteps:i.beforeSteps,steps:i.steps,afterSteps:i.afterSteps},logger:Cn,useSnapshotIdentityCache:o.config.fileFormat==="v2"}),t.status(200).json(i);}catch(s){t.status(400).send({error:s.message});return}(async()=>{try{await sw({relativeTestPath:n,stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps},schemaVersion:at,momenticFiles:r,project:o});}catch(s){Cn.error({err:s},"Failed to save migrated test to disk after initial fetch");}})();}));Oc.get("/:testPath/metadata",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=st(),r=Jn__default.join(o.rootDir,n);if(!Oo__default.existsSync(r)){t.status(404).json({error:"Test file not found."});return}let i=Oo__default.statSync(r),s=await Aa(Cn),a={gitBranch:s.gitBranchName??"unknown",fileMtime:i.mtime,gitCommitSha:s.gitCommitSha??"unknown"};t.status(200).json(a);}));Oc.patch("/:testPath/metadata",St(async(e,t)=>{if(!e.params.testPath){t.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=n1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${i}`});return}let r={message:"ok",newRelativeTestPath:fT(e.params.testPath,n,st()).newRelativeTestPath};t.status(200).json(r);}));Oc.patch("/:testPath",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=t1.parse(e.body);}catch(m){Cn.warn({err:m},"Invalid save request"),t.status(400).json({error:`Invalid request body: ${m}`});return}Cn.info({testPath:n},"Save received");let r=st(),i=await ks(r),s;try{s=bd(n,r);}catch(m){t.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let a=r.config.fileFormat==="v2",{stepsToSave:l,moduleUpdates:c,cachesToSave:d,snapshotCachesToSave:u}=await Yn({stepLists:o.stepLists,useSnapshotIdentityCache:a,cacheCreationParams:{orgId:oo(),testId:s.id,environment:s.envs?.find(m=>m.default)?.name}}),p=await ui({logger:Cn,orgId:oo(),project:r});a&&await p.saveSnapshotCacheEntries({logger:Cn,entries:u}),await p.saveStepCacheEntries({logger:Cn,entries:d}),nD({relativeTestPath:n,stepsToSave:l,moduleUpdates:c,schemaVersion:o.schemaVersion,momenticFiles:i,project:r}),t.status(201).json({message:"ok"});}));Oc.patch("/:testPath/environments",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=d1.parse(e.body);}catch(r){t.status(400).json({error:`Invalid request body: ${r}`});return}fT(n,{envs:o.defaultEnv?[{name:o.defaultEnv,default:true}]:[]},st()),t.status(201).json({message:"ok"});}));Oc.patch("/:testPath/move",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=c1.parse(e.body);}catch(i){t.status(400).json({error:`Invalid request body: ${X(i)}`});return}let r=st();if(!Oo__default.existsSync(Jn__default.join(r.rootDir,n))){t.status(404).json({error:"Test not found."});return}await bQ({relativeTestPath:n,targetFolderRelativePath:o.folderPath,project:r}),t.status(200).json({message:"ok"});}));Oc.delete("/:testPath",St((e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o=st(),r=Jn__default.join(o.rootDir,n);if(!Oo__default.existsSync(r)){t.status(404).json({error:"Test not found."});return}Oo__default.unlinkSync(r),t.status(200).json({message:"ok"});}));Oc.post("/:testPath/duplicate",St(async(e,t)=>{let{testPath:n}=e.params;if(!n){t.status(400).json({error:"Missing testPath in url path."});return}let o;try{o=r1.parse(e.body);}catch(h){t.status(400).json({error:`Invalid request body: ${h}`});return}try{Fl(o.name);}catch(h){t.status(400).json({error:h.message});return}let r=st(),i=Jn__default.join(r.rootDir,n);if(!Oo__default.existsSync(i)){t.status(404).json({error:"Test not found."});return}let s=await Ve(r),a;try{a=await rs(i,Cn,s);}catch(h){t.status(400).send({error:h.message});return}let l=cc({projectConfig:r.config,momenticFiles:s,entityType:"test"}),c=Zn.parse({...a,name:o.name,id:l}),{stepsToSave:d}=await Yn({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps},createNewCacheIds:true}),u=Jn__default.dirname(i),p=Jn__default.join(u,`${o.name}.test.yaml`);Sa({test:{fileType:De.TEST,...c,...d},filePath:p,projectConfig:r.config,momenticFiles:s});let m={relativeFilePath:Jn__default.relative(r.rootDir,p)};Ws({type:"test_editor:test_duplicated"}),t.status(201).json(m);}));var bie=Oc;var Tie=z$1.object({name:z$1.string().min(1).describe("Short, human-readable name for the slice you are delegating (used as a label)."),instructions:z$1.string().min(1).describe("Focused, self-contained instructions for the child: which area it should own and what to cover. The child inherits the same input you received but cannot see your conversation, so these instructions must stand alone."),budget:z$1.number().int().positive().optional().describe("Maximum number of test plans this child should produce. Allocate a portion of your remaining budget to each child. Omit to let the child use its own judgement.")});function Aie(e){return e.kind==="diff"?e.diffSummary:yt`
7524
7524
  You are seeding end-to-end test coverage for this entire application from scratch. There is no diff and no single assigned surface — the whole product is in scope.
7525
7525
 
7526
7526
  Map the application's user-facing surfaces from the codebase, then cover them. Whenever you identify a self-contained area that warrants its own focused pass, delegate it to a child explorer with ${ia} as described in your instructions, and explore the rest yourself. Fold the children's findings into your final submission so it reflects the whole app.
@@ -8174,7 +8174,7 @@ ${xU(a,l,Ct())}`),{explorerResult:a,bugs:l,repoRoot:n,writtenPaths:u,baseSha:r,h
8174
8174
  <tool-model>
8175
8175
  Evidence tools:
8176
8176
  - ${_n}: start by calling this with runId "${e.runId}". That is the run that failed and motivated this repair target.
8177
- - ${bt}: use runId "${e.runId}" when inspecting failed-step evidence, screenshots, traces, and before/after context from the failing attempt. You can also pass a passing run's id from ${Yt} to see what the step looked like when it last passed \u2014 do this when the checked text or element no longer renders, so you know where it used to live before choosing its replacement.
8177
+ - ${bt}: use runId "${e.runId}" when inspecting failed-step evidence, screenshots, traces, and before/after context from the failing attempt. You can also pass a passing run's id from ${Yt} to see what the step looked like when it last passed \u2014 do this when the checked text or element no longer renders, so you know where it used to live before choosing its replacement. Treat these results as snapshots of previous runs at a point in their browser flow: each is a single screenshot at the before or after moment of a step, so it is a good indicator of the state it captured but a weak indicator about timing. A step result cannot show what happened between its screenshots, so a state that looks highly irregular compared to other runs may be an intermediary that only got caught this time: a spinner gone while content is still streaming in, a section that hydrates after the page already looks settled, an entry rendering transiently in one location before settling in another, or a list that has not populated yet. A settled-looking screenshot without the target is not proof the target never renders.
8178
8178
  - ${Yt}: fixed to testId "${e.testId}" so you can compare recent pass/fail history for this same test. Do not pass testId.
8179
8179
 
8180
8180
  Browser and execution tools:
@@ -8254,16 +8254,17 @@ ${o}
8254
8254
  </cannot-fix-fast-path>
8255
8255
 
8256
8256
  <minimal-diff-discipline>
8257
+ When the application changed and you need to heal a check, building a stable and accurate replacement check is the objective. Preserving intent in a stable way takes precedence over raw speed of the step. Before splicing a replacement check, state your hypothesis for the root cause, and preview the check you intend to splice against the live page as necessary. If your repair contradicts a rule in this prompt, that is a signal your diagnosis is premature, you can always take a second to run up to the failure.
8257
8258
  Prefer the smallest edit that makes the original failed behavior pass while preserving intent.
8258
8259
  "Smallest edit" means the smallest durable repair, not the fewest changed lines.
8259
8260
  - Do not proactively modernize, generalize, or restructure working steps. Change an authoring pattern only when evidence ties that pattern to the current failure and a same-pattern edit would remain incorrect or brittle for the intended behavior. In that case change the pattern as much as necessary, and do not keep a failing hard-coded runtime value merely because changing only the literal would produce a smaller diff.
8260
8261
  - For example, replace one step with several, or insert an \`AI_EXTRACT\` and thread its \`--env-key\` value into later steps with \`{{env.KEY}}\`.
8261
8262
  - Sometimes the cheapest durable repair is to refine an assertion rather than add a step. For example, when the page grew longer and an image is no longer visible, switching the check to assert the image is present in the browser snapshot is still viable; conversely, scope a purely visual cue to the screenshot. Do not force it \u2014 if neither fits cleanly, add the step instead.
8262
- - When you must touch an assertion that strict-matches a part of the page that changed, reason about what it is verifying. If it proves a behavior or state, re-pin it to semantically describe that concept rather than the exact copy, since text the product could reword (a toast, badge, or status label) just reintroduces the brittleness that failed.
8263
- - When the text or element a check targeted no longer renders, locate where it used to render by pulling a prior passing run's step evidence and comparing its screenshot against the live page, and look at what now occupies that spot before choosing replacement content. A check that referenced an element once is generally signaling page state, such as that the page loaded or is in the correct state. Whatever now renders there generally carries a similar type of signal and determines the outcome: either the change breaks the test's intent and you cannot fix it, or the occupant is a new valid option in that location. If only one assertion references the spot and the new state is reasonable given the rest of the test, treat the occupant as the valid replacement. Repairing the check to target the slot's new occupant is generally better than dropping it, weakening it, or re-pinning it to a different signal entirely. If the replacement is the new steady state, target it directly; if the slot can render one of several valid variants, describe the slot positionally with whatever conditions make sense so the check holds for valid variants.
8263
+ - When you must touch an assertion that strict-matches a part of the page that changed, reason about what it is verifying. If it proves a behavior or state, re-pin it to semantically describe that concept rather than the exact copy, since text the product could reword (a toast, badge, or status label) just reintroduces the brittleness that failed. In practice this often means downgrading strict queries or changing a page check to an element check or AI assertion on the concept.
8264
+ - When the text or element a check targeted no longer renders, locate where it used to render by pulling a prior passing run's step evidence and comparing its screenshot against the live page, and look at what now occupies that spot before choosing replacement content. A check that referenced an element once is generally signaling page state, such as that the page loaded or is in the correct state. Whatever now renders there generally carries a similar type of signal and determines the outcome: either the change breaks the test's intent and you cannot fix it, or the occupant is a new valid option in that location. If only one assertion references the spot and the new state is reasonable given the rest of the test, treat the occupant as the valid replacement. Repairing the check to target the slot's new occupant is generally better than dropping it, weakening it, or re-pinning it to a different signal entirely. If the replacement is the new steady state, target it directly; if the slot can render one of several valid variants, describe the slot positionally with whatever conditions make sense so the check holds for valid variants. Target the occupant as an element check or AI assertion rather than a page check on its current copy, which just re-pins to rewordable text.
8264
8265
  - Check types are a ladder, not a commitment. When a check keeps flaking or its current type can no longer express the fact reliably, back it off to the next type that can: a brittle strict query or PAGE_CHECK generally becomes an ELEMENT_CHECK anchored to the element that owns the fact with some check on its state (visible, exists, contains), or an AI_ASSERTION that describes the condition in a more stable way when the fact needs semantic or visual judgment.
8265
8266
  - Never relax a value the test genuinely enforces. An id, code, amount, or \`{{env.KEY}}\` reference must match exactly because changing it would hide a real bug, and de-brittling copy is never license to edit adjacent steps you would not otherwise touch.
8266
- Preserve the original step shape by default. A stale AI_ASSERTION should usually remain one assertion. The exception is when evidence shows that the assertion fails because it bundles too many independent facts or judges too much of the page at once. Then split it into the minimum focused checks needed to preserve the full intent, using stable, high-signal elements that prove the intended page state. Do not add nearby facts just because the current page exposes them.
8267
+ Preserve the original step shape by default. Preserving shape means preserving what is already good, not keeping a check that has proven itself bad: a check that failed because its anchor was unstable may be flaky again if repaired in the same form, so change it to a stable form. Apply the check-type ladder to repair it as warranted for the page. A stale AI_ASSERTION should usually remain one assertion. The exception is when evidence shows that the assertion fails because it bundles too many independent facts or judges too much of the page at once. Then split it into the minimum focused checks needed to preserve the full intent, using stable, high-signal elements that prove the intended page state. Do not add nearby facts just because the current page exposes them.
8267
8268
  Do not update an expected value merely because the new value makes the current run pass. First establish that the old value is stale and the new value represents the same intended behavior, rather than unexpected product output.
8268
8269
  When evidence establishes a repeated product-copy or expected-value migration, update every occurrence in the target test that asserts the same UI contract (only the first one can fail in a specific run); leaving known-stale duplicates behind creates partial healing. Verify a representative occurrence for a proven mechanical family; for anything less clearly mechanical, run the test up to each proposed edit and validate the replacement against the actual page state first. Keep the sweep narrowly scoped to the target test and the proven pattern; do not let repeated issues cause scope creep into unrelated steps, speculative variants, other tests, or shared modules.
8269
8270
  For assertions that include a primary outcome plus secondary text, identify which details express the test's actual contract. Preserve stable, meaningful detail when current evidence supports a direct replacement, but do not weaken an assertion merely because a shorter one would pass. Conversely, do not replace stale incidental copy with a newly observed dynamic detail just to retain the same sentence length. Remove or generalize secondary text only when it is volatile, contextual, or unnecessary to prove the original behavior, and explain that reasoning in the repair attempt.
@@ -8273,6 +8274,8 @@ ${o}
8273
8274
 
8274
8275
  <repair-what-broke>
8275
8276
  A failed step is not necessarily a broken step. Before editing it, check whether the step is stale or whether the page state it ran against was broken (a timeout, an unsettled transition, or an earlier step that did not do its job). Compare against recent passing runs with ${Yt} and ${bt}: if the same step passed recently and the page still reaches the same state, the page state is what broke, not the step.
8277
+ Be especially suspicious when an entity the test just created shows up in a transient surface (a recents list, notifications, activity feed) but not yet in the permanent location the assertion expects: transient surfaces update immediately while permanent ones often populate async, so the permanent entry frequently appears if you wait more. Reproduce the flow live and wait it out before concluding the placement changed; if the entry does eventually land in the expected location, keep the assertion's original target and raise its timeout within the readiness and waits rules' guided limit. Do not re-anchor to the transient surface.
8278
+ When a captured state is hard to believe or looks broken (the checked target absent while the page looks settled, or content that contradicts other runs), do not trust the screenshot alone. Run up to that point live and check whether the state recurs. If it does not, treat it as a race or late render: keep the original target and extend the failing check's timeout or add an element check on the expected content with a generous timeout, rather than re-anchoring to whatever transient state the screenshot showed.
8276
8279
  In that case, fix reaching the state: repair the upstream step, add a readiness check before the dependent step, or adjust the timeout per the readiness and waits rules. Do not edit the failed assertion or interaction; it is not what broke, and the healed test must keep the same interactions and checks as the previous passing runs.
8277
8280
  If the state cannot be restored because the product or environment is broken or too slow, submit CANNOT_FIX_TEST with that evidence.
8278
8281
  When you model behavior from previous runs, be incredibly skeptical of recovered steps. A prior run that passed only because failure recovery worked around an in-flow failure is not evidence of the test's intent. Recovery's job is to get through the run. Your job is a correct and stable test. You can still use recovered steps as evidence of what happened, but treat the recovery path as a workaround by default rather than the flow to preserve or codify. For example, if the test says click X, clicking X does not trigger the expected state transition, and recovery clicks Exit instead, which lets the run pass, that does not show intent. The intent was clearly for X to work. Figure out why X stopped working and solve that. Do not rewrite the test to follow recovery's path. If unclear try to infer intent from the authored steps and prior clean passing runs. If you cannot infer the intent and are relying on the recovery path to define it, you are taking a risk, and it is better to submit CANNOT_FIX_TEST than to bake the workaround into the test.
@@ -8834,7 +8837,7 @@ ${i.length===0?"(none)":l}
8834
8837
  `);for(let l of e){let c=l.files.map(h=>t.get(h)).filter(h=>h!==void 0),d=l.files.map(h=>n.get(h)).filter(h=>h!==void 0),u=YA({bfsSummaries:d}),p=Y_({fileSummaries:c,bfsSummaries:u,candidateTestsBlock:a,tokenBudget:r});if(!Vle({estimatedTokens:p.estimatedTokens,tokenBudget:r,fileCount:l.files.length})){s.push(l);continue}i.debug({folder:l.folder,files:l.files.length},"Splitting oversized folder group");let m=Math.ceil(l.files.length/2);s.push({folder:`${l.folder} (1/2)`,files:l.files.slice(0,m)},{folder:`${l.folder} (2/2)`,files:l.files.slice(m)});}return s}async function Y4e({groups:e,logger:t,insightStore:n}){let o=new Set,r=new Map;for(let d of e){let u=d.folder.split("/").filter(m=>m.length>0),p=[d.folder];for(let m=u.length-1;m>0;m--)p.push(u.slice(0,m).join("/"));r.set(d.folder,p);for(let m of p)o.add(m);}let i=[...o];if(i.length===0)return new Map;let s=50,a=[];try{for(let d=0;d<i.length;d+=s){let u=i.slice(d,d+s),p=await n.getInsightsForFolders(u);a.push(...p);}}catch(d){return t.warn({err:d},"Code insights prefetch failed, continuing without KB context"),new Map}t.info({folderCount:i.length,insightCount:a.length},"Code insights prefetch complete");let l=new Map;for(let d of a){let u=l.get(d.folderPath)??[];u.push(d),l.set(d.folderPath,u);}let c=new Map;for(let d of e){let u=r.get(d.folder)??[d.folder],p=[];for(let m of u){let h=l.get(m);h&&p.push(...h);}c.set(d.folder,p);}return c}function J4e(e,t){e?.write(`${t}
8835
8838
  `);}var Sl="/v1/app-graph",eP=class{constructor(t,n){this.apiClient=t;this.logger=n;}async claim(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/claim`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return tV.parse(n)}async getPlan(t){let n=new URLSearchParams({repository:t.repository,headSha:t.headSha}),o=await this.apiClient.sendRequest(`${Sl}/ai-select/plan?${n.toString()}`,{method:"GET",retries:1,requestTimeoutMs:1e4});return oV.parse(o)}async finalize(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/finalize`,{method:"POST",body:t,retries:2,requestTimeoutMs:3e4});return nV.parse(n)}async release(t){await this.apiClient.sendRequest(`${Sl}/ai-select/release`,{method:"POST",body:{selectionPlanKey:t},retries:1,requestTimeoutMs:5e3}).catch(n=>{this.logger.warn({err:n,selectionPlanKey:t},"Failed to release ai-select lock");});}async searchObservedTests(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/search/observed-tests`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return eM.parse(n)}async searchSegments(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/search/segments`,{method:"POST",body:t,retries:2,requestTimeoutMs:15e3});return eM.parse(n)}async getObservedTest(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/observed-tests/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return rV.parse(n)}async getSegment(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/segments/${encodeURIComponent(t)}`,{method:"GET",retries:2,requestTimeoutMs:1e4});return iV.parse(n)}async listObservedTestsForSegment(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/segments/${encodeURIComponent(t)}/observed-tests`,{method:"GET",retries:2,requestTimeoutMs:1e4});return sV.parse(n)}async getCodeInsights(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/code-insights`,{method:"POST",body:{repository:t.repository,folderPaths:t.folderPaths},retries:1,requestTimeoutMs:1e4});return aV.parse(n).insights}async createCodeInsight(t){let n=await this.apiClient.sendRequest(`${Sl}/ai-select/code-insight`,{method:"POST",body:t,retries:1,requestTimeoutMs:15e3});return lV.parse(n)}},X4e=2e3,bce=12e4;async function Tce(e){let t=Date.now()+(e.timeoutMs??bce),n=0;for(;;){n+=1;let o=await e.client.claim(e.claim);if(o.status==="claimed")return {kind:"claimed",selectionPlanKey:o.selectionPlanKey,trackId:o.trackId};if(o.status==="ready")return {kind:"ready",plan:o.plan,planId:o.planId};if(Date.now()>=t)throw new Error(`ai-select: timed out waiting for plan after ${e.timeoutMs??bce}ms`);e.logger.info({attempt:n,claimedBy:o.claimedBy},"ai-select plan computing on another shard; polling"),await Qe(o.retryAfterMs??X4e);}}async function Z4e(e){try{return await V_({repoRoot:e.repoRoot,explicitBase:"HEAD~1",logger:e.logger})}catch{return QU({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:null,logger:e.logger})}}async function CH(e){return He({name:"ai_select.resolve_plan",root:true,attributes:{"momentic.repository":e.repository},fn:()=>eQe(e)})}async function eQe(e){let t=new eP(e.apiClient,e.logger),n=e.agentOutputStream?Ct(e.agentOutputStream):Ct();e.agentOutputStream!==void 0&&!!e.agentOutputStream.isTTY;e.agentOutputStream&&e.agentOutputStream.write(`Selecting tests to run with AI:
8836
8839
  `);let r;try{r=await He({name:"ai_select.assemble_diff",attributes:{"momentic.explicit_base":e.explicitBase??"auto"},fn:()=>go({text:"Analyzing code changes...",screen:n},()=>V_({repoRoot:e.repoRoot,explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch,logger:e.logger}))});}catch(p){let m=p instanceof ih?p.message:`Could not assemble diff against base ref: ${X(p)}.`,h=Tle({explicitBase:e.explicitBase,configBase:e.config?.baseRef,mainBranch:e.mainBranch}),g=h?await QU({repoRoot:e.repoRoot,client:e.apiClient,repository:e.repository,base:h,logger:e.logger}):null;if(g)r=g;else {let f=e.config?.onBaseUnavailable??"use-head";switch(f){case "fail":throw new ih(`AI selection base unavailable and ai.select.onBaseUnavailable is "fail": ${m}`);case "run-all":return {kind:"run-all",reason:m,diff:null};case "use-head":{let y=await Z4e(e);if(y===null)return {kind:"run-all",reason:`Could not assemble diff against the HEAD commit's parent: ${m}`,diff:null};r=y;break}default:return Je(f)}}}if(e.logger.info({changedFiles:r.changedFiles.length},"Diff assembled"),r.changedFiles.length===0)return {kind:"run-none",reason:"No source-code changes detected between base and head.",diff:r};let i=createHash("sha256").update(e.candidateTests.map(p=>p.testPath).sort().join(`
8837
- `)).digest("hex").slice(0,12),s=`${r.headSha}:${i}`,a=r.repoRoot,l=Jn__default.relative(a,e.repoRoot),c=l?e.candidateTests.map(p=>({...p,testPath:Jn__default.posix.join(l.split(Jn__default.sep).join("/"),p.testPath)})):e.candidateTests;if(e.dryRun){let p=await AH({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:a,projectRoot:e.repoRoot,diff:r,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:q_(a),agentOutputStream:e.agentOutputStream});return p.fallbackToRunAll?{kind:"run-all",reason:p.userSummary,diff:r}:{kind:"ready",plan:{version:2,userSummary:p.userSummary,toolCallCount:p.toolCallCount,selectedTests:p.selectedTests,anchorSegmentIds:p.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap??null},generatedAt:new Date().toISOString()},planId:`dry-run-${s}`,mode:"SELECTED",diff:r}}let d=await Tce({client:t,claim:{repository:e.repository,headSha:s,baseRef:r.baseRef,changedFiles:r.changedFiles.map(p=>p.path),diffSummary:null,budgetCap:e.budgetCap,dryRun:e.dryRun},logger:e.logger});if(d.kind==="ready")return e.logger.info({planId:d.planId,planSize:d.plan.selectedTests.length,suiteHash:i},"ai-select: reusing cached plan from server"),{kind:"ready",plan:d.plan,planId:d.planId,mode:"SELECTED",diff:r};let u=await AH({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:a,projectRoot:e.repoRoot,diff:r,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:q_(a),agentOutputStream:e.agentOutputStream});if(u.fallbackToRunAll)return await t.release(d.selectionPlanKey),{kind:"run-all",reason:u.userSummary,diff:r};try{e.logger.info({selectedCount:u.selectedTests.length,durationMs:u.totalDurationMs,suiteHash:i},"ai-select: computed fresh plan");let p=await t.finalize({selectionPlanKey:d.selectionPlanKey,repository:e.repository,headSha:s,mode:"SELECTED",userSummary:u.userSummary,toolCallCount:u.toolCallCount,selectedTests:u.selectedTests,anchorSegmentIds:u.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap}});return {kind:"ready",plan:p.plan,planId:p.planId,mode:"SELECTED",diff:r}}catch(p){return e.logger.error({err:p},"ai-select finalize failed; falling back to run-all"),await t.release(d.selectionPlanKey),{kind:"run-all",reason:`Could not record selection plan: ${X(p)}.`,diff:r}}}function lh(e){let t=e??rQe();return Ace()&&t===1&&R.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function rQe(){let e=Ace(),t=e?2:1;return R.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var Ace=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function tP(e,t=true,n=false){let o=lQe(e),r=await sQe.which(o[0],true),i=o.slice(1),s=iQe.exec(aQe(r),i,{delay:100,silent:n});if(t)return s}var Ece="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function cQe(e,{context:t}){return e instanceof no?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${Ece}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${X(e)}`}function Cce(e){return e instanceof no?e.rawError.includes("Resource not accessible by integration")?Ece:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":X(e)}function vce(e,t){R.error(cQe(e,t));}function nP(e){return Rce(e,"runs","run")}function vH(e){return Rce(e,"run-groups","run group")}function Rce(e,t,n){let o=e.trim(),r=/^https?:\/\//i.test(o)?uQe(o,t,n):o;if(!z$1.guid().safeParse(r).success)throw new Error(`Invalid ${n} ID: ${e}. Expected a UUID or a URL like https://app.momentic.ai/${t}/<id>.`);return r}function uQe(e,t,n){let o;try{o=new URL(e);}catch{throw new Error(`Invalid ${n} URL: ${e}`)}let r=o.pathname.split("/").filter(i=>i.length>0);if(r.length!==2||r[0]!==t)throw new Error(`Could not extract ${n} ID from URL: ${e}. Expected a URL like https://app.momentic.ai/${t}/<id>.`);return r[1]}function oP(e){return new Promise((t,n)=>{let o=[];createReadStream(e).pipe(pQe()).on("data",r=>o.push(r)).on("end",()=>t(o)).on("error",r=>n(r));})}var Zt="3.16.2",{checkCLIVersion:Mr,getLatestCLIVersion:wce}=I6({packageName:"momentic",currentVersion:Zt,changelogUrl:"https://github.com/momentic-ai/cli/releases",updateCommand:"npx momentic@latest upgrade"});hDe("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:Xd,setAnalyticsIdentity:rP,shutdownAnalytics:Ice}=yv({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:N6});async function lt(){try{await _e(Promise.all([gv(),At.flush(),Ice(),xv()]),{milliseconds:5e3});}catch{}}async function ch({tests:e,momenticFiles:t,project:n,yes:o,include:r,exclude:i,labels:s,logger:a}){let l=new Set;if(e&&e.length>0){let d=e.some(p=>Oo__default.existsSync(p)),u=cwd();d?(u!==n.rootDir&&a.warn(`Test paths resolve against the current directory ('${u}'), not the project root ('${n.rootDir}'). Run from the project root or use substring filters to avoid surprises.`),e.forEach(p=>{if(!Oo__default.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m;try{m=Oo__default.statSync(p).isDirectory();}catch(g){a.warn({err:g},`Skipping path ${p} because it cannot be read`);return}let h=Jn__default.resolve(p);Object.values(t.tests).filter(g=>m?g.fullFilePath.startsWith(h):g.fullFilePath===h).forEach(g=>{l.add(g.fullFilePath);});})):Object.values(t.tests).forEach(p=>{e.some(m=>p.relativePath.includes(m))&&l.add(p.fullFilePath);});}else !o&&!await sr("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1)),Object.values(t.tests).forEach(u=>{l.add(u.fullFilePath);});for(let d of l){let u=Jn__default.relative(n.rootDir,d);r&&!r.some(p=>new RegExp(p).test(u))&&l.delete(d),i&&i.some(p=>new RegExp(p).test(u))&&l.delete(d);}let c=Array.from(l).map(async d=>{try{let u=await rs(d,Ee,t);if(Ld.gt(u.schemaVersion,at)&&a.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),s&&s.length>0){let p=u.labels||[];if(!s.some(h=>p.includes(h)))return null}return {...u,fullFilePath:d,relativeFilePath:Jn__default.relative(n.rootDir,d)}}catch(u){a.error(`Failed to read and resolve test at '${d}': ${X(u)}`),process.exit(1);}});return compact(await Promise.all(c))}function _ce({testDefinitions:e,quarantinedTestsMetadata:t,onlyQuarantined:n=false,skipQuarantined:o=false}){let[r,i]=partition(e,l=>l.disabled),[s,a]=partition(i,l=>l.id in t);return {testsToSkip:r,quarantinedTestsToSkip:o?s:[],testsToRun:n?[]:a,quarantinedTestsToRun:o?[]:s}}function Pce({testsToRun:e,quarantinedTestsToRun:t,quarantinedTestsMetadata:n,testInputMatrix:o}){let r=[],i=(s,a,l)=>{o?o.forEach((c,d)=>{r.push({inputs:c,inputIndex:d,testDefinition:s,quarantined:a,quarantinedMetadata:l});}):r.push({inputs:void 0,testDefinition:s,quarantined:a,quarantinedMetadata:l});};return e.forEach(s=>i(s,false)),t.forEach(s=>i(s,true,n[s.id])),r}var Oce=()=>process.exit(130),Mce=()=>process.exit(143);process.on("SIGINT",Oce);process.on("SIGTERM",Mce);function JA(){process.off("SIGINT",Oce),process.off("SIGTERM",Mce);}async function Nce({orgId:e,codeEvalTools:t,logger:n,outputDefinitions:o,testContext:r}){let i={};for(let s of o){let{name:a,value:l}=s;i[a]=await li({orgId:e,s:l,localTools:t,logger:n,context:r});}return i}var Lce=new Set;async function kce({baseUrl:e,envName:t,devicePixelRatio:n,apiClient:o,test:r,storageClient:i,codeEvalTools:s,generator:a,orgId:l,variables:c,logger:d,customHeaders:u,testInputs:p,localBrowserConfig:m,aiSettings:h,visualDiffScreenshotStorage:g,tracer:f,runId:y,browserTypeOverride:S,attemptedRemoteBrowserProviders:T}){let E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:Ee,mode:o.mode,runner:o.runner},{controller:C,context:w}=await CA({baseUrl:e,envName:t,test:r,variables:c,logger:d,orgId:l,localBrowserConfig:m,aiSettings:h,customHeaders:u,codeEvalTools:s,storage:i,enricher:new Id(E,a),generator:a,visualDiffScreenshotStorage:g,devicePixelRatio:n,browserTypeOverride:S,callbacks:{onNetworkPage:x=>f.onNetworkPage(x),onNetworkLogs:x=>f.onNetworkLogs(x)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:x,timestamp:I})=>{f.setActiveVideo(x,I);}}:void 0,validateBrowserType:x=>{Ub(x)||(Ee.warn({browserType:x,testName:r.name},"Browser required by test does not appear to be installed"),!Lce.has(x)&&(Lce.add(x),R.warn(`Browser ${x} does not appear to be installed. Run '${cu(x)}' if you hit launch errors.`)));},createRemoteBrowserConnection:m.remoteBrowser?async()=>{let x=await o.createRemoteBrowserConnection({testId:r.id,testName:r.name,runId:y,attemptedProviders:T});return x.provider&&T?.push(x.provider),x}:void 0});try{await zx({orgId:l,test:r,testInputs:p,localTools:s,logger:d,context:w});}catch(x){try{await C.browser.cleanup();}catch(I){d.error({err:I},"Failed to clean up browser after test input resolution failed");}throw x instanceof vA&&(R.error(x.message),process.exit(1)),x}return {controller:C,context:w}}function Dce({testAdvancedSettings:e,orgSettings:t,logger:n}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!nm){let o="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(o),R.debug(o),false}return true}async function Fce({attemptInputs:e,attemptFixtures:t,attemptMetadata:n,runFixtures:o,recordVideo:r,stepCallbacks:i}){let{orgId:s,userId:a,runId:l}=n,{runTracer:c,runGroupTracer:d,project:u,apiClient:p}=o,{controller:m,context:h,codeEvalTools:g,storageClient:f,logger:y,usageTracker:S,tracer:T}=t,{test:E,orgSettings:C}=e;y.info(`Running test '${E.name}' locally (run link: https://app.momentic.ai/runs/${l})`);let w={controller:m,storage:f,usageTracker:S,context:h,logger:y,codeEvalTools:g},x={orgId:s,userId:a,runId:l,testMetadata:E,steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps,orgSettings:C},I={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await Dce({testAdvancedSettings:E.advanced,orgSettings:C.ai,logger:y})};return lre({fixtures:w,inputs:x,options:I,callbacks:{step:i??{},test:{onTestComplete:async _=>{await m.browser.cleanup({saveRemoteVideos:r!=="on-fail"||_?.status!=="PASSED"}),await g.dispose();}}},testParams:{attemptTracer:T},runParams:{runTracer:c,runGroupTracer:d,project:u,apiClient:p,captureEvent:Xd,abortSignal:o.abortSignal}})}async function Bce(e){let{testDefinition:t,logger:n}=e,o=new Date;try{return await TQe(e)}catch(r){wu(r);let{customHeaders:i,envName:s,testInputs:a,urlOverride:l}=e,c={customHeaders:i,envName:s,testInputs:a,urlOverride:l},d="Fatal error running test";return n.error({err:r},d),R.error({err:r},d),Uce({err:Fp(r),parameters:c,test:t,failureReason:te.reasonFor(r,"UnknownError"),startedAt:o,lastAttemptStartedAt:o,attempts:0,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata})}}async function TQe(e){let{testDefinition:t,snapshot:n,project:o,apiClient:r,orgId:i,userId:s,urlOverride:a,runGroupTracer:l,logger:c,gitMetadata:d,cacheOptions:u,runId:p,testInputs:m,quarantined:h,quarantinedMetadata:g,usageTracker:f}=e,y=n?{...o.config,...n.metadata.config}:o.config,S=new wf(r,i),T=Pd({logger:c,orgId:i,client:r,gitMetadata:d,regenerateCache:u.regenerateCache,alwaysSaveCache:u.alwaysSaveCache,noCache:n?true:u.noCache,isolateCachesByEnvironment:o.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:u.bustOldestCachePercentage}),E,C;n?(E={envName:n.metadata.environment.envName,resolvedEnv:n.metadata.environment.resolvedEnv,environmentVariables:{...n.metadata.environment.variables},baseUrl:n.metadata.environment.baseUrl},C={steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps}):(E=If({test:t,envNameOverride:e.envName,urlOverride:a,resolveEnv:ne=>Za(ne,o,c)}),C=await ga({cacheStorage:T,logger:c,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:E.envName,useSnapshotIdentityCache:o.config.fileFormat==="v2"}));let{envName:w,resolvedEnv:x,environmentVariables:I,baseUrl:v}=E,_=C.steps,P=C.beforeSteps??void 0,L=C.afterSteps??void 0,k=await l.startRun({logger:c,runId:p,originalSteps:{beforeSteps:t.beforeSteps,steps:t.steps,afterSteps:t.afterSteps},testId:t.id,testName:t.name,directory:dirname(t.relativeFilePath),testDescription:t.description??void 0,testLabels:t.labels,baseUrl:v,environmentName:w,schemaVersion:t.schemaVersion,resolvedInputs:m,quarantined:h,quarantinedReason:g?.quarantinedReason,aiSettings:y.ai}),V=c.child(k.loggerBindings||{});Object.entries(k.envVarBindings||{}).forEach(([ne,G])=>{I[ne]=G;});let re=await AQe({...e,effectiveConfig:y,variables:I,envName:w,resolvedEnv:x,baseUrl:v,storageClient:S,tracer:k,runGroupTracer:l,logger:V,cacheStorage:T,stepsWithCaches:_,beforeStepsWithCaches:P,afterStepsWithCaches:L,usageTracker:f});return await k.finish({logger:c,status:re.status,finishedAt:re.finishedAt,failureDetails:re.failureDetails,failureReason:re.failureReason,isFlake:re.isFlake,failureRecoveryDetails:re.failureRecoveryDetails}),{runId:k.runId,...re}}async function AQe(e){let{testDefinition:t,effectiveConfig:n,stepsWithCaches:o,beforeStepsWithCaches:r,afterStepsWithCaches:i,project:s,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:d,storageClient:u,orgId:p,userId:m,envName:h,urlOverride:g,customHeaders:f,testInputs:y,variables:S,resolvedEnv:T,retriesOverride:E,devicePixelRatio:C,logUpdate:w,tracer:x,runGroupTracer:I,logger:v,cacheStorage:_,gitMetadata:P,quarantined:L,quarantinedMetadata:k,usageTracker:V}=e,re=n,ne=re.ai?.aiFailureAnalysis??false,G=new Date,W=new hf(s,l,a),M={envName:h,urlOverride:g,customHeaders:f,testInputs:y},Y={...re.browser||{},...T?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},$=Y.remoteBrowser===true,B=[],Q,K=Math.abs(E??t.retries??n.retries??1),ve=[];v.info({...P,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let pe=0;pe<=K;pe++){let Re=randomUUID(),Ye=await x.startAttempt(Re),me=v.child(Ye.loggerBindings||{}),se={...t,steps:cloneDeep(o),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)};pe!==0&&w("RETRY",`attempt ${pe+1}/${K+1}`);let Ie=new Date,Ke=new _d({httpClient:new Fi({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:me,mode:l.mode,runner:l.runner}),fakerSeed:re.advanced?.fakerConstantSeed?ib:void 0});try{let{controller:je,context:Ge}=await kce({tracer:Ye,runId:x.runId,baseUrl:d,envName:h,apiClient:l,devicePixelRatio:C,logger:me,storageClient:u,codeEvalTools:Ke,test:se,generator:c,orgId:p,variables:S,customHeaders:f,testInputs:y,localBrowserConfig:Y,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:B,aiSettings:{...re.ai||{},...se.advanced||{}},visualDiffScreenshotStorage:W});e.abortSignal&&(e.abortSignal.aborted?je.executeAbortController.abort():e.abortSignal.addEventListener("abort",()=>{je.executeAbortController.abort();},{once:!0})),Q=await Fce({attemptMetadata:{attemptNumber:pe+1,orgId:p,userId:m,runId:x.runId},attemptFixtures:{logger:me,storageClient:u,usageTracker:V,codeEvalTools:Ke,context:Ge,controller:je,tracer:Ye},attemptInputs:{test:se,orgSettings:re},runFixtures:{runTracer:x,runGroupTracer:I,project:s,apiClient:l,abortSignal:e.abortSignal},recordVideo:e.recordVideo??!1,stepCallbacks:{onStepStart:e.onStepStart}});let wt=new Date,dn={logger:v,cacheStorage:_,orgId:p,testId:t.id,environment:h,originalStepsWithCaches:{steps:cloneDeep(o),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)},updatedStepsWithCaches:{steps:se.steps,beforeSteps:se.beforeSteps,afterSteps:se.afterSteps}};await um({logger:v,cacheStorage:_,orgId:p,testId:t.id,environment:h,stepLists:dn.updatedStepsWithCaches,useSnapshotIdentityCache:s.config.fileFormat==="v2"}),Q?.status==="PASSED"?await pm(dn):Q?.status==="FAILED"&&pe===K&&await Vg(dn),await Ye.finish({logger:me,result:Q}),ve.unshift(Q.status);let io=await Nce({orgId:p,codeEvalTools:Ke,logger:me,outputDefinitions:t.outputs??[],testContext:Ge}),Xs=EV(ve),gi=pe+1;if(Q.status!=="FAILED")return {...Q,runAttemptId:Re,parameters:M,test:se,filePath:se.relativeFilePath,startedAt:G,lastAttemptStartedAt:Ie,finishedAt:wt,attempts:gi,baseUrl:d,outputs:io,isFlake:Xs,quarantined:L,quarantinedMetadata:k,usedRemoteBrowser:$};let Wi=Q.failedStepResult,Mo=Wi?.message||"Unknown failure",jn=Wi?.failureReason??e$(Mo)??"UnknownError",fi=me.child({failureReason:jn,errorMessage:Mo,numAttempts:(K+1).toString(),name:se.name});if(pe<K){fi.warn(`Retrying failed execution attempt for run: ${Mo}`);continue}fi.error(`Test failed after all exhausting attempts: ${Mo}`);let Ho=new Error(Mo),gr={errorMessage:Mo,errorStack:Ho.stack},yi;if(re.ai?.classification?.enabled===!0){let $n=Wi?.failureClassification;$n||(e.onStepStart?.(Op),$n=await Ix({runTracer:x,runGroupTracer:I,outputDir:e.outputDir,orgId:p,project:s,generator:c,apiClient:l,logger:v,testPlatform:"web",aiSettings:re.ai,captureEvent:Xd,abortSignal:e.abortSignal,failedStepMessage:Wi?.message})),$n&&(yi=$n.classification.category,jn=$n.classification.category,gr.classification={reason:$n.classification.category,secondaryCategories:$n.classification.secondaryCategories,summary:$n.classification.reasoning,recoverable:$n.classification.recoverable,confidence:$n.classification.confidence,action:$n.action,citations:$n.classification.citations,source:"v2"});}else if(ne){let $n;try{if(Q.results&&Q.results.length>0){e.onStepStart?.(Op);let{classification:F,aiFailureReason:ye}=await WX({logger:me,browserStateStorage:Ye,generator:c,fullResults:Q,failureReason:jn,error:Ho,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});$n=F,yi=ye;}}catch(F){me.warn({err:F},"Failed to classify test results");}$n&&(gr.classification=$n,jn=yi??jn,gr.classification.source="v1");}return {...Q,runAttemptId:Re,parameters:M,failureDetails:gr,failureReason:jn,test:se,filePath:se.relativeFilePath,startedAt:G,lastAttemptStartedAt:Ie,finishedAt:wt,attempts:pe+1,baseUrl:d,outputs:io,quarantined:L,quarantinedMetadata:k,usedRemoteBrowser:$}}catch(je){let Ge=`Encountered fatal platform error while running test '${se.name}'`;return me.error({err:je},Ge),R.error({err:je},Ge),await Ye.finish({logger:me,result:{status:"FAILED"}}),Uce({err:Fp(je),parameters:M,test:se,failureReason:te.reasonFor(je,"InternalPlatformError"),startedAt:G,lastAttemptStartedAt:Ie,attempts:pe+1,quarantined:L,quarantinedMetadata:k,runAttemptId:Re,baseUrl:d,usedRemoteBrowser:$})}}throw new Error("This code should not be reachable")}function Uce({err:e,parameters:t,test:n,failureReason:o,startedAt:r,lastAttemptStartedAt:i,attempts:s,quarantined:a,quarantinedMetadata:l,runAttemptId:c,baseUrl:d,usedRemoteBrowser:u}){return {status:"FAILED",results:[],parameters:t,test:n,filePath:n.relativeFilePath,failureReason:o,failureDetails:{errorMessage:e.message,errorStack:e.stack},startedAt:r,lastAttemptStartedAt:i,finishedAt:new Date,attempts:s,outputs:{},quarantined:a,quarantinedMetadata:l,runAttemptId:c,baseUrl:d,usedRemoteBrowser:u}}var Hce=3e4;async function xy({timeoutMinutes:e,cancel:t,run:n}){let o=()=>void t("SIGINT received"),r=()=>void t("SIGTERM received");JA(),process.once("SIGINT",o),process.once("SIGTERM",r);let i;e!==void 0&&e>0&&(i=setTimeout(()=>void t(`Timeout of ${e} minute(s) reached`),e*60*1e3));try{return await n()}finally{process.off("SIGINT",o),process.off("SIGTERM",r),clearTimeout(i);}}var Iy=class{constructor(t){this.params=t;}runQueue={};runResults=[];cancelledRunsById=new Map;cancelled=false;cancellationReason;async cancel(t,n=true){if(this.cancelled)return;this.cancelled=true,this.cancellationReason=t;for(let r of Object.values(this.runQueue))r.done||r.abortController.abort();n&&await _e(Promise.allSettled(Object.values(this.runQueue).map(r=>r.promise)),{milliseconds:Hce}).catch(()=>{this.params.runGroupLogger.warn(`Graceful shutdown timeout of ${Hce}ms reached while waiting for running tests to settle.`);});let o=new Set(this.runResults.map(r=>r.runId).filter(r=>!!r));for(let r of Object.values(this.runQueue)){if(r.done||o.has(r.activeRun.runId))continue;let{activeRun:i}=r,s={results:[],beforeResults:[],afterResults:[],test:i.testDefinition,filePath:i.testDefinition.relativeFilePath,startedAt:i.startedAt,lastAttemptStartedAt:i.startedAt,finishedAt:new Date,status:"CANCELLED",attempts:0,runId:i.runId,cancellationReason:t,quarantined:i.quarantined,quarantinedMetadata:i.quarantinedMetadata,parameters:{testInputs:i.inputs,envName:this.params.envName,urlOverride:this.params.urlOverride,customHeaders:this.params.customHeaders},outputs:{}};this.cancelledRunsById.set(i.runId,s);}}resolveNext(){if(this.params.next)return this.params.next;let t=[...this.params.testsToRun??[]];return ()=>Promise.resolve(t.shift())}async run(){let t=this.resolveNext(),{parallel:n,reporter:o,runGroupTracer:r,runGroupLogger:i,logger:s,project:a,client:l,generator:c,orgId:d,userId:u,devicePixelRatio:p,outputDir:m,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:S,gitMetadata:T,cacheOptions:E,browserTypeOverride:C,remoteBrowserOverride:w,onResult:x,onFatal:I}=this.params,v=0,_=true;for(;_;){let P=Object.values(this.runQueue);if(P.length===n&&await Promise.race(P.map(ne=>ne.promise)),this.cancelled){_=false;continue}let L=await t();if(L===void 0){_=false;continue}let k=`test-${v++}`,V={...L,startedAt:new Date},re=new AbortController;this.runQueue[k]={done:false,activeRun:V,abortController:re,promise:(async({inputs:ne,quarantined:G,quarantinedMetadata:W,testDefinition:M,snapshot:Y,runId:$})=>{let B=M.relativeFilePath.includes("..")?M.fullFilePath:M.relativeFilePath;o.onTestBegin(B);let Q=i.child({testId:M.id,runId:$}),K=new gd({logger:Q,reporter:new wd(l),runType:"test-run",runId:$,testMetadata:M,suiteMetadata:void 0,runner:"test-runner"});try{let ve=await Bce({testDefinition:M,snapshot:Y,project:a,testInputs:ne,quarantined:G,quarantinedMetadata:W,orgId:d,userId:u,runId:$,devicePixelRatio:p,apiClient:l,runGroupTracer:r,outputDir:m,generator:c,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:S,logUpdate:(pe,Re)=>o.onTestStatus(B,pe,Re),...u6(o,B),logger:Q,gitMetadata:T,cacheOptions:E,usageTracker:K,browserTypeOverride:C,remoteBrowserOverride:w,recordVideo:this.params.recordVideo,abortSignal:re.signal});o.onTestEnd(B,ve.status,{recovered:ve.status==="PASSED"&&!!ve.failureRecoveryDetails?.attempts}),this.runResults.push(ve),x?.(ve);}catch(ve){let pe=`Encountered unexpected fatal error when running test '${M.name}'`;Q.error({err:ve},pe),R.error({err:ve},pe),wu(ve),I?.(ve),await this.cancel("Fatal error occurred",false);}finally{let ve=this.runQueue[k];ve&&(ve.done=true),await K.flush(s),delete this.runQueue[k];}})(V)};}return await Promise.allSettled(Object.values(this.runQueue).map(P=>P.promise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}};var CQe=200,vQe=new Set(qj),RQe=new Set(["PASSED","FAILED","CANCELLED"]);function jce(e){return e.length}function sP(e){return e.filter(t=>vQe.has(t.status)).length}var XA=class{constructor(t,n){this.sink=t;this.runId=n;}reportCompletedSteps(t){this.sink.updateRun(this.runId,{completedSteps:t});}setStatus(t){this.sink.updateRun(this.runId,{status:t});}},iP=class{constructor(t,n,o){this.runGroupId=n;this.logger=o;this.filePath=Jn__default.join(t,KK);}filePath;runs=new Map;startedAt=new Date;runGroupStatus="RUNNING";lastWriteMs=0;registerRun(t){let n=new Date;return this.runs.set(t.runId,{runId:t.runId,testId:t.testId,testName:t.testName,directory:t.directory,status:"RUNNING",completedSteps:0,totalSteps:t.totalSteps,startedAt:n,updatedAt:n}),this.write(true),new XA(this,t.runId)}updateRun(t,n){let o=this.runs.get(t);o&&(n.completedSteps!==void 0&&(o.completedSteps=n.completedSteps,o.completedSteps>o.totalSteps&&(o.totalSteps=o.completedSteps)),n.status!==void 0&&(o.status=n.status),o.updatedAt=new Date,this.write(n.status!==void 0));}finish(t){this.runGroupStatus=t,this.write(true);}write(t){let n=Date.now();if(!t&&n-this.lastWriteMs<CQe)return;this.lastWriteMs=n;let o=[...this.runs.values()],r={schemaVersion:YK,runGroupId:this.runGroupId,status:this.runGroupStatus,totalRuns:o.length,completedRuns:o.filter(s=>RQe.has(s.status)).length,completedSteps:o.reduce((s,a)=>s+a.completedSteps,0),totalSteps:o.reduce((s,a)=>s+a.totalSteps,0),startedAt:this.startedAt,updatedAt:new Date,runs:o},i=`${this.filePath}.tmp`;try{Oo__default.writeFileSync(i,JSON.stringify(r,null,2)),Oo__default.renameSync(i,this.filePath);}catch(s){this.logger.warn({err:s},"Failed to write run progress file");}}};function IH(e){return createHash("sha1").update(e).digest("hex")}var IQe=["tab","view","mode","step"],xQe=[/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i,/^(?=.*\d)[A-Za-z0-9_-]{16,256}$/,/^\d{3,32}$/,/^[0-9A-HJKMNP-TV-Z]{26}$/];function _Qe(e){return xQe.some(t=>t.test(e))}function $ce(e,t={}){let n;try{n=new URL(e);}catch{return e}let o=new Set(t.queryAllowlist??IQe),i=n.pathname.split("/").map(c=>c.length>0&&_Qe(c)?"{id}":c).join("/"),s=[],a=Array.from(n.searchParams.keys()).sort();for(let c of a){if(!o.has(c))continue;let d=n.searchParams.getAll(c).sort();for(let u of d)s.push(`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);}let l=s.length>0?`?${s.join("&")}`:"";return `${n.protocol}//${n.host}${i}${l}`}var PQe=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),OQe=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,MQe=[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,/\b[0-9a-f]{12,64}\b/gi,/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,/\b\d{5,}\b/g,/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,16}\b/g],Vce=new Set(["h1","h2","h3","h4","h5","h6"]),NQe=new Set(["input","select","textarea"]);function LQe(e){let t=e;for(let n of MQe)t=t.replace(n,"{id}");return t}function zce(e){return LQe(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function kQe(e){let t=e.length;return t<=4?"txt:xs":t<=16?"txt:s":t<=64?"txt:m":t<=256?"txt:l":"txt:xl"}function DQe(e,t){return e==="href"?t.startsWith("#")?"href:hash":t.startsWith("/")?"href:rel":/^https?:\/\//.test(t)?"href:abs":/^(mailto|tel):/.test(t)?`href:${t.split(":")[0]}`:"href:other":OQe.test(t)?"@gen":zce(t)}function Wce(e,t,n){let o=e.tag.toLowerCase(),r=(e.role??e.attributes?.role)?.toLowerCase(),i=Math.min(Math.floor(t/4),6),s=`<${o}@${i}`;if(r!==void 0&&(s+=` role=${r}`),e.attributes!==void 0){let l=Object.keys(e.attributes).filter(c=>PQe.has(c.toLowerCase())).sort();for(let c of l){let d=c.toLowerCase();if(d==="role")continue;let u=e.attributes[c];if(u===void 0)continue;let p=DQe(d,u);s+=` ${d}=${p}`;}}n.tokens.push(s);let a=e.text?.trim();a!==void 0&&a.length>0&&(r==="button"||r==="link"||r==="heading"||o==="button"||o==="a"||o==="label"||Vce.has(o)?n.tokens.push(`label=${zce(a)}`):n.tokens.push(kQe(a))),(o==="button"||r==="button")&&(n.counts.buttons+=1),(o==="a"||r==="link")&&(n.counts.links+=1),(NQe.has(o)||r==="textbox"||r==="combobox")&&(n.counts.formFields+=1),(Vce.has(o)||r==="heading")&&(n.counts.headings+=1);for(let l of e.children??[])Wce(l,t+1,n);}function qce(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return Wce(e,0,t),{tokens:t.tokens,counts:t.counts}}function Kce(e,t){let n=new TextEncoder().encode(e),o=n.length,r=Math.floor(o/4),i=t>>>0,s=3432918353,a=461845907;for(let u=0;u<r;u++){let p=u*4,m=n[p]|n[p+1]<<8|n[p+2]<<16|n[p+3]<<24;m=Math.imul(m,s),m=m<<15|m>>>17,m=Math.imul(m,a),i^=m,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}let l=0,c=o&3,d=r*4;return c===3&&(l^=n[d+2]<<16),c>=2&&(l^=n[d+1]<<8),c>=1&&(l^=n[d],l=Math.imul(l,s),l=l<<15|l>>>17,l=Math.imul(l,a),i^=l),i^=o,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}var aP=128,FQe=4294967295,BQe=(()=>{let e=[];for(let t=0;t<aP;t++)e.push(Kce(`perm:${t}`,0));return e})();function Yce(e){let t=new Uint32Array(aP);for(let o=0;o<aP;o++)t[o]=FQe;let n=new Set(e);for(let o of n)for(let r=0;r<aP;r++){let i=Kce(o,BQe[r]);i<t[r]&&(t[r]=i);}return t}var HQe=32;function xH(e){let t=$ce(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:n,counts:o}=qce(e.dom),r=[`url:${t}`,`counts:buttons=${o.buttons}`,`counts:links=${o.links}`,`counts:formFields=${o.formFields}`,`counts:headings=${o.headings}`,...n],i=Yce(r),s=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(s).digest("hex").slice(0,HQe),minhash:Array.from(i),canonicalUrl:t}}var GQe=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),Gn="\uFFFD",N;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z";})(N||(N={}));var $i={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function lP(e){return e>=55296&&e<=57343}function Jce(e){return e>=56320&&e<=57343}function Xce(e,t){return (e-55296)*1024+9216+t}function cP(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function dP(e){return e>=64976&&e<=65007||GQe.has(e)}var ce;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text";})(ce||(ce={}));var $Qe=65536,uP=class{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=false,this.lastChunkWritten=false,this.endOfChunkHit=false,this.bufferWaterline=$Qe,this.isEol=false,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1;}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){let{line:o,col:r,offset:i}=this,s=r+n,a=i+n;return {code:t,startLine:o,endLine:o,startCol:s,endCol:s,startOffset:a,endOffset:a}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)));}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos;}_processSurrogate(t){if(this.pos!==this.html.length-1){let n=this.html.charCodeAt(this.pos+1);if(Jce(n))return this.pos++,this._addGap(),Xce(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,N.EOF;return this._err(ce.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0);}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=false,this.lastChunkWritten=n;}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=false;}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,false;if(n)return this.html.startsWith(t,this.pos);for(let o=0;o<t.length;o++)if((this.html.charCodeAt(this.pos+o)|32)!==t.charCodeAt(o))return false;return true}peek(t){let n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,N.EOF;let o=this.html.charCodeAt(n);return o===N.CARRIAGE_RETURN?N.LINE_FEED:o}advance(){if(this.pos++,this.isEol&&(this.isEol=false,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,N.EOF;let t=this.html.charCodeAt(this.pos);return t===N.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,N.LINE_FEED):t===N.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,lP(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===N.LINE_FEED||t===N.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){cP(t)?this._err(ce.controlCharacterInInputStream):dP(t)&&this._err(ce.noncharacterInInputStream);}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=false;}};var Kt;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION";})(Kt||(Kt={}));function pP(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}var zQe=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function Qce(e){return e>=55296&&e<=57343||e>1114111?65533:zQe.get(e)??e}function Zce(e){let t=atob(e),n=t.length&-2,o=new Uint16Array(n/2);for(let r=0,i=0;r<n;r+=2){let s=t.charCodeAt(r),a=t.charCodeAt(r+1);o[i++]=s|a<<8;}return o}var _H=Zce("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var pi;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE";})(pi||(pi={}));var bo;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z";})(bo||(bo={}));var ede=32;function PH(e){return e>=bo.ZERO&&e<=bo.NINE}function WQe(e){return e>=bo.UPPER_A&&e<=bo.UPPER_F||e>=bo.LOWER_A&&e<=bo.LOWER_F}function qQe(e){return e>=bo.UPPER_A&&e<=bo.UPPER_Z||e>=bo.LOWER_A&&e<=bo.LOWER_Z||PH(e)}function KQe(e){return e===bo.EQUALS||qQe(e)}var Nr;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity";})(Nr||(Nr={}));var Bc;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(Bc||(Bc={}));var mP=class{decodeTree;emitCodePoint;errors;constructor(t,n,o){this.decodeTree=t,this.emitCodePoint=n,this.errors=o;}state=Nr.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Bc.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=Nr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,n){switch(this.state){case Nr.EntityStart:return t.charCodeAt(n)===bo.NUM?(this.state=Nr.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Nr.NamedEntity,this.stateNamedEntity(t,n));case Nr.NumericStart:return this.stateNumericStart(t,n);case Nr.NumericDecimal:return this.stateNumericDecimal(t,n);case Nr.NumericHex:return this.stateNumericHex(t,n);case Nr.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|ede)===bo.LOWER_X?(this.state=Nr.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Nr.NumericDecimal,this.stateNumericDecimal(t,n))}stateNumericHex(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(PH(o)||WQe(o)){let r=o<=bo.NINE?o-bo.ZERO:(o|ede)-bo.LOWER_A+10;this.result=this.result*16+r,this.consumed++,n++;}else return this.emitNumericEntity(o,3)}return -1}stateNumericDecimal(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(PH(o))this.result=this.result*10+(o-bo.ZERO),this.consumed++,n++;else return this.emitNumericEntity(o,2)}return -1}emitNumericEntity(t,n){if(this.consumed<=n)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===bo.SEMI)this.consumed+=1;else if(this.decodeMode===Bc.Strict)return 0;return this.emitCodePoint(Qce(this.result),this.consumed),this.errors&&(t!==bo.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){let{decodeTree:o}=this,r=o[this.treeIndex],i=(r&pi.VALUE_LENGTH)>>14;for(;n<t.length;){if(i===0&&r&pi.FLAG13){let a=(r&pi.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&pi.JUMP_TABLE;if(t.charCodeAt(n)!==l)return this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}for(;this.runConsumed<a;){if(n>=t.length)return -1;let l=this.runConsumed-1,c=o[this.treeIndex+1+(l>>1)],d=l%2===0?c&255:c>>8&255;if(t.charCodeAt(n)!==d)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}this.runConsumed=0,this.treeIndex+=1+(a>>1),r=o[this.treeIndex],i=(r&pi.VALUE_LENGTH)>>14;}if(n>=t.length)break;let s=t.charCodeAt(n);if(s===bo.SEMI&&i!==0&&r&pi.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=YQe(o,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Bc.Attribute&&(i===0||KQe(s))?0:this.emitNotTerminatedNamedEntity();if(r=o[this.treeIndex],i=(r&pi.VALUE_LENGTH)>>14,i!==0){if(s===bo.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==Bc.Strict&&!(r&pi.FLAG13)&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}n++,this.excess++;}return -1}emitNotTerminatedNamedEntity(){let{result:t,decodeTree:n}=this,o=(n[t]&pi.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,o,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,o){let{decodeTree:r}=this;return this.emitCodePoint(n===1?r[t]&~(pi.VALUE_LENGTH|pi.FLAG13):r[t+1],o),n===3&&this.emitCodePoint(r[t+2],o),o}end(){switch(this.state){case Nr.NamedEntity:return this.result!==0&&(this.decodeMode!==Bc.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Nr.NumericDecimal:return this.emitNumericEntity(0,2);case Nr.NumericHex:return this.emitNumericEntity(0,3);case Nr.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Nr.EntityStart:return 0}}};function YQe(e,t,n,o){let r=(t&pi.BRANCH_LENGTH)>>7,i=t&pi.JUMP_TABLE;if(r===0)return i!==0&&o===i?n:-1;if(i){let c=o-i;return c<0||c>=r?-1:e[n+c]-1}let s=r+1>>1,a=0,l=r-1;for(;a<=l;){let c=a+l>>>1,d=c>>1,p=e[n+d]>>(c&1)*8&255;if(p<o)a=c+1;else if(p>o)l=c-1;else return e[n+s+c]}return -1}var Te;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/";})(Te||(Te={}));var Qd;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size";})(Qd||(Qd={}));var Vi;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(Vi||(Vi={}));var ie;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp";})(ie||(ie={}));var b;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP";})(b||(b={}));var JQe=new Map([[ie.A,b.A],[ie.ADDRESS,b.ADDRESS],[ie.ANNOTATION_XML,b.ANNOTATION_XML],[ie.APPLET,b.APPLET],[ie.AREA,b.AREA],[ie.ARTICLE,b.ARTICLE],[ie.ASIDE,b.ASIDE],[ie.B,b.B],[ie.BASE,b.BASE],[ie.BASEFONT,b.BASEFONT],[ie.BGSOUND,b.BGSOUND],[ie.BIG,b.BIG],[ie.BLOCKQUOTE,b.BLOCKQUOTE],[ie.BODY,b.BODY],[ie.BR,b.BR],[ie.BUTTON,b.BUTTON],[ie.CAPTION,b.CAPTION],[ie.CENTER,b.CENTER],[ie.CODE,b.CODE],[ie.COL,b.COL],[ie.COLGROUP,b.COLGROUP],[ie.DD,b.DD],[ie.DESC,b.DESC],[ie.DETAILS,b.DETAILS],[ie.DIALOG,b.DIALOG],[ie.DIR,b.DIR],[ie.DIV,b.DIV],[ie.DL,b.DL],[ie.DT,b.DT],[ie.EM,b.EM],[ie.EMBED,b.EMBED],[ie.FIELDSET,b.FIELDSET],[ie.FIGCAPTION,b.FIGCAPTION],[ie.FIGURE,b.FIGURE],[ie.FONT,b.FONT],[ie.FOOTER,b.FOOTER],[ie.FOREIGN_OBJECT,b.FOREIGN_OBJECT],[ie.FORM,b.FORM],[ie.FRAME,b.FRAME],[ie.FRAMESET,b.FRAMESET],[ie.H1,b.H1],[ie.H2,b.H2],[ie.H3,b.H3],[ie.H4,b.H4],[ie.H5,b.H5],[ie.H6,b.H6],[ie.HEAD,b.HEAD],[ie.HEADER,b.HEADER],[ie.HGROUP,b.HGROUP],[ie.HR,b.HR],[ie.HTML,b.HTML],[ie.I,b.I],[ie.IMG,b.IMG],[ie.IMAGE,b.IMAGE],[ie.INPUT,b.INPUT],[ie.IFRAME,b.IFRAME],[ie.KEYGEN,b.KEYGEN],[ie.LABEL,b.LABEL],[ie.LI,b.LI],[ie.LINK,b.LINK],[ie.LISTING,b.LISTING],[ie.MAIN,b.MAIN],[ie.MALIGNMARK,b.MALIGNMARK],[ie.MARQUEE,b.MARQUEE],[ie.MATH,b.MATH],[ie.MENU,b.MENU],[ie.META,b.META],[ie.MGLYPH,b.MGLYPH],[ie.MI,b.MI],[ie.MO,b.MO],[ie.MN,b.MN],[ie.MS,b.MS],[ie.MTEXT,b.MTEXT],[ie.NAV,b.NAV],[ie.NOBR,b.NOBR],[ie.NOFRAMES,b.NOFRAMES],[ie.NOEMBED,b.NOEMBED],[ie.NOSCRIPT,b.NOSCRIPT],[ie.OBJECT,b.OBJECT],[ie.OL,b.OL],[ie.OPTGROUP,b.OPTGROUP],[ie.OPTION,b.OPTION],[ie.P,b.P],[ie.PARAM,b.PARAM],[ie.PLAINTEXT,b.PLAINTEXT],[ie.PRE,b.PRE],[ie.RB,b.RB],[ie.RP,b.RP],[ie.RT,b.RT],[ie.RTC,b.RTC],[ie.RUBY,b.RUBY],[ie.S,b.S],[ie.SCRIPT,b.SCRIPT],[ie.SEARCH,b.SEARCH],[ie.SECTION,b.SECTION],[ie.SELECT,b.SELECT],[ie.SOURCE,b.SOURCE],[ie.SMALL,b.SMALL],[ie.SPAN,b.SPAN],[ie.STRIKE,b.STRIKE],[ie.STRONG,b.STRONG],[ie.STYLE,b.STYLE],[ie.SUB,b.SUB],[ie.SUMMARY,b.SUMMARY],[ie.SUP,b.SUP],[ie.TABLE,b.TABLE],[ie.TBODY,b.TBODY],[ie.TEMPLATE,b.TEMPLATE],[ie.TEXTAREA,b.TEXTAREA],[ie.TFOOT,b.TFOOT],[ie.TD,b.TD],[ie.TH,b.TH],[ie.THEAD,b.THEAD],[ie.TITLE,b.TITLE],[ie.TR,b.TR],[ie.TRACK,b.TRACK],[ie.TT,b.TT],[ie.U,b.U],[ie.UL,b.UL],[ie.SVG,b.SVG],[ie.VAR,b.VAR],[ie.WBR,b.WBR],[ie.XMP,b.XMP]]);function dh(e){var t;return (t=JQe.get(e))!==null&&t!==void 0?t:b.UNKNOWN}var Pe=b,tde={[Te.HTML]:new Set([Pe.ADDRESS,Pe.APPLET,Pe.AREA,Pe.ARTICLE,Pe.ASIDE,Pe.BASE,Pe.BASEFONT,Pe.BGSOUND,Pe.BLOCKQUOTE,Pe.BODY,Pe.BR,Pe.BUTTON,Pe.CAPTION,Pe.CENTER,Pe.COL,Pe.COLGROUP,Pe.DD,Pe.DETAILS,Pe.DIR,Pe.DIV,Pe.DL,Pe.DT,Pe.EMBED,Pe.FIELDSET,Pe.FIGCAPTION,Pe.FIGURE,Pe.FOOTER,Pe.FORM,Pe.FRAME,Pe.FRAMESET,Pe.H1,Pe.H2,Pe.H3,Pe.H4,Pe.H5,Pe.H6,Pe.HEAD,Pe.HEADER,Pe.HGROUP,Pe.HR,Pe.HTML,Pe.IFRAME,Pe.IMG,Pe.INPUT,Pe.LI,Pe.LINK,Pe.LISTING,Pe.MAIN,Pe.MARQUEE,Pe.MENU,Pe.META,Pe.NAV,Pe.NOEMBED,Pe.NOFRAMES,Pe.NOSCRIPT,Pe.OBJECT,Pe.OL,Pe.P,Pe.PARAM,Pe.PLAINTEXT,Pe.PRE,Pe.SCRIPT,Pe.SECTION,Pe.SELECT,Pe.SOURCE,Pe.STYLE,Pe.SUMMARY,Pe.TABLE,Pe.TBODY,Pe.TD,Pe.TEMPLATE,Pe.TEXTAREA,Pe.TFOOT,Pe.TH,Pe.THEAD,Pe.TITLE,Pe.TR,Pe.TRACK,Pe.UL,Pe.WBR,Pe.XMP]),[Te.MATHML]:new Set([Pe.MI,Pe.MO,Pe.MN,Pe.MS,Pe.MTEXT,Pe.ANNOTATION_XML]),[Te.SVG]:new Set([Pe.TITLE,Pe.FOREIGN_OBJECT,Pe.DESC]),[Te.XLINK]:new Set,[Te.XML]:new Set,[Te.XMLNS]:new Set},QA=new Set([Pe.H1,Pe.H2,Pe.H3,Pe.H4,Pe.H5,Pe.H6]);new Set([ie.STYLE,ie.SCRIPT,ie.XMP,ie.IFRAME,ie.NOEMBED,ie.NOFRAMES,ie.PLAINTEXT]);var U;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND";})(U||(U={}));var mi={DATA:U.DATA,RCDATA:U.RCDATA,RAWTEXT:U.RAWTEXT,SCRIPT_DATA:U.SCRIPT_DATA,PLAINTEXT:U.PLAINTEXT,CDATA_SECTION:U.CDATA_SECTION};function QQe(e){return e>=N.DIGIT_0&&e<=N.DIGIT_9}function ZA(e){return e>=N.LATIN_CAPITAL_A&&e<=N.LATIN_CAPITAL_Z}function ZQe(e){return e>=N.LATIN_SMALL_A&&e<=N.LATIN_SMALL_Z}function wp(e){return ZQe(e)||ZA(e)}function nde(e){return wp(e)||QQe(e)}function hP(e){return e+32}function rde(e){return e===N.SPACE||e===N.LINE_FEED||e===N.TABULATION||e===N.FORM_FEED}function ode(e){return rde(e)||e===N.SOLIDUS||e===N.GREATER_THAN_SIGN}function e5e(e){return e===N.NULL?ce.nullCharacterReference:e>1114111?ce.characterReferenceOutsideUnicodeRange:lP(e)?ce.surrogateCharacterReference:dP(e)?ce.noncharacterCharacterReference:cP(e)||e===N.CARRIAGE_RETURN?ce.controlCharacterReference:null}var eE=class{constructor(t,n){this.options=t,this.handler=n,this.paused=false,this.inLoop=false,this.inForeignNode=false,this.lastStartTagName="",this.active=false,this.state=U.DATA,this.returnState=U.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new uP(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new mP(_H,(o,r)=>{this.preprocessor.pos=this.entityStartPos+r-1,this._flushCodePointConsumedAsCharacterReference(o);},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(ce.missingSemicolonAfterCharacterReference,1);},absenceOfDigitsInNumericCharacterReference:o=>{this._err(ce.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+o);},validateNumericCharacterReference:o=>{let r=e5e(o);r&&this._err(r,1);}}:void 0);}_err(t,n=0){var o,r;(r=(o=this.handler).onParseError)===null||r===void 0||r.call(o,this.preprocessor.getError(t,n));}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=true;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let t=this._consume();this._ensureHibernation()||this._callState(t);}this.inLoop=false;}}pause(){this.paused=true;}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=false,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.());}write(t,n,o){this.active=true,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||o?.();}insertHtmlAtCurrentPos(t){this.active=true,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop();}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=false,true):false}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance();}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),true):false}_createStartTagToken(){this.currentToken={type:Kt.START_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:Kt.END_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:Kt.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:Kt.DOCTYPE,name:t,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation};}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation};}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0);}_leaveAttrName(){var t,n;let o=this.currentToken;if(pP(o,this.currentAttr.name)===null){if(o.attrs.push(this.currentAttr),o.location&&this.currentLocation){let r=(t=(n=o.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue();}}else this._err(ce.duplicateAttribute);}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset);}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1);}emitCurrentTagToken(){let t=this.currentToken;this.prepareToken(t),t.tagID=dh(t.tagName),t.type===Kt.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(ce.endTagWithAttributes),t.selfClosing&&this._err(ce.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk();}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk();}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk();}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Kt.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Kt.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Kt.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null;}}_emitEOFToken(){let t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Kt.EOF,location:t}),this.active=false;}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n);}_emitCodePoint(t){let n=rde(t)?Kt.WHITESPACE_CHARACTER:t===N.NULL?Kt.NULL_CHARACTER:Kt.CHARACTER;this._appendCharToCurrentCharacterToken(n,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(Kt.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=U.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Bc.Attribute:Bc.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===U.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===U.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===U.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case U.DATA:{this._stateData(t);break}case U.RCDATA:{this._stateRcdata(t);break}case U.RAWTEXT:{this._stateRawtext(t);break}case U.SCRIPT_DATA:{this._stateScriptData(t);break}case U.PLAINTEXT:{this._statePlaintext(t);break}case U.TAG_OPEN:{this._stateTagOpen(t);break}case U.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case U.TAG_NAME:{this._stateTagName(t);break}case U.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case U.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case U.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case U.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case U.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case U.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case U.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case U.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case U.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case U.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case U.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case U.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case U.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case U.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case U.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case U.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case U.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case U.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case U.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case U.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case U.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case U.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case U.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case U.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case U.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case U.BOGUS_COMMENT:{this._stateBogusComment(t);break}case U.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case U.COMMENT_START:{this._stateCommentStart(t);break}case U.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case U.COMMENT:{this._stateComment(t);break}case U.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case U.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case U.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case U.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case U.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case U.COMMENT_END:{this._stateCommentEnd(t);break}case U.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case U.DOCTYPE:{this._stateDoctype(t);break}case U.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case U.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case U.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case U.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case U.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case U.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case U.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case U.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case U.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case U.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case U.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case U.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case U.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case U.CDATA_SECTION:{this._stateCdataSection(t);break}case U.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case U.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case U.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case U.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case N.LESS_THAN_SIGN:{this.state=U.TAG_OPEN;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitCodePoint(t);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case N.AMPERSAND:{this._startCharacterReference();break}case N.LESS_THAN_SIGN:{this.state=U.RCDATA_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case N.LESS_THAN_SIGN:{this.state=U.RAWTEXT_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(wp(t))this._createStartTagToken(),this.state=U.TAG_NAME,this._stateTagName(t);else switch(t){case N.EXCLAMATION_MARK:{this.state=U.MARKUP_DECLARATION_OPEN;break}case N.SOLIDUS:{this.state=U.END_TAG_OPEN;break}case N.QUESTION_MARK:{this._err(ce.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=U.BOGUS_COMMENT,this._stateBogusComment(t);break}case N.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=U.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(wp(t))this._createEndTagToken(),this.state=U.TAG_NAME,this._stateTagName(t);else switch(t){case N.GREATER_THAN_SIGN:{this._err(ce.missingEndTagName),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=U.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_ATTRIBUTE_NAME;break}case N.SOLIDUS:{this.state=U.SELF_CLOSING_START_TAG;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentTagToken();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.tagName+=Gn;break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(ZA(t)?hP(t):t);}}_stateRcdataLessThanSign(t){t===N.SOLIDUS?this.state=U.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=U.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){wp(t)?(this.state=U.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=U.RCDATA,this._stateRcdata(t));}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,false))return !this._ensureHibernation();this._createEndTagToken();let n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=U.BEFORE_ATTRIBUTE_NAME,false;case N.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=U.SELF_CLOSING_START_TAG,false;case N.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=U.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===N.SOLIDUS?this.state=U.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=U.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){wp(t)?(this.state=U.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=U.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case N.SOLIDUS:{this.state=U.SCRIPT_DATA_END_TAG_OPEN;break}case N.EXCLAMATION_MARK:{this.state=U.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=U.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){wp(t)?(this.state=U.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===N.HYPHEN_MINUS?(this.state=U.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===N.HYPHEN_MINUS?(this.state=U.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case N.HYPHEN_MINUS:{this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case N.GREATER_THAN_SIGN:{this.state=U.SCRIPT_DATA,this._emitChars(">");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===N.SOLIDUS?this.state=U.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:wp(t)?(this._emitChars("<"),this.state=U.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){wp(t)?(this.state=U.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith($i.SCRIPT,false)&&ode(this.preprocessor.peek($i.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<$i.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case N.HYPHEN_MINUS:{this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case N.GREATER_THAN_SIGN:{this.state=U.SCRIPT_DATA,this._emitChars(">");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===N.SOLIDUS?(this.state=U.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith($i.SCRIPT,false)&&ode(this.preprocessor.peek($i.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<$i.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=U.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.SOLIDUS:case N.GREATER_THAN_SIGN:case N.EOF:{this.state=U.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case N.EQUALS_SIGN:{this._err(ce.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=U.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=U.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:case N.SOLIDUS:case N.GREATER_THAN_SIGN:case N.EOF:{this._leaveAttrName(),this.state=U.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case N.EQUALS_SIGN:{this._leaveAttrName(),this.state=U.BEFORE_ATTRIBUTE_VALUE;break}case N.QUOTATION_MARK:case N.APOSTROPHE:case N.LESS_THAN_SIGN:{this._err(ce.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.name+=Gn;break}default:this.currentAttr.name+=String.fromCodePoint(ZA(t)?hP(t):t);}}_stateAfterAttributeName(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.SOLIDUS:{this.state=U.SELF_CLOSING_START_TAG;break}case N.EQUALS_SIGN:{this.state=U.BEFORE_ATTRIBUTE_VALUE;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentTagToken();break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=U.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.QUOTATION_MARK:{this.state=U.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this.state=U.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingAttributeValue),this.state=U.DATA,this.emitCurrentTagToken();break}default:this.state=U.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case N.QUOTATION_MARK:{this.state=U.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Gn;break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case N.APOSTROPHE:{this.state=U.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Gn;break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this._leaveAttrValue(),this.state=U.BEFORE_ATTRIBUTE_NAME;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=U.DATA,this.emitCurrentTagToken();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Gn;break}case N.QUOTATION_MARK:case N.APOSTROPHE:case N.LESS_THAN_SIGN:case N.EQUALS_SIGN:case N.GRAVE_ACCENT:{this._err(ce.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this._leaveAttrValue(),this.state=U.BEFORE_ATTRIBUTE_NAME;break}case N.SOLIDUS:{this._leaveAttrValue(),this.state=U.SELF_CLOSING_START_TAG;break}case N.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=U.DATA,this.emitCurrentTagToken();break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.missingWhitespaceBetweenAttributes),this.state=U.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case N.GREATER_THAN_SIGN:{let n=this.currentToken;n.selfClosing=true,this.state=U.DATA,this.emitCurrentTagToken();break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.unexpectedSolidusInTag),this.state=U.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let n=this.currentToken;switch(t){case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentComment(n);break}case N.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Gn;break}default:n.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch($i.DASH_DASH,true)?(this._createCommentToken($i.DASH_DASH.length+1),this.state=U.COMMENT_START):this._consumeSequenceIfMatch($i.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation($i.DOCTYPE.length+1),this.state=U.DOCTYPE):this._consumeSequenceIfMatch($i.CDATA_START,true)?this.inForeignNode?this.state=U.CDATA_SECTION:(this._err(ce.cdataInHtmlContent),this._createCommentToken($i.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=U.BOGUS_COMMENT):this._ensureHibernation()||(this._err(ce.incorrectlyOpenedComment),this._createCommentToken(2),this.state=U.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_START_DASH;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=U.DATA;let n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=U.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_END;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=U.DATA,this.emitCurrentComment(n);break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=U.COMMENT,this._stateComment(t);}}_stateComment(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_END_DASH;break}case N.LESS_THAN_SIGN:{n.data+="<",this.state=U.COMMENT_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Gn;break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t);}}_stateCommentLessThanSign(t){let n=this.currentToken;switch(t){case N.EXCLAMATION_MARK:{n.data+="!",this.state=U.COMMENT_LESS_THAN_SIGN_BANG;break}case N.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=U.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===N.HYPHEN_MINUS?this.state=U.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=U.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===N.HYPHEN_MINUS?this.state=U.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=U.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==N.GREATER_THAN_SIGN&&t!==N.EOF&&this._err(ce.nestedComment),this.state=U.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_END;break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=U.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let n=this.currentToken;switch(t){case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentComment(n);break}case N.EXCLAMATION_MARK:{this.state=U.COMMENT_END_BANG;break}case N.HYPHEN_MINUS:{n.data+="-";break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=U.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{n.data+="--!",this.state=U.COMMENT_END_DASH;break}case N.GREATER_THAN_SIGN:{this._err(ce.incorrectlyClosedComment),this.state=U.DATA,this.emitCurrentComment(n);break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=U.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_DOCTYPE_NAME;break}case N.GREATER_THAN_SIGN:{this.state=U.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case N.EOF:{this._err(ce.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingWhitespaceBeforeDoctypeName),this.state=U.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(ZA(t))this._createDoctypeToken(String.fromCharCode(hP(t))),this.state=U.DOCTYPE_NAME;else switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.NULL:{this._err(ce.unexpectedNullCharacter),this._createDoctypeToken(Gn),this.state=U.DOCTYPE_NAME;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeName),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=U.DOCTYPE_NAME;}}_stateDoctypeName(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.AFTER_DOCTYPE_NAME;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.name+=Gn;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(ZA(t)?hP(t):t);}}_stateAfterDoctypeName(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch($i.PUBLIC,false)?this.state=U.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch($i.SYSTEM,false)?this.state=U.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(ce.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case N.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.QUOTATION_MARK:{n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case N.QUOTATION_MARK:{this.state=U.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateDoctypePublicIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case N.APOSTROPHE:{this.state=U.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateAfterDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.QUOTATION_MARK:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.QUOTATION_MARK:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case N.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.QUOTATION_MARK:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case N.QUOTATION_MARK:{this.state=U.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateDoctypeSystemIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case N.APOSTROPHE:{this.state=U.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateAfterDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let n=this.currentToken;switch(t){case N.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.NULL:{this._err(ce.unexpectedNullCharacter);break}case N.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case N.RIGHT_SQUARE_BRACKET:{this.state=U.CDATA_SECTION_BRACKET;break}case N.EOF:{this._err(ce.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===N.RIGHT_SQUARE_BRACKET?this.state=U.CDATA_SECTION_END:(this._emitChars("]"),this.state=U.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case N.GREATER_THAN_SIGN:{this.state=U.DATA;break}case N.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=U.CDATA_SECTION,this._stateCdataSection(t);}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else {this.active=false,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=true;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(N.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&nde(this.preprocessor.peek(1))?U.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){nde(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===N.SEMICOLON&&this._err(ce.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var lde=new Set([b.DD,b.DT,b.LI,b.OPTGROUP,b.OPTION,b.P,b.RB,b.RP,b.RT,b.RTC]),ide=new Set([...lde,b.CAPTION,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]),gP=new Set([b.APPLET,b.CAPTION,b.HTML,b.MARQUEE,b.OBJECT,b.TABLE,b.TD,b.TEMPLATE,b.TH]),t5e=new Set([...gP,b.OL,b.UL]),n5e=new Set([...gP,b.BUTTON]),sde=new Set([b.ANNOTATION_XML,b.MI,b.MN,b.MO,b.MS,b.MTEXT]),ade=new Set([b.DESC,b.FOREIGN_OBJECT,b.TITLE]),o5e=new Set([b.TR,b.TEMPLATE,b.HTML]),r5e=new Set([b.TBODY,b.TFOOT,b.THEAD,b.TEMPLATE,b.HTML]),i5e=new Set([b.TABLE,b.TEMPLATE,b.HTML]),s5e=new Set([b.TD,b.TH]),fP=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,o){this.treeAdapter=n,this.handler=o,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=b.UNKNOWN,this.current=t;}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===b.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===Te.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop];}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,true);}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,true);}replace(t,n){let o=this._indexOf(t);this.items[o]=n,o===this.stackTop&&(this.current=n);}insertAfter(t,n,o){let r=this._indexOf(t)+1;this.items.splice(r,0,n),this.tagIDs.splice(r,0,o),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop);}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==Te.HTML);this.shortenToLength(Math.max(n,0));}shortenToLength(t){for(;this.stackTop>=t;){let n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t);}}popUntilElementPopped(t){let n=this._indexOf(t);this.shortenToLength(Math.max(n,0));}popUntilPopped(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(o,0));}popUntilNumberedHeaderPopped(){this.popUntilPopped(QA,Te.HTML);}popUntilTableCellPopped(){this.popUntilPopped(s5e,Te.HTML);}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1);}_indexOfTagNames(t,n){for(let o=this.stackTop;o>=0;o--)if(t.has(this.tagIDs[o])&&this.treeAdapter.getNamespaceURI(this.items[o])===n)return o;return -1}clearBackTo(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(o+1);}clearBackToTableContext(){this.clearBackTo(i5e,Te.HTML);}clearBackToTableBodyContext(){this.clearBackTo(r5e,Te.HTML);}clearBackToTableRowContext(){this.clearBackTo(o5e,Te.HTML);}remove(t){let n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,false)));}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===b.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===b.HTML}hasInDynamicScope(t,n){for(let o=this.stackTop;o>=0;o--){let r=this.tagIDs[o];switch(this.treeAdapter.getNamespaceURI(this.items[o])){case Te.HTML:{if(r===t)return true;if(n.has(r))return false;break}case Te.SVG:{if(ade.has(r))return false;break}case Te.MATHML:{if(sde.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,gP)}hasInListItemScope(t){return this.hasInDynamicScope(t,t5e)}hasInButtonScope(t){return this.hasInDynamicScope(t,n5e)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Te.HTML:{if(QA.has(n))return true;if(gP.has(n))return false;break}case Te.SVG:{if(ade.has(n))return false;break}case Te.MATHML:{if(sde.has(n))return false;break}}}return true}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===Te.HTML)switch(this.tagIDs[n]){case t:return true;case b.TABLE:case b.HTML:return false}return true}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===Te.HTML)switch(this.tagIDs[t]){case b.TBODY:case b.THEAD:case b.TFOOT:return true;case b.TABLE:case b.HTML:return false}return true}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===Te.HTML)switch(this.tagIDs[n]){case t:return true;case b.OPTION:case b.OPTGROUP:break;default:return false}return true}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&lde.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&ide.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&ide.has(this.currentTagId);)this.pop();}};var bl;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(bl||(bl={}));var cde={type:bl.Marker},yP=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null;}_getNoahArkConditionCandidates(t,n){let o=[],r=n.length,i=this.treeAdapter.getTagName(t),s=this.treeAdapter.getNamespaceURI(t);for(let a=0;a<this.entries.length;a++){let l=this.entries[a];if(l.type===bl.Marker)break;let{element:c}=l;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===s){let d=this.treeAdapter.getAttrList(c);d.length===r&&o.push({idx:a,attrs:d});}}return o}_ensureNoahArkCondition(t){if(this.entries.length<3)return;let n=this.treeAdapter.getAttrList(t),o=this._getNoahArkConditionCandidates(t,n);if(o.length<3)return;let r=new Map(n.map(s=>[s.name,s.value])),i=0;for(let s=0;s<o.length;s++){let a=o[s];a.attrs.every(l=>r.get(l.name)===l.value)&&(i+=1,i>=3&&this.entries.splice(a.idx,1));}}insertMarker(){this.entries.unshift(cde);}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:bl.Element,element:t,token:n});}insertElementAfterBookmark(t,n){let o=this.entries.indexOf(this.bookmark);this.entries.splice(o,0,{type:bl.Element,element:t,token:n});}removeEntry(t){let n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1);}clearToLastMarker(){let t=this.entries.indexOf(cde);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let n=this.entries.find(o=>o.type===bl.Marker||this.treeAdapter.getTagName(o.element)===t);return n&&n.type===bl.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===bl.Element&&n.element===t)}};var Tl={createDocument(){return {nodeName:"#document",mode:Vi.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return {nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return {nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return {nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return {nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e;},insertBefore(e,t,n){let o=e.childNodes.indexOf(n);e.childNodes.splice(o,0,t),t.parentNode=e;},setTemplateContent(e,t){e.content=t;},getTemplateContent(e){return e.content},setDocumentType(e,t,n,o){let r=e.childNodes.find(i=>i.nodeName==="#documentType");if(r)r.name=t,r.publicId=n,r.systemId=o;else {let i={nodeName:"#documentType",name:t,publicId:n,systemId:o,parentNode:null};Tl.appendChild(e,i);}},setDocumentMode(e,t){e.mode=t;},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){let t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null;}},insertText(e,t){if(e.childNodes.length>0){let n=e.childNodes[e.childNodes.length-1];if(Tl.isTextNode(n)){n.value+=t;return}}Tl.appendChild(e,Tl.createTextNode(t));},insertTextBefore(e,t,n){let o=e.childNodes[e.childNodes.indexOf(n)-1];o&&Tl.isTextNode(o)?o.value+=t:Tl.insertBefore(e,Tl.createTextNode(t),n);},adoptAttributes(e,t){let n=new Set(e.attrs.map(o=>o.name));for(let o=0;o<t.length;o++)n.has(t[o].name)||e.attrs.push(t[o]);},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t;},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t};}};var ude="html",a5e="about:legacy-compat",l5e="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",pde=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],c5e=[...pde,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],d5e=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),mde=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],u5e=[...mde,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function dde(e,t){return t.some(n=>e.startsWith(n))}function hde(e){return e.name===ude&&e.publicId===null&&(e.systemId===null||e.systemId===a5e)}function gde(e){if(e.name!==ude)return Vi.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===l5e)return Vi.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),d5e.has(n))return Vi.QUIRKS;let o=t===null?c5e:pde;if(dde(n,o))return Vi.QUIRKS;if(o=t===null?mde:u5e,dde(n,o))return Vi.LIMITED_QUIRKS}return Vi.NO_QUIRKS}var fde={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},m5e="definitionurl",h5e="definitionURL",g5e=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),f5e=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Te.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Te.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Te.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Te.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Te.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Te.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Te.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Te.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Te.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Te.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Te.XMLNS}]]),y5e=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),S5e=new Set([b.B,b.BIG,b.BLOCKQUOTE,b.BODY,b.BR,b.CENTER,b.CODE,b.DD,b.DIV,b.DL,b.DT,b.EM,b.EMBED,b.H1,b.H2,b.H3,b.H4,b.H5,b.H6,b.HEAD,b.HR,b.I,b.IMG,b.LI,b.LISTING,b.MENU,b.META,b.NOBR,b.OL,b.P,b.PRE,b.RUBY,b.S,b.SMALL,b.SPAN,b.STRONG,b.STRIKE,b.SUB,b.SUP,b.TABLE,b.TT,b.U,b.UL,b.VAR]);function yde(e){let t=e.tagID;return t===b.FONT&&e.attrs.some(({name:o})=>o===Qd.COLOR||o===Qd.SIZE||o===Qd.FACE)||S5e.has(t)}function OH(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===m5e){e.attrs[t].name=h5e;break}}function MH(e){for(let t=0;t<e.attrs.length;t++){let n=g5e.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n);}}function SP(e){for(let t=0;t<e.attrs.length;t++){let n=f5e.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace);}}function Sde(e){let t=y5e.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=dh(e.tagName));}function b5e(e,t){return t===Te.MATHML&&(e===b.MI||e===b.MO||e===b.MN||e===b.MS||e===b.MTEXT)}function T5e(e,t,n){if(t===Te.MATHML&&e===b.ANNOTATION_XML){for(let o=0;o<n.length;o++)if(n[o].name===Qd.ENCODING){let r=n[o].value.toLowerCase();return r===fde.TEXT_HTML||r===fde.APPLICATION_XML}}return t===Te.SVG&&(e===b.FOREIGN_OBJECT||e===b.DESC||e===b.TITLE)}function bde(e,t,n,o){return (!o||o===Te.HTML)&&T5e(e,t,n)||(!o||o===Te.MATHML)&&b5e(e,t)}var A5e="hidden",E5e=8,C5e=3,j;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET";})(j||(j={}));var v5e={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},vde=new Set([b.TABLE,b.TBODY,b.TFOOT,b.THEAD,b.TR]),Ade={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:Tl,onParseError:null},lE=class{constructor(t,n,o=null,r=null){this.fragmentContext=o,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=j.INITIAL,this.originalInsertionMode=j.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=false,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=false,this.framesetOk=true,this.skipNextNewLine=false,this.fosterParentingEnabled=false,this.options={...Ade,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=true),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new eE(this.options,this),this.activeFormattingElements=new yP(this.treeAdapter),this.fragmentContextID=o?dh(this.treeAdapter.getTagName(o)):b.UNKNOWN,this._setContextModes(o??this.document,this.fragmentContextID),this.openElements=new fP(this.document,this.treeAdapter,this);}static parse(t,n){let o=new this(n);return o.tokenizer.write(t,true),o.document}static getFragmentParser(t,n){let o={...Ade,...n};t??(t=o.treeAdapter.createElement(ie.TEMPLATE,Te.HTML,[]));let r=o.treeAdapter.createElement("documentmock",Te.HTML,[]),i=new this(o,r,t);return i.fragmentContextID===b.TEMPLATE&&i.tmplInsertionModeStack.unshift(j.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,o){var r;if(!this.onParseError)return;let i=(r=t.location)!==null&&r!==void 0?r:v5e,s={code:n,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:o?i.startLine:i.endLine,endCol:o?i.startCol:i.endCol,endOffset:o?i.startOffset:i.endOffset};this.onParseError(s);}onItemPush(t,n,o){var r,i;(i=(r=this.treeAdapter).onItemPush)===null||i===void 0||i.call(r,t),o&&this.openElements.stackTop>0&&this._setContextModes(t,n);}onItemPop(t,n){var o,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(r=(o=this.treeAdapter).onItemPop)===null||r===void 0||r.call(o,t,this.openElements.current),n){let i,s;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,s=this.fragmentContextID):{current:i,currentTagId:s}=this.openElements,this._setContextModes(i,s);}}_setContextModes(t,n){let o=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===Te.HTML;this.currentNotInHTML=!o,this.tokenizer.inForeignNode=!o&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t);}_switchToTextParsing(t,n){this._insertElement(t,Te.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=j.TEXT;}switchToPlaintextParsing(){this.insertionMode=j.TEXT,this.originalInsertionMode=j.IN_BODY,this.tokenizer.state=mi.PLAINTEXT;}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===ie.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t);}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==Te.HTML))switch(this.fragmentContextID){case b.TITLE:case b.TEXTAREA:{this.tokenizer.state=mi.RCDATA;break}case b.STYLE:case b.XMP:case b.IFRAME:case b.NOEMBED:case b.NOFRAMES:case b.NOSCRIPT:{this.tokenizer.state=mi.RAWTEXT;break}case b.SCRIPT:{this.tokenizer.state=mi.SCRIPT_DATA;break}case b.PLAINTEXT:{this.tokenizer.state=mi.PLAINTEXT;break}}}_setDocumentType(t){let n=t.name||"",o=t.publicId||"",r=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,o,r),t.location){let s=this.treeAdapter.getChildNodes(this.document).find(a=>this.treeAdapter.isDocumentTypeNode(a));s&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){let o=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,o);}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else {let o=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(o??this.document,t);}}_appendElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location);}_insertElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location),this.openElements.push(o,t.tagID);}_insertFakeElement(t,n){let o=this.treeAdapter.createElement(t,Te.HTML,[]);this._attachElementToTree(o,null),this.openElements.push(o,n);}_insertTemplate(t){let n=this.treeAdapter.createElement(t.tagName,Te.HTML,t.attrs),o=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,o),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,null);}_insertFakeRootElement(){let t=this.treeAdapter.createElement(ie.HTML,Te.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,b.HTML);}_appendCommentNode(t,n){let o=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,o),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location);}_insertCharacters(t){let n,o;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:o}=this._findFosterParentingLocation(),o?this.treeAdapter.insertTextBefore(n,t.chars,o):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;let r=this.treeAdapter.getChildNodes(n),i=o?r.lastIndexOf(o):r.length,s=r[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(s)){let{endLine:l,endCol:c,endOffset:d}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(s,{endLine:l,endCol:c,endOffset:d});}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}_adoptNodes(t,n){for(let o=this.treeAdapter.getFirstChild(t);o;o=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(o),this.treeAdapter.appendChild(n,o);}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){let o=n.location,r=this.treeAdapter.getTagName(t),i=n.type===Kt.END_TAG&&r===n.tagName?{endTag:{...o},endLine:o.endLine,endCol:o.endCol,endOffset:o.endOffset}:{endLine:o.startLine,endCol:o.startCol,endOffset:o.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i);}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return false;let n,o;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,o=this.fragmentContextID):{current:n,currentTagId:o}=this.openElements,t.tagID===b.SVG&&this.treeAdapter.getTagName(n)===ie.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===Te.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===b.MGLYPH||t.tagID===b.MALIGNMARK)&&o!==void 0&&!this._isIntegrationPoint(o,n,Te.HTML)}_processToken(t){switch(t.type){case Kt.CHARACTER:{this.onCharacter(t);break}case Kt.NULL_CHARACTER:{this.onNullCharacter(t);break}case Kt.COMMENT:{this.onComment(t);break}case Kt.DOCTYPE:{this.onDoctype(t);break}case Kt.START_TAG:{this._processStartTag(t);break}case Kt.END_TAG:{this.onEndTag(t);break}case Kt.EOF:{this.onEof(t);break}case Kt.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,o){let r=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return bde(t,r,i,o)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let n=this.activeFormattingElements.entries.findIndex(r=>r.type===bl.Marker||this.openElements.contains(r.element)),o=n===-1?t-1:n-1;for(let r=o;r>=0;r--){let i=this.activeFormattingElements.entries[r];this._insertElement(i.token,this.treeAdapter.getNamespaceURI(i.element)),i.element=this.openElements.current;}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=j.IN_ROW;}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(b.P),this.openElements.popUntilTagNamePopped(b.P);}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case b.TR:{this.insertionMode=j.IN_ROW;return}case b.TBODY:case b.THEAD:case b.TFOOT:{this.insertionMode=j.IN_TABLE_BODY;return}case b.CAPTION:{this.insertionMode=j.IN_CAPTION;return}case b.COLGROUP:{this.insertionMode=j.IN_COLUMN_GROUP;return}case b.TABLE:{this.insertionMode=j.IN_TABLE;return}case b.BODY:{this.insertionMode=j.IN_BODY;return}case b.FRAMESET:{this.insertionMode=j.IN_FRAMESET;return}case b.SELECT:{this._resetInsertionModeForSelect(t);return}case b.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case b.HTML:{this.insertionMode=this.headElement?j.AFTER_HEAD:j.BEFORE_HEAD;return}case b.TD:case b.TH:{if(t>0){this.insertionMode=j.IN_CELL;return}break}case b.HEAD:{if(t>0){this.insertionMode=j.IN_HEAD;return}break}}this.insertionMode=j.IN_BODY;}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){let o=this.openElements.tagIDs[n];if(o===b.TEMPLATE)break;if(o===b.TABLE){this.insertionMode=j.IN_SELECT_IN_TABLE;return}}this.insertionMode=j.IN_SELECT;}_isElementCausesFosterParenting(t){return vde.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){let n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case b.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===Te.HTML)return {parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case b.TABLE:{let o=this.treeAdapter.getParentNode(n);return o?{parent:o,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return {parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t);}_isSpecialElement(t,n){let o=this.treeAdapter.getNamespaceURI(t);return tde[o].has(n)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){e6e(this,t);return}switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{oE(this,t);break}case j.BEFORE_HEAD:{rE(this,t);break}case j.IN_HEAD:{iE(this,t);break}case j.IN_HEAD_NO_SCRIPT:{sE(this,t);break}case j.AFTER_HEAD:{aE(this,t);break}case j.IN_BODY:case j.IN_CAPTION:case j.IN_CELL:case j.IN_TEMPLATE:{wde(this,t);break}case j.TEXT:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case j.IN_TABLE:case j.IN_TABLE_BODY:case j.IN_ROW:{NH(this,t);break}case j.IN_TABLE_TEXT:{Mde(this,t);break}case j.IN_COLUMN_GROUP:{TP(this,t);break}case j.AFTER_BODY:{AP(this,t);break}case j.AFTER_AFTER_BODY:{bP(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){ZZe(this,t);return}switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{oE(this,t);break}case j.BEFORE_HEAD:{rE(this,t);break}case j.IN_HEAD:{iE(this,t);break}case j.IN_HEAD_NO_SCRIPT:{sE(this,t);break}case j.AFTER_HEAD:{aE(this,t);break}case j.TEXT:{this._insertCharacters(t);break}case j.IN_TABLE:case j.IN_TABLE_BODY:case j.IN_ROW:{NH(this,t);break}case j.IN_COLUMN_GROUP:{TP(this,t);break}case j.AFTER_BODY:{AP(this,t);break}case j.AFTER_AFTER_BODY:{bP(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){LH(this,t);return}switch(this.insertionMode){case j.INITIAL:case j.BEFORE_HTML:case j.BEFORE_HEAD:case j.IN_HEAD:case j.IN_HEAD_NO_SCRIPT:case j.AFTER_HEAD:case j.IN_BODY:case j.IN_TABLE:case j.IN_CAPTION:case j.IN_COLUMN_GROUP:case j.IN_TABLE_BODY:case j.IN_ROW:case j.IN_CELL:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:case j.IN_TEMPLATE:case j.IN_FRAMESET:case j.AFTER_FRAMESET:{LH(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.AFTER_BODY:{O5e(this,t);break}case j.AFTER_AFTER_BODY:case j.AFTER_AFTER_FRAMESET:{M5e(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case j.INITIAL:{N5e(this,t);break}case j.BEFORE_HEAD:case j.IN_HEAD:case j.IN_HEAD_NO_SCRIPT:case j.AFTER_HEAD:{this._err(t,ce.misplacedDoctype);break}case j.IN_TABLE_TEXT:{nE(this,t);break}}}onStartTag(t){this.skipNextNewLine=false,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,ce.nonVoidHtmlElementStartTagWithTrailingSolidus);}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?t6e(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{L5e(this,t);break}case j.BEFORE_HEAD:{D5e(this,t);break}case j.IN_HEAD:{Al(this,t);break}case j.IN_HEAD_NO_SCRIPT:{U5e(this,t);break}case j.AFTER_HEAD:{G5e(this,t);break}case j.IN_BODY:{hi(this,t);break}case j.IN_TABLE:{_y(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.IN_CAPTION:{FZe(this,t);break}case j.IN_COLUMN_GROUP:{BH(this,t);break}case j.IN_TABLE_BODY:{vP(this,t);break}case j.IN_ROW:{RP(this,t);break}case j.IN_CELL:{HZe(this,t);break}case j.IN_SELECT:{kde(this,t);break}case j.IN_SELECT_IN_TABLE:{jZe(this,t);break}case j.IN_TEMPLATE:{VZe(this,t);break}case j.AFTER_BODY:{WZe(this,t);break}case j.IN_FRAMESET:{qZe(this,t);break}case j.AFTER_FRAMESET:{YZe(this,t);break}case j.AFTER_AFTER_BODY:{XZe(this,t);break}case j.AFTER_AFTER_FRAMESET:{QZe(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?n6e(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{k5e(this,t);break}case j.BEFORE_HEAD:{F5e(this,t);break}case j.IN_HEAD:{B5e(this,t);break}case j.IN_HEAD_NO_SCRIPT:{H5e(this,t);break}case j.AFTER_HEAD:{j5e(this,t);break}case j.IN_BODY:{CP(this,t);break}case j.TEXT:{IZe(this,t);break}case j.IN_TABLE:{cE(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.IN_CAPTION:{BZe(this,t);break}case j.IN_COLUMN_GROUP:{UZe(this,t);break}case j.IN_TABLE_BODY:{kH(this,t);break}case j.IN_ROW:{Lde(this,t);break}case j.IN_CELL:{GZe(this,t);break}case j.IN_SELECT:{Dde(this,t);break}case j.IN_SELECT_IN_TABLE:{$Ze(this,t);break}case j.IN_TEMPLATE:{zZe(this,t);break}case j.AFTER_BODY:{Bde(this,t);break}case j.IN_FRAMESET:{KZe(this,t);break}case j.AFTER_FRAMESET:{JZe(this,t);break}case j.AFTER_AFTER_BODY:{bP(this,t);break}}}onEof(t){switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{oE(this,t);break}case j.BEFORE_HEAD:{rE(this,t);break}case j.IN_HEAD:{iE(this,t);break}case j.IN_HEAD_NO_SCRIPT:{sE(this,t);break}case j.AFTER_HEAD:{aE(this,t);break}case j.IN_BODY:case j.IN_TABLE:case j.IN_CAPTION:case j.IN_COLUMN_GROUP:case j.IN_TABLE_BODY:case j.IN_ROW:case j.IN_CELL:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:{Pde(this,t);break}case j.TEXT:{xZe(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.IN_TEMPLATE:{Fde(this,t);break}case j.AFTER_BODY:case j.IN_FRAMESET:case j.AFTER_FRAMESET:case j.AFTER_AFTER_BODY:case j.AFTER_AFTER_FRAMESET:{FH(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===N.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1);}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case j.IN_HEAD:case j.IN_HEAD_NO_SCRIPT:case j.AFTER_HEAD:case j.TEXT:case j.IN_COLUMN_GROUP:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:case j.IN_FRAMESET:case j.AFTER_FRAMESET:{this._insertCharacters(t);break}case j.IN_BODY:case j.IN_CAPTION:case j.IN_CELL:case j.IN_TEMPLATE:case j.AFTER_BODY:case j.AFTER_AFTER_BODY:case j.AFTER_AFTER_FRAMESET:{Rde(this,t);break}case j.IN_TABLE:case j.IN_TABLE_BODY:case j.IN_ROW:{NH(this,t);break}case j.IN_TABLE_TEXT:{Ode(this,t);break}}}};function R5e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):_de(e,t),n}function w5e(e,t){let n=null,o=e.openElements.stackTop;for(;o>=0;o--){let r=e.openElements.items[o];if(r===t.element)break;e._isSpecialElement(r,e.openElements.tagIDs[o])&&(n=r);}return n||(e.openElements.shortenToLength(Math.max(o,0)),e.activeFormattingElements.removeEntry(t)),n}function I5e(e,t,n){let o=t,r=e.openElements.getCommonAncestor(t);for(let i=0,s=r;s!==n;i++,s=r){r=e.openElements.getCommonAncestor(s);let a=e.activeFormattingElements.getElementEntry(s),l=a&&i>=C5e;!a||l?(l&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(s)):(s=x5e(e,a),o===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(o),e.treeAdapter.appendChild(s,o),o=s);}return o}function x5e(e,t){let n=e.treeAdapter.getNamespaceURI(t.element),o=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,o),t.element=o,o}function _5e(e,t,n){let o=e.treeAdapter.getTagName(t),r=dh(o);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else {let i=e.treeAdapter.getNamespaceURI(t);r===b.TEMPLATE&&i===Te.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n);}}function P5e(e,t,n){let o=e.treeAdapter.getNamespaceURI(n.element),{token:r}=n,i=e.treeAdapter.createElement(r.tagName,o,r.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,r),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,r.tagID);}function DH(e,t){for(let n=0;n<E5e;n++){let o=R5e(e,t);if(!o)break;let r=w5e(e,o);if(!r)break;e.activeFormattingElements.bookmark=o;let i=I5e(e,r,o.element),s=e.openElements.getCommonAncestor(o.element);e.treeAdapter.detachNode(i),s&&_5e(e,s,i),P5e(e,r,o);}}function LH(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function O5e(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function M5e(e,t){e._appendCommentNode(t,e.document);}function FH(e,t){if(e.stopped=true,t.location){let n=e.fragmentContext?0:2;for(let o=e.openElements.stackTop;o>=n;o--)e._setEndLocation(e.openElements.items[o],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let o=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(o);if(r&&!r.endTag&&(e._setEndLocation(o,t),e.openElements.stackTop>=1)){let i=e.openElements.items[1],s=e.treeAdapter.getNodeSourceCodeLocation(i);s&&!s.endTag&&e._setEndLocation(i,t);}}}}function N5e(e,t){e._setDocumentType(t);let n=t.forceQuirks?Vi.QUIRKS:gde(t);hde(t)||e._err(t,ce.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=j.BEFORE_HTML;}function tE(e,t){e._err(t,ce.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,Vi.QUIRKS),e.insertionMode=j.BEFORE_HTML,e._processToken(t);}function L5e(e,t){t.tagID===b.HTML?(e._insertElement(t,Te.HTML),e.insertionMode=j.BEFORE_HEAD):oE(e,t);}function k5e(e,t){let n=t.tagID;(n===b.HTML||n===b.HEAD||n===b.BODY||n===b.BR)&&oE(e,t);}function oE(e,t){e._insertFakeRootElement(),e.insertionMode=j.BEFORE_HEAD,e._processToken(t);}function D5e(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.HEAD:{e._insertElement(t,Te.HTML),e.headElement=e.openElements.current,e.insertionMode=j.IN_HEAD;break}default:rE(e,t);}}function F5e(e,t){let n=t.tagID;n===b.HEAD||n===b.BODY||n===b.HTML||n===b.BR?rE(e,t):e._err(t,ce.endTagWithoutMatchingOpenElement);}function rE(e,t){e._insertFakeElement(ie.HEAD,b.HEAD),e.headElement=e.openElements.current,e.insertionMode=j.IN_HEAD,e._processToken(t);}function Al(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:{e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.TITLE:{e._switchToTextParsing(t,mi.RCDATA);break}case b.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,mi.RAWTEXT):(e._insertElement(t,Te.HTML),e.insertionMode=j.IN_HEAD_NO_SCRIPT);break}case b.NOFRAMES:case b.STYLE:{e._switchToTextParsing(t,mi.RAWTEXT);break}case b.SCRIPT:{e._switchToTextParsing(t,mi.SCRIPT_DATA);break}case b.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=j.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(j.IN_TEMPLATE);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:iE(e,t);}}function B5e(e,t){switch(t.tagID){case b.HEAD:{e.openElements.pop(),e.insertionMode=j.AFTER_HEAD;break}case b.BODY:case b.BR:case b.HTML:{iE(e,t);break}case b.TEMPLATE:{uh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function uh(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==b.TEMPLATE&&e._err(t,ce.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(b.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,ce.endTagWithoutMatchingOpenElement);}function iE(e,t){e.openElements.pop(),e.insertionMode=j.AFTER_HEAD,e._processToken(t);}function U5e(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.BASEFONT:case b.BGSOUND:case b.HEAD:case b.LINK:case b.META:case b.NOFRAMES:case b.STYLE:{Al(e,t);break}case b.NOSCRIPT:{e._err(t,ce.nestedNoscriptInHead);break}default:sE(e,t);}}function H5e(e,t){switch(t.tagID){case b.NOSCRIPT:{e.openElements.pop(),e.insertionMode=j.IN_HEAD;break}case b.BR:{sE(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function sE(e,t){let n=t.type===Kt.EOF?ce.openElementsLeftAfterEof:ce.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=j.IN_HEAD,e._processToken(t);}function G5e(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.BODY:{e._insertElement(t,Te.HTML),e.framesetOk=false,e.insertionMode=j.IN_BODY;break}case b.FRAMESET:{e._insertElement(t,Te.HTML),e.insertionMode=j.IN_FRAMESET;break}case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:case b.NOFRAMES:case b.SCRIPT:case b.STYLE:case b.TEMPLATE:case b.TITLE:{e._err(t,ce.abandonedHeadElementChild),e.openElements.push(e.headElement,b.HEAD),Al(e,t),e.openElements.remove(e.headElement);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:aE(e,t);}}function j5e(e,t){switch(t.tagID){case b.BODY:case b.HTML:case b.BR:{aE(e,t);break}case b.TEMPLATE:{uh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function aE(e,t){e._insertFakeElement(ie.BODY,b.BODY),e.insertionMode=j.IN_BODY,EP(e,t);}function EP(e,t){switch(t.type){case Kt.CHARACTER:{wde(e,t);break}case Kt.WHITESPACE_CHARACTER:{Rde(e,t);break}case Kt.COMMENT:{LH(e,t);break}case Kt.START_TAG:{hi(e,t);break}case Kt.END_TAG:{CP(e,t);break}case Kt.EOF:{Pde(e,t);break}}}function Rde(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function wde(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function $5e(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function V5e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(n,t.attrs));}function z5e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_FRAMESET);}function W5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML);}function q5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&QA.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Te.HTML);}function K5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function Y5e(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),n||(e.formElement=e.openElements.current));}function J5e(e,t){e.framesetOk=false;let n=t.tagID;for(let o=e.openElements.stackTop;o>=0;o--){let r=e.openElements.tagIDs[o];if(n===b.LI&&r===b.LI||(n===b.DD||n===b.DT)&&(r===b.DD||r===b.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==b.ADDRESS&&r!==b.DIV&&r!==b.P&&e._isSpecialElement(e.openElements.items[o],r))break}e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML);}function X5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),e.tokenizer.state=mi.PLAINTEXT;}function Q5e(e,t){e.openElements.hasInScope(b.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.framesetOk=false;}function Z5e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(ie.A);n&&(DH(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function eZe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function tZe(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(b.NOBR)&&(DH(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function nZe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function oZe(e,t){e.treeAdapter.getDocumentMode(e.document)!==Vi.QUIRKS&&e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),e.framesetOk=false,e.insertionMode=j.IN_TABLE;}function Ide(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Te.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function xde(e){let t=pP(e,Qd.TYPE);return t!=null&&t.toLowerCase()===A5e}function rZe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Te.HTML),xde(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function iZe(e,t){e._appendElement(t,Te.HTML),t.ackSelfClosing=true;}function sZe(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._appendElement(t,Te.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function aZe(e,t){t.tagName=ie.IMG,t.tagID=b.IMG,Ide(e,t);}function lZe(e,t){e._insertElement(t,Te.HTML),e.skipNextNewLine=true,e.tokenizer.state=mi.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=j.TEXT;}function cZe(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,mi.RAWTEXT);}function dZe(e,t){e.framesetOk=false,e._switchToTextParsing(t,mi.RAWTEXT);}function Ede(e,t){e._switchToTextParsing(t,mi.RAWTEXT);}function uZe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===j.IN_TABLE||e.insertionMode===j.IN_CAPTION||e.insertionMode===j.IN_TABLE_BODY||e.insertionMode===j.IN_ROW||e.insertionMode===j.IN_CELL?j.IN_SELECT_IN_TABLE:j.IN_SELECT;}function pZe(e,t){e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML);}function mZe(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Te.HTML);}function hZe(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(b.RTC),e._insertElement(t,Te.HTML);}function gZe(e,t){e._reconstructActiveFormattingElements(),OH(t),SP(t),t.selfClosing?e._appendElement(t,Te.MATHML):e._insertElement(t,Te.MATHML),t.ackSelfClosing=true;}function fZe(e,t){e._reconstructActiveFormattingElements(),MH(t),SP(t),t.selfClosing?e._appendElement(t,Te.SVG):e._insertElement(t,Te.SVG),t.ackSelfClosing=true;}function Cde(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML);}function hi(e,t){switch(t.tagID){case b.I:case b.S:case b.B:case b.U:case b.EM:case b.TT:case b.BIG:case b.CODE:case b.FONT:case b.SMALL:case b.STRIKE:case b.STRONG:{eZe(e,t);break}case b.A:{Z5e(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{q5e(e,t);break}case b.P:case b.DL:case b.OL:case b.UL:case b.DIV:case b.DIR:case b.NAV:case b.MAIN:case b.MENU:case b.ASIDE:case b.CENTER:case b.FIGURE:case b.FOOTER:case b.HEADER:case b.HGROUP:case b.DIALOG:case b.DETAILS:case b.ADDRESS:case b.ARTICLE:case b.SEARCH:case b.SECTION:case b.SUMMARY:case b.FIELDSET:case b.BLOCKQUOTE:case b.FIGCAPTION:{W5e(e,t);break}case b.LI:case b.DD:case b.DT:{J5e(e,t);break}case b.BR:case b.IMG:case b.WBR:case b.AREA:case b.EMBED:case b.KEYGEN:{Ide(e,t);break}case b.HR:{sZe(e,t);break}case b.RB:case b.RTC:{mZe(e,t);break}case b.RT:case b.RP:{hZe(e,t);break}case b.PRE:case b.LISTING:{K5e(e,t);break}case b.XMP:{cZe(e,t);break}case b.SVG:{fZe(e,t);break}case b.HTML:{$5e(e,t);break}case b.BASE:case b.LINK:case b.META:case b.STYLE:case b.TITLE:case b.SCRIPT:case b.BGSOUND:case b.BASEFONT:case b.TEMPLATE:{Al(e,t);break}case b.BODY:{V5e(e,t);break}case b.FORM:{Y5e(e,t);break}case b.NOBR:{tZe(e,t);break}case b.MATH:{gZe(e,t);break}case b.TABLE:{oZe(e,t);break}case b.INPUT:{rZe(e,t);break}case b.PARAM:case b.TRACK:case b.SOURCE:{iZe(e,t);break}case b.IMAGE:{aZe(e,t);break}case b.BUTTON:{Q5e(e,t);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{nZe(e,t);break}case b.IFRAME:{dZe(e,t);break}case b.SELECT:{uZe(e,t);break}case b.OPTION:case b.OPTGROUP:{pZe(e,t);break}case b.NOEMBED:case b.NOFRAMES:{Ede(e,t);break}case b.FRAMESET:{z5e(e,t);break}case b.TEXTAREA:{lZe(e,t);break}case b.NOSCRIPT:{e.options.scriptingEnabled?Ede(e,t):Cde(e,t);break}case b.PLAINTEXT:{X5e(e,t);break}case b.COL:case b.TH:case b.TD:case b.TR:case b.HEAD:case b.FRAME:case b.TBODY:case b.TFOOT:case b.THEAD:case b.CAPTION:case b.COLGROUP:break;default:Cde(e,t);}}function yZe(e,t){if(e.openElements.hasInScope(b.BODY)&&(e.insertionMode=j.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t);}}function SZe(e,t){e.openElements.hasInScope(b.BODY)&&(e.insertionMode=j.AFTER_BODY,Bde(e,t));}function bZe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n));}function TZe(e){let t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(b.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(b.FORM):n&&e.openElements.remove(n));}function AZe(e){e.openElements.hasInButtonScope(b.P)||e._insertFakeElement(ie.P,b.P),e._closePElement();}function EZe(e){e.openElements.hasInListItemScope(b.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(b.LI),e.openElements.popUntilTagNamePopped(b.LI));}function CZe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n));}function vZe(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function RZe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker());}function wZe(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(ie.BR,b.BR),e.openElements.pop(),e.framesetOk=false;}function _de(e,t){let n=t.tagName,o=t.tagID;for(let r=e.openElements.stackTop;r>0;r--){let i=e.openElements.items[r],s=e.openElements.tagIDs[r];if(o===s&&(o!==b.UNKNOWN||e.treeAdapter.getTagName(i)===n)){e.openElements.generateImpliedEndTagsWithExclusion(o),e.openElements.stackTop>=r&&e.openElements.shortenToLength(r);break}if(e._isSpecialElement(i,s))break}}function CP(e,t){switch(t.tagID){case b.A:case b.B:case b.I:case b.S:case b.U:case b.EM:case b.TT:case b.BIG:case b.CODE:case b.FONT:case b.NOBR:case b.SMALL:case b.STRIKE:case b.STRONG:{DH(e,t);break}case b.P:{AZe(e);break}case b.DL:case b.UL:case b.OL:case b.DIR:case b.DIV:case b.NAV:case b.PRE:case b.MAIN:case b.MENU:case b.ASIDE:case b.BUTTON:case b.CENTER:case b.FIGURE:case b.FOOTER:case b.HEADER:case b.HGROUP:case b.DIALOG:case b.ADDRESS:case b.ARTICLE:case b.DETAILS:case b.SEARCH:case b.SECTION:case b.SUMMARY:case b.LISTING:case b.FIELDSET:case b.BLOCKQUOTE:case b.FIGCAPTION:{bZe(e,t);break}case b.LI:{EZe(e);break}case b.DD:case b.DT:{CZe(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{vZe(e);break}case b.BR:{wZe(e);break}case b.BODY:{yZe(e,t);break}case b.HTML:{SZe(e,t);break}case b.FORM:{TZe(e);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{RZe(e,t);break}case b.TEMPLATE:{uh(e,t);break}default:_de(e,t);}}function Pde(e,t){e.tmplInsertionModeStack.length>0?Fde(e,t):FH(e,t);}function IZe(e,t){var n;t.tagID===b.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode;}function xZe(e,t){e._err(t,ce.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function NH(e,t){if(e.openElements.currentTagId!==void 0&&vde.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=j.IN_TABLE_TEXT,t.type){case Kt.CHARACTER:{Mde(e,t);break}case Kt.WHITESPACE_CHARACTER:{Ode(e,t);break}}else dE(e,t);}function _Ze(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_CAPTION;}function PZe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_COLUMN_GROUP;}function OZe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.COLGROUP,b.COLGROUP),e.insertionMode=j.IN_COLUMN_GROUP,BH(e,t);}function MZe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_TABLE_BODY;}function NZe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.TBODY,b.TBODY),e.insertionMode=j.IN_TABLE_BODY,vP(e,t);}function LZe(e,t){e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function kZe(e,t){xde(t)?e._appendElement(t,Te.HTML):dE(e,t),t.ackSelfClosing=true;}function DZe(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Te.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function _y(e,t){switch(t.tagID){case b.TD:case b.TH:case b.TR:{NZe(e,t);break}case b.STYLE:case b.SCRIPT:case b.TEMPLATE:{Al(e,t);break}case b.COL:{OZe(e,t);break}case b.FORM:{DZe(e,t);break}case b.TABLE:{LZe(e,t);break}case b.TBODY:case b.TFOOT:case b.THEAD:{MZe(e,t);break}case b.INPUT:{kZe(e,t);break}case b.CAPTION:{_Ze(e,t);break}case b.COLGROUP:{PZe(e,t);break}default:dE(e,t);}}function cE(e,t){switch(t.tagID){case b.TABLE:{e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode());break}case b.TEMPLATE:{uh(e,t);break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:case b.TBODY:case b.TD:case b.TFOOT:case b.TH:case b.THEAD:case b.TR:break;default:dE(e,t);}}function dE(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=true,EP(e,t),e.fosterParentingEnabled=n;}function Ode(e,t){e.pendingCharacterTokens.push(t);}function Mde(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function nE(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)dE(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var Nde=new Set([b.CAPTION,b.COL,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]);function FZe(e,t){let n=t.tagID;Nde.has(n)?e.openElements.hasInTableScope(b.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=j.IN_TABLE,_y(e,t)):hi(e,t);}function BZe(e,t){let n=t.tagID;switch(n){case b.CAPTION:case b.TABLE:{e.openElements.hasInTableScope(b.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=j.IN_TABLE,n===b.TABLE&&cE(e,t));break}case b.BODY:case b.COL:case b.COLGROUP:case b.HTML:case b.TBODY:case b.TD:case b.TFOOT:case b.TH:case b.THEAD:case b.TR:break;default:CP(e,t);}}function BH(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.COL:{e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.TEMPLATE:{Al(e,t);break}default:TP(e,t);}}function UZe(e,t){switch(t.tagID){case b.COLGROUP:{e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=j.IN_TABLE);break}case b.TEMPLATE:{uh(e,t);break}case b.COL:break;default:TP(e,t);}}function TP(e,t){e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=j.IN_TABLE,e._processToken(t));}function vP(e,t){switch(t.tagID){case b.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_ROW;break}case b.TH:case b.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(ie.TR,b.TR),e.insertionMode=j.IN_ROW,RP(e,t);break}case b.CAPTION:case b.COL:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE,_y(e,t));break}default:_y(e,t);}}function kH(e,t){let n=t.tagID;switch(t.tagID){case b.TBODY:case b.TFOOT:case b.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE);break}case b.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE,cE(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:case b.TD:case b.TH:case b.TR:break;default:cE(e,t);}}function RP(e,t){switch(t.tagID){case b.TH:case b.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_CELL,e.activeFormattingElements.insertMarker();break}case b.CAPTION:case b.COL:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:case b.TR:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY,vP(e,t));break}default:_y(e,t);}}function Lde(e,t){switch(t.tagID){case b.TR:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY);break}case b.TABLE:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY,kH(e,t));break}case b.TBODY:case b.TFOOT:case b.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(b.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY,kH(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:case b.TD:case b.TH:break;default:cE(e,t);}}function HZe(e,t){let n=t.tagID;Nde.has(n)?(e.openElements.hasInTableScope(b.TD)||e.openElements.hasInTableScope(b.TH))&&(e._closeTableCell(),RP(e,t)):hi(e,t);}function GZe(e,t){let n=t.tagID;switch(n){case b.TD:case b.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=j.IN_ROW);break}case b.TABLE:case b.TBODY:case b.TFOOT:case b.THEAD:case b.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),Lde(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:break;default:CP(e,t);}}function kde(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.OPTION:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._insertElement(t,Te.HTML);break}case b.OPTGROUP:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Te.HTML);break}case b.HR:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.INPUT:case b.KEYGEN:case b.TEXTAREA:case b.SELECT:{e.openElements.hasInSelectScope(b.SELECT)&&(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode(),t.tagID!==b.SELECT&&e._processStartTag(t));break}case b.SCRIPT:case b.TEMPLATE:{Al(e,t);break}}}function Dde(e,t){switch(t.tagID){case b.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===b.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===b.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop();break}case b.OPTION:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop();break}case b.SELECT:{e.openElements.hasInSelectScope(b.SELECT)&&(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode());break}case b.TEMPLATE:{uh(e,t);break}}}function jZe(e,t){let n=t.tagID;n===b.CAPTION||n===b.TABLE||n===b.TBODY||n===b.TFOOT||n===b.THEAD||n===b.TR||n===b.TD||n===b.TH?(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode(),e._processStartTag(t)):kde(e,t);}function $Ze(e,t){let n=t.tagID;n===b.CAPTION||n===b.TABLE||n===b.TBODY||n===b.TFOOT||n===b.THEAD||n===b.TR||n===b.TD||n===b.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Dde(e,t);}function VZe(e,t){switch(t.tagID){case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:case b.NOFRAMES:case b.SCRIPT:case b.STYLE:case b.TEMPLATE:case b.TITLE:{Al(e,t);break}case b.CAPTION:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:{e.tmplInsertionModeStack[0]=j.IN_TABLE,e.insertionMode=j.IN_TABLE,_y(e,t);break}case b.COL:{e.tmplInsertionModeStack[0]=j.IN_COLUMN_GROUP,e.insertionMode=j.IN_COLUMN_GROUP,BH(e,t);break}case b.TR:{e.tmplInsertionModeStack[0]=j.IN_TABLE_BODY,e.insertionMode=j.IN_TABLE_BODY,vP(e,t);break}case b.TD:case b.TH:{e.tmplInsertionModeStack[0]=j.IN_ROW,e.insertionMode=j.IN_ROW,RP(e,t);break}default:e.tmplInsertionModeStack[0]=j.IN_BODY,e.insertionMode=j.IN_BODY,hi(e,t);}}function zZe(e,t){t.tagID===b.TEMPLATE&&uh(e,t);}function Fde(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(b.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):FH(e,t);}function WZe(e,t){t.tagID===b.HTML?hi(e,t):AP(e,t);}function Bde(e,t){var n;if(t.tagID===b.HTML){if(e.fragmentContext||(e.insertionMode=j.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===b.HTML){e._setEndLocation(e.openElements.items[0],t);let o=e.openElements.items[1];o&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(o))===null||n===void 0)&&n.endTag)&&e._setEndLocation(o,t);}}else AP(e,t);}function AP(e,t){e.insertionMode=j.IN_BODY,EP(e,t);}function qZe(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.FRAMESET:{e._insertElement(t,Te.HTML);break}case b.FRAME:{e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.NOFRAMES:{Al(e,t);break}}}function KZe(e,t){t.tagID===b.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==b.FRAMESET&&(e.insertionMode=j.AFTER_FRAMESET));}function YZe(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.NOFRAMES:{Al(e,t);break}}}function JZe(e,t){t.tagID===b.HTML&&(e.insertionMode=j.AFTER_AFTER_FRAMESET);}function XZe(e,t){t.tagID===b.HTML?hi(e,t):bP(e,t);}function bP(e,t){e.insertionMode=j.IN_BODY,EP(e,t);}function QZe(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.NOFRAMES:{Al(e,t);break}}}function ZZe(e,t){t.chars=Gn,e._insertCharacters(t);}function e6e(e,t){e._insertCharacters(t),e.framesetOk=false;}function Ude(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Te.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function t6e(e,t){if(yde(t))Ude(e),e._startTagOutsideForeignContent(t);else {let n=e._getAdjustedCurrentElement(),o=e.treeAdapter.getNamespaceURI(n);o===Te.MATHML?OH(t):o===Te.SVG&&(Sde(t),MH(t)),SP(t),t.selfClosing?e._appendElement(t,o):e._insertElement(t,o),t.ackSelfClosing=true;}}function n6e(e,t){if(t.tagID===b.P||t.tagID===b.BR){Ude(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){let o=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(o)===Te.HTML){e._endTagOutsideForeignContent(t);break}let r=e.treeAdapter.getTagName(o);if(r.toLowerCase()===t.tagName){t.tagName=r,e.openElements.shortenToLength(n);break}}}new Set([ie.AREA,ie.BASE,ie.BASEFONT,ie.BGSOUND,ie.BR,ie.COL,ie.EMBED,ie.FRAME,ie.HR,ie.IMG,ie.INPUT,ie.KEYGEN,ie.LINK,ie.META,ie.PARAM,ie.SOURCE,ie.TRACK,ie.WBR]);function Hde(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);let o=lE.getFragmentParser(e,n);return o.tokenizer.write(t,true),o.getFragment()}var o6e=5e3,Gde=1024;function UH(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function r6e(e){return e.nodeName==="#text"}function HH(e,t){if(t.nodesLeft<=0)return;t.nodesLeft-=1;let n=e.tagName.toLowerCase(),o,r;for(let{name:l,value:c}of e.attrs){let d=l.toLowerCase();if(d==="role"){r=c;continue}o===void 0&&(o={}),o[d]=c;}let i,s=[];for(let l of e.childNodes){if(t.nodesLeft<=0)break;if(r6e(l)){let c=l.value;if(c&&c.trim().length>0){let d=c.length>Gde?c.slice(0,Gde):c;i=i===void 0?d:`${i} ${d}`;}}else if(UH(l)){let c=HH(l,t);c!==void 0&&s.push(c);}}let a={tag:n};return r!==void 0&&(a.role=r),o!==void 0&&(a.attributes=o),i!==void 0&&(a.text=i),s.length>0&&(a.children=s),a}function GH(e){let t=Hde(e),n={nodesLeft:o6e};for(let i of t.childNodes)if(UH(i)&&i.tagName.toLowerCase()==="body"){let s=HH(i,n);if(s!==void 0)return s}let o=[];for(let i of t.childNodes){if(n.nodesLeft<=0)break;if(UH(i)){let s=HH(i,n);s!==void 0&&o.push(s);}}let r={tag:"body"};return o.length>0&&(r.children=o),r}var i6e=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),ph=class{constructor(t,n,o,r,i,s){this.orgId=t;this.testId=n;this.testName=o;this.diskStorage=r;this.parentFlushResults=i;this.appGraphSink=s;}children=[];finished=false;stepFrequenciesByType={};currentResults=[];async getScreenshot(t,n){return this.diskStorage.readFile(`${Fr}/${n}.jpeg`)}async getHtmlSnapshot(t,n){return this.diskStorage.readFile(`${Fr}/${n}.html`)?.toString()}recordStepStat(t){t.type!=="PRESET_ACTION"?this.stepFrequenciesByType[t.type]=(this.stepFrequenciesByType[t.type]||0)+1:this.stepFrequenciesByType[t.command.type]=(this.stepFrequenciesByType[t.command.type]||0)+1;}sendFinalizedStepStats(){for(let[t,n]of Object.entries(this.stepFrequenciesByType))At.increment("test_step_execution",n,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}flushResults(t){this.currentResults=t,this.parentFlushResults(t);}async startStep(t,n){let{step:o,parentStepIdChain:r}=t;this.recordStepStat(o);let i={step:o,status:"RUNNING",startedAt:new Date},s=[...n];this.currentResults=s;let a=new jH(this.orgId,this.testId,this.testName,i,this.diskStorage,l=>{this.flushResults([...s,l]);},r??[],this.appGraphSink);return this.children.push(a),a}async finish(t){this.finished||(this.finished=true,await Promise.all(this.children.map(n=>n.finishInternal({status:kV(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function s6e(e){switch(e){case "SUCCESS":return "PASSED";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":return "RUNNING";case "IDLE":return "PENDING";default:return Je(e)}}function wP(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var jH=class{constructor(t,n,o,r,i,s,a,l){this.orgId=t;this.testId=n;this.testName=o;this.metadata=r;this.diskStorage=i;this.parentFlushResults=s;this.parentStepIdChain=a;this.appGraphSink=l;this.interactionTracer=new op(void 0,c=>this.storeTraceAsset(c)),np.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;attachBeforeScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.jpeg`,contents:o});}attachAfterScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.jpeg`,contents:o});}attachBeforeHtmlSnapshot(t){let{snapshotId:n,html:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.html`,contents:o});}attachAfterHtmlSnapshot(t){let{snapshotId:n,html:o,url:r,logger:i}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.html`,contents:o}),this.appGraphSink&&i6e.has(this.metadata.step.type)&&this.appGraphSink({html:o,url:r,stepId:this.metadata.step.id,parentStepIdChain:[...this.parentStepIdChain],logger:i});}recordTargetAutoHeal(t){let{healType:n}=t,o=n==="AI"?"ai-target-heal":"cache-heal";At.increment("test_event",1,[`name:${o}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:n,healedAt:new Date};}storeTraceAsset(t){this.diskStorage.storeFile({name:`${Fr}/${t.snapshotId}.${t.extension??"jpeg"}`,contents:t.data});}async finishInternal(t){this.finished||(this.finished=true,this.interactionTracer.finish(),await Promise.all(this.children.map(n=>n.finish({status:s6e(t.status),finishedAt:t.finishedAt}))));}recordStepDuration(t,n){if(!hv(t))return;let o=mv(t);At.distribution("test_step_duration",n,[`type:${o}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}async finish(t){!this.finished&&t.resolvedStep!==void 0&&t.durationMs!==void 0&&this.recordStepDuration(t.resolvedStep,t.durationMs),await this.finishInternal(t.step),t.step.trace=this.interactionTracer.getRootSpan();}getResultBuilderForCurrentStep(){let t=this.metadata.step;switch(t.type){case "RESOLVED_MODULE":return n=>({...t,status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n,type:"MODULE"});case "CONDITIONAL":return n=>({...t,blocks:t.blocks.map(r=>({assertion:r.assertion,steps:hd(r.steps)})),elseSteps:t.elseSteps?hd(t.elseSteps):void 0,status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "WHILE_LOOP":return n=>({...t,steps:hd(t.steps),status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "AI_ACTION":case "AI_ACTION_DYNAMIC":case "PRESET_ACTION":case "SECTION":return n=>({...t,status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});default:return Je(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),n=new ph(this.orgId,this.testId,this.testName,this.diskStorage,o=>{let r=t(o);this.parentFlushResults(r);});return this.children.push(n),n}};var IP=class{constructor(t,n,o,r,i,s,a,l){this.orgId=t;this.testId=n;this.testName=o;this.runAttemptId=r;this.metadata=i;this.diskStorage=s;this.recordVideo=a;this.progressHandle=l;this.diskStorage.mkdir(Fr),this.harPagesStream=this.diskStorage.createFileStream(`${Fr}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${Fr}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${Fr}/resource-usage.ndjson`),this.resourceUsageSampler=pY({keepSamples:false,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
8840
+ `)).digest("hex").slice(0,12),s=`${r.headSha}:${i}`,a=r.repoRoot,l=Jn__default.relative(a,e.repoRoot),c=l?e.candidateTests.map(p=>({...p,testPath:Jn__default.posix.join(l.split(Jn__default.sep).join("/"),p.testPath)})):e.candidateTests;if(e.dryRun){let p=await AH({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:a,projectRoot:e.repoRoot,diff:r,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:q_(a),agentOutputStream:e.agentOutputStream});return p.fallbackToRunAll?{kind:"run-all",reason:p.userSummary,diff:r}:{kind:"ready",plan:{version:2,userSummary:p.userSummary,toolCallCount:p.toolCallCount,selectedTests:p.selectedTests,anchorSegmentIds:p.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap??null},generatedAt:new Date().toISOString()},planId:`dry-run-${s}`,mode:"SELECTED",diff:r}}let d=await Tce({client:t,claim:{repository:e.repository,headSha:s,baseRef:r.baseRef,changedFiles:r.changedFiles.map(p=>p.path),diffSummary:null,budgetCap:e.budgetCap,dryRun:e.dryRun},logger:e.logger});if(d.kind==="ready")return e.logger.info({planId:d.planId,planSize:d.plan.selectedTests.length,suiteHash:i},"ai-select: reusing cached plan from server"),{kind:"ready",plan:d.plan,planId:d.planId,mode:"SELECTED",diff:r};let u=await AH({apiClient:t,generator:e.generator,logger:e.logger,repository:e.repository,repoRoot:a,projectRoot:e.repoRoot,diff:r,candidateTests:c,allTestDefinitions:e.allTestDefinitions,importIndexCachePath:q_(a),agentOutputStream:e.agentOutputStream});if(u.fallbackToRunAll)return await t.release(d.selectionPlanKey),{kind:"run-all",reason:u.userSummary,diff:r};try{e.logger.info({selectedCount:u.selectedTests.length,durationMs:u.totalDurationMs,suiteHash:i},"ai-select: computed fresh plan");let p=await t.finalize({selectionPlanKey:d.selectionPlanKey,repository:e.repository,headSha:s,mode:"SELECTED",userSummary:u.userSummary,toolCallCount:u.toolCallCount,selectedTests:u.selectedTests,anchorSegmentIds:u.anchorSegmentIds,budget:{source:e.budgetSource,cap:e.budgetCap}});return {kind:"ready",plan:p.plan,planId:p.planId,mode:"SELECTED",diff:r}}catch(p){return e.logger.error({err:p},"ai-select finalize failed; falling back to run-all"),await t.release(d.selectionPlanKey),{kind:"run-all",reason:`Could not record selection plan: ${X(p)}.`,diff:r}}}function lh(e){let t=e??rQe();return Ace()&&t===1&&R.warn("Running with --pixel-ratio=1 on a Retina screen. Viewport calculations may be incorrect; omit the flag to auto-detect."),t}function rQe(){let e=Ace(),t=e?2:1;return R.debug(`Auto-detected device pixel ratio ${t} (Mac OS Retina: ${e}).`),t}var Ace=once(()=>{if(platform()!=="darwin")return false;try{return execSync("system_profiler SPDisplaysDataType").toString().includes("Retina")}catch{return false}});async function tP(e,t=true,n=false){let o=lQe(e),r=await sQe.which(o[0],true),i=o.slice(1),s=iQe.exec(aQe(r),i,{delay:100,silent:n});if(t)return s}var Ece="the Momentic GitHub app is missing permission to create pull requests or write branches for this repository";function cQe(e,{context:t}){return e instanceof no?e.rawError.includes("Resource not accessible by integration")?`Cannot create ${t} because ${Ece}.`:e.status>=400&&e.status<500?e.rawError:`Could not create ${t} due to a GitHub error.`:`Could not create ${t}: ${X(e)}`}function Cce(e){return e instanceof no?e.rawError.includes("Resource not accessible by integration")?Ece:e.status>=400&&e.status<500?e.rawError:"a GitHub error occurred":X(e)}function vce(e,t){R.error(cQe(e,t));}function nP(e){return Rce(e,"runs","run")}function vH(e){return Rce(e,"run-groups","run group")}function Rce(e,t,n){let o=e.trim(),r=/^https?:\/\//i.test(o)?uQe(o,t,n):o;if(!z$1.guid().safeParse(r).success)throw new Error(`Invalid ${n} ID: ${e}. Expected a UUID or a URL like https://app.momentic.ai/${t}/<id>.`);return r}function uQe(e,t,n){let o;try{o=new URL(e);}catch{throw new Error(`Invalid ${n} URL: ${e}`)}let r=o.pathname.split("/").filter(i=>i.length>0);if(r.length!==2||r[0]!==t)throw new Error(`Could not extract ${n} ID from URL: ${e}. Expected a URL like https://app.momentic.ai/${t}/<id>.`);return r[1]}function oP(e){return new Promise((t,n)=>{let o=[];createReadStream(e).pipe(pQe()).on("data",r=>o.push(r)).on("end",()=>t(o)).on("error",r=>n(r));})}var Zt="3.16.3",{checkCLIVersion:Mr,getLatestCLIVersion:wce}=I6({packageName:"momentic",currentVersion:Zt,changelogUrl:"https://github.com/momentic-ai/cli/releases",updateCommand:"npx momentic@latest upgrade"});hDe("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI","POSTHOG_WEB_WRITE_KEY is not set");var{captureEvent:Xd,setAnalyticsIdentity:rP,shutdownAnalytics:Ice}=yv({writeKey:"phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",host:"https://p.momentic.ai",platform:"cli",identity:"stashed",flushImmediately:true,onIdentify:N6});async function lt(){try{await _e(Promise.all([gv(),At.flush(),Ice(),xv()]),{milliseconds:5e3});}catch{}}async function ch({tests:e,momenticFiles:t,project:n,yes:o,include:r,exclude:i,labels:s,logger:a}){let l=new Set;if(e&&e.length>0){let d=e.some(p=>Oo__default.existsSync(p)),u=cwd();d?(u!==n.rootDir&&a.warn(`Test paths resolve against the current directory ('${u}'), not the project root ('${n.rootDir}'). Run from the project root or use substring filters to avoid surprises.`),e.forEach(p=>{if(!Oo__default.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m;try{m=Oo__default.statSync(p).isDirectory();}catch(g){a.warn({err:g},`Skipping path ${p} because it cannot be read`);return}let h=Jn__default.resolve(p);Object.values(t.tests).filter(g=>m?g.fullFilePath.startsWith(h):g.fullFilePath===h).forEach(g=>{l.add(g.fullFilePath);});})):Object.values(t.tests).forEach(p=>{e.some(m=>p.relativePath.includes(m))&&l.add(p.fullFilePath);});}else !o&&!await sr("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1)),Object.values(t.tests).forEach(u=>{l.add(u.fullFilePath);});for(let d of l){let u=Jn__default.relative(n.rootDir,d);r&&!r.some(p=>new RegExp(p).test(u))&&l.delete(d),i&&i.some(p=>new RegExp(p).test(u))&&l.delete(d);}let c=Array.from(l).map(async d=>{try{let u=await rs(d,Ee,t);if(Ld.gt(u.schemaVersion,at)&&a.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),s&&s.length>0){let p=u.labels||[];if(!s.some(h=>p.includes(h)))return null}return {...u,fullFilePath:d,relativeFilePath:Jn__default.relative(n.rootDir,d)}}catch(u){a.error(`Failed to read and resolve test at '${d}': ${X(u)}`),process.exit(1);}});return compact(await Promise.all(c))}function _ce({testDefinitions:e,quarantinedTestsMetadata:t,onlyQuarantined:n=false,skipQuarantined:o=false}){let[r,i]=partition(e,l=>l.disabled),[s,a]=partition(i,l=>l.id in t);return {testsToSkip:r,quarantinedTestsToSkip:o?s:[],testsToRun:n?[]:a,quarantinedTestsToRun:o?[]:s}}function Pce({testsToRun:e,quarantinedTestsToRun:t,quarantinedTestsMetadata:n,testInputMatrix:o}){let r=[],i=(s,a,l)=>{o?o.forEach((c,d)=>{r.push({inputs:c,inputIndex:d,testDefinition:s,quarantined:a,quarantinedMetadata:l});}):r.push({inputs:void 0,testDefinition:s,quarantined:a,quarantinedMetadata:l});};return e.forEach(s=>i(s,false)),t.forEach(s=>i(s,true,n[s.id])),r}var Oce=()=>process.exit(130),Mce=()=>process.exit(143);process.on("SIGINT",Oce);process.on("SIGTERM",Mce);function JA(){process.off("SIGINT",Oce),process.off("SIGTERM",Mce);}async function Nce({orgId:e,codeEvalTools:t,logger:n,outputDefinitions:o,testContext:r}){let i={};for(let s of o){let{name:a,value:l}=s;i[a]=await li({orgId:e,s:l,localTools:t,logger:n,context:r});}return i}var Lce=new Set;async function kce({baseUrl:e,envName:t,devicePixelRatio:n,apiClient:o,test:r,storageClient:i,codeEvalTools:s,generator:a,orgId:l,variables:c,logger:d,customHeaders:u,testInputs:p,localBrowserConfig:m,aiSettings:h,visualDiffScreenshotStorage:g,tracer:f,runId:y,browserTypeOverride:S,attemptedRemoteBrowserProviders:T}){let E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:Ee,mode:o.mode,runner:o.runner},{controller:C,context:w}=await CA({baseUrl:e,envName:t,test:r,variables:c,logger:d,orgId:l,localBrowserConfig:m,aiSettings:h,customHeaders:u,codeEvalTools:s,storage:i,enricher:new Id(E,a),generator:a,visualDiffScreenshotStorage:g,devicePixelRatio:n,browserTypeOverride:S,callbacks:{onNetworkPage:x=>f.onNetworkPage(x),onNetworkLogs:x=>f.onNetworkLogs(x)},videoOptions:f.videoOutputPath?{videoOutputPath:f.videoOutputPath,onVideoPageChange:({videoName:x,timestamp:I})=>{f.setActiveVideo(x,I);}}:void 0,validateBrowserType:x=>{Ub(x)||(Ee.warn({browserType:x,testName:r.name},"Browser required by test does not appear to be installed"),!Lce.has(x)&&(Lce.add(x),R.warn(`Browser ${x} does not appear to be installed. Run '${cu(x)}' if you hit launch errors.`)));},createRemoteBrowserConnection:m.remoteBrowser?async()=>{let x=await o.createRemoteBrowserConnection({testId:r.id,testName:r.name,runId:y,attemptedProviders:T});return x.provider&&T?.push(x.provider),x}:void 0});try{await zx({orgId:l,test:r,testInputs:p,localTools:s,logger:d,context:w});}catch(x){try{await C.browser.cleanup();}catch(I){d.error({err:I},"Failed to clean up browser after test input resolution failed");}throw x instanceof vA&&(R.error(x.message),process.exit(1)),x}return {controller:C,context:w}}function Dce({testAdvancedSettings:e,orgSettings:t,logger:n}){if(e.failureRecovery===false||e.failureRecovery===void 0&&!t?.failureRecovery)return false;if(!nm){let o="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(o),R.debug(o),false}return true}async function Fce({attemptInputs:e,attemptFixtures:t,attemptMetadata:n,runFixtures:o,recordVideo:r,stepCallbacks:i}){let{orgId:s,userId:a,runId:l}=n,{runTracer:c,runGroupTracer:d,project:u,apiClient:p}=o,{controller:m,context:h,codeEvalTools:g,storageClient:f,logger:y,usageTracker:S,tracer:T}=t,{test:E,orgSettings:C}=e;y.info(`Running test '${E.name}' locally (run link: https://app.momentic.ai/runs/${l})`);let w={controller:m,storage:f,usageTracker:S,context:h,logger:y,codeEvalTools:g},x={orgId:s,userId:a,runId:l,testMetadata:E,steps:E.steps,beforeSteps:E.beforeSteps,afterSteps:E.afterSteps,orgSettings:C},I={collectDebugData:true,reinitializeBrowser:true,disableHealing:!await Dce({testAdvancedSettings:E.advanced,orgSettings:C.ai,logger:y})};return lre({fixtures:w,inputs:x,options:I,callbacks:{step:i??{},test:{onTestComplete:async _=>{await m.browser.cleanup({saveRemoteVideos:r!=="on-fail"||_?.status!=="PASSED"}),await g.dispose();}}},testParams:{attemptTracer:T},runParams:{runTracer:c,runGroupTracer:d,project:u,apiClient:p,captureEvent:Xd,abortSignal:o.abortSignal}})}async function Bce(e){let{testDefinition:t,logger:n}=e,o=new Date;try{return await TQe(e)}catch(r){wu(r);let{customHeaders:i,envName:s,testInputs:a,urlOverride:l}=e,c={customHeaders:i,envName:s,testInputs:a,urlOverride:l},d="Fatal error running test";return n.error({err:r},d),R.error({err:r},d),Uce({err:Fp(r),parameters:c,test:t,failureReason:te.reasonFor(r,"UnknownError"),startedAt:o,lastAttemptStartedAt:o,attempts:0,quarantined:e.quarantined,quarantinedMetadata:e.quarantinedMetadata})}}async function TQe(e){let{testDefinition:t,snapshot:n,project:o,apiClient:r,orgId:i,userId:s,urlOverride:a,runGroupTracer:l,logger:c,gitMetadata:d,cacheOptions:u,runId:p,testInputs:m,quarantined:h,quarantinedMetadata:g,usageTracker:f}=e,y=n?{...o.config,...n.metadata.config}:o.config,S=new wf(r,i),T=Pd({logger:c,orgId:i,client:r,gitMetadata:d,regenerateCache:u.regenerateCache,alwaysSaveCache:u.alwaysSaveCache,noCache:n?true:u.noCache,isolateCachesByEnvironment:o.config?.advanced?.isolateCachesByEnvironment,bustOldestCachePercentage:u.bustOldestCachePercentage}),E,C;n?(E={envName:n.metadata.environment.envName,resolvedEnv:n.metadata.environment.resolvedEnv,environmentVariables:{...n.metadata.environment.variables},baseUrl:n.metadata.environment.baseUrl},C={steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps}):(E=If({test:t,envNameOverride:e.envName,urlOverride:a,resolveEnv:ne=>Za(ne,o,c)}),C=await ga({cacheStorage:T,logger:c,schemaVersion:t.schemaVersion,stepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},testId:t.id,environment:E.envName,useSnapshotIdentityCache:o.config.fileFormat==="v2"}));let{envName:w,resolvedEnv:x,environmentVariables:I,baseUrl:v}=E,_=C.steps,P=C.beforeSteps??void 0,L=C.afterSteps??void 0,k=await l.startRun({logger:c,runId:p,originalSteps:{beforeSteps:t.beforeSteps,steps:t.steps,afterSteps:t.afterSteps},testId:t.id,testName:t.name,directory:dirname(t.relativeFilePath),testDescription:t.description??void 0,testLabels:t.labels,baseUrl:v,environmentName:w,schemaVersion:t.schemaVersion,resolvedInputs:m,quarantined:h,quarantinedReason:g?.quarantinedReason,aiSettings:y.ai}),V=c.child(k.loggerBindings||{});Object.entries(k.envVarBindings||{}).forEach(([ne,G])=>{I[ne]=G;});let re=await AQe({...e,effectiveConfig:y,variables:I,envName:w,resolvedEnv:x,baseUrl:v,storageClient:S,tracer:k,runGroupTracer:l,logger:V,cacheStorage:T,stepsWithCaches:_,beforeStepsWithCaches:P,afterStepsWithCaches:L,usageTracker:f});return await k.finish({logger:c,status:re.status,finishedAt:re.finishedAt,failureDetails:re.failureDetails,failureReason:re.failureReason,isFlake:re.isFlake,failureRecoveryDetails:re.failureRecoveryDetails}),{runId:k.runId,...re}}async function AQe(e){let{testDefinition:t,effectiveConfig:n,stepsWithCaches:o,beforeStepsWithCaches:r,afterStepsWithCaches:i,project:s,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:d,storageClient:u,orgId:p,userId:m,envName:h,urlOverride:g,customHeaders:f,testInputs:y,variables:S,resolvedEnv:T,retriesOverride:E,devicePixelRatio:C,logUpdate:w,tracer:x,runGroupTracer:I,logger:v,cacheStorage:_,gitMetadata:P,quarantined:L,quarantinedMetadata:k,usageTracker:V}=e,re=n,ne=re.ai?.aiFailureAnalysis??false,G=new Date,W=new hf(s,l,a),M={envName:h,urlOverride:g,customHeaders:f,testInputs:y},Y={...re.browser||{},...T?.browser||{},...t.advanced||{},...e.remoteBrowserOverride?{remoteBrowser:true}:{}},$=Y.remoteBrowser===true,B=[],Q,K=Math.abs(E??t.retries??n.retries??1),ve=[];v.info({...P,labels:t.labels,name:t.name,cwd:process.cwd()},"Starting test run using CLI");for(let pe=0;pe<=K;pe++){let Re=randomUUID(),Ye=await x.startAttempt(Re),me=v.child(Ye.loggerBindings||{}),se={...t,steps:cloneDeep(o),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)};pe!==0&&w("RETRY",`attempt ${pe+1}/${K+1}`);let Ie=new Date,Ke=new _d({httpClient:new Fi({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:me,mode:l.mode,runner:l.runner}),fakerSeed:re.advanced?.fakerConstantSeed?ib:void 0});try{let{controller:je,context:Ge}=await kce({tracer:Ye,runId:x.runId,baseUrl:d,envName:h,apiClient:l,devicePixelRatio:C,logger:me,storageClient:u,codeEvalTools:Ke,test:se,generator:c,orgId:p,variables:S,customHeaders:f,testInputs:y,localBrowserConfig:Y,browserTypeOverride:e.browserTypeOverride,attemptedRemoteBrowserProviders:B,aiSettings:{...re.ai||{},...se.advanced||{}},visualDiffScreenshotStorage:W});e.abortSignal&&(e.abortSignal.aborted?je.executeAbortController.abort():e.abortSignal.addEventListener("abort",()=>{je.executeAbortController.abort();},{once:!0})),Q=await Fce({attemptMetadata:{attemptNumber:pe+1,orgId:p,userId:m,runId:x.runId},attemptFixtures:{logger:me,storageClient:u,usageTracker:V,codeEvalTools:Ke,context:Ge,controller:je,tracer:Ye},attemptInputs:{test:se,orgSettings:re},runFixtures:{runTracer:x,runGroupTracer:I,project:s,apiClient:l,abortSignal:e.abortSignal},recordVideo:e.recordVideo??!1,stepCallbacks:{onStepStart:e.onStepStart}});let wt=new Date,dn={logger:v,cacheStorage:_,orgId:p,testId:t.id,environment:h,originalStepsWithCaches:{steps:cloneDeep(o),beforeSteps:cloneDeep(r),afterSteps:cloneDeep(i)},updatedStepsWithCaches:{steps:se.steps,beforeSteps:se.beforeSteps,afterSteps:se.afterSteps}};await um({logger:v,cacheStorage:_,orgId:p,testId:t.id,environment:h,stepLists:dn.updatedStepsWithCaches,useSnapshotIdentityCache:s.config.fileFormat==="v2"}),Q?.status==="PASSED"?await pm(dn):Q?.status==="FAILED"&&pe===K&&await Vg(dn),await Ye.finish({logger:me,result:Q}),ve.unshift(Q.status);let io=await Nce({orgId:p,codeEvalTools:Ke,logger:me,outputDefinitions:t.outputs??[],testContext:Ge}),Xs=EV(ve),gi=pe+1;if(Q.status!=="FAILED")return {...Q,runAttemptId:Re,parameters:M,test:se,filePath:se.relativeFilePath,startedAt:G,lastAttemptStartedAt:Ie,finishedAt:wt,attempts:gi,baseUrl:d,outputs:io,isFlake:Xs,quarantined:L,quarantinedMetadata:k,usedRemoteBrowser:$};let Wi=Q.failedStepResult,Mo=Wi?.message||"Unknown failure",jn=Wi?.failureReason??e$(Mo)??"UnknownError",fi=me.child({failureReason:jn,errorMessage:Mo,numAttempts:(K+1).toString(),name:se.name});if(pe<K){fi.warn(`Retrying failed execution attempt for run: ${Mo}`);continue}fi.error(`Test failed after all exhausting attempts: ${Mo}`);let Ho=new Error(Mo),gr={errorMessage:Mo,errorStack:Ho.stack},yi;if(re.ai?.classification?.enabled===!0){let $n=Wi?.failureClassification;$n||(e.onStepStart?.(Op),$n=await Ix({runTracer:x,runGroupTracer:I,outputDir:e.outputDir,orgId:p,project:s,generator:c,apiClient:l,logger:v,testPlatform:"web",aiSettings:re.ai,captureEvent:Xd,abortSignal:e.abortSignal,failedStepMessage:Wi?.message})),$n&&(yi=$n.classification.category,jn=$n.classification.category,gr.classification={reason:$n.classification.category,secondaryCategories:$n.classification.secondaryCategories,summary:$n.classification.reasoning,recoverable:$n.classification.recoverable,confidence:$n.classification.confidence,action:$n.action,citations:$n.classification.citations,source:"v2"});}else if(ne){let $n;try{if(Q.results&&Q.results.length>0){e.onStepStart?.(Op);let{classification:F,aiFailureReason:ye}=await WX({logger:me,browserStateStorage:Ye,generator:c,fullResults:Q,failureReason:jn,error:Ho,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});$n=F,yi=ye;}}catch(F){me.warn({err:F},"Failed to classify test results");}$n&&(gr.classification=$n,jn=yi??jn,gr.classification.source="v1");}return {...Q,runAttemptId:Re,parameters:M,failureDetails:gr,failureReason:jn,test:se,filePath:se.relativeFilePath,startedAt:G,lastAttemptStartedAt:Ie,finishedAt:wt,attempts:pe+1,baseUrl:d,outputs:io,quarantined:L,quarantinedMetadata:k,usedRemoteBrowser:$}}catch(je){let Ge=`Encountered fatal platform error while running test '${se.name}'`;return me.error({err:je},Ge),R.error({err:je},Ge),await Ye.finish({logger:me,result:{status:"FAILED"}}),Uce({err:Fp(je),parameters:M,test:se,failureReason:te.reasonFor(je,"InternalPlatformError"),startedAt:G,lastAttemptStartedAt:Ie,attempts:pe+1,quarantined:L,quarantinedMetadata:k,runAttemptId:Re,baseUrl:d,usedRemoteBrowser:$})}}throw new Error("This code should not be reachable")}function Uce({err:e,parameters:t,test:n,failureReason:o,startedAt:r,lastAttemptStartedAt:i,attempts:s,quarantined:a,quarantinedMetadata:l,runAttemptId:c,baseUrl:d,usedRemoteBrowser:u}){return {status:"FAILED",results:[],parameters:t,test:n,filePath:n.relativeFilePath,failureReason:o,failureDetails:{errorMessage:e.message,errorStack:e.stack},startedAt:r,lastAttemptStartedAt:i,finishedAt:new Date,attempts:s,outputs:{},quarantined:a,quarantinedMetadata:l,runAttemptId:c,baseUrl:d,usedRemoteBrowser:u}}var Hce=3e4;async function xy({timeoutMinutes:e,cancel:t,run:n}){let o=()=>void t("SIGINT received"),r=()=>void t("SIGTERM received");JA(),process.once("SIGINT",o),process.once("SIGTERM",r);let i;e!==void 0&&e>0&&(i=setTimeout(()=>void t(`Timeout of ${e} minute(s) reached`),e*60*1e3));try{return await n()}finally{process.off("SIGINT",o),process.off("SIGTERM",r),clearTimeout(i);}}var Iy=class{constructor(t){this.params=t;}runQueue={};runResults=[];cancelledRunsById=new Map;cancelled=false;cancellationReason;async cancel(t,n=true){if(this.cancelled)return;this.cancelled=true,this.cancellationReason=t;for(let r of Object.values(this.runQueue))r.done||r.abortController.abort();n&&await _e(Promise.allSettled(Object.values(this.runQueue).map(r=>r.promise)),{milliseconds:Hce}).catch(()=>{this.params.runGroupLogger.warn(`Graceful shutdown timeout of ${Hce}ms reached while waiting for running tests to settle.`);});let o=new Set(this.runResults.map(r=>r.runId).filter(r=>!!r));for(let r of Object.values(this.runQueue)){if(r.done||o.has(r.activeRun.runId))continue;let{activeRun:i}=r,s={results:[],beforeResults:[],afterResults:[],test:i.testDefinition,filePath:i.testDefinition.relativeFilePath,startedAt:i.startedAt,lastAttemptStartedAt:i.startedAt,finishedAt:new Date,status:"CANCELLED",attempts:0,runId:i.runId,cancellationReason:t,quarantined:i.quarantined,quarantinedMetadata:i.quarantinedMetadata,parameters:{testInputs:i.inputs,envName:this.params.envName,urlOverride:this.params.urlOverride,customHeaders:this.params.customHeaders},outputs:{}};this.cancelledRunsById.set(i.runId,s);}}resolveNext(){if(this.params.next)return this.params.next;let t=[...this.params.testsToRun??[]];return ()=>Promise.resolve(t.shift())}async run(){let t=this.resolveNext(),{parallel:n,reporter:o,runGroupTracer:r,runGroupLogger:i,logger:s,project:a,client:l,generator:c,orgId:d,userId:u,devicePixelRatio:p,outputDir:m,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:S,gitMetadata:T,cacheOptions:E,browserTypeOverride:C,remoteBrowserOverride:w,onResult:x,onFatal:I}=this.params,v=0,_=true;for(;_;){let P=Object.values(this.runQueue);if(P.length===n&&await Promise.race(P.map(ne=>ne.promise)),this.cancelled){_=false;continue}let L=await t();if(L===void 0){_=false;continue}let k=`test-${v++}`,V={...L,startedAt:new Date},re=new AbortController;this.runQueue[k]={done:false,activeRun:V,abortController:re,promise:(async({inputs:ne,quarantined:G,quarantinedMetadata:W,testDefinition:M,snapshot:Y,runId:$})=>{let B=M.relativeFilePath.includes("..")?M.fullFilePath:M.relativeFilePath;o.onTestBegin(B);let Q=i.child({testId:M.id,runId:$}),K=new gd({logger:Q,reporter:new wd(l),runType:"test-run",runId:$,testMetadata:M,suiteMetadata:void 0,runner:"test-runner"});try{let ve=await Bce({testDefinition:M,snapshot:Y,project:a,testInputs:ne,quarantined:G,quarantinedMetadata:W,orgId:d,userId:u,runId:$,devicePixelRatio:p,apiClient:l,runGroupTracer:r,outputDir:m,generator:c,retriesOverride:h,urlOverride:g,envName:f,customHeaders:y,regenerateGoldenFiles:S,logUpdate:(pe,Re)=>o.onTestStatus(B,pe,Re),...u6(o,B),logger:Q,gitMetadata:T,cacheOptions:E,usageTracker:K,browserTypeOverride:C,remoteBrowserOverride:w,recordVideo:this.params.recordVideo,abortSignal:re.signal});o.onTestEnd(B,ve.status,{recovered:ve.status==="PASSED"&&!!ve.failureRecoveryDetails?.attempts}),this.runResults.push(ve),x?.(ve);}catch(ve){let pe=`Encountered unexpected fatal error when running test '${M.name}'`;Q.error({err:ve},pe),R.error({err:ve},pe),wu(ve),I?.(ve),await this.cancel("Fatal error occurred",false);}finally{let ve=this.runQueue[k];ve&&(ve.done=true),await K.flush(s),delete this.runQueue[k];}})(V)};}return await Promise.allSettled(Object.values(this.runQueue).map(P=>P.promise)),{runResults:this.runResults,cancelledRunsById:this.cancelledRunsById,cancelled:this.cancelled,cancellationReason:this.cancellationReason}}};var CQe=200,vQe=new Set(qj),RQe=new Set(["PASSED","FAILED","CANCELLED"]);function jce(e){return e.length}function sP(e){return e.filter(t=>vQe.has(t.status)).length}var XA=class{constructor(t,n){this.sink=t;this.runId=n;}reportCompletedSteps(t){this.sink.updateRun(this.runId,{completedSteps:t});}setStatus(t){this.sink.updateRun(this.runId,{status:t});}},iP=class{constructor(t,n,o){this.runGroupId=n;this.logger=o;this.filePath=Jn__default.join(t,KK);}filePath;runs=new Map;startedAt=new Date;runGroupStatus="RUNNING";lastWriteMs=0;registerRun(t){let n=new Date;return this.runs.set(t.runId,{runId:t.runId,testId:t.testId,testName:t.testName,directory:t.directory,status:"RUNNING",completedSteps:0,totalSteps:t.totalSteps,startedAt:n,updatedAt:n}),this.write(true),new XA(this,t.runId)}updateRun(t,n){let o=this.runs.get(t);o&&(n.completedSteps!==void 0&&(o.completedSteps=n.completedSteps,o.completedSteps>o.totalSteps&&(o.totalSteps=o.completedSteps)),n.status!==void 0&&(o.status=n.status),o.updatedAt=new Date,this.write(n.status!==void 0));}finish(t){this.runGroupStatus=t,this.write(true);}write(t){let n=Date.now();if(!t&&n-this.lastWriteMs<CQe)return;this.lastWriteMs=n;let o=[...this.runs.values()],r={schemaVersion:YK,runGroupId:this.runGroupId,status:this.runGroupStatus,totalRuns:o.length,completedRuns:o.filter(s=>RQe.has(s.status)).length,completedSteps:o.reduce((s,a)=>s+a.completedSteps,0),totalSteps:o.reduce((s,a)=>s+a.totalSteps,0),startedAt:this.startedAt,updatedAt:new Date,runs:o},i=`${this.filePath}.tmp`;try{Oo__default.writeFileSync(i,JSON.stringify(r,null,2)),Oo__default.renameSync(i,this.filePath);}catch(s){this.logger.warn({err:s},"Failed to write run progress file");}}};function IH(e){return createHash("sha1").update(e).digest("hex")}var IQe=["tab","view","mode","step"],xQe=[/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i,/^(?=.*\d)[A-Za-z0-9_-]{16,256}$/,/^\d{3,32}$/,/^[0-9A-HJKMNP-TV-Z]{26}$/];function _Qe(e){return xQe.some(t=>t.test(e))}function $ce(e,t={}){let n;try{n=new URL(e);}catch{return e}let o=new Set(t.queryAllowlist??IQe),i=n.pathname.split("/").map(c=>c.length>0&&_Qe(c)?"{id}":c).join("/"),s=[],a=Array.from(n.searchParams.keys()).sort();for(let c of a){if(!o.has(c))continue;let d=n.searchParams.getAll(c).sort();for(let u of d)s.push(`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);}let l=s.length>0?`?${s.join("&")}`:"";return `${n.protocol}//${n.host}${i}${l}`}var PQe=new Set(["id","name","role","type","href","for","placeholder","aria-label","data-testid"]),OQe=/^[A-Za-z0-9_-]{16,256}$|^:r[0-9a-z]{1,32}:$/,MQe=[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,/\b[0-9a-f]{12,64}\b/gi,/\b[0-9A-HJKMNP-TV-Z]{26}\b/g,/\b\d{5,}\b/g,/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,16}\b/g],Vce=new Set(["h1","h2","h3","h4","h5","h6"]),NQe=new Set(["input","select","textarea"]);function LQe(e){let t=e;for(let n of MQe)t=t.replace(n,"{id}");return t}function zce(e){return LQe(e).toLowerCase().replace(/\s+/g," ").trim().replace(/[.,:;!?]+$/u,"").replace(/\s*\d+\s*$/u,"").trim()}function kQe(e){let t=e.length;return t<=4?"txt:xs":t<=16?"txt:s":t<=64?"txt:m":t<=256?"txt:l":"txt:xl"}function DQe(e,t){return e==="href"?t.startsWith("#")?"href:hash":t.startsWith("/")?"href:rel":/^https?:\/\//.test(t)?"href:abs":/^(mailto|tel):/.test(t)?`href:${t.split(":")[0]}`:"href:other":OQe.test(t)?"@gen":zce(t)}function Wce(e,t,n){let o=e.tag.toLowerCase(),r=(e.role??e.attributes?.role)?.toLowerCase(),i=Math.min(Math.floor(t/4),6),s=`<${o}@${i}`;if(r!==void 0&&(s+=` role=${r}`),e.attributes!==void 0){let l=Object.keys(e.attributes).filter(c=>PQe.has(c.toLowerCase())).sort();for(let c of l){let d=c.toLowerCase();if(d==="role")continue;let u=e.attributes[c];if(u===void 0)continue;let p=DQe(d,u);s+=` ${d}=${p}`;}}n.tokens.push(s);let a=e.text?.trim();a!==void 0&&a.length>0&&(r==="button"||r==="link"||r==="heading"||o==="button"||o==="a"||o==="label"||Vce.has(o)?n.tokens.push(`label=${zce(a)}`):n.tokens.push(kQe(a))),(o==="button"||r==="button")&&(n.counts.buttons+=1),(o==="a"||r==="link")&&(n.counts.links+=1),(NQe.has(o)||r==="textbox"||r==="combobox")&&(n.counts.formFields+=1),(Vce.has(o)||r==="heading")&&(n.counts.headings+=1);for(let l of e.children??[])Wce(l,t+1,n);}function qce(e){let t={tokens:[],counts:{buttons:0,links:0,formFields:0,headings:0}};return Wce(e,0,t),{tokens:t.tokens,counts:t.counts}}function Kce(e,t){let n=new TextEncoder().encode(e),o=n.length,r=Math.floor(o/4),i=t>>>0,s=3432918353,a=461845907;for(let u=0;u<r;u++){let p=u*4,m=n[p]|n[p+1]<<8|n[p+2]<<16|n[p+3]<<24;m=Math.imul(m,s),m=m<<15|m>>>17,m=Math.imul(m,a),i^=m,i=i<<13|i>>>19,i=Math.imul(i,5)+3864292196;}let l=0,c=o&3,d=r*4;return c===3&&(l^=n[d+2]<<16),c>=2&&(l^=n[d+1]<<8),c>=1&&(l^=n[d],l=Math.imul(l,s),l=l<<15|l>>>17,l=Math.imul(l,a),i^=l),i^=o,i^=i>>>16,i=Math.imul(i,2246822507),i^=i>>>13,i=Math.imul(i,3266489909),i^=i>>>16,i>>>0}var aP=128,FQe=4294967295,BQe=(()=>{let e=[];for(let t=0;t<aP;t++)e.push(Kce(`perm:${t}`,0));return e})();function Yce(e){let t=new Uint32Array(aP);for(let o=0;o<aP;o++)t[o]=FQe;let n=new Set(e);for(let o of n)for(let r=0;r<aP;r++){let i=Kce(o,BQe[r]);i<t[r]&&(t[r]=i);}return t}var HQe=32;function xH(e){let t=$ce(e.url,{queryAllowlist:e.queryAllowlist}),{tokens:n,counts:o}=qce(e.dom),r=[`url:${t}`,`counts:buttons=${o.buttons}`,`counts:links=${o.links}`,`counts:formFields=${o.formFields}`,`counts:headings=${o.headings}`,...n],i=Yce(r),s=Buffer.from(i.buffer,i.byteOffset,i.byteLength);return {fingerprintHash:createHash$1("sha256").update(s).digest("hex").slice(0,HQe),minhash:Array.from(i),canonicalUrl:t}}var GQe=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),Gn="\uFFFD",N;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z";})(N||(N={}));var $i={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function lP(e){return e>=55296&&e<=57343}function Jce(e){return e>=56320&&e<=57343}function Xce(e,t){return (e-55296)*1024+9216+t}function cP(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function dP(e){return e>=64976&&e<=65007||GQe.has(e)}var ce;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text";})(ce||(ce={}));var $Qe=65536,uP=class{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=false,this.lastChunkWritten=false,this.endOfChunkHit=false,this.bufferWaterline=$Qe,this.isEol=false,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1;}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){let{line:o,col:r,offset:i}=this,s=r+n,a=i+n;return {code:t,startLine:o,endLine:o,startCol:s,endCol:s,startOffset:a,endOffset:a}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)));}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos;}_processSurrogate(t){if(this.pos!==this.html.length-1){let n=this.html.charCodeAt(this.pos+1);if(Jce(n))return this.pos++,this._addGap(),Xce(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=true,N.EOF;return this._err(ce.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0);}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=false,this.lastChunkWritten=n;}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=false;}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,false;if(n)return this.html.startsWith(t,this.pos);for(let o=0;o<t.length;o++)if((this.html.charCodeAt(this.pos+o)|32)!==t.charCodeAt(o))return false;return true}peek(t){let n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,N.EOF;let o=this.html.charCodeAt(n);return o===N.CARRIAGE_RETURN?N.LINE_FEED:o}advance(){if(this.pos++,this.isEol&&(this.isEol=false,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,N.EOF;let t=this.html.charCodeAt(this.pos);return t===N.CARRIAGE_RETURN?(this.isEol=true,this.skipNextNewLine=true,N.LINE_FEED):t===N.LINE_FEED&&(this.isEol=true,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=false,this._addGap(),this.advance()):(this.skipNextNewLine=false,lP(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===N.LINE_FEED||t===N.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){cP(t)?this._err(ce.controlCharacterInInputStream):dP(t)&&this._err(ce.noncharacterInInputStream);}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=false;}};var Kt;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION";})(Kt||(Kt={}));function pP(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}var zQe=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function Qce(e){return e>=55296&&e<=57343||e>1114111?65533:zQe.get(e)??e}function Zce(e){let t=atob(e),n=t.length&-2,o=new Uint16Array(n/2);for(let r=0,i=0;r<n;r+=2){let s=t.charCodeAt(r),a=t.charCodeAt(r+1);o[i++]=s|a<<8;}return o}var _H=Zce("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var pi;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE";})(pi||(pi={}));var bo;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z";})(bo||(bo={}));var ede=32;function PH(e){return e>=bo.ZERO&&e<=bo.NINE}function WQe(e){return e>=bo.UPPER_A&&e<=bo.UPPER_F||e>=bo.LOWER_A&&e<=bo.LOWER_F}function qQe(e){return e>=bo.UPPER_A&&e<=bo.UPPER_Z||e>=bo.LOWER_A&&e<=bo.LOWER_Z||PH(e)}function KQe(e){return e===bo.EQUALS||qQe(e)}var Nr;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity";})(Nr||(Nr={}));var Bc;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute";})(Bc||(Bc={}));var mP=class{decodeTree;emitCodePoint;errors;constructor(t,n,o){this.decodeTree=t,this.emitCodePoint=n,this.errors=o;}state=Nr.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Bc.Strict;runConsumed=0;startEntity(t){this.decodeMode=t,this.state=Nr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0;}write(t,n){switch(this.state){case Nr.EntityStart:return t.charCodeAt(n)===bo.NUM?(this.state=Nr.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Nr.NamedEntity,this.stateNamedEntity(t,n));case Nr.NumericStart:return this.stateNumericStart(t,n);case Nr.NumericDecimal:return this.stateNumericDecimal(t,n);case Nr.NumericHex:return this.stateNumericHex(t,n);case Nr.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|ede)===bo.LOWER_X?(this.state=Nr.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Nr.NumericDecimal,this.stateNumericDecimal(t,n))}stateNumericHex(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(PH(o)||WQe(o)){let r=o<=bo.NINE?o-bo.ZERO:(o|ede)-bo.LOWER_A+10;this.result=this.result*16+r,this.consumed++,n++;}else return this.emitNumericEntity(o,3)}return -1}stateNumericDecimal(t,n){for(;n<t.length;){let o=t.charCodeAt(n);if(PH(o))this.result=this.result*10+(o-bo.ZERO),this.consumed++,n++;else return this.emitNumericEntity(o,2)}return -1}emitNumericEntity(t,n){if(this.consumed<=n)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===bo.SEMI)this.consumed+=1;else if(this.decodeMode===Bc.Strict)return 0;return this.emitCodePoint(Qce(this.result),this.consumed),this.errors&&(t!==bo.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){let{decodeTree:o}=this,r=o[this.treeIndex],i=(r&pi.VALUE_LENGTH)>>14;for(;n<t.length;){if(i===0&&r&pi.FLAG13){let a=(r&pi.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let l=r&pi.JUMP_TABLE;if(t.charCodeAt(n)!==l)return this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}for(;this.runConsumed<a;){if(n>=t.length)return -1;let l=this.runConsumed-1,c=o[this.treeIndex+1+(l>>1)],d=l%2===0?c&255:c>>8&255;if(t.charCodeAt(n)!==d)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();n++,this.excess++,this.runConsumed++;}this.runConsumed=0,this.treeIndex+=1+(a>>1),r=o[this.treeIndex],i=(r&pi.VALUE_LENGTH)>>14;}if(n>=t.length)break;let s=t.charCodeAt(n);if(s===bo.SEMI&&i!==0&&r&pi.FLAG13)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=YQe(o,r,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Bc.Attribute&&(i===0||KQe(s))?0:this.emitNotTerminatedNamedEntity();if(r=o[this.treeIndex],i=(r&pi.VALUE_LENGTH)>>14,i!==0){if(s===bo.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==Bc.Strict&&!(r&pi.FLAG13)&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}n++,this.excess++;}return -1}emitNotTerminatedNamedEntity(){let{result:t,decodeTree:n}=this,o=(n[t]&pi.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,o,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,o){let{decodeTree:r}=this;return this.emitCodePoint(n===1?r[t]&~(pi.VALUE_LENGTH|pi.FLAG13):r[t+1],o),n===3&&this.emitCodePoint(r[t+2],o),o}end(){switch(this.state){case Nr.NamedEntity:return this.result!==0&&(this.decodeMode!==Bc.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Nr.NumericDecimal:return this.emitNumericEntity(0,2);case Nr.NumericHex:return this.emitNumericEntity(0,3);case Nr.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Nr.EntityStart:return 0}}};function YQe(e,t,n,o){let r=(t&pi.BRANCH_LENGTH)>>7,i=t&pi.JUMP_TABLE;if(r===0)return i!==0&&o===i?n:-1;if(i){let c=o-i;return c<0||c>=r?-1:e[n+c]-1}let s=r+1>>1,a=0,l=r-1;for(;a<=l;){let c=a+l>>>1,d=c>>1,p=e[n+d]>>(c&1)*8&255;if(p<o)a=c+1;else if(p>o)l=c-1;else return e[n+s+c]}return -1}var Te;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/";})(Te||(Te={}));var Qd;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size";})(Qd||(Qd={}));var Vi;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks";})(Vi||(Vi={}));var ie;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp";})(ie||(ie={}));var b;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP";})(b||(b={}));var JQe=new Map([[ie.A,b.A],[ie.ADDRESS,b.ADDRESS],[ie.ANNOTATION_XML,b.ANNOTATION_XML],[ie.APPLET,b.APPLET],[ie.AREA,b.AREA],[ie.ARTICLE,b.ARTICLE],[ie.ASIDE,b.ASIDE],[ie.B,b.B],[ie.BASE,b.BASE],[ie.BASEFONT,b.BASEFONT],[ie.BGSOUND,b.BGSOUND],[ie.BIG,b.BIG],[ie.BLOCKQUOTE,b.BLOCKQUOTE],[ie.BODY,b.BODY],[ie.BR,b.BR],[ie.BUTTON,b.BUTTON],[ie.CAPTION,b.CAPTION],[ie.CENTER,b.CENTER],[ie.CODE,b.CODE],[ie.COL,b.COL],[ie.COLGROUP,b.COLGROUP],[ie.DD,b.DD],[ie.DESC,b.DESC],[ie.DETAILS,b.DETAILS],[ie.DIALOG,b.DIALOG],[ie.DIR,b.DIR],[ie.DIV,b.DIV],[ie.DL,b.DL],[ie.DT,b.DT],[ie.EM,b.EM],[ie.EMBED,b.EMBED],[ie.FIELDSET,b.FIELDSET],[ie.FIGCAPTION,b.FIGCAPTION],[ie.FIGURE,b.FIGURE],[ie.FONT,b.FONT],[ie.FOOTER,b.FOOTER],[ie.FOREIGN_OBJECT,b.FOREIGN_OBJECT],[ie.FORM,b.FORM],[ie.FRAME,b.FRAME],[ie.FRAMESET,b.FRAMESET],[ie.H1,b.H1],[ie.H2,b.H2],[ie.H3,b.H3],[ie.H4,b.H4],[ie.H5,b.H5],[ie.H6,b.H6],[ie.HEAD,b.HEAD],[ie.HEADER,b.HEADER],[ie.HGROUP,b.HGROUP],[ie.HR,b.HR],[ie.HTML,b.HTML],[ie.I,b.I],[ie.IMG,b.IMG],[ie.IMAGE,b.IMAGE],[ie.INPUT,b.INPUT],[ie.IFRAME,b.IFRAME],[ie.KEYGEN,b.KEYGEN],[ie.LABEL,b.LABEL],[ie.LI,b.LI],[ie.LINK,b.LINK],[ie.LISTING,b.LISTING],[ie.MAIN,b.MAIN],[ie.MALIGNMARK,b.MALIGNMARK],[ie.MARQUEE,b.MARQUEE],[ie.MATH,b.MATH],[ie.MENU,b.MENU],[ie.META,b.META],[ie.MGLYPH,b.MGLYPH],[ie.MI,b.MI],[ie.MO,b.MO],[ie.MN,b.MN],[ie.MS,b.MS],[ie.MTEXT,b.MTEXT],[ie.NAV,b.NAV],[ie.NOBR,b.NOBR],[ie.NOFRAMES,b.NOFRAMES],[ie.NOEMBED,b.NOEMBED],[ie.NOSCRIPT,b.NOSCRIPT],[ie.OBJECT,b.OBJECT],[ie.OL,b.OL],[ie.OPTGROUP,b.OPTGROUP],[ie.OPTION,b.OPTION],[ie.P,b.P],[ie.PARAM,b.PARAM],[ie.PLAINTEXT,b.PLAINTEXT],[ie.PRE,b.PRE],[ie.RB,b.RB],[ie.RP,b.RP],[ie.RT,b.RT],[ie.RTC,b.RTC],[ie.RUBY,b.RUBY],[ie.S,b.S],[ie.SCRIPT,b.SCRIPT],[ie.SEARCH,b.SEARCH],[ie.SECTION,b.SECTION],[ie.SELECT,b.SELECT],[ie.SOURCE,b.SOURCE],[ie.SMALL,b.SMALL],[ie.SPAN,b.SPAN],[ie.STRIKE,b.STRIKE],[ie.STRONG,b.STRONG],[ie.STYLE,b.STYLE],[ie.SUB,b.SUB],[ie.SUMMARY,b.SUMMARY],[ie.SUP,b.SUP],[ie.TABLE,b.TABLE],[ie.TBODY,b.TBODY],[ie.TEMPLATE,b.TEMPLATE],[ie.TEXTAREA,b.TEXTAREA],[ie.TFOOT,b.TFOOT],[ie.TD,b.TD],[ie.TH,b.TH],[ie.THEAD,b.THEAD],[ie.TITLE,b.TITLE],[ie.TR,b.TR],[ie.TRACK,b.TRACK],[ie.TT,b.TT],[ie.U,b.U],[ie.UL,b.UL],[ie.SVG,b.SVG],[ie.VAR,b.VAR],[ie.WBR,b.WBR],[ie.XMP,b.XMP]]);function dh(e){var t;return (t=JQe.get(e))!==null&&t!==void 0?t:b.UNKNOWN}var Pe=b,tde={[Te.HTML]:new Set([Pe.ADDRESS,Pe.APPLET,Pe.AREA,Pe.ARTICLE,Pe.ASIDE,Pe.BASE,Pe.BASEFONT,Pe.BGSOUND,Pe.BLOCKQUOTE,Pe.BODY,Pe.BR,Pe.BUTTON,Pe.CAPTION,Pe.CENTER,Pe.COL,Pe.COLGROUP,Pe.DD,Pe.DETAILS,Pe.DIR,Pe.DIV,Pe.DL,Pe.DT,Pe.EMBED,Pe.FIELDSET,Pe.FIGCAPTION,Pe.FIGURE,Pe.FOOTER,Pe.FORM,Pe.FRAME,Pe.FRAMESET,Pe.H1,Pe.H2,Pe.H3,Pe.H4,Pe.H5,Pe.H6,Pe.HEAD,Pe.HEADER,Pe.HGROUP,Pe.HR,Pe.HTML,Pe.IFRAME,Pe.IMG,Pe.INPUT,Pe.LI,Pe.LINK,Pe.LISTING,Pe.MAIN,Pe.MARQUEE,Pe.MENU,Pe.META,Pe.NAV,Pe.NOEMBED,Pe.NOFRAMES,Pe.NOSCRIPT,Pe.OBJECT,Pe.OL,Pe.P,Pe.PARAM,Pe.PLAINTEXT,Pe.PRE,Pe.SCRIPT,Pe.SECTION,Pe.SELECT,Pe.SOURCE,Pe.STYLE,Pe.SUMMARY,Pe.TABLE,Pe.TBODY,Pe.TD,Pe.TEMPLATE,Pe.TEXTAREA,Pe.TFOOT,Pe.TH,Pe.THEAD,Pe.TITLE,Pe.TR,Pe.TRACK,Pe.UL,Pe.WBR,Pe.XMP]),[Te.MATHML]:new Set([Pe.MI,Pe.MO,Pe.MN,Pe.MS,Pe.MTEXT,Pe.ANNOTATION_XML]),[Te.SVG]:new Set([Pe.TITLE,Pe.FOREIGN_OBJECT,Pe.DESC]),[Te.XLINK]:new Set,[Te.XML]:new Set,[Te.XMLNS]:new Set},QA=new Set([Pe.H1,Pe.H2,Pe.H3,Pe.H4,Pe.H5,Pe.H6]);new Set([ie.STYLE,ie.SCRIPT,ie.XMP,ie.IFRAME,ie.NOEMBED,ie.NOFRAMES,ie.PLAINTEXT]);var U;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND";})(U||(U={}));var mi={DATA:U.DATA,RCDATA:U.RCDATA,RAWTEXT:U.RAWTEXT,SCRIPT_DATA:U.SCRIPT_DATA,PLAINTEXT:U.PLAINTEXT,CDATA_SECTION:U.CDATA_SECTION};function QQe(e){return e>=N.DIGIT_0&&e<=N.DIGIT_9}function ZA(e){return e>=N.LATIN_CAPITAL_A&&e<=N.LATIN_CAPITAL_Z}function ZQe(e){return e>=N.LATIN_SMALL_A&&e<=N.LATIN_SMALL_Z}function wp(e){return ZQe(e)||ZA(e)}function nde(e){return wp(e)||QQe(e)}function hP(e){return e+32}function rde(e){return e===N.SPACE||e===N.LINE_FEED||e===N.TABULATION||e===N.FORM_FEED}function ode(e){return rde(e)||e===N.SOLIDUS||e===N.GREATER_THAN_SIGN}function e5e(e){return e===N.NULL?ce.nullCharacterReference:e>1114111?ce.characterReferenceOutsideUnicodeRange:lP(e)?ce.surrogateCharacterReference:dP(e)?ce.noncharacterCharacterReference:cP(e)||e===N.CARRIAGE_RETURN?ce.controlCharacterReference:null}var eE=class{constructor(t,n){this.options=t,this.handler=n,this.paused=false,this.inLoop=false,this.inForeignNode=false,this.lastStartTagName="",this.active=false,this.state=U.DATA,this.returnState=U.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new uP(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new mP(_H,(o,r)=>{this.preprocessor.pos=this.entityStartPos+r-1,this._flushCodePointConsumedAsCharacterReference(o);},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(ce.missingSemicolonAfterCharacterReference,1);},absenceOfDigitsInNumericCharacterReference:o=>{this._err(ce.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+o);},validateNumericCharacterReference:o=>{let r=e5e(o);r&&this._err(r,1);}}:void 0);}_err(t,n=0){var o,r;(r=(o=this.handler).onParseError)===null||r===void 0||r.call(o,this.preprocessor.getError(t,n));}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=true;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let t=this._consume();this._ensureHibernation()||this._callState(t);}this.inLoop=false;}}pause(){this.paused=true;}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=false,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.());}write(t,n,o){this.active=true,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||o?.();}insertHtmlAtCurrentPos(t){this.active=true,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop();}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=false,true):false}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance();}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),true):false}_createStartTagToken(){this.currentToken={type:Kt.START_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(1)};}_createEndTagToken(){this.currentToken={type:Kt.END_TAG,tagName:"",tagID:b.UNKNOWN,selfClosing:false,ackSelfClosing:false,attrs:[],location:this.getCurrentLocation(2)};}_createCommentToken(t){this.currentToken={type:Kt.COMMENT,data:"",location:this.getCurrentLocation(t)};}_createDoctypeToken(t){this.currentToken={type:Kt.DOCTYPE,name:t,forceQuirks:false,publicId:null,systemId:null,location:this.currentLocation};}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation};}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0);}_leaveAttrName(){var t,n;let o=this.currentToken;if(pP(o,this.currentAttr.name)===null){if(o.attrs.push(this.currentAttr),o.location&&this.currentLocation){let r=(t=(n=o.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue();}}else this._err(ce.duplicateAttribute);}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset);}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1);}emitCurrentTagToken(){let t=this.currentToken;this.prepareToken(t),t.tagID=dh(t.tagName),t.type===Kt.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(ce.endTagWithAttributes),t.selfClosing&&this._err(ce.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk();}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk();}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk();}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Kt.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Kt.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Kt.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null;}}_emitEOFToken(){let t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Kt.EOF,location:t}),this.active=false;}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n);}_emitCodePoint(t){let n=rde(t)?Kt.WHITESPACE_CHARACTER:t===N.NULL?Kt.NULL_CHARACTER:Kt.CHARACTER;this._appendCharToCurrentCharacterToken(n,t<65536?String.fromCharCode(t):String.fromCodePoint(t));}_emitChars(t){this._appendCharToCurrentCharacterToken(Kt.CHARACTER,t);}_startCharacterReference(){this.returnState=this.state,this.state=U.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Bc.Attribute:Bc.Legacy);}_isCharacterReferenceInAttribute(){return this.returnState===U.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===U.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===U.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t);}_callState(t){switch(this.state){case U.DATA:{this._stateData(t);break}case U.RCDATA:{this._stateRcdata(t);break}case U.RAWTEXT:{this._stateRawtext(t);break}case U.SCRIPT_DATA:{this._stateScriptData(t);break}case U.PLAINTEXT:{this._statePlaintext(t);break}case U.TAG_OPEN:{this._stateTagOpen(t);break}case U.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case U.TAG_NAME:{this._stateTagName(t);break}case U.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case U.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case U.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case U.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case U.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case U.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case U.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case U.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case U.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case U.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case U.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case U.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case U.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case U.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case U.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case U.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case U.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case U.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case U.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case U.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case U.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case U.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case U.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case U.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case U.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case U.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case U.BOGUS_COMMENT:{this._stateBogusComment(t);break}case U.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case U.COMMENT_START:{this._stateCommentStart(t);break}case U.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case U.COMMENT:{this._stateComment(t);break}case U.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case U.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case U.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case U.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case U.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case U.COMMENT_END:{this._stateCommentEnd(t);break}case U.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case U.DOCTYPE:{this._stateDoctype(t);break}case U.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case U.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case U.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case U.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case U.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case U.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case U.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case U.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case U.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case U.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case U.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case U.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case U.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case U.CDATA_SECTION:{this._stateCdataSection(t);break}case U.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case U.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case U.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case U.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case N.LESS_THAN_SIGN:{this.state=U.TAG_OPEN;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitCodePoint(t);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRcdata(t){switch(t){case N.AMPERSAND:{this._startCharacterReference();break}case N.LESS_THAN_SIGN:{this.state=U.RCDATA_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateRawtext(t){switch(t){case N.LESS_THAN_SIGN:{this.state=U.RAWTEXT_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptData(t){switch(t){case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_statePlaintext(t){switch(t){case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateTagOpen(t){if(wp(t))this._createStartTagToken(),this.state=U.TAG_NAME,this._stateTagName(t);else switch(t){case N.EXCLAMATION_MARK:{this.state=U.MARKUP_DECLARATION_OPEN;break}case N.SOLIDUS:{this.state=U.END_TAG_OPEN;break}case N.QUESTION_MARK:{this._err(ce.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=U.BOGUS_COMMENT,this._stateBogusComment(t);break}case N.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=U.DATA,this._stateData(t);}}_stateEndTagOpen(t){if(wp(t))this._createEndTagToken(),this.state=U.TAG_NAME,this._stateTagName(t);else switch(t){case N.GREATER_THAN_SIGN:{this._err(ce.missingEndTagName),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(ce.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=U.BOGUS_COMMENT,this._stateBogusComment(t);}}_stateTagName(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_ATTRIBUTE_NAME;break}case N.SOLIDUS:{this.state=U.SELF_CLOSING_START_TAG;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentTagToken();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.tagName+=Gn;break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(ZA(t)?hP(t):t);}}_stateRcdataLessThanSign(t){t===N.SOLIDUS?this.state=U.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=U.RCDATA,this._stateRcdata(t));}_stateRcdataEndTagOpen(t){wp(t)?(this.state=U.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=U.RCDATA,this._stateRcdata(t));}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,false))return !this._ensureHibernation();this._createEndTagToken();let n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=U.BEFORE_ATTRIBUTE_NAME,false;case N.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=U.SELF_CLOSING_START_TAG,false;case N.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=U.DATA,false;default:return !this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.RCDATA,this._stateRcdata(t));}_stateRawtextLessThanSign(t){t===N.SOLIDUS?this.state=U.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=U.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagOpen(t){wp(t)?(this.state=U.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=U.RAWTEXT,this._stateRawtext(t));}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.RAWTEXT,this._stateRawtext(t));}_stateScriptDataLessThanSign(t){switch(t){case N.SOLIDUS:{this.state=U.SCRIPT_DATA_END_TAG_OPEN;break}case N.EXCLAMATION_MARK:{this.state=U.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=U.SCRIPT_DATA,this._stateScriptData(t);}}_stateScriptDataEndTagOpen(t){wp(t)?(this.state=U.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStart(t){t===N.HYPHEN_MINUS?(this.state=U.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscapeStartDash(t){t===N.HYPHEN_MINUS?(this.state=U.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=U.SCRIPT_DATA,this._stateScriptData(t));}_stateScriptDataEscaped(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataEscapedDash(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedDashDash(t){switch(t){case N.HYPHEN_MINUS:{this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case N.GREATER_THAN_SIGN:{this.state=U.SCRIPT_DATA,this._emitChars(">");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataEscapedLessThanSign(t){t===N.SOLIDUS?this.state=U.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:wp(t)?(this._emitChars("<"),this.state=U.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagOpen(t){wp(t)?(this.state=U.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith($i.SCRIPT,false)&&ode(this.preprocessor.peek($i.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<$i.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED;}else this._ensureHibernation()||(this.state=U.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t));}_stateScriptDataDoubleEscaped(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDash(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case N.HYPHEN_MINUS:{this._emitChars("-");break}case N.LESS_THAN_SIGN:{this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case N.GREATER_THAN_SIGN:{this.state=U.SCRIPT_DATA,this._emitChars(">");break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Gn);break}case N.EOF:{this._err(ce.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t);}}_stateScriptDataDoubleEscapedLessThanSign(t){t===N.SOLIDUS?(this.state=U.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith($i.SCRIPT,false)&&ode(this.preprocessor.peek($i.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<$i.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=U.SCRIPT_DATA_ESCAPED;}else this._ensureHibernation()||(this.state=U.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t));}_stateBeforeAttributeName(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.SOLIDUS:case N.GREATER_THAN_SIGN:case N.EOF:{this.state=U.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case N.EQUALS_SIGN:{this._err(ce.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=U.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=U.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateAttributeName(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:case N.SOLIDUS:case N.GREATER_THAN_SIGN:case N.EOF:{this._leaveAttrName(),this.state=U.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case N.EQUALS_SIGN:{this._leaveAttrName(),this.state=U.BEFORE_ATTRIBUTE_VALUE;break}case N.QUOTATION_MARK:case N.APOSTROPHE:case N.LESS_THAN_SIGN:{this._err(ce.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.name+=Gn;break}default:this.currentAttr.name+=String.fromCodePoint(ZA(t)?hP(t):t);}}_stateAfterAttributeName(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.SOLIDUS:{this.state=U.SELF_CLOSING_START_TAG;break}case N.EQUALS_SIGN:{this.state=U.BEFORE_ATTRIBUTE_VALUE;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentTagToken();break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=U.ATTRIBUTE_NAME,this._stateAttributeName(t);}}_stateBeforeAttributeValue(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.QUOTATION_MARK:{this.state=U.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this.state=U.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingAttributeValue),this.state=U.DATA,this.emitCurrentTagToken();break}default:this.state=U.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t);}}_stateAttributeValueDoubleQuoted(t){switch(t){case N.QUOTATION_MARK:{this.state=U.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Gn;break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueSingleQuoted(t){switch(t){case N.APOSTROPHE:{this.state=U.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Gn;break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAttributeValueUnquoted(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this._leaveAttrValue(),this.state=U.BEFORE_ATTRIBUTE_NAME;break}case N.AMPERSAND:{this._startCharacterReference();break}case N.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=U.DATA,this.emitCurrentTagToken();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),this.currentAttr.value+=Gn;break}case N.QUOTATION_MARK:case N.APOSTROPHE:case N.LESS_THAN_SIGN:case N.EQUALS_SIGN:case N.GRAVE_ACCENT:{this._err(ce.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t);}}_stateAfterAttributeValueQuoted(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this._leaveAttrValue(),this.state=U.BEFORE_ATTRIBUTE_NAME;break}case N.SOLIDUS:{this._leaveAttrValue(),this.state=U.SELF_CLOSING_START_TAG;break}case N.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=U.DATA,this.emitCurrentTagToken();break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.missingWhitespaceBetweenAttributes),this.state=U.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateSelfClosingStartTag(t){switch(t){case N.GREATER_THAN_SIGN:{let n=this.currentToken;n.selfClosing=true,this.state=U.DATA,this.emitCurrentTagToken();break}case N.EOF:{this._err(ce.eofInTag),this._emitEOFToken();break}default:this._err(ce.unexpectedSolidusInTag),this.state=U.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t);}}_stateBogusComment(t){let n=this.currentToken;switch(t){case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentComment(n);break}case N.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Gn;break}default:n.data+=String.fromCodePoint(t);}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch($i.DASH_DASH,true)?(this._createCommentToken($i.DASH_DASH.length+1),this.state=U.COMMENT_START):this._consumeSequenceIfMatch($i.DOCTYPE,false)?(this.currentLocation=this.getCurrentLocation($i.DOCTYPE.length+1),this.state=U.DOCTYPE):this._consumeSequenceIfMatch($i.CDATA_START,true)?this.inForeignNode?this.state=U.CDATA_SECTION:(this._err(ce.cdataInHtmlContent),this._createCommentToken($i.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=U.BOGUS_COMMENT):this._ensureHibernation()||(this._err(ce.incorrectlyOpenedComment),this._createCommentToken(2),this.state=U.BOGUS_COMMENT,this._stateBogusComment(t));}_stateCommentStart(t){switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_START_DASH;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=U.DATA;let n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=U.COMMENT,this._stateComment(t);}}_stateCommentStartDash(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_END;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptClosingOfEmptyComment),this.state=U.DATA,this.emitCurrentComment(n);break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=U.COMMENT,this._stateComment(t);}}_stateComment(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_END_DASH;break}case N.LESS_THAN_SIGN:{n.data+="<",this.state=U.COMMENT_LESS_THAN_SIGN;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.data+=Gn;break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t);}}_stateCommentLessThanSign(t){let n=this.currentToken;switch(t){case N.EXCLAMATION_MARK:{n.data+="!",this.state=U.COMMENT_LESS_THAN_SIGN_BANG;break}case N.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=U.COMMENT,this._stateComment(t);}}_stateCommentLessThanSignBang(t){t===N.HYPHEN_MINUS?this.state=U.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=U.COMMENT,this._stateComment(t));}_stateCommentLessThanSignBangDash(t){t===N.HYPHEN_MINUS?this.state=U.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=U.COMMENT_END_DASH,this._stateCommentEndDash(t));}_stateCommentLessThanSignBangDashDash(t){t!==N.GREATER_THAN_SIGN&&t!==N.EOF&&this._err(ce.nestedComment),this.state=U.COMMENT_END,this._stateCommentEnd(t);}_stateCommentEndDash(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{this.state=U.COMMENT_END;break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=U.COMMENT,this._stateComment(t);}}_stateCommentEnd(t){let n=this.currentToken;switch(t){case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentComment(n);break}case N.EXCLAMATION_MARK:{this.state=U.COMMENT_END_BANG;break}case N.HYPHEN_MINUS:{n.data+="-";break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=U.COMMENT,this._stateComment(t);}}_stateCommentEndBang(t){let n=this.currentToken;switch(t){case N.HYPHEN_MINUS:{n.data+="--!",this.state=U.COMMENT_END_DASH;break}case N.GREATER_THAN_SIGN:{this._err(ce.incorrectlyClosedComment),this.state=U.DATA,this.emitCurrentComment(n);break}case N.EOF:{this._err(ce.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=U.COMMENT,this._stateComment(t);}}_stateDoctype(t){switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_DOCTYPE_NAME;break}case N.GREATER_THAN_SIGN:{this.state=U.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case N.EOF:{this._err(ce.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingWhitespaceBeforeDoctypeName),this.state=U.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);}}_stateBeforeDoctypeName(t){if(ZA(t))this._createDoctypeToken(String.fromCharCode(hP(t))),this.state=U.DOCTYPE_NAME;else switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.NULL:{this._err(ce.unexpectedNullCharacter),this._createDoctypeToken(Gn),this.state=U.DOCTYPE_NAME;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeName),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),this._createDoctypeToken(null);let n=this.currentToken;n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=U.DOCTYPE_NAME;}}_stateDoctypeName(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.AFTER_DOCTYPE_NAME;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.name+=Gn;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(ZA(t)?hP(t):t);}}_stateAfterDoctypeName(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch($i.PUBLIC,false)?this.state=U.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch($i.SYSTEM,false)?this.state=U.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(ce.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t));}}_stateAfterDoctypePublicKeyword(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case N.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.QUOTATION_MARK:{n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{n.publicId="",this.state=U.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypePublicIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case N.QUOTATION_MARK:{this.state=U.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateDoctypePublicIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case N.APOSTROPHE:{this.state=U.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.publicId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypePublicIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t);}}_stateAfterDoctypePublicIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case N.GREATER_THAN_SIGN:{this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.QUOTATION_MARK:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this._err(ce.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.QUOTATION_MARK:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateAfterDoctypeSystemKeyword(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:{this.state=U.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case N.QUOTATION_MARK:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{this._err(ce.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBeforeDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.QUOTATION_MARK:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case N.APOSTROPHE:{n.systemId="",this.state=U.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case N.GREATER_THAN_SIGN:{this._err(ce.missingDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.DATA,this.emitCurrentDoctype(n);break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=true,this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateDoctypeSystemIdentifierDoubleQuoted(t){let n=this.currentToken;switch(t){case N.QUOTATION_MARK:{this.state=U.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateDoctypeSystemIdentifierSingleQuoted(t){let n=this.currentToken;switch(t){case N.APOSTROPHE:{this.state=U.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case N.NULL:{this._err(ce.unexpectedNullCharacter),n.systemId+=Gn;break}case N.GREATER_THAN_SIGN:{this._err(ce.abruptDoctypeSystemIdentifier),n.forceQuirks=true,this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t);}}_stateAfterDoctypeSystemIdentifier(t){let n=this.currentToken;switch(t){case N.SPACE:case N.LINE_FEED:case N.TABULATION:case N.FORM_FEED:break;case N.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.EOF:{this._err(ce.eofInDoctype),n.forceQuirks=true,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(ce.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=U.BOGUS_DOCTYPE,this._stateBogusDoctype(t);}}_stateBogusDoctype(t){let n=this.currentToken;switch(t){case N.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=U.DATA;break}case N.NULL:{this._err(ce.unexpectedNullCharacter);break}case N.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case N.RIGHT_SQUARE_BRACKET:{this.state=U.CDATA_SECTION_BRACKET;break}case N.EOF:{this._err(ce.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t);}}_stateCdataSectionBracket(t){t===N.RIGHT_SQUARE_BRACKET?this.state=U.CDATA_SECTION_END:(this._emitChars("]"),this.state=U.CDATA_SECTION,this._stateCdataSection(t));}_stateCdataSectionEnd(t){switch(t){case N.GREATER_THAN_SIGN:{this.state=U.DATA;break}case N.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=U.CDATA_SECTION,this._stateCdataSection(t);}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else {this.active=false,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=true;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(N.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&nde(this.preprocessor.peek(1))?U.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState;}_stateAmbiguousAmpersand(t){nde(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===N.SEMICOLON&&this._err(ce.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t));}};var lde=new Set([b.DD,b.DT,b.LI,b.OPTGROUP,b.OPTION,b.P,b.RB,b.RP,b.RT,b.RTC]),ide=new Set([...lde,b.CAPTION,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]),gP=new Set([b.APPLET,b.CAPTION,b.HTML,b.MARQUEE,b.OBJECT,b.TABLE,b.TD,b.TEMPLATE,b.TH]),t5e=new Set([...gP,b.OL,b.UL]),n5e=new Set([...gP,b.BUTTON]),sde=new Set([b.ANNOTATION_XML,b.MI,b.MN,b.MO,b.MS,b.MTEXT]),ade=new Set([b.DESC,b.FOREIGN_OBJECT,b.TITLE]),o5e=new Set([b.TR,b.TEMPLATE,b.HTML]),r5e=new Set([b.TBODY,b.TFOOT,b.THEAD,b.TEMPLATE,b.HTML]),i5e=new Set([b.TABLE,b.TEMPLATE,b.HTML]),s5e=new Set([b.TD,b.TH]),fP=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,o){this.treeAdapter=n,this.handler=o,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=b.UNKNOWN,this.current=t;}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===b.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===Te.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop];}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,true);}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,true);}replace(t,n){let o=this._indexOf(t);this.items[o]=n,o===this.stackTop&&(this.current=n);}insertAfter(t,n,o){let r=this._indexOf(t)+1;this.items.splice(r,0,n),this.tagIDs.splice(r,0,o),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop);}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==Te.HTML);this.shortenToLength(Math.max(n,0));}shortenToLength(t){for(;this.stackTop>=t;){let n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t);}}popUntilElementPopped(t){let n=this._indexOf(t);this.shortenToLength(Math.max(n,0));}popUntilPopped(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(o,0));}popUntilNumberedHeaderPopped(){this.popUntilPopped(QA,Te.HTML);}popUntilTableCellPopped(){this.popUntilPopped(s5e,Te.HTML);}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1);}_indexOfTagNames(t,n){for(let o=this.stackTop;o>=0;o--)if(t.has(this.tagIDs[o])&&this.treeAdapter.getNamespaceURI(this.items[o])===n)return o;return -1}clearBackTo(t,n){let o=this._indexOfTagNames(t,n);this.shortenToLength(o+1);}clearBackToTableContext(){this.clearBackTo(i5e,Te.HTML);}clearBackToTableBodyContext(){this.clearBackTo(r5e,Te.HTML);}clearBackToTableRowContext(){this.clearBackTo(o5e,Te.HTML);}remove(t){let n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,false)));}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===b.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===b.HTML}hasInDynamicScope(t,n){for(let o=this.stackTop;o>=0;o--){let r=this.tagIDs[o];switch(this.treeAdapter.getNamespaceURI(this.items[o])){case Te.HTML:{if(r===t)return true;if(n.has(r))return false;break}case Te.SVG:{if(ade.has(r))return false;break}case Te.MATHML:{if(sde.has(r))return false;break}}}return true}hasInScope(t){return this.hasInDynamicScope(t,gP)}hasInListItemScope(t){return this.hasInDynamicScope(t,t5e)}hasInButtonScope(t){return this.hasInDynamicScope(t,n5e)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Te.HTML:{if(QA.has(n))return true;if(gP.has(n))return false;break}case Te.SVG:{if(ade.has(n))return false;break}case Te.MATHML:{if(sde.has(n))return false;break}}}return true}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===Te.HTML)switch(this.tagIDs[n]){case t:return true;case b.TABLE:case b.HTML:return false}return true}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===Te.HTML)switch(this.tagIDs[t]){case b.TBODY:case b.THEAD:case b.TFOOT:return true;case b.TABLE:case b.HTML:return false}return true}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===Te.HTML)switch(this.tagIDs[n]){case t:return true;case b.OPTION:case b.OPTGROUP:break;default:return false}return true}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&lde.has(this.currentTagId);)this.pop();}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&ide.has(this.currentTagId);)this.pop();}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&ide.has(this.currentTagId);)this.pop();}};var bl;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element";})(bl||(bl={}));var cde={type:bl.Marker},yP=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null;}_getNoahArkConditionCandidates(t,n){let o=[],r=n.length,i=this.treeAdapter.getTagName(t),s=this.treeAdapter.getNamespaceURI(t);for(let a=0;a<this.entries.length;a++){let l=this.entries[a];if(l.type===bl.Marker)break;let{element:c}=l;if(this.treeAdapter.getTagName(c)===i&&this.treeAdapter.getNamespaceURI(c)===s){let d=this.treeAdapter.getAttrList(c);d.length===r&&o.push({idx:a,attrs:d});}}return o}_ensureNoahArkCondition(t){if(this.entries.length<3)return;let n=this.treeAdapter.getAttrList(t),o=this._getNoahArkConditionCandidates(t,n);if(o.length<3)return;let r=new Map(n.map(s=>[s.name,s.value])),i=0;for(let s=0;s<o.length;s++){let a=o[s];a.attrs.every(l=>r.get(l.name)===l.value)&&(i+=1,i>=3&&this.entries.splice(a.idx,1));}}insertMarker(){this.entries.unshift(cde);}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:bl.Element,element:t,token:n});}insertElementAfterBookmark(t,n){let o=this.entries.indexOf(this.bookmark);this.entries.splice(o,0,{type:bl.Element,element:t,token:n});}removeEntry(t){let n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1);}clearToLastMarker(){let t=this.entries.indexOf(cde);t===-1?this.entries.length=0:this.entries.splice(0,t+1);}getElementEntryInScopeWithTagName(t){let n=this.entries.find(o=>o.type===bl.Marker||this.treeAdapter.getTagName(o.element)===t);return n&&n.type===bl.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===bl.Element&&n.element===t)}};var Tl={createDocument(){return {nodeName:"#document",mode:Vi.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return {nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return {nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return {nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return {nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e;},insertBefore(e,t,n){let o=e.childNodes.indexOf(n);e.childNodes.splice(o,0,t),t.parentNode=e;},setTemplateContent(e,t){e.content=t;},getTemplateContent(e){return e.content},setDocumentType(e,t,n,o){let r=e.childNodes.find(i=>i.nodeName==="#documentType");if(r)r.name=t,r.publicId=n,r.systemId=o;else {let i={nodeName:"#documentType",name:t,publicId:n,systemId:o,parentNode:null};Tl.appendChild(e,i);}},setDocumentMode(e,t){e.mode=t;},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){let t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null;}},insertText(e,t){if(e.childNodes.length>0){let n=e.childNodes[e.childNodes.length-1];if(Tl.isTextNode(n)){n.value+=t;return}}Tl.appendChild(e,Tl.createTextNode(t));},insertTextBefore(e,t,n){let o=e.childNodes[e.childNodes.indexOf(n)-1];o&&Tl.isTextNode(o)?o.value+=t:Tl.insertBefore(e,Tl.createTextNode(t),n);},adoptAttributes(e,t){let n=new Set(e.attrs.map(o=>o.name));for(let o=0;o<t.length;o++)n.has(t[o].name)||e.attrs.push(t[o]);},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t;},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t};}};var ude="html",a5e="about:legacy-compat",l5e="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",pde=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],c5e=[...pde,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],d5e=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),mde=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],u5e=[...mde,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function dde(e,t){return t.some(n=>e.startsWith(n))}function hde(e){return e.name===ude&&e.publicId===null&&(e.systemId===null||e.systemId===a5e)}function gde(e){if(e.name!==ude)return Vi.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===l5e)return Vi.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),d5e.has(n))return Vi.QUIRKS;let o=t===null?c5e:pde;if(dde(n,o))return Vi.QUIRKS;if(o=t===null?mde:u5e,dde(n,o))return Vi.LIMITED_QUIRKS}return Vi.NO_QUIRKS}var fde={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},m5e="definitionurl",h5e="definitionURL",g5e=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),f5e=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Te.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Te.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Te.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Te.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Te.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Te.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Te.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Te.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Te.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Te.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Te.XMLNS}]]),y5e=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),S5e=new Set([b.B,b.BIG,b.BLOCKQUOTE,b.BODY,b.BR,b.CENTER,b.CODE,b.DD,b.DIV,b.DL,b.DT,b.EM,b.EMBED,b.H1,b.H2,b.H3,b.H4,b.H5,b.H6,b.HEAD,b.HR,b.I,b.IMG,b.LI,b.LISTING,b.MENU,b.META,b.NOBR,b.OL,b.P,b.PRE,b.RUBY,b.S,b.SMALL,b.SPAN,b.STRONG,b.STRIKE,b.SUB,b.SUP,b.TABLE,b.TT,b.U,b.UL,b.VAR]);function yde(e){let t=e.tagID;return t===b.FONT&&e.attrs.some(({name:o})=>o===Qd.COLOR||o===Qd.SIZE||o===Qd.FACE)||S5e.has(t)}function OH(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===m5e){e.attrs[t].name=h5e;break}}function MH(e){for(let t=0;t<e.attrs.length;t++){let n=g5e.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n);}}function SP(e){for(let t=0;t<e.attrs.length;t++){let n=f5e.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace);}}function Sde(e){let t=y5e.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=dh(e.tagName));}function b5e(e,t){return t===Te.MATHML&&(e===b.MI||e===b.MO||e===b.MN||e===b.MS||e===b.MTEXT)}function T5e(e,t,n){if(t===Te.MATHML&&e===b.ANNOTATION_XML){for(let o=0;o<n.length;o++)if(n[o].name===Qd.ENCODING){let r=n[o].value.toLowerCase();return r===fde.TEXT_HTML||r===fde.APPLICATION_XML}}return t===Te.SVG&&(e===b.FOREIGN_OBJECT||e===b.DESC||e===b.TITLE)}function bde(e,t,n,o){return (!o||o===Te.HTML)&&T5e(e,t,n)||(!o||o===Te.MATHML)&&b5e(e,t)}var A5e="hidden",E5e=8,C5e=3,j;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET";})(j||(j={}));var v5e={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},vde=new Set([b.TABLE,b.TBODY,b.TFOOT,b.THEAD,b.TR]),Ade={scriptingEnabled:true,sourceCodeLocationInfo:false,treeAdapter:Tl,onParseError:null},lE=class{constructor(t,n,o=null,r=null){this.fragmentContext=o,this.scriptHandler=r,this.currentToken=null,this.stopped=false,this.insertionMode=j.INITIAL,this.originalInsertionMode=j.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=false,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=false,this.framesetOk=true,this.skipNextNewLine=false,this.fosterParentingEnabled=false,this.options={...Ade,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=true),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new eE(this.options,this),this.activeFormattingElements=new yP(this.treeAdapter),this.fragmentContextID=o?dh(this.treeAdapter.getTagName(o)):b.UNKNOWN,this._setContextModes(o??this.document,this.fragmentContextID),this.openElements=new fP(this.document,this.treeAdapter,this);}static parse(t,n){let o=new this(n);return o.tokenizer.write(t,true),o.document}static getFragmentParser(t,n){let o={...Ade,...n};t??(t=o.treeAdapter.createElement(ie.TEMPLATE,Te.HTML,[]));let r=o.treeAdapter.createElement("documentmock",Te.HTML,[]),i=new this(o,r,t);return i.fragmentContextID===b.TEMPLATE&&i.tmplInsertionModeStack.unshift(j.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,o){var r;if(!this.onParseError)return;let i=(r=t.location)!==null&&r!==void 0?r:v5e,s={code:n,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:o?i.startLine:i.endLine,endCol:o?i.startCol:i.endCol,endOffset:o?i.startOffset:i.endOffset};this.onParseError(s);}onItemPush(t,n,o){var r,i;(i=(r=this.treeAdapter).onItemPush)===null||i===void 0||i.call(r,t),o&&this.openElements.stackTop>0&&this._setContextModes(t,n);}onItemPop(t,n){var o,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(r=(o=this.treeAdapter).onItemPop)===null||r===void 0||r.call(o,t,this.openElements.current),n){let i,s;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,s=this.fragmentContextID):{current:i,currentTagId:s}=this.openElements,this._setContextModes(i,s);}}_setContextModes(t,n){let o=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===Te.HTML;this.currentNotInHTML=!o,this.tokenizer.inForeignNode=!o&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t);}_switchToTextParsing(t,n){this._insertElement(t,Te.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=j.TEXT;}switchToPlaintextParsing(){this.insertionMode=j.TEXT,this.originalInsertionMode=j.IN_BODY,this.tokenizer.state=mi.PLAINTEXT;}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===ie.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t);}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==Te.HTML))switch(this.fragmentContextID){case b.TITLE:case b.TEXTAREA:{this.tokenizer.state=mi.RCDATA;break}case b.STYLE:case b.XMP:case b.IFRAME:case b.NOEMBED:case b.NOFRAMES:case b.NOSCRIPT:{this.tokenizer.state=mi.RAWTEXT;break}case b.SCRIPT:{this.tokenizer.state=mi.SCRIPT_DATA;break}case b.PLAINTEXT:{this.tokenizer.state=mi.PLAINTEXT;break}}}_setDocumentType(t){let n=t.name||"",o=t.publicId||"",r=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,o,r),t.location){let s=this.treeAdapter.getChildNodes(this.document).find(a=>this.treeAdapter.isDocumentTypeNode(a));s&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){let o=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,o);}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else {let o=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(o??this.document,t);}}_appendElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location);}_insertElement(t,n){let o=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(o,t.location),this.openElements.push(o,t.tagID);}_insertFakeElement(t,n){let o=this.treeAdapter.createElement(t,Te.HTML,[]);this._attachElementToTree(o,null),this.openElements.push(o,n);}_insertTemplate(t){let n=this.treeAdapter.createElement(t.tagName,Te.HTML,t.attrs),o=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,o),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,null);}_insertFakeRootElement(){let t=this.treeAdapter.createElement(ie.HTML,Te.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,b.HTML);}_appendCommentNode(t,n){let o=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,o),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location);}_insertCharacters(t){let n,o;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:o}=this._findFosterParentingLocation(),o?this.treeAdapter.insertTextBefore(n,t.chars,o):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;let r=this.treeAdapter.getChildNodes(n),i=o?r.lastIndexOf(o):r.length,s=r[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(s)){let{endLine:l,endCol:c,endOffset:d}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(s,{endLine:l,endCol:c,endOffset:d});}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(s,t.location);}_adoptNodes(t,n){for(let o=this.treeAdapter.getFirstChild(t);o;o=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(o),this.treeAdapter.appendChild(n,o);}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){let o=n.location,r=this.treeAdapter.getTagName(t),i=n.type===Kt.END_TAG&&r===n.tagName?{endTag:{...o},endLine:o.endLine,endCol:o.endCol,endOffset:o.endOffset}:{endLine:o.startLine,endCol:o.startCol,endOffset:o.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i);}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return false;let n,o;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,o=this.fragmentContextID):{current:n,currentTagId:o}=this.openElements,t.tagID===b.SVG&&this.treeAdapter.getTagName(n)===ie.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===Te.MATHML?false:this.tokenizer.inForeignNode||(t.tagID===b.MGLYPH||t.tagID===b.MALIGNMARK)&&o!==void 0&&!this._isIntegrationPoint(o,n,Te.HTML)}_processToken(t){switch(t.type){case Kt.CHARACTER:{this.onCharacter(t);break}case Kt.NULL_CHARACTER:{this.onNullCharacter(t);break}case Kt.COMMENT:{this.onComment(t);break}case Kt.DOCTYPE:{this.onDoctype(t);break}case Kt.START_TAG:{this._processStartTag(t);break}case Kt.END_TAG:{this.onEndTag(t);break}case Kt.EOF:{this.onEof(t);break}case Kt.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,o){let r=this.treeAdapter.getNamespaceURI(n),i=this.treeAdapter.getAttrList(n);return bde(t,r,i,o)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let n=this.activeFormattingElements.entries.findIndex(r=>r.type===bl.Marker||this.openElements.contains(r.element)),o=n===-1?t-1:n-1;for(let r=o;r>=0;r--){let i=this.activeFormattingElements.entries[r];this._insertElement(i.token,this.treeAdapter.getNamespaceURI(i.element)),i.element=this.openElements.current;}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=j.IN_ROW;}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(b.P),this.openElements.popUntilTagNamePopped(b.P);}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case b.TR:{this.insertionMode=j.IN_ROW;return}case b.TBODY:case b.THEAD:case b.TFOOT:{this.insertionMode=j.IN_TABLE_BODY;return}case b.CAPTION:{this.insertionMode=j.IN_CAPTION;return}case b.COLGROUP:{this.insertionMode=j.IN_COLUMN_GROUP;return}case b.TABLE:{this.insertionMode=j.IN_TABLE;return}case b.BODY:{this.insertionMode=j.IN_BODY;return}case b.FRAMESET:{this.insertionMode=j.IN_FRAMESET;return}case b.SELECT:{this._resetInsertionModeForSelect(t);return}case b.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case b.HTML:{this.insertionMode=this.headElement?j.AFTER_HEAD:j.BEFORE_HEAD;return}case b.TD:case b.TH:{if(t>0){this.insertionMode=j.IN_CELL;return}break}case b.HEAD:{if(t>0){this.insertionMode=j.IN_HEAD;return}break}}this.insertionMode=j.IN_BODY;}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){let o=this.openElements.tagIDs[n];if(o===b.TEMPLATE)break;if(o===b.TABLE){this.insertionMode=j.IN_SELECT_IN_TABLE;return}}this.insertionMode=j.IN_SELECT;}_isElementCausesFosterParenting(t){return vde.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){let n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case b.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===Te.HTML)return {parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case b.TABLE:{let o=this.treeAdapter.getParentNode(n);return o?{parent:o,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return {parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t);}_isSpecialElement(t,n){let o=this.treeAdapter.getNamespaceURI(t);return tde[o].has(n)}onCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){e6e(this,t);return}switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{oE(this,t);break}case j.BEFORE_HEAD:{rE(this,t);break}case j.IN_HEAD:{iE(this,t);break}case j.IN_HEAD_NO_SCRIPT:{sE(this,t);break}case j.AFTER_HEAD:{aE(this,t);break}case j.IN_BODY:case j.IN_CAPTION:case j.IN_CELL:case j.IN_TEMPLATE:{wde(this,t);break}case j.TEXT:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case j.IN_TABLE:case j.IN_TABLE_BODY:case j.IN_ROW:{NH(this,t);break}case j.IN_TABLE_TEXT:{Mde(this,t);break}case j.IN_COLUMN_GROUP:{TP(this,t);break}case j.AFTER_BODY:{AP(this,t);break}case j.AFTER_AFTER_BODY:{bP(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=false,this.tokenizer.inForeignNode){ZZe(this,t);return}switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{oE(this,t);break}case j.BEFORE_HEAD:{rE(this,t);break}case j.IN_HEAD:{iE(this,t);break}case j.IN_HEAD_NO_SCRIPT:{sE(this,t);break}case j.AFTER_HEAD:{aE(this,t);break}case j.TEXT:{this._insertCharacters(t);break}case j.IN_TABLE:case j.IN_TABLE_BODY:case j.IN_ROW:{NH(this,t);break}case j.IN_COLUMN_GROUP:{TP(this,t);break}case j.AFTER_BODY:{AP(this,t);break}case j.AFTER_AFTER_BODY:{bP(this,t);break}}}onComment(t){if(this.skipNextNewLine=false,this.currentNotInHTML){LH(this,t);return}switch(this.insertionMode){case j.INITIAL:case j.BEFORE_HTML:case j.BEFORE_HEAD:case j.IN_HEAD:case j.IN_HEAD_NO_SCRIPT:case j.AFTER_HEAD:case j.IN_BODY:case j.IN_TABLE:case j.IN_CAPTION:case j.IN_COLUMN_GROUP:case j.IN_TABLE_BODY:case j.IN_ROW:case j.IN_CELL:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:case j.IN_TEMPLATE:case j.IN_FRAMESET:case j.AFTER_FRAMESET:{LH(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.AFTER_BODY:{O5e(this,t);break}case j.AFTER_AFTER_BODY:case j.AFTER_AFTER_FRAMESET:{M5e(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=false,this.insertionMode){case j.INITIAL:{N5e(this,t);break}case j.BEFORE_HEAD:case j.IN_HEAD:case j.IN_HEAD_NO_SCRIPT:case j.AFTER_HEAD:{this._err(t,ce.misplacedDoctype);break}case j.IN_TABLE_TEXT:{nE(this,t);break}}}onStartTag(t){this.skipNextNewLine=false,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,ce.nonVoidHtmlElementStartTagWithTrailingSolidus);}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?t6e(this,t):this._startTagOutsideForeignContent(t);}_startTagOutsideForeignContent(t){switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{L5e(this,t);break}case j.BEFORE_HEAD:{D5e(this,t);break}case j.IN_HEAD:{Al(this,t);break}case j.IN_HEAD_NO_SCRIPT:{U5e(this,t);break}case j.AFTER_HEAD:{G5e(this,t);break}case j.IN_BODY:{hi(this,t);break}case j.IN_TABLE:{_y(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.IN_CAPTION:{FZe(this,t);break}case j.IN_COLUMN_GROUP:{BH(this,t);break}case j.IN_TABLE_BODY:{vP(this,t);break}case j.IN_ROW:{RP(this,t);break}case j.IN_CELL:{HZe(this,t);break}case j.IN_SELECT:{kde(this,t);break}case j.IN_SELECT_IN_TABLE:{jZe(this,t);break}case j.IN_TEMPLATE:{VZe(this,t);break}case j.AFTER_BODY:{WZe(this,t);break}case j.IN_FRAMESET:{qZe(this,t);break}case j.AFTER_FRAMESET:{YZe(this,t);break}case j.AFTER_AFTER_BODY:{XZe(this,t);break}case j.AFTER_AFTER_FRAMESET:{QZe(this,t);break}}}onEndTag(t){this.skipNextNewLine=false,this.currentToken=t,this.currentNotInHTML?n6e(this,t):this._endTagOutsideForeignContent(t);}_endTagOutsideForeignContent(t){switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{k5e(this,t);break}case j.BEFORE_HEAD:{F5e(this,t);break}case j.IN_HEAD:{B5e(this,t);break}case j.IN_HEAD_NO_SCRIPT:{H5e(this,t);break}case j.AFTER_HEAD:{j5e(this,t);break}case j.IN_BODY:{CP(this,t);break}case j.TEXT:{IZe(this,t);break}case j.IN_TABLE:{cE(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.IN_CAPTION:{BZe(this,t);break}case j.IN_COLUMN_GROUP:{UZe(this,t);break}case j.IN_TABLE_BODY:{kH(this,t);break}case j.IN_ROW:{Lde(this,t);break}case j.IN_CELL:{GZe(this,t);break}case j.IN_SELECT:{Dde(this,t);break}case j.IN_SELECT_IN_TABLE:{$Ze(this,t);break}case j.IN_TEMPLATE:{zZe(this,t);break}case j.AFTER_BODY:{Bde(this,t);break}case j.IN_FRAMESET:{KZe(this,t);break}case j.AFTER_FRAMESET:{JZe(this,t);break}case j.AFTER_AFTER_BODY:{bP(this,t);break}}}onEof(t){switch(this.insertionMode){case j.INITIAL:{tE(this,t);break}case j.BEFORE_HTML:{oE(this,t);break}case j.BEFORE_HEAD:{rE(this,t);break}case j.IN_HEAD:{iE(this,t);break}case j.IN_HEAD_NO_SCRIPT:{sE(this,t);break}case j.AFTER_HEAD:{aE(this,t);break}case j.IN_BODY:case j.IN_TABLE:case j.IN_CAPTION:case j.IN_COLUMN_GROUP:case j.IN_TABLE_BODY:case j.IN_ROW:case j.IN_CELL:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:{Pde(this,t);break}case j.TEXT:{xZe(this,t);break}case j.IN_TABLE_TEXT:{nE(this,t);break}case j.IN_TEMPLATE:{Fde(this,t);break}case j.AFTER_BODY:case j.IN_FRAMESET:case j.AFTER_FRAMESET:case j.AFTER_AFTER_BODY:case j.AFTER_AFTER_FRAMESET:{FH(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=false,t.chars.charCodeAt(0)===N.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1);}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case j.IN_HEAD:case j.IN_HEAD_NO_SCRIPT:case j.AFTER_HEAD:case j.TEXT:case j.IN_COLUMN_GROUP:case j.IN_SELECT:case j.IN_SELECT_IN_TABLE:case j.IN_FRAMESET:case j.AFTER_FRAMESET:{this._insertCharacters(t);break}case j.IN_BODY:case j.IN_CAPTION:case j.IN_CELL:case j.IN_TEMPLATE:case j.AFTER_BODY:case j.AFTER_AFTER_BODY:case j.AFTER_AFTER_FRAMESET:{Rde(this,t);break}case j.IN_TABLE:case j.IN_TABLE_BODY:case j.IN_ROW:{NH(this,t);break}case j.IN_TABLE_TEXT:{Ode(this,t);break}}}};function R5e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):_de(e,t),n}function w5e(e,t){let n=null,o=e.openElements.stackTop;for(;o>=0;o--){let r=e.openElements.items[o];if(r===t.element)break;e._isSpecialElement(r,e.openElements.tagIDs[o])&&(n=r);}return n||(e.openElements.shortenToLength(Math.max(o,0)),e.activeFormattingElements.removeEntry(t)),n}function I5e(e,t,n){let o=t,r=e.openElements.getCommonAncestor(t);for(let i=0,s=r;s!==n;i++,s=r){r=e.openElements.getCommonAncestor(s);let a=e.activeFormattingElements.getElementEntry(s),l=a&&i>=C5e;!a||l?(l&&e.activeFormattingElements.removeEntry(a),e.openElements.remove(s)):(s=x5e(e,a),o===t&&(e.activeFormattingElements.bookmark=a),e.treeAdapter.detachNode(o),e.treeAdapter.appendChild(s,o),o=s);}return o}function x5e(e,t){let n=e.treeAdapter.getNamespaceURI(t.element),o=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,o),t.element=o,o}function _5e(e,t,n){let o=e.treeAdapter.getTagName(t),r=dh(o);if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else {let i=e.treeAdapter.getNamespaceURI(t);r===b.TEMPLATE&&i===Te.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n);}}function P5e(e,t,n){let o=e.treeAdapter.getNamespaceURI(n.element),{token:r}=n,i=e.treeAdapter.createElement(r.tagName,o,r.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,r),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,r.tagID);}function DH(e,t){for(let n=0;n<E5e;n++){let o=R5e(e,t);if(!o)break;let r=w5e(e,o);if(!r)break;e.activeFormattingElements.bookmark=o;let i=I5e(e,r,o.element),s=e.openElements.getCommonAncestor(o.element);e.treeAdapter.detachNode(i),s&&_5e(e,s,i),P5e(e,r,o);}}function LH(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode);}function O5e(e,t){e._appendCommentNode(t,e.openElements.items[0]);}function M5e(e,t){e._appendCommentNode(t,e.document);}function FH(e,t){if(e.stopped=true,t.location){let n=e.fragmentContext?0:2;for(let o=e.openElements.stackTop;o>=n;o--)e._setEndLocation(e.openElements.items[o],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let o=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(o);if(r&&!r.endTag&&(e._setEndLocation(o,t),e.openElements.stackTop>=1)){let i=e.openElements.items[1],s=e.treeAdapter.getNodeSourceCodeLocation(i);s&&!s.endTag&&e._setEndLocation(i,t);}}}}function N5e(e,t){e._setDocumentType(t);let n=t.forceQuirks?Vi.QUIRKS:gde(t);hde(t)||e._err(t,ce.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=j.BEFORE_HTML;}function tE(e,t){e._err(t,ce.missingDoctype,true),e.treeAdapter.setDocumentMode(e.document,Vi.QUIRKS),e.insertionMode=j.BEFORE_HTML,e._processToken(t);}function L5e(e,t){t.tagID===b.HTML?(e._insertElement(t,Te.HTML),e.insertionMode=j.BEFORE_HEAD):oE(e,t);}function k5e(e,t){let n=t.tagID;(n===b.HTML||n===b.HEAD||n===b.BODY||n===b.BR)&&oE(e,t);}function oE(e,t){e._insertFakeRootElement(),e.insertionMode=j.BEFORE_HEAD,e._processToken(t);}function D5e(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.HEAD:{e._insertElement(t,Te.HTML),e.headElement=e.openElements.current,e.insertionMode=j.IN_HEAD;break}default:rE(e,t);}}function F5e(e,t){let n=t.tagID;n===b.HEAD||n===b.BODY||n===b.HTML||n===b.BR?rE(e,t):e._err(t,ce.endTagWithoutMatchingOpenElement);}function rE(e,t){e._insertFakeElement(ie.HEAD,b.HEAD),e.headElement=e.openElements.current,e.insertionMode=j.IN_HEAD,e._processToken(t);}function Al(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:{e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.TITLE:{e._switchToTextParsing(t,mi.RCDATA);break}case b.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,mi.RAWTEXT):(e._insertElement(t,Te.HTML),e.insertionMode=j.IN_HEAD_NO_SCRIPT);break}case b.NOFRAMES:case b.STYLE:{e._switchToTextParsing(t,mi.RAWTEXT);break}case b.SCRIPT:{e._switchToTextParsing(t,mi.SCRIPT_DATA);break}case b.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=false,e.insertionMode=j.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(j.IN_TEMPLATE);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:iE(e,t);}}function B5e(e,t){switch(t.tagID){case b.HEAD:{e.openElements.pop(),e.insertionMode=j.AFTER_HEAD;break}case b.BODY:case b.BR:case b.HTML:{iE(e,t);break}case b.TEMPLATE:{uh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function uh(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==b.TEMPLATE&&e._err(t,ce.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(b.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,ce.endTagWithoutMatchingOpenElement);}function iE(e,t){e.openElements.pop(),e.insertionMode=j.AFTER_HEAD,e._processToken(t);}function U5e(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.BASEFONT:case b.BGSOUND:case b.HEAD:case b.LINK:case b.META:case b.NOFRAMES:case b.STYLE:{Al(e,t);break}case b.NOSCRIPT:{e._err(t,ce.nestedNoscriptInHead);break}default:sE(e,t);}}function H5e(e,t){switch(t.tagID){case b.NOSCRIPT:{e.openElements.pop(),e.insertionMode=j.IN_HEAD;break}case b.BR:{sE(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function sE(e,t){let n=t.type===Kt.EOF?ce.openElementsLeftAfterEof:ce.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=j.IN_HEAD,e._processToken(t);}function G5e(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.BODY:{e._insertElement(t,Te.HTML),e.framesetOk=false,e.insertionMode=j.IN_BODY;break}case b.FRAMESET:{e._insertElement(t,Te.HTML),e.insertionMode=j.IN_FRAMESET;break}case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:case b.NOFRAMES:case b.SCRIPT:case b.STYLE:case b.TEMPLATE:case b.TITLE:{e._err(t,ce.abandonedHeadElementChild),e.openElements.push(e.headElement,b.HEAD),Al(e,t),e.openElements.remove(e.headElement);break}case b.HEAD:{e._err(t,ce.misplacedStartTagForHeadElement);break}default:aE(e,t);}}function j5e(e,t){switch(t.tagID){case b.BODY:case b.HTML:case b.BR:{aE(e,t);break}case b.TEMPLATE:{uh(e,t);break}default:e._err(t,ce.endTagWithoutMatchingOpenElement);}}function aE(e,t){e._insertFakeElement(ie.BODY,b.BODY),e.insertionMode=j.IN_BODY,EP(e,t);}function EP(e,t){switch(t.type){case Kt.CHARACTER:{wde(e,t);break}case Kt.WHITESPACE_CHARACTER:{Rde(e,t);break}case Kt.COMMENT:{LH(e,t);break}case Kt.START_TAG:{hi(e,t);break}case Kt.END_TAG:{CP(e,t);break}case Kt.EOF:{Pde(e,t);break}}}function Rde(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t);}function wde(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=false;}function $5e(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs);}function V5e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=false,e.treeAdapter.adoptAttributes(n,t.attrs));}function z5e(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_FRAMESET);}function W5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML);}function q5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&QA.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Te.HTML);}function K5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),e.skipNextNewLine=true,e.framesetOk=false;}function Y5e(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),n||(e.formElement=e.openElements.current));}function J5e(e,t){e.framesetOk=false;let n=t.tagID;for(let o=e.openElements.stackTop;o>=0;o--){let r=e.openElements.tagIDs[o];if(n===b.LI&&r===b.LI||(n===b.DD||n===b.DT)&&(r===b.DD||r===b.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==b.ADDRESS&&r!==b.DIV&&r!==b.P&&e._isSpecialElement(e.openElements.items[o],r))break}e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML);}function X5e(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),e.tokenizer.state=mi.PLAINTEXT;}function Q5e(e,t){e.openElements.hasInScope(b.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.framesetOk=false;}function Z5e(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(ie.A);n&&(DH(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function eZe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function tZe(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(b.NOBR)&&(DH(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t);}function nZe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=false;}function oZe(e,t){e.treeAdapter.getDocumentMode(e.document)!==Vi.QUIRKS&&e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._insertElement(t,Te.HTML),e.framesetOk=false,e.insertionMode=j.IN_TABLE;}function Ide(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Te.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function xde(e){let t=pP(e,Qd.TYPE);return t!=null&&t.toLowerCase()===A5e}function rZe(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Te.HTML),xde(t)||(e.framesetOk=false),t.ackSelfClosing=true;}function iZe(e,t){e._appendElement(t,Te.HTML),t.ackSelfClosing=true;}function sZe(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._appendElement(t,Te.HTML),e.framesetOk=false,t.ackSelfClosing=true;}function aZe(e,t){t.tagName=ie.IMG,t.tagID=b.IMG,Ide(e,t);}function lZe(e,t){e._insertElement(t,Te.HTML),e.skipNextNewLine=true,e.tokenizer.state=mi.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=false,e.insertionMode=j.TEXT;}function cZe(e,t){e.openElements.hasInButtonScope(b.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=false,e._switchToTextParsing(t,mi.RAWTEXT);}function dZe(e,t){e.framesetOk=false,e._switchToTextParsing(t,mi.RAWTEXT);}function Ede(e,t){e._switchToTextParsing(t,mi.RAWTEXT);}function uZe(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML),e.framesetOk=false,e.insertionMode=e.insertionMode===j.IN_TABLE||e.insertionMode===j.IN_CAPTION||e.insertionMode===j.IN_TABLE_BODY||e.insertionMode===j.IN_ROW||e.insertionMode===j.IN_CELL?j.IN_SELECT_IN_TABLE:j.IN_SELECT;}function pZe(e,t){e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML);}function mZe(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Te.HTML);}function hZe(e,t){e.openElements.hasInScope(b.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(b.RTC),e._insertElement(t,Te.HTML);}function gZe(e,t){e._reconstructActiveFormattingElements(),OH(t),SP(t),t.selfClosing?e._appendElement(t,Te.MATHML):e._insertElement(t,Te.MATHML),t.ackSelfClosing=true;}function fZe(e,t){e._reconstructActiveFormattingElements(),MH(t),SP(t),t.selfClosing?e._appendElement(t,Te.SVG):e._insertElement(t,Te.SVG),t.ackSelfClosing=true;}function Cde(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Te.HTML);}function hi(e,t){switch(t.tagID){case b.I:case b.S:case b.B:case b.U:case b.EM:case b.TT:case b.BIG:case b.CODE:case b.FONT:case b.SMALL:case b.STRIKE:case b.STRONG:{eZe(e,t);break}case b.A:{Z5e(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{q5e(e,t);break}case b.P:case b.DL:case b.OL:case b.UL:case b.DIV:case b.DIR:case b.NAV:case b.MAIN:case b.MENU:case b.ASIDE:case b.CENTER:case b.FIGURE:case b.FOOTER:case b.HEADER:case b.HGROUP:case b.DIALOG:case b.DETAILS:case b.ADDRESS:case b.ARTICLE:case b.SEARCH:case b.SECTION:case b.SUMMARY:case b.FIELDSET:case b.BLOCKQUOTE:case b.FIGCAPTION:{W5e(e,t);break}case b.LI:case b.DD:case b.DT:{J5e(e,t);break}case b.BR:case b.IMG:case b.WBR:case b.AREA:case b.EMBED:case b.KEYGEN:{Ide(e,t);break}case b.HR:{sZe(e,t);break}case b.RB:case b.RTC:{mZe(e,t);break}case b.RT:case b.RP:{hZe(e,t);break}case b.PRE:case b.LISTING:{K5e(e,t);break}case b.XMP:{cZe(e,t);break}case b.SVG:{fZe(e,t);break}case b.HTML:{$5e(e,t);break}case b.BASE:case b.LINK:case b.META:case b.STYLE:case b.TITLE:case b.SCRIPT:case b.BGSOUND:case b.BASEFONT:case b.TEMPLATE:{Al(e,t);break}case b.BODY:{V5e(e,t);break}case b.FORM:{Y5e(e,t);break}case b.NOBR:{tZe(e,t);break}case b.MATH:{gZe(e,t);break}case b.TABLE:{oZe(e,t);break}case b.INPUT:{rZe(e,t);break}case b.PARAM:case b.TRACK:case b.SOURCE:{iZe(e,t);break}case b.IMAGE:{aZe(e,t);break}case b.BUTTON:{Q5e(e,t);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{nZe(e,t);break}case b.IFRAME:{dZe(e,t);break}case b.SELECT:{uZe(e,t);break}case b.OPTION:case b.OPTGROUP:{pZe(e,t);break}case b.NOEMBED:case b.NOFRAMES:{Ede(e,t);break}case b.FRAMESET:{z5e(e,t);break}case b.TEXTAREA:{lZe(e,t);break}case b.NOSCRIPT:{e.options.scriptingEnabled?Ede(e,t):Cde(e,t);break}case b.PLAINTEXT:{X5e(e,t);break}case b.COL:case b.TH:case b.TD:case b.TR:case b.HEAD:case b.FRAME:case b.TBODY:case b.TFOOT:case b.THEAD:case b.CAPTION:case b.COLGROUP:break;default:Cde(e,t);}}function yZe(e,t){if(e.openElements.hasInScope(b.BODY)&&(e.insertionMode=j.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t);}}function SZe(e,t){e.openElements.hasInScope(b.BODY)&&(e.insertionMode=j.AFTER_BODY,Bde(e,t));}function bZe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n));}function TZe(e){let t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(b.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(b.FORM):n&&e.openElements.remove(n));}function AZe(e){e.openElements.hasInButtonScope(b.P)||e._insertFakeElement(ie.P,b.P),e._closePElement();}function EZe(e){e.openElements.hasInListItemScope(b.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(b.LI),e.openElements.popUntilTagNamePopped(b.LI));}function CZe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n));}function vZe(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped());}function RZe(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker());}function wZe(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(ie.BR,b.BR),e.openElements.pop(),e.framesetOk=false;}function _de(e,t){let n=t.tagName,o=t.tagID;for(let r=e.openElements.stackTop;r>0;r--){let i=e.openElements.items[r],s=e.openElements.tagIDs[r];if(o===s&&(o!==b.UNKNOWN||e.treeAdapter.getTagName(i)===n)){e.openElements.generateImpliedEndTagsWithExclusion(o),e.openElements.stackTop>=r&&e.openElements.shortenToLength(r);break}if(e._isSpecialElement(i,s))break}}function CP(e,t){switch(t.tagID){case b.A:case b.B:case b.I:case b.S:case b.U:case b.EM:case b.TT:case b.BIG:case b.CODE:case b.FONT:case b.NOBR:case b.SMALL:case b.STRIKE:case b.STRONG:{DH(e,t);break}case b.P:{AZe(e);break}case b.DL:case b.UL:case b.OL:case b.DIR:case b.DIV:case b.NAV:case b.PRE:case b.MAIN:case b.MENU:case b.ASIDE:case b.BUTTON:case b.CENTER:case b.FIGURE:case b.FOOTER:case b.HEADER:case b.HGROUP:case b.DIALOG:case b.ADDRESS:case b.ARTICLE:case b.DETAILS:case b.SEARCH:case b.SECTION:case b.SUMMARY:case b.LISTING:case b.FIELDSET:case b.BLOCKQUOTE:case b.FIGCAPTION:{bZe(e,t);break}case b.LI:{EZe(e);break}case b.DD:case b.DT:{CZe(e,t);break}case b.H1:case b.H2:case b.H3:case b.H4:case b.H5:case b.H6:{vZe(e);break}case b.BR:{wZe(e);break}case b.BODY:{yZe(e,t);break}case b.HTML:{SZe(e,t);break}case b.FORM:{TZe(e);break}case b.APPLET:case b.OBJECT:case b.MARQUEE:{RZe(e,t);break}case b.TEMPLATE:{uh(e,t);break}default:_de(e,t);}}function Pde(e,t){e.tmplInsertionModeStack.length>0?Fde(e,t):FH(e,t);}function IZe(e,t){var n;t.tagID===b.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode;}function xZe(e,t){e._err(t,ce.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t);}function NH(e,t){if(e.openElements.currentTagId!==void 0&&vde.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=false,e.originalInsertionMode=e.insertionMode,e.insertionMode=j.IN_TABLE_TEXT,t.type){case Kt.CHARACTER:{Mde(e,t);break}case Kt.WHITESPACE_CHARACTER:{Ode(e,t);break}}else dE(e,t);}function _Ze(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_CAPTION;}function PZe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_COLUMN_GROUP;}function OZe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.COLGROUP,b.COLGROUP),e.insertionMode=j.IN_COLUMN_GROUP,BH(e,t);}function MZe(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_TABLE_BODY;}function NZe(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(ie.TBODY,b.TBODY),e.insertionMode=j.IN_TABLE_BODY,vP(e,t);}function LZe(e,t){e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode(),e._processStartTag(t));}function kZe(e,t){xde(t)?e._appendElement(t,Te.HTML):dE(e,t),t.ackSelfClosing=true;}function DZe(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Te.HTML),e.formElement=e.openElements.current,e.openElements.pop());}function _y(e,t){switch(t.tagID){case b.TD:case b.TH:case b.TR:{NZe(e,t);break}case b.STYLE:case b.SCRIPT:case b.TEMPLATE:{Al(e,t);break}case b.COL:{OZe(e,t);break}case b.FORM:{DZe(e,t);break}case b.TABLE:{LZe(e,t);break}case b.TBODY:case b.TFOOT:case b.THEAD:{MZe(e,t);break}case b.INPUT:{kZe(e,t);break}case b.CAPTION:{_Ze(e,t);break}case b.COLGROUP:{PZe(e,t);break}default:dE(e,t);}}function cE(e,t){switch(t.tagID){case b.TABLE:{e.openElements.hasInTableScope(b.TABLE)&&(e.openElements.popUntilTagNamePopped(b.TABLE),e._resetInsertionMode());break}case b.TEMPLATE:{uh(e,t);break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:case b.TBODY:case b.TD:case b.TFOOT:case b.TH:case b.THEAD:case b.TR:break;default:dE(e,t);}}function dE(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=true,EP(e,t),e.fosterParentingEnabled=n;}function Ode(e,t){e.pendingCharacterTokens.push(t);}function Mde(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=true;}function nE(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)dE(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t);}var Nde=new Set([b.CAPTION,b.COL,b.COLGROUP,b.TBODY,b.TD,b.TFOOT,b.TH,b.THEAD,b.TR]);function FZe(e,t){let n=t.tagID;Nde.has(n)?e.openElements.hasInTableScope(b.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=j.IN_TABLE,_y(e,t)):hi(e,t);}function BZe(e,t){let n=t.tagID;switch(n){case b.CAPTION:case b.TABLE:{e.openElements.hasInTableScope(b.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(b.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=j.IN_TABLE,n===b.TABLE&&cE(e,t));break}case b.BODY:case b.COL:case b.COLGROUP:case b.HTML:case b.TBODY:case b.TD:case b.TFOOT:case b.TH:case b.THEAD:case b.TR:break;default:CP(e,t);}}function BH(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.COL:{e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.TEMPLATE:{Al(e,t);break}default:TP(e,t);}}function UZe(e,t){switch(t.tagID){case b.COLGROUP:{e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=j.IN_TABLE);break}case b.TEMPLATE:{uh(e,t);break}case b.COL:break;default:TP(e,t);}}function TP(e,t){e.openElements.currentTagId===b.COLGROUP&&(e.openElements.pop(),e.insertionMode=j.IN_TABLE,e._processToken(t));}function vP(e,t){switch(t.tagID){case b.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_ROW;break}case b.TH:case b.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(ie.TR,b.TR),e.insertionMode=j.IN_ROW,RP(e,t);break}case b.CAPTION:case b.COL:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE,_y(e,t));break}default:_y(e,t);}}function kH(e,t){let n=t.tagID;switch(t.tagID){case b.TBODY:case b.TFOOT:case b.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE);break}case b.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE,cE(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:case b.TD:case b.TH:case b.TR:break;default:cE(e,t);}}function RP(e,t){switch(t.tagID){case b.TH:case b.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Te.HTML),e.insertionMode=j.IN_CELL,e.activeFormattingElements.insertMarker();break}case b.CAPTION:case b.COL:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:case b.TR:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY,vP(e,t));break}default:_y(e,t);}}function Lde(e,t){switch(t.tagID){case b.TR:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY);break}case b.TABLE:{e.openElements.hasInTableScope(b.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY,kH(e,t));break}case b.TBODY:case b.TFOOT:case b.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(b.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=j.IN_TABLE_BODY,kH(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:case b.TD:case b.TH:break;default:cE(e,t);}}function HZe(e,t){let n=t.tagID;Nde.has(n)?(e.openElements.hasInTableScope(b.TD)||e.openElements.hasInTableScope(b.TH))&&(e._closeTableCell(),RP(e,t)):hi(e,t);}function GZe(e,t){let n=t.tagID;switch(n){case b.TD:case b.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=j.IN_ROW);break}case b.TABLE:case b.TBODY:case b.TFOOT:case b.THEAD:case b.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),Lde(e,t));break}case b.BODY:case b.CAPTION:case b.COL:case b.COLGROUP:case b.HTML:break;default:CP(e,t);}}function kde(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.OPTION:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e._insertElement(t,Te.HTML);break}case b.OPTGROUP:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Te.HTML);break}case b.HR:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.INPUT:case b.KEYGEN:case b.TEXTAREA:case b.SELECT:{e.openElements.hasInSelectScope(b.SELECT)&&(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode(),t.tagID!==b.SELECT&&e._processStartTag(t));break}case b.SCRIPT:case b.TEMPLATE:{Al(e,t);break}}}function Dde(e,t){switch(t.tagID){case b.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===b.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===b.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===b.OPTGROUP&&e.openElements.pop();break}case b.OPTION:{e.openElements.currentTagId===b.OPTION&&e.openElements.pop();break}case b.SELECT:{e.openElements.hasInSelectScope(b.SELECT)&&(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode());break}case b.TEMPLATE:{uh(e,t);break}}}function jZe(e,t){let n=t.tagID;n===b.CAPTION||n===b.TABLE||n===b.TBODY||n===b.TFOOT||n===b.THEAD||n===b.TR||n===b.TD||n===b.TH?(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode(),e._processStartTag(t)):kde(e,t);}function $Ze(e,t){let n=t.tagID;n===b.CAPTION||n===b.TABLE||n===b.TBODY||n===b.TFOOT||n===b.THEAD||n===b.TR||n===b.TD||n===b.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(b.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Dde(e,t);}function VZe(e,t){switch(t.tagID){case b.BASE:case b.BASEFONT:case b.BGSOUND:case b.LINK:case b.META:case b.NOFRAMES:case b.SCRIPT:case b.STYLE:case b.TEMPLATE:case b.TITLE:{Al(e,t);break}case b.CAPTION:case b.COLGROUP:case b.TBODY:case b.TFOOT:case b.THEAD:{e.tmplInsertionModeStack[0]=j.IN_TABLE,e.insertionMode=j.IN_TABLE,_y(e,t);break}case b.COL:{e.tmplInsertionModeStack[0]=j.IN_COLUMN_GROUP,e.insertionMode=j.IN_COLUMN_GROUP,BH(e,t);break}case b.TR:{e.tmplInsertionModeStack[0]=j.IN_TABLE_BODY,e.insertionMode=j.IN_TABLE_BODY,vP(e,t);break}case b.TD:case b.TH:{e.tmplInsertionModeStack[0]=j.IN_ROW,e.insertionMode=j.IN_ROW,RP(e,t);break}default:e.tmplInsertionModeStack[0]=j.IN_BODY,e.insertionMode=j.IN_BODY,hi(e,t);}}function zZe(e,t){t.tagID===b.TEMPLATE&&uh(e,t);}function Fde(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(b.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):FH(e,t);}function WZe(e,t){t.tagID===b.HTML?hi(e,t):AP(e,t);}function Bde(e,t){var n;if(t.tagID===b.HTML){if(e.fragmentContext||(e.insertionMode=j.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===b.HTML){e._setEndLocation(e.openElements.items[0],t);let o=e.openElements.items[1];o&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(o))===null||n===void 0)&&n.endTag)&&e._setEndLocation(o,t);}}else AP(e,t);}function AP(e,t){e.insertionMode=j.IN_BODY,EP(e,t);}function qZe(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.FRAMESET:{e._insertElement(t,Te.HTML);break}case b.FRAME:{e._appendElement(t,Te.HTML),t.ackSelfClosing=true;break}case b.NOFRAMES:{Al(e,t);break}}}function KZe(e,t){t.tagID===b.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==b.FRAMESET&&(e.insertionMode=j.AFTER_FRAMESET));}function YZe(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.NOFRAMES:{Al(e,t);break}}}function JZe(e,t){t.tagID===b.HTML&&(e.insertionMode=j.AFTER_AFTER_FRAMESET);}function XZe(e,t){t.tagID===b.HTML?hi(e,t):bP(e,t);}function bP(e,t){e.insertionMode=j.IN_BODY,EP(e,t);}function QZe(e,t){switch(t.tagID){case b.HTML:{hi(e,t);break}case b.NOFRAMES:{Al(e,t);break}}}function ZZe(e,t){t.chars=Gn,e._insertCharacters(t);}function e6e(e,t){e._insertCharacters(t),e.framesetOk=false;}function Ude(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Te.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop();}function t6e(e,t){if(yde(t))Ude(e),e._startTagOutsideForeignContent(t);else {let n=e._getAdjustedCurrentElement(),o=e.treeAdapter.getNamespaceURI(n);o===Te.MATHML?OH(t):o===Te.SVG&&(Sde(t),MH(t)),SP(t),t.selfClosing?e._appendElement(t,o):e._insertElement(t,o),t.ackSelfClosing=true;}}function n6e(e,t){if(t.tagID===b.P||t.tagID===b.BR){Ude(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){let o=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(o)===Te.HTML){e._endTagOutsideForeignContent(t);break}let r=e.treeAdapter.getTagName(o);if(r.toLowerCase()===t.tagName){t.tagName=r,e.openElements.shortenToLength(n);break}}}new Set([ie.AREA,ie.BASE,ie.BASEFONT,ie.BGSOUND,ie.BR,ie.COL,ie.EMBED,ie.FRAME,ie.HR,ie.IMG,ie.INPUT,ie.KEYGEN,ie.LINK,ie.META,ie.PARAM,ie.SOURCE,ie.TRACK,ie.WBR]);function Hde(e,t,n){typeof e=="string"&&(n=t,t=e,e=null);let o=lE.getFragmentParser(e,n);return o.tokenizer.write(t,true),o.getFragment()}var o6e=5e3,Gde=1024;function UH(e){return typeof e.tagName=="string"&&Array.isArray(e.attrs)}function r6e(e){return e.nodeName==="#text"}function HH(e,t){if(t.nodesLeft<=0)return;t.nodesLeft-=1;let n=e.tagName.toLowerCase(),o,r;for(let{name:l,value:c}of e.attrs){let d=l.toLowerCase();if(d==="role"){r=c;continue}o===void 0&&(o={}),o[d]=c;}let i,s=[];for(let l of e.childNodes){if(t.nodesLeft<=0)break;if(r6e(l)){let c=l.value;if(c&&c.trim().length>0){let d=c.length>Gde?c.slice(0,Gde):c;i=i===void 0?d:`${i} ${d}`;}}else if(UH(l)){let c=HH(l,t);c!==void 0&&s.push(c);}}let a={tag:n};return r!==void 0&&(a.role=r),o!==void 0&&(a.attributes=o),i!==void 0&&(a.text=i),s.length>0&&(a.children=s),a}function GH(e){let t=Hde(e),n={nodesLeft:o6e};for(let i of t.childNodes)if(UH(i)&&i.tagName.toLowerCase()==="body"){let s=HH(i,n);if(s!==void 0)return s}let o=[];for(let i of t.childNodes){if(n.nodesLeft<=0)break;if(UH(i)){let s=HH(i,n);s!==void 0&&o.push(s);}}let r={tag:"body"};return o.length>0&&(r.children=o),r}var i6e=new Set(["PRESET_ACTION","AI_ACTION_DYNAMIC"]),ph=class{constructor(t,n,o,r,i,s){this.orgId=t;this.testId=n;this.testName=o;this.diskStorage=r;this.parentFlushResults=i;this.appGraphSink=s;}children=[];finished=false;stepFrequenciesByType={};currentResults=[];async getScreenshot(t,n){return this.diskStorage.readFile(`${Fr}/${n}.jpeg`)}async getHtmlSnapshot(t,n){return this.diskStorage.readFile(`${Fr}/${n}.html`)?.toString()}recordStepStat(t){t.type!=="PRESET_ACTION"?this.stepFrequenciesByType[t.type]=(this.stepFrequenciesByType[t.type]||0)+1:this.stepFrequenciesByType[t.command.type]=(this.stepFrequenciesByType[t.command.type]||0)+1;}sendFinalizedStepStats(){for(let[t,n]of Object.entries(this.stepFrequenciesByType))At.increment("test_step_execution",n,[`type:${t}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}flushResults(t){this.currentResults=t,this.parentFlushResults(t);}async startStep(t,n){let{step:o,parentStepIdChain:r}=t;this.recordStepStat(o);let i={step:o,status:"RUNNING",startedAt:new Date},s=[...n];this.currentResults=s;let a=new jH(this.orgId,this.testId,this.testName,i,this.diskStorage,l=>{this.flushResults([...s,l]);},r??[],this.appGraphSink);return this.children.push(a),a}async finish(t){this.finished||(this.finished=true,await Promise.all(this.children.map(n=>n.finishInternal({status:kV(t.status),finishedAt:t.finishedAt}))),this.sendFinalizedStepStats());}};function s6e(e){switch(e){case "SUCCESS":return "PASSED";case "FAILED":return "FAILED";case "CANCELLED":return "CANCELLED";case "RUNNING":return "RUNNING";case "IDLE":return "PENDING";default:return Je(e)}}function wP(e){return e.some(t=>t.status==="FAILED")?"FAILED":e.some(t=>t.status==="CANCELLED")?"CANCELLED":"RUNNING"}var jH=class{constructor(t,n,o,r,i,s,a,l){this.orgId=t;this.testId=n;this.testName=o;this.metadata=r;this.diskStorage=i;this.parentFlushResults=s;this.parentStepIdChain=a;this.appGraphSink=l;this.interactionTracer=new op(void 0,c=>this.storeTraceAsset(c)),np.initializeRootTracerContext(this.interactionTracer);}children=[];finished=false;interactionTracer;attachBeforeScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.jpeg`,contents:o});}attachAfterScreenshot(t){let{snapshotId:n,screenshot:o}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.jpeg`,contents:o});}attachBeforeHtmlSnapshot(t){let{snapshotId:n,html:o}=t;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.html`,contents:o});}attachAfterHtmlSnapshot(t){let{snapshotId:n,html:o,url:r,logger:i}=t;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Fr}/${n}.html`,contents:o}),this.appGraphSink&&i6e.has(this.metadata.step.type)&&this.appGraphSink({html:o,url:r,stepId:this.metadata.step.id,parentStepIdChain:[...this.parentStepIdChain],logger:i});}recordTargetAutoHeal(t){let{healType:n}=t,o=n==="AI"?"ai-target-heal":"cache-heal";At.increment("test_event",1,[`name:${o}`,`orgId:${this.orgId}`]),this.metadata.healMetadata={healType:n,healedAt:new Date};}storeTraceAsset(t){this.diskStorage.storeFile({name:`${Fr}/${t.snapshotId}.${t.extension??"jpeg"}`,contents:t.data});}async finishInternal(t){this.finished||(this.finished=true,this.interactionTracer.finish(),await Promise.all(this.children.map(n=>n.finish({status:s6e(t.status),finishedAt:t.finishedAt}))));}recordStepDuration(t,n){if(!hv(t))return;let o=mv(t);At.distribution("test_step_duration",n,[`type:${o}`,"platform:browser","executor:cli",`orgId:${this.orgId}`]);}async finish(t){!this.finished&&t.resolvedStep!==void 0&&t.durationMs!==void 0&&this.recordStepDuration(t.resolvedStep,t.durationMs),await this.finishInternal(t.step),t.step.trace=this.interactionTracer.getRootSpan();}getResultBuilderForCurrentStep(){let t=this.metadata.step;switch(t.type){case "RESOLVED_MODULE":return n=>({...t,status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n,type:"MODULE"});case "CONDITIONAL":return n=>({...t,blocks:t.blocks.map(r=>({assertion:r.assertion,steps:hd(r.steps)})),elseSteps:t.elseSteps?hd(t.elseSteps):void 0,status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "WHILE_LOOP":return n=>({...t,steps:hd(t.steps),status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});case "AI_ACTION":case "AI_ACTION_DYNAMIC":case "PRESET_ACTION":case "SECTION":return n=>({...t,status:wP(n),startedAt:this.metadata.startedAt,finishedAt:new Date,results:n});default:return Je(t)}}async startSubSteps(){let t=this.getResultBuilderForCurrentStep(),n=new ph(this.orgId,this.testId,this.testName,this.diskStorage,o=>{let r=t(o);this.parentFlushResults(r);});return this.children.push(n),n}};var IP=class{constructor(t,n,o,r,i,s,a,l){this.orgId=t;this.testId=n;this.testName=o;this.runAttemptId=r;this.metadata=i;this.diskStorage=s;this.recordVideo=a;this.progressHandle=l;this.diskStorage.mkdir(Fr),this.harPagesStream=this.diskStorage.createFileStream(`${Fr}/har-pages.log`),this.inProgressHarEntries={},this.harEntriesStream=this.diskStorage.createFileStream(`${Fr}/har-entries.log`),this.resourceUsageStream=this.diskStorage.createFileStream(`${Fr}/resource-usage.ndjson`),this.resourceUsageSampler=pY({keepSamples:false,onSample:c=>{this.resourceUsageStream.write(`${JSON.stringify(c)}
8838
8841
  `),c.system.cpu&&(this.cpuUsageSum+=c.system.cpu.total,this.cpuSampleCount++);let d=c.system.memory.total-c.system.memory.free;this.memoryUsageSum+=d,this.memorySampleCount++;}});}finished=false;children=[];beforeResults;mainResults=[];afterResults;harPagesStream;inProgressHarEntries;harEntriesStream;resourceUsageStream;resourceUsageSampler;uiStatesStream;previousHtmlByteHash;previousFingerprint;cpuUsageSum=0;cpuSampleCount=0;memoryUsageSum=0;memorySampleCount=0;get loggerBindings(){return {runAttemptId:this.runAttemptId}}getResourceUsageAverages(){return {avgCpuUsage:this.cpuSampleCount>0?this.cpuUsageSum/this.cpuSampleCount:0,avgMemoryUsage:this.memorySampleCount>0?this.memoryUsageSum/this.memorySampleCount:0}}get videoOutputPath(){if(this.recordVideo)return Jn__default.resolve(this.diskStorage.cwd(),Fr)}setActiveVideo(t,n){this.recordVideo&&(this.metadata.activeVideos=this.metadata.activeVideos||[],this.metadata.activeVideos.push({videoName:t,timestamp:n}));}setViewport(t){this.metadata.viewport=t;}onNetworkPage(t){this.finished||this.harPagesStream.write(`${JSON.stringify(t)}
8839
8842
  `);}appendUiState(t){this.finished||(this.uiStatesStream||(this.uiStatesStream=this.diskStorage.createFileStream(iW)),this.uiStatesStream.write(`${JSON.stringify(t)}
8840
8843
  `));}buildAppGraphSink(){return ({html:t,url:n,stepId:o,parentStepIdChain:r,logger:i})=>{let s=IH(t),a=s===this.previousHtmlByteHash?this.previousFingerprint:void 0;if(!a){try{a=xH({url:n,dom:GH(t)});}catch(l){i.debug({err:l,stepId:o},"Failed to compute app-graph UIState fingerprint");return}this.previousHtmlByteHash=s,this.previousFingerprint=a;}this.appendUiState({stepId:o,parentStepIdChain:r,fingerprintHash:a.fingerprintHash,minhash:Array.from(a.minhash),canonicalUrl:a.canonicalUrl,capturedAt:Date.now()});}}onNetworkLogs(t){if(!this.finished)for(let[n,o]of Object.entries(t))o.response?(delete this.inProgressHarEntries[n],this.harEntriesStream.write(`${JSON.stringify(o)}
@@ -8906,4 +8909,4 @@ Entering interactive mode. Ask follow-up questions about run ${k.context.runId??
8906
8909
  `),L&&!L.timedOut&&(Ee.error({sessionId:t,reason:L.reason},"AI explore run failed; emitted partial results"),R.error(`AI explore failed before completing: ${L.reason}. Partial results above reflect work done before the failure.`),await lt(),process.exit(1)),L?.timedOut&&(Ee.warn({sessionId:t,reason:L.reason,timeoutMinutes:C},"AI explore hit its timeout; emitted partial results"),R.warn(`AI explore stopped at the ${C}-minute timeout. Partial results above reflect work completed before the deadline.`));let k;if(e.build){let{pullRequestUrl:V,authors:re}=await Spe({behavior:XH({configured:g.onSuccess,patch:e.patch??!1}),requestCommitAuthorsAsReviewers:g.requestCommitAuthorsAsReviewers,apiClient:l,generator:h,gitMetadata:y,repoRoot:I,project:m,explorerResult:w,bugs:x,writtenPaths:v,logger:u,baseSha:_,headSha:P}),ne=Tpe({explorerResult:w,bugs:x,gitMetadata:y,pullRequestUrl:V,authors:re&&re.length>0?re:Ape({repoRoot:I,baseSha:_,headSha:P,logger:u}),baseSha:_,headSha:P});ne&&(k=l.sendExploreSlackNotification(ne).catch(G=>{u.error({err:G},"Failed to send explore Slack notification");}));}await Promise.all([lt(),k]),process.exit(L?.timedOut?1:0);}catch(a){o.signal.aborted&&(Ee.warn({err:a,sessionId:t},"AI explore command cancelled by signal"),R.warn("AI explore cancelled."),await lt(),process.exit(130));let l=LG(a);Ee.error({err:l,sessionId:t},"AI explore command failed"),R.error({err:l},"AI explore command failed"),await lt(),process.exit(1);}finally{Dd(),process.off("SIGINT",i),process.off("SIGTERM",s);}});BG.command("triage").alias("heal").description("Group failed test results by shared test fixes. Alias: heal. Pass --dry-run to print the bucketing plan without healing.").addArgument(new Argument("[results]","Path to the results archive. Omit when using --run-group-id, --run-id, or --git-commit.").argOptional()).addOption(hG).addOption(gG).addOption(fG).addOption(Dn).addOption(Nn).addOption(mn).addOption(hr).addOption(Ma).addOption(fE).addOption(WP).addOption(Ny).addOption(Ly).addOption(fh).addOption(My).addOption(Oy).addOption(SG).addOption(yG).addOption(zP).addOption(new Option("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Option("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Option("--wait-on-proxy <waitOnProxy>","HTTP proxy to use with the --wait-on command. Specify as https://username:pass@domain.com:2345")).addOption(new Option("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(zi)).addOption(KP).addOption(new Option("--limit <limit>","Abort if the number of healable failed runs exceeds this threshold.").argParser(gh)).addOption(CG).addOption(RG).addOption($P).addOption(lG).addOption(jP).option("--dry-run","Print the failure bucketing plan that would be dispatched to healing subagents, then exit without healing any tests.").option("--json","Suppress progress output and print the triage result as JSON.").addOption(new Option("--save","Persist triage heal metadata. Local archives are updated in place, and cloud runs are updated in the cloud.").default(true)).option("--no-save","Do not persist triage heal metadata.").option("--no-upload","Deprecated alias for --no-save.").addOption(cG).addOption(jue).addOption($ue).addOption(Vue).action(async(e,t)=>{let n=t.json??false;n&&R.setMinLevel(50);let o=t.runGroupId?vH(t.runGroupId):void 0,r=Array.from(new Set((t.runId??[]).map(nP))),i=t.gitCommit,s=t.dryRun??false,a=t.save!==false&&t.upload!==false,l=Bg(t),c=gE(t.customHeaders),d=await sn({configFilePath:t.config,nameFilter:t.filter}),u=new Dt({baseUrl:t.server,apiKey:t.apiKey,logger:Ee,mode:"runner",runner:"result-classification"});await Mr(Ee,{announcementsClient:n?void 0:u});let{orgId:p,userId:m,email:h,selfServe:g}=await wm({client:u,skipPrompts:t.yes});rP({userId:m,orgId:p,email:h,selfServe:g});let f=await Fs({project:d,apiClient:u}),y=f.config.ai?.triage,S=y?.remoteBrowser??f.config.browser?.remoteBrowser??false,T="default";y?.remoteBrowser!==void 0?T="ai.triage.remoteBrowser":f.config.browser?.remoteBrowser!==void 0&&(T="browser.remoteBrowser");let{parallel:E,autoParallel:C}=UG({options:t,project:f});C||IJ({parallel:E,remoteBrowser:S});let w;t.inputCsv&&(w=await oP(t.inputCsv));let x=lh(t.pixelRatio),I=t.headfulBrowser??false,v=EE.parse({onFail:t.onHealFail??y?.onHealFail,onSuccess:y?.onHealSuccess,requestCommitAuthorsAsReviewers:y?.requestCommitAuthorsAsReviewers}),_={...v,onSuccess:XH({configured:v.onSuccess,patch:t.patch??false,explicitOverride:t.onHealSuccess})},P=await ri(Ee,u,f),L=yue({resultsDir:e,runGroupId:o,runIds:r,gitCommitSha:i});if(!L){JH({output:void 0,dryRun:s,jsonOutput:n});return}let k=Ee.child({cliVersion:Zt,orgId:p,userId:m,serverId:L.serverId});k.info({gitMetadata:P,config:f.config,nodeVersion:process.versions.node},"Got local metadata"),k.info({remoteBrowserRequested:S,remoteBrowserSource:T,aiTriageRemoteBrowser:y?.remoteBrowser,projectRemoteBrowser:f.config.browser?.remoteBrowser,parallel:E,autoParallel:C},"Resolved heal remote browser configuration");let V=new lr(f.config.ai?.agentConfig,{baseUrl:t.server,apiKey:t.apiKey,logger:k,mode:"runner",runner:"heal"}),re=new AbortController,ne=new AbortController,G=new fl({sessionGuard:{maxConcurrentSessions:E,mode:"queue"}});Ou(k),oc(async K=>{re.abort(),ne.abort(),await G.killAllSessions(K);});let W={limit:t.limit,project:f,apiClient:u,generator:V,logger:k,gitMetadata:P,parallel:E,orgId:p,serverId:L.serverId,apiKey:t.apiKey,start:t.start,waitOn:t.waitOn,waitOnProxy:t.waitOnProxy,waitOnTimeout:t.waitOnTimeout,alwaysSaveCache:l.alwaysSaveCache,noCache:l.noCache,regenerateHeal:t.regenerateHeal??false,excludePatterns:t.exclude,skipQuarantined:t.skipQuarantined,sessionOptions:{envName:t.env,urlOverride:t.urlOverride,customHeaders:c,devicePixelRatio:x,testInputs:w&&w.length===1?w[0]:void 0,browserTypeOverride:t.browser,remoteBrowserOverride:S,headfulOverride:I},timeoutMinutes:t.timeoutMinutes,sessionManager:G,agentOutputStream:t.quiet||n?void 0:process.stdout,dryRun:s,jsonOutput:n,abortController:re};await Ru({serviceName:"heal",enabled:t.shareDiagnostics===true});let M=Ev(k);k.info({platform:M?.platform,cpuMetadata:M?.cpuMetadata,healTargetKind:L.kind,parallel:E,remoteBrowser:S},"Starting heal triage command"),oc(async()=>{clearInterval(M?.interval);});let Y=0,$;try{$=await He({name:"heal.run",root:!0,attributes:{"momentic.org_id":p,"momentic.server_id":L.serverId,"momentic.parallel":E,"momentic.dry_run":s},fn:async()=>{switch(L.kind){case "run-group":return Jde({...W,runGroupId:L.runGroupId});case "results":return Yde({...W,resultsDir:L.resultsDir});case "run":return Xde({...W,runIds:L.runIds});case "commit":return Qde({...W,gitCommitSha:L.gitCommitSha});default:return Je(L)}}});}catch(K){$={heals:[],bucketingIterations:[],healPatches:[],failure:{err:K,message:X(K)}};}if(ne.signal.aborted)return;let B=false,Q=$;if(!s&&!$?.failure)try{let K=await pue({output:$,resultsDir:a&&L.kind==="results"?L.resultsDir:void 0,resultsUrl:fue({target:L,appUrl:u.getAppUrl()}),healingConfig:_,gitMetadata:P,project:f,apiClient:u,generator:V,logger:k,suppressOutput:n});Q=K.output,Y=K.exitCode;}catch(K){Q={...$??{heals:[],bucketingIterations:[],healPatches:[]},failure:{err:K,message:X(K)}};}try{if(JH({output:Q,dryRun:s,jsonOutput:n}),ne.signal.aborted)return;let K=L.kind==="results"?await Zde({output:Q,generator:V,logger:k,serverId:L.runGroupId,dryRun:s,categoryDefinitions:f.config.ai?.classification?.categories??qi,healingConfig:_,abortSignal:ne.signal}):void 0;if(ne.signal.aborted)return;if(a&&Q&&Q.heals.length>0&&L.kind!=="results"){try{await iue({apiClient:u,logger:k,healResults:Q.heals});}catch(ve){k.warn({err:ve},"Failed to persist heal metadata to cloud");}if(Q.healTimeline&&Q.healTimelineAssetsDir)try{await sue({apiClient:u,logger:k,healResults:Q.heals,healTimeline:Q.healTimeline,healTimelineAssetsDir:Q.healTimelineAssetsDir});}catch(ve){k.warn({err:ve},"Failed to upload heal traces to cloud");}}else if(a&&L.kind==="results"){K&&eue({resultsDir:L.resultsDir,summary:K});let ve=Ct(),pe=()=>He({name:"file-storage.upload_test_outputs",serviceName:"file-storage",fn:()=>wT({client:u,resultsPath:L.resultsDir})}),Re=n?await pe():await go({text:"Uploading results to Momentic\u2026",screen:ve},pe);B=Re.success,Re.success?(R.success("Uploaded results to Momentic."),R.dimmed(` ${ld(Re.runGroupUrl,ve)}`)):R.error(`Results upload failed: ${Re.error}.`);}if(a&&L.kind==="results"&&K&&!B)try{await u.updateGithubPRHealRiskSummary(L.runGroupId,{summary:K});}catch(ve){k.warn({err:ve},"Failed to submit GitHub PR triage summary update");}}finally{Q?.healTimelineAssetsDir&&Oo__default.rmSync(Q.healTimelineAssetsDir,{recursive:true,force:true});}if(Q?.failure)throw Q.failure.err;await lt(),process.exit(Y);});en.command("upgrade").description("Upgrade your configuration to the latest recommended settings").addOption(mn).addOption(hr).addOption(Nn).addOption(Dn).option("--dry-run","Preview the upgrade without writing any files or pushing snapshots.").action(async e=>{let t=await sn({configFilePath:e.config,nameFilter:e.filter}),n=e.dryRun??false;n||await Bpe();let o=new Dt({baseUrl:e.server,apiKey:e.apiKey,logger:Ee,mode:"runner",runner:"test-runner"}),{orgId:r}=await o.getAuthInfo(),i=await ri(Ee,o,t),s=await O6({project:t,dryRun:n,migrate:()=>YP({project:t,apiClient:o,gitMetadata:i,orgId:r,dryRun:n})});gF({summary:s.migration,fileFormatChanged:s.fileFormatChanged,aiSettings:s.aiSettings,dryRun:n}),s.fileFormatChanged||mF(s.aiSettings)?n?R.success("Dry run complete. Rerun without --dry-run to apply."):(R.success("Upgraded project to latest recommended settings."),R.dimmed(" Optional: rerun tests with --regenerate-cache to rebuild caches from scratch (slower).")):R.success("Project is already up to date."),await lt(),process.exit(0);});async function v9e(e){if(e.prompt!==void 0)return e.prompt;if(e.promptFile!==void 0){let t=Jn__default.resolve(process.cwd(),e.promptFile);return Oo__default.promises.readFile(t,"utf-8")}}function UG({options:e,project:t}){let n=e.parallel??t.config.parallel??1;if(n!=="auto")return {parallel:n,autoParallel:false};let o=e.remoteBrowsers??t.config.browser?.remoteBrowser??false,r=cpus().length;return {parallel:o?Math.max(1,r*4-2):Math.max(1,Math.floor(r/2)),autoParallel:true}}async function HG(e){let t=e.config.fileFormat==="v2",{totalErrors:n,parsingErrors:o,parsingErrorDetails:r,failedTestFilePaths:i,failedModuleFilePaths:s}=t?await nG({project:e}):await tG({project:e,fix:false});o>0&&(Hg({parsingErrors:o,parsingErrorDetails:r,failedTestFilePaths:i,failedModuleFilePaths:s,rootDir:e.rootDir}),process.exit(1)),n>0&&(R.error(`Found ${n} ${t?"lint ":""}errors`),R.warn(t?"Run 'npx momentic lint' for details":"To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));}async function R9e(){jpe("Main program started");try{await en.parseAsync(process.argv),await lt();}catch(e){let t={};try{t.playwrightVersion=execSync("npx playwright --version").toString();}catch(o){Ee.error({err:o},"Error fetching debug information");}let n=$E(e,ke);n?(Ee.error({err:e,debugInfo:t},"User-facing error in CLI"),R.error(n.message)):(Ee.error({err:e,debugInfo:t},"Uncaught error in CLI"),R.error({err:e},"Momentic CLI exited unexpectedly")),await lt(),process.exit(1);}}y3e.setMaxListeners(25);process.on("warning",e=>{Ee.warn({err:e},`Node warning received on CLI: ${e.message}`);});jpe("CLI parsing setup complete");R9e();
8907
8910
  //# sourceMappingURL=out.js.map
8908
8911
  //# sourceMappingURL=cli.js.map
8909
- //# debugId=8c39e463-cfe2-5529-b4fd-e08b9a5ce37b
8912
+ //# debugId=86404b74-7b88-53d0-b555-5f571622f70d